videojs-http-streaming.es.js 905 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440
  1. /*! @name @videojs/http-streaming @version 3.10.0 @license Apache-2.0 */
  2. import document from 'global/document';
  3. import window$1 from 'global/window';
  4. import _extends from '@babel/runtime/helpers/extends';
  5. import _resolveUrl from '@videojs/vhs-utils/es/resolve-url.js';
  6. import videojs from 'video.js';
  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. let seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
  674. if (seekableEnd === null) {
  675. return createTimeRanges();
  676. } // Clamp seekable end since it can not be less than the seekable start
  677. if (seekableEnd < seekableStart) {
  678. seekableEnd = seekableStart;
  679. }
  680. return createTimeRanges(seekableStart, seekableEnd);
  681. };
  682. /**
  683. * Determine the index and estimated starting time of the segment that
  684. * contains a specified playback position in a media playlist.
  685. *
  686. * @param {Object} options.playlist the media playlist to query
  687. * @param {number} options.currentTime The number of seconds since the earliest
  688. * possible position to determine the containing segment for
  689. * @param {number} options.startTime the time when the segment/part starts
  690. * @param {number} options.startingSegmentIndex the segment index to start looking at.
  691. * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
  692. *
  693. * @return {Object} an object with partIndex, segmentIndex, and startTime.
  694. */
  695. const getMediaInfoForTime = function ({
  696. playlist,
  697. currentTime,
  698. startingSegmentIndex,
  699. startingPartIndex,
  700. startTime,
  701. exactManifestTimings
  702. }) {
  703. let time = currentTime - startTime;
  704. const partsAndSegments = getPartsAndSegments(playlist);
  705. let startIndex = 0;
  706. for (let i = 0; i < partsAndSegments.length; i++) {
  707. const partAndSegment = partsAndSegments[i];
  708. if (startingSegmentIndex !== partAndSegment.segmentIndex) {
  709. continue;
  710. } // skip this if part index does not match.
  711. if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
  712. continue;
  713. }
  714. startIndex = i;
  715. break;
  716. }
  717. if (time < 0) {
  718. // Walk backward from startIndex in the playlist, adding durations
  719. // until we find a segment that contains `time` and return it
  720. if (startIndex > 0) {
  721. for (let i = startIndex - 1; i >= 0; i--) {
  722. const partAndSegment = partsAndSegments[i];
  723. time += partAndSegment.duration;
  724. if (exactManifestTimings) {
  725. if (time < 0) {
  726. continue;
  727. }
  728. } else if (time + TIME_FUDGE_FACTOR <= 0) {
  729. continue;
  730. }
  731. return {
  732. partIndex: partAndSegment.partIndex,
  733. segmentIndex: partAndSegment.segmentIndex,
  734. startTime: startTime - sumDurations({
  735. defaultDuration: playlist.targetDuration,
  736. durationList: partsAndSegments,
  737. startIndex,
  738. endIndex: i
  739. })
  740. };
  741. }
  742. } // We were unable to find a good segment within the playlist
  743. // so select the first segment
  744. return {
  745. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  746. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  747. startTime: currentTime
  748. };
  749. } // When startIndex is negative, we first walk forward to first segment
  750. // adding target durations. If we "run out of time" before getting to
  751. // the first segment, return the first segment
  752. if (startIndex < 0) {
  753. for (let i = startIndex; i < 0; i++) {
  754. time -= playlist.targetDuration;
  755. if (time < 0) {
  756. return {
  757. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  758. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  759. startTime: currentTime
  760. };
  761. }
  762. }
  763. startIndex = 0;
  764. } // Walk forward from startIndex in the playlist, subtracting durations
  765. // until we find a segment that contains `time` and return it
  766. for (let i = startIndex; i < partsAndSegments.length; i++) {
  767. const partAndSegment = partsAndSegments[i];
  768. time -= partAndSegment.duration;
  769. const canUseFudgeFactor = partAndSegment.duration > TIME_FUDGE_FACTOR;
  770. const isExactlyAtTheEnd = time === 0;
  771. const isExtremelyCloseToTheEnd = canUseFudgeFactor && time + TIME_FUDGE_FACTOR >= 0;
  772. if (isExactlyAtTheEnd || isExtremelyCloseToTheEnd) {
  773. // 1) We are exactly at the end of the current segment.
  774. // 2) We are extremely close to the end of the current segment (The difference is less than 1 / 30).
  775. // We may encounter this situation when
  776. // we don't have exact match between segment duration info in the manifest and the actual duration of the segment
  777. // For example:
  778. // We appended 3 segments 10 seconds each, meaning we should have 30 sec buffered,
  779. // but we the actual buffered is 29.99999
  780. //
  781. // In both cases:
  782. // if we passed current time -> it means that we already played current segment
  783. // if we passed buffered.end -> it means that this segment is already loaded and buffered
  784. // we should select the next segment if we have one:
  785. if (i !== partsAndSegments.length - 1) {
  786. continue;
  787. }
  788. }
  789. if (exactManifestTimings) {
  790. if (time > 0) {
  791. continue;
  792. }
  793. } else if (time - TIME_FUDGE_FACTOR >= 0) {
  794. continue;
  795. }
  796. return {
  797. partIndex: partAndSegment.partIndex,
  798. segmentIndex: partAndSegment.segmentIndex,
  799. startTime: startTime + sumDurations({
  800. defaultDuration: playlist.targetDuration,
  801. durationList: partsAndSegments,
  802. startIndex,
  803. endIndex: i
  804. })
  805. };
  806. } // We are out of possible candidates so load the last one...
  807. return {
  808. segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
  809. partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
  810. startTime: currentTime
  811. };
  812. };
  813. /**
  814. * Check whether the playlist is excluded or not.
  815. *
  816. * @param {Object} playlist the media playlist object
  817. * @return {boolean} whether the playlist is excluded or not
  818. * @function isExcluded
  819. */
  820. const isExcluded = function (playlist) {
  821. return playlist.excludeUntil && playlist.excludeUntil > Date.now();
  822. };
  823. /**
  824. * Check whether the playlist is compatible with current playback configuration or has
  825. * been excluded permanently for being incompatible.
  826. *
  827. * @param {Object} playlist the media playlist object
  828. * @return {boolean} whether the playlist is incompatible or not
  829. * @function isIncompatible
  830. */
  831. const isIncompatible = function (playlist) {
  832. return playlist.excludeUntil && playlist.excludeUntil === Infinity;
  833. };
  834. /**
  835. * Check whether the playlist is enabled or not.
  836. *
  837. * @param {Object} playlist the media playlist object
  838. * @return {boolean} whether the playlist is enabled or not
  839. * @function isEnabled
  840. */
  841. const isEnabled = function (playlist) {
  842. const excluded = isExcluded(playlist);
  843. return !playlist.disabled && !excluded;
  844. };
  845. /**
  846. * Check whether the playlist has been manually disabled through the representations api.
  847. *
  848. * @param {Object} playlist the media playlist object
  849. * @return {boolean} whether the playlist is disabled manually or not
  850. * @function isDisabled
  851. */
  852. const isDisabled = function (playlist) {
  853. return playlist.disabled;
  854. };
  855. /**
  856. * Returns whether the current playlist is an AES encrypted HLS stream
  857. *
  858. * @return {boolean} true if it's an AES encrypted HLS stream
  859. */
  860. const isAes = function (media) {
  861. for (let i = 0; i < media.segments.length; i++) {
  862. if (media.segments[i].key) {
  863. return true;
  864. }
  865. }
  866. return false;
  867. };
  868. /**
  869. * Checks if the playlist has a value for the specified attribute
  870. *
  871. * @param {string} attr
  872. * Attribute to check for
  873. * @param {Object} playlist
  874. * The media playlist object
  875. * @return {boolean}
  876. * Whether the playlist contains a value for the attribute or not
  877. * @function hasAttribute
  878. */
  879. const hasAttribute = function (attr, playlist) {
  880. return playlist.attributes && playlist.attributes[attr];
  881. };
  882. /**
  883. * Estimates the time required to complete a segment download from the specified playlist
  884. *
  885. * @param {number} segmentDuration
  886. * Duration of requested segment
  887. * @param {number} bandwidth
  888. * Current measured bandwidth of the player
  889. * @param {Object} playlist
  890. * The media playlist object
  891. * @param {number=} bytesReceived
  892. * Number of bytes already received for the request. Defaults to 0
  893. * @return {number|NaN}
  894. * The estimated time to request the segment. NaN if bandwidth information for
  895. * the given playlist is unavailable
  896. * @function estimateSegmentRequestTime
  897. */
  898. const estimateSegmentRequestTime = function (segmentDuration, bandwidth, playlist, bytesReceived = 0) {
  899. if (!hasAttribute('BANDWIDTH', playlist)) {
  900. return NaN;
  901. }
  902. const size = segmentDuration * playlist.attributes.BANDWIDTH;
  903. return (size - bytesReceived * 8) / bandwidth;
  904. };
  905. /*
  906. * Returns whether the current playlist is the lowest rendition
  907. *
  908. * @return {Boolean} true if on lowest rendition
  909. */
  910. const isLowestEnabledRendition = (main, media) => {
  911. if (main.playlists.length === 1) {
  912. return true;
  913. }
  914. const currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
  915. return main.playlists.filter(playlist => {
  916. if (!isEnabled(playlist)) {
  917. return false;
  918. }
  919. return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
  920. }).length === 0;
  921. };
  922. const playlistMatch = (a, b) => {
  923. // both playlits are null
  924. // or only one playlist is non-null
  925. // no match
  926. if (!a && !b || !a && b || a && !b) {
  927. return false;
  928. } // playlist objects are the same, match
  929. if (a === b) {
  930. return true;
  931. } // first try to use id as it should be the most
  932. // accurate
  933. if (a.id && b.id && a.id === b.id) {
  934. return true;
  935. } // next try to use reslovedUri as it should be the
  936. // second most accurate.
  937. if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
  938. return true;
  939. } // finally try to use uri as it should be accurate
  940. // but might miss a few cases for relative uris
  941. if (a.uri && b.uri && a.uri === b.uri) {
  942. return true;
  943. }
  944. return false;
  945. };
  946. const someAudioVariant = function (main, callback) {
  947. const AUDIO = main && main.mediaGroups && main.mediaGroups.AUDIO || {};
  948. let found = false;
  949. for (const groupName in AUDIO) {
  950. for (const label in AUDIO[groupName]) {
  951. found = callback(AUDIO[groupName][label]);
  952. if (found) {
  953. break;
  954. }
  955. }
  956. if (found) {
  957. break;
  958. }
  959. }
  960. return !!found;
  961. };
  962. const isAudioOnly = main => {
  963. // we are audio only if we have no main playlists but do
  964. // have media group playlists.
  965. if (!main || !main.playlists || !main.playlists.length) {
  966. // without audio variants or playlists this
  967. // is not an audio only main.
  968. const found = someAudioVariant(main, variant => variant.playlists && variant.playlists.length || variant.uri);
  969. return found;
  970. } // if every playlist has only an audio codec it is audio only
  971. for (let i = 0; i < main.playlists.length; i++) {
  972. const playlist = main.playlists[i];
  973. const CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.
  974. if (CODECS && CODECS.split(',').every(c => isAudioCodec(c))) {
  975. continue;
  976. } // playlist is in an audio group it is audio only
  977. const found = someAudioVariant(main, variant => playlistMatch(playlist, variant));
  978. if (found) {
  979. continue;
  980. } // if we make it here this playlist isn't audio and we
  981. // are not audio only
  982. return false;
  983. } // if we make it past every playlist without returning, then
  984. // this is an audio only playlist.
  985. return true;
  986. }; // exports
  987. var Playlist = {
  988. liveEdgeDelay,
  989. duration,
  990. seekable,
  991. getMediaInfoForTime,
  992. isEnabled,
  993. isDisabled,
  994. isExcluded,
  995. isIncompatible,
  996. playlistEnd,
  997. isAes,
  998. hasAttribute,
  999. estimateSegmentRequestTime,
  1000. isLowestEnabledRendition,
  1001. isAudioOnly,
  1002. playlistMatch,
  1003. segmentDurationWithParts
  1004. };
  1005. const {
  1006. log
  1007. } = videojs;
  1008. const createPlaylistID = (index, uri) => {
  1009. return `${index}-${uri}`;
  1010. }; // default function for creating a group id
  1011. const groupID = (type, group, label) => {
  1012. return `placeholder-uri-${type}-${group}-${label}`;
  1013. };
  1014. /**
  1015. * Parses a given m3u8 playlist
  1016. *
  1017. * @param {Function} [onwarn]
  1018. * a function to call when the parser triggers a warning event.
  1019. * @param {Function} [oninfo]
  1020. * a function to call when the parser triggers an info event.
  1021. * @param {string} manifestString
  1022. * The downloaded manifest string
  1023. * @param {Object[]} [customTagParsers]
  1024. * An array of custom tag parsers for the m3u8-parser instance
  1025. * @param {Object[]} [customTagMappers]
  1026. * An array of custom tag mappers for the m3u8-parser instance
  1027. * @param {boolean} [llhls]
  1028. * Whether to keep ll-hls features in the manifest after parsing.
  1029. * @return {Object}
  1030. * The manifest object
  1031. */
  1032. const parseManifest = ({
  1033. onwarn,
  1034. oninfo,
  1035. manifestString,
  1036. customTagParsers = [],
  1037. customTagMappers = [],
  1038. llhls
  1039. }) => {
  1040. const parser = new Parser();
  1041. if (onwarn) {
  1042. parser.on('warn', onwarn);
  1043. }
  1044. if (oninfo) {
  1045. parser.on('info', oninfo);
  1046. }
  1047. customTagParsers.forEach(customParser => parser.addParser(customParser));
  1048. customTagMappers.forEach(mapper => parser.addTagMapper(mapper));
  1049. parser.push(manifestString);
  1050. parser.end();
  1051. const manifest = parser.manifest; // remove llhls features from the parsed manifest
  1052. // if we don't want llhls support.
  1053. if (!llhls) {
  1054. ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {
  1055. if (manifest.hasOwnProperty(k)) {
  1056. delete manifest[k];
  1057. }
  1058. });
  1059. if (manifest.segments) {
  1060. manifest.segments.forEach(function (segment) {
  1061. ['parts', 'preloadHints'].forEach(function (k) {
  1062. if (segment.hasOwnProperty(k)) {
  1063. delete segment[k];
  1064. }
  1065. });
  1066. });
  1067. }
  1068. }
  1069. if (!manifest.targetDuration) {
  1070. let targetDuration = 10;
  1071. if (manifest.segments && manifest.segments.length) {
  1072. targetDuration = manifest.segments.reduce((acc, s) => Math.max(acc, s.duration), 0);
  1073. }
  1074. if (onwarn) {
  1075. onwarn({
  1076. message: `manifest has no targetDuration defaulting to ${targetDuration}`
  1077. });
  1078. }
  1079. manifest.targetDuration = targetDuration;
  1080. }
  1081. const parts = getLastParts(manifest);
  1082. if (parts.length && !manifest.partTargetDuration) {
  1083. const partTargetDuration = parts.reduce((acc, p) => Math.max(acc, p.duration), 0);
  1084. if (onwarn) {
  1085. onwarn({
  1086. message: `manifest has no partTargetDuration defaulting to ${partTargetDuration}`
  1087. });
  1088. 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.');
  1089. }
  1090. manifest.partTargetDuration = partTargetDuration;
  1091. }
  1092. return manifest;
  1093. };
  1094. /**
  1095. * Loops through all supported media groups in main and calls the provided
  1096. * callback for each group
  1097. *
  1098. * @param {Object} main
  1099. * The parsed main manifest object
  1100. * @param {Function} callback
  1101. * Callback to call for each media group
  1102. */
  1103. const forEachMediaGroup = (main, callback) => {
  1104. if (!main.mediaGroups) {
  1105. return;
  1106. }
  1107. ['AUDIO', 'SUBTITLES'].forEach(mediaType => {
  1108. if (!main.mediaGroups[mediaType]) {
  1109. return;
  1110. }
  1111. for (const groupKey in main.mediaGroups[mediaType]) {
  1112. for (const labelKey in main.mediaGroups[mediaType][groupKey]) {
  1113. const mediaProperties = main.mediaGroups[mediaType][groupKey][labelKey];
  1114. callback(mediaProperties, mediaType, groupKey, labelKey);
  1115. }
  1116. }
  1117. });
  1118. };
  1119. /**
  1120. * Adds properties and attributes to the playlist to keep consistent functionality for
  1121. * playlists throughout VHS.
  1122. *
  1123. * @param {Object} config
  1124. * Arguments object
  1125. * @param {Object} config.playlist
  1126. * The media playlist
  1127. * @param {string} [config.uri]
  1128. * The uri to the media playlist (if media playlist is not from within a main
  1129. * playlist)
  1130. * @param {string} id
  1131. * ID to use for the playlist
  1132. */
  1133. const setupMediaPlaylist = ({
  1134. playlist,
  1135. uri,
  1136. id
  1137. }) => {
  1138. playlist.id = id;
  1139. playlist.playlistErrors_ = 0;
  1140. if (uri) {
  1141. // For media playlists, m3u8-parser does not have access to a URI, as HLS media
  1142. // playlists do not contain their own source URI, but one is needed for consistency in
  1143. // VHS.
  1144. playlist.uri = uri;
  1145. } // For HLS main playlists, even though certain attributes MUST be defined, the
  1146. // stream may still be played without them.
  1147. // For HLS media playlists, m3u8-parser does not attach an attributes object to the
  1148. // manifest.
  1149. //
  1150. // To avoid undefined reference errors through the project, and make the code easier
  1151. // to write/read, add an empty attributes object for these cases.
  1152. playlist.attributes = playlist.attributes || {};
  1153. };
  1154. /**
  1155. * Adds ID, resolvedUri, and attributes properties to each playlist of the main, where
  1156. * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
  1157. * playlist references to the playlists array.
  1158. *
  1159. * @param {Object} main
  1160. * The main playlist
  1161. */
  1162. const setupMediaPlaylists = main => {
  1163. let i = main.playlists.length;
  1164. while (i--) {
  1165. const playlist = main.playlists[i];
  1166. setupMediaPlaylist({
  1167. playlist,
  1168. id: createPlaylistID(i, playlist.uri)
  1169. });
  1170. playlist.resolvedUri = resolveUrl(main.uri, playlist.uri);
  1171. main.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility
  1172. main.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
  1173. // the stream can be played without it. Although an attributes property may have been
  1174. // added to the playlist to prevent undefined references, issue a warning to fix the
  1175. // manifest.
  1176. if (!playlist.attributes.BANDWIDTH) {
  1177. log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
  1178. }
  1179. }
  1180. };
  1181. /**
  1182. * Adds resolvedUri properties to each media group.
  1183. *
  1184. * @param {Object} main
  1185. * The main playlist
  1186. */
  1187. const resolveMediaGroupUris = main => {
  1188. forEachMediaGroup(main, properties => {
  1189. if (properties.uri) {
  1190. properties.resolvedUri = resolveUrl(main.uri, properties.uri);
  1191. }
  1192. });
  1193. };
  1194. /**
  1195. * Creates a main playlist wrapper to insert a sole media playlist into.
  1196. *
  1197. * @param {Object} media
  1198. * Media playlist
  1199. * @param {string} uri
  1200. * The media URI
  1201. *
  1202. * @return {Object}
  1203. * main playlist
  1204. */
  1205. const mainForMedia = (media, uri) => {
  1206. const id = createPlaylistID(0, uri);
  1207. const main = {
  1208. mediaGroups: {
  1209. 'AUDIO': {},
  1210. 'VIDEO': {},
  1211. 'CLOSED-CAPTIONS': {},
  1212. 'SUBTITLES': {}
  1213. },
  1214. uri: window$1.location.href,
  1215. resolvedUri: window$1.location.href,
  1216. playlists: [{
  1217. uri,
  1218. id,
  1219. resolvedUri: uri,
  1220. // m3u8-parser does not attach an attributes property to media playlists so make
  1221. // sure that the property is attached to avoid undefined reference errors
  1222. attributes: {}
  1223. }]
  1224. }; // set up ID reference
  1225. main.playlists[id] = main.playlists[0]; // URI reference added for backwards compatibility
  1226. main.playlists[uri] = main.playlists[0];
  1227. return main;
  1228. };
  1229. /**
  1230. * Does an in-place update of the main manifest to add updated playlist URI references
  1231. * as well as other properties needed by VHS that aren't included by the parser.
  1232. *
  1233. * @param {Object} main
  1234. * main manifest object
  1235. * @param {string} uri
  1236. * The source URI
  1237. * @param {function} createGroupID
  1238. * A function to determine how to create the groupID for mediaGroups
  1239. */
  1240. const addPropertiesToMain = (main, uri, createGroupID = groupID) => {
  1241. main.uri = uri;
  1242. for (let i = 0; i < main.playlists.length; i++) {
  1243. if (!main.playlists[i].uri) {
  1244. // Set up phony URIs for the playlists since playlists are referenced by their URIs
  1245. // throughout VHS, but some formats (e.g., DASH) don't have external URIs
  1246. // TODO: consider adding dummy URIs in mpd-parser
  1247. const phonyUri = `placeholder-uri-${i}`;
  1248. main.playlists[i].uri = phonyUri;
  1249. }
  1250. }
  1251. const audioOnlyMain = isAudioOnly(main);
  1252. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  1253. // add a playlist array under properties
  1254. if (!properties.playlists || !properties.playlists.length) {
  1255. // If the manifest is audio only and this media group does not have a uri, check
  1256. // if the media group is located in the main list of playlists. If it is, don't add
  1257. // placeholder properties as it shouldn't be considered an alternate audio track.
  1258. if (audioOnlyMain && mediaType === 'AUDIO' && !properties.uri) {
  1259. for (let i = 0; i < main.playlists.length; i++) {
  1260. const p = main.playlists[i];
  1261. if (p.attributes && p.attributes.AUDIO && p.attributes.AUDIO === groupKey) {
  1262. return;
  1263. }
  1264. }
  1265. }
  1266. properties.playlists = [_extends({}, properties)];
  1267. }
  1268. properties.playlists.forEach(function (p, i) {
  1269. const groupId = createGroupID(mediaType, groupKey, labelKey, p);
  1270. const id = createPlaylistID(i, groupId);
  1271. if (p.uri) {
  1272. p.resolvedUri = p.resolvedUri || resolveUrl(main.uri, p.uri);
  1273. } else {
  1274. // DEPRECATED, this has been added to prevent a breaking change.
  1275. // previously we only ever had a single media group playlist, so
  1276. // we mark the first playlist uri without prepending the index as we used to
  1277. // ideally we would do all of the playlists the same way.
  1278. p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use
  1279. // the placeholder again
  1280. p.resolvedUri = p.uri;
  1281. }
  1282. p.id = p.id || id; // add an empty attributes object, all playlists are
  1283. // expected to have this.
  1284. p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)
  1285. main.playlists[p.id] = p;
  1286. main.playlists[p.uri] = p;
  1287. });
  1288. });
  1289. setupMediaPlaylists(main);
  1290. resolveMediaGroupUris(main);
  1291. };
  1292. class DateRangesStorage {
  1293. constructor() {
  1294. this.offset_ = null;
  1295. this.pendingDateRanges_ = new Map();
  1296. this.processedDateRanges_ = new Map();
  1297. }
  1298. setOffset(segments = []) {
  1299. // already set
  1300. if (this.offset_ !== null) {
  1301. return;
  1302. } // no segment to process
  1303. if (!segments.length) {
  1304. return;
  1305. }
  1306. const [firstSegment] = segments; // no program date time
  1307. if (firstSegment.programDateTime === undefined) {
  1308. return;
  1309. } // Set offset as ProgramDateTime for the very first segment of the very first playlist load:
  1310. this.offset_ = firstSegment.programDateTime / 1000;
  1311. }
  1312. setPendingDateRanges(dateRanges = []) {
  1313. if (!dateRanges.length) {
  1314. return;
  1315. }
  1316. const [dateRange] = dateRanges;
  1317. const startTime = dateRange.startDate.getTime();
  1318. this.trimProcessedDateRanges_(startTime);
  1319. this.pendingDateRanges_ = dateRanges.reduce((map, pendingDateRange) => {
  1320. map.set(pendingDateRange.id, pendingDateRange);
  1321. return map;
  1322. }, new Map());
  1323. }
  1324. processDateRange(dateRange) {
  1325. this.pendingDateRanges_.delete(dateRange.id);
  1326. this.processedDateRanges_.set(dateRange.id, dateRange);
  1327. }
  1328. getDateRangesToProcess() {
  1329. if (this.offset_ === null) {
  1330. return [];
  1331. }
  1332. const dateRangeClasses = {};
  1333. const dateRangesToProcess = [];
  1334. this.pendingDateRanges_.forEach((dateRange, id) => {
  1335. if (this.processedDateRanges_.has(id)) {
  1336. return;
  1337. }
  1338. dateRange.startTime = dateRange.startDate.getTime() / 1000 - this.offset_;
  1339. dateRange.processDateRange = () => this.processDateRange(dateRange);
  1340. dateRangesToProcess.push(dateRange);
  1341. if (!dateRange.class) {
  1342. return;
  1343. }
  1344. if (dateRangeClasses[dateRange.class]) {
  1345. const length = dateRangeClasses[dateRange.class].push(dateRange);
  1346. dateRange.classListIndex = length - 1;
  1347. } else {
  1348. dateRangeClasses[dateRange.class] = [dateRange];
  1349. dateRange.classListIndex = 0;
  1350. }
  1351. });
  1352. for (const dateRange of dateRangesToProcess) {
  1353. const classList = dateRangeClasses[dateRange.class] || [];
  1354. if (dateRange.endDate) {
  1355. dateRange.endTime = dateRange.endDate.getTime() / 1000 - this.offset_;
  1356. } else if (dateRange.endOnNext && classList[dateRange.classListIndex + 1]) {
  1357. dateRange.endTime = classList[dateRange.classListIndex + 1].startTime;
  1358. } else if (dateRange.duration) {
  1359. dateRange.endTime = dateRange.startTime + dateRange.duration;
  1360. } else if (dateRange.plannedDuration) {
  1361. dateRange.endTime = dateRange.startTime + dateRange.plannedDuration;
  1362. } else {
  1363. dateRange.endTime = dateRange.startTime;
  1364. }
  1365. }
  1366. return dateRangesToProcess;
  1367. }
  1368. trimProcessedDateRanges_(startTime) {
  1369. const copy = new Map(this.processedDateRanges_);
  1370. copy.forEach((dateRange, id) => {
  1371. if (dateRange.startDate.getTime() < startTime) {
  1372. this.processedDateRanges_.delete(id);
  1373. }
  1374. });
  1375. }
  1376. }
  1377. const {
  1378. EventTarget: EventTarget$1
  1379. } = videojs;
  1380. const addLLHLSQueryDirectives = (uri, media) => {
  1381. if (media.endList || !media.serverControl) {
  1382. return uri;
  1383. }
  1384. const parameters = {};
  1385. if (media.serverControl.canBlockReload) {
  1386. const {
  1387. preloadSegment
  1388. } = media; // next msn is a zero based value, length is not.
  1389. let nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely
  1390. // that we are going to request a part of that preload segment.
  1391. // the logic below is used to determine that.
  1392. if (preloadSegment) {
  1393. const parts = preloadSegment.parts || []; // _HLS_part is a zero based index
  1394. const nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the
  1395. // length of parts, then we know we had part preload hints
  1396. // and we need to add the _HLS_part= query
  1397. if (nextPart > -1 && nextPart !== parts.length - 1) {
  1398. // add existing parts to our preload hints
  1399. // eslint-disable-next-line
  1400. parameters._HLS_part = nextPart;
  1401. } // this if statement makes sure that we request the msn
  1402. // of the preload segment if:
  1403. // 1. the preload segment had parts (and was not yet a full segment)
  1404. // but was added to our segments array
  1405. // 2. the preload segment had preload hints for parts that are not in
  1406. // the manifest yet.
  1407. // in all other cases we want the segment after the preload segment
  1408. // which will be given by using media.segments.length because it is 1 based
  1409. // rather than 0 based.
  1410. if (nextPart > -1 || parts.length) {
  1411. nextMSN--;
  1412. }
  1413. } // add _HLS_msn= in front of any _HLS_part query
  1414. // eslint-disable-next-line
  1415. parameters._HLS_msn = nextMSN;
  1416. }
  1417. if (media.serverControl && media.serverControl.canSkipUntil) {
  1418. // add _HLS_skip= infront of all other queries.
  1419. // eslint-disable-next-line
  1420. parameters._HLS_skip = media.serverControl.canSkipDateranges ? 'v2' : 'YES';
  1421. }
  1422. if (Object.keys(parameters).length) {
  1423. const parsedUri = new window$1.URL(uri);
  1424. ['_HLS_skip', '_HLS_msn', '_HLS_part'].forEach(function (name) {
  1425. if (!parameters.hasOwnProperty(name)) {
  1426. return;
  1427. }
  1428. parsedUri.searchParams.set(name, parameters[name]);
  1429. });
  1430. uri = parsedUri.toString();
  1431. }
  1432. return uri;
  1433. };
  1434. /**
  1435. * Returns a new segment object with properties and
  1436. * the parts array merged.
  1437. *
  1438. * @param {Object} a the old segment
  1439. * @param {Object} b the new segment
  1440. *
  1441. * @return {Object} the merged segment
  1442. */
  1443. const updateSegment = (a, b) => {
  1444. if (!a) {
  1445. return b;
  1446. }
  1447. const result = merge(a, b); // if only the old segment has preload hints
  1448. // and the new one does not, remove preload hints.
  1449. if (a.preloadHints && !b.preloadHints) {
  1450. delete result.preloadHints;
  1451. } // if only the old segment has parts
  1452. // then the parts are no longer valid
  1453. if (a.parts && !b.parts) {
  1454. delete result.parts; // if both segments have parts
  1455. // copy part propeties from the old segment
  1456. // to the new one.
  1457. } else if (a.parts && b.parts) {
  1458. for (let i = 0; i < b.parts.length; i++) {
  1459. if (a.parts && a.parts[i]) {
  1460. result.parts[i] = merge(a.parts[i], b.parts[i]);
  1461. }
  1462. }
  1463. } // set skipped to false for segments that have
  1464. // have had information merged from the old segment.
  1465. if (!a.skipped && b.skipped) {
  1466. result.skipped = false;
  1467. } // set preload to false for segments that have
  1468. // had information added in the new segment.
  1469. if (a.preload && !b.preload) {
  1470. result.preload = false;
  1471. }
  1472. return result;
  1473. };
  1474. /**
  1475. * Returns a new array of segments that is the result of merging
  1476. * properties from an older list of segments onto an updated
  1477. * list. No properties on the updated playlist will be ovewritten.
  1478. *
  1479. * @param {Array} original the outdated list of segments
  1480. * @param {Array} update the updated list of segments
  1481. * @param {number=} offset the index of the first update
  1482. * segment in the original segment list. For non-live playlists,
  1483. * this should always be zero and does not need to be
  1484. * specified. For live playlists, it should be the difference
  1485. * between the media sequence numbers in the original and updated
  1486. * playlists.
  1487. * @return {Array} a list of merged segment objects
  1488. */
  1489. const updateSegments = (original, update, offset) => {
  1490. const oldSegments = original.slice();
  1491. const newSegments = update.slice();
  1492. offset = offset || 0;
  1493. const result = [];
  1494. let currentMap;
  1495. for (let newIndex = 0; newIndex < newSegments.length; newIndex++) {
  1496. const oldSegment = oldSegments[newIndex + offset];
  1497. const newSegment = newSegments[newIndex];
  1498. if (oldSegment) {
  1499. currentMap = oldSegment.map || currentMap;
  1500. result.push(updateSegment(oldSegment, newSegment));
  1501. } else {
  1502. // carry over map to new segment if it is missing
  1503. if (currentMap && !newSegment.map) {
  1504. newSegment.map = currentMap;
  1505. }
  1506. result.push(newSegment);
  1507. }
  1508. }
  1509. return result;
  1510. };
  1511. const resolveSegmentUris = (segment, baseUri) => {
  1512. // preloadSegment will not have a uri at all
  1513. // as the segment isn't actually in the manifest yet, only parts
  1514. if (!segment.resolvedUri && segment.uri) {
  1515. segment.resolvedUri = resolveUrl(baseUri, segment.uri);
  1516. }
  1517. if (segment.key && !segment.key.resolvedUri) {
  1518. segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
  1519. }
  1520. if (segment.map && !segment.map.resolvedUri) {
  1521. segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
  1522. }
  1523. if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
  1524. segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
  1525. }
  1526. if (segment.parts && segment.parts.length) {
  1527. segment.parts.forEach(p => {
  1528. if (p.resolvedUri) {
  1529. return;
  1530. }
  1531. p.resolvedUri = resolveUrl(baseUri, p.uri);
  1532. });
  1533. }
  1534. if (segment.preloadHints && segment.preloadHints.length) {
  1535. segment.preloadHints.forEach(p => {
  1536. if (p.resolvedUri) {
  1537. return;
  1538. }
  1539. p.resolvedUri = resolveUrl(baseUri, p.uri);
  1540. });
  1541. }
  1542. };
  1543. const getAllSegments = function (media) {
  1544. const segments = media.segments || [];
  1545. const preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently
  1546. // a usable segment, only include a preloadSegment that has
  1547. // parts.
  1548. if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
  1549. // if preloadHints has a MAP that means that the
  1550. // init segment is going to change. We cannot use any of the parts
  1551. // from this preload segment.
  1552. if (preloadSegment.preloadHints) {
  1553. for (let i = 0; i < preloadSegment.preloadHints.length; i++) {
  1554. if (preloadSegment.preloadHints[i].type === 'MAP') {
  1555. return segments;
  1556. }
  1557. }
  1558. } // set the duration for our preload segment to target duration.
  1559. preloadSegment.duration = media.targetDuration;
  1560. preloadSegment.preload = true;
  1561. segments.push(preloadSegment);
  1562. }
  1563. return segments;
  1564. }; // consider the playlist unchanged if the playlist object is the same or
  1565. // the number of segments is equal, the media sequence number is unchanged,
  1566. // and this playlist hasn't become the end of the playlist
  1567. 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;
  1568. /**
  1569. * Returns a new main playlist that is the result of merging an
  1570. * updated media playlist into the original version. If the
  1571. * updated media playlist does not match any of the playlist
  1572. * entries in the original main playlist, null is returned.
  1573. *
  1574. * @param {Object} main a parsed main M3U8 object
  1575. * @param {Object} media a parsed media M3U8 object
  1576. * @return {Object} a new object that represents the original
  1577. * main playlist with the updated media playlist merged in, or
  1578. * null if the merge produced no change.
  1579. */
  1580. const updateMain$1 = (main, newMedia, unchangedCheck = isPlaylistUnchanged) => {
  1581. const result = merge(main, {});
  1582. const oldMedia = result.playlists[newMedia.id];
  1583. if (!oldMedia) {
  1584. return null;
  1585. }
  1586. if (unchangedCheck(oldMedia, newMedia)) {
  1587. return null;
  1588. }
  1589. newMedia.segments = getAllSegments(newMedia);
  1590. const mergedPlaylist = merge(oldMedia, newMedia); // always use the new media's preload segment
  1591. if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
  1592. delete mergedPlaylist.preloadSegment;
  1593. } // if the update could overlap existing segment information, merge the two segment lists
  1594. if (oldMedia.segments) {
  1595. if (newMedia.skip) {
  1596. newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge
  1597. // old properties into the new segments
  1598. for (let i = 0; i < newMedia.skip.skippedSegments; i++) {
  1599. newMedia.segments.unshift({
  1600. skipped: true
  1601. });
  1602. }
  1603. }
  1604. mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
  1605. } // resolve any segment URIs to prevent us from having to do it later
  1606. mergedPlaylist.segments.forEach(segment => {
  1607. resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
  1608. }); // TODO Right now in the playlists array there are two references to each playlist, one
  1609. // that is referenced by index, and one by URI. The index reference may no longer be
  1610. // necessary.
  1611. for (let i = 0; i < result.playlists.length; i++) {
  1612. if (result.playlists[i].id === newMedia.id) {
  1613. result.playlists[i] = mergedPlaylist;
  1614. }
  1615. }
  1616. result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility
  1617. result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.
  1618. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  1619. if (!properties.playlists) {
  1620. return;
  1621. }
  1622. for (let i = 0; i < properties.playlists.length; i++) {
  1623. if (newMedia.id === properties.playlists[i].id) {
  1624. properties.playlists[i] = mergedPlaylist;
  1625. }
  1626. }
  1627. });
  1628. return result;
  1629. };
  1630. /**
  1631. * Calculates the time to wait before refreshing a live playlist
  1632. *
  1633. * @param {Object} media
  1634. * The current media
  1635. * @param {boolean} update
  1636. * True if there were any updates from the last refresh, false otherwise
  1637. * @return {number}
  1638. * The time in ms to wait before refreshing the live playlist
  1639. */
  1640. const refreshDelay = (media, update) => {
  1641. const segments = media.segments || [];
  1642. const lastSegment = segments[segments.length - 1];
  1643. const lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
  1644. const lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
  1645. if (update && lastDuration) {
  1646. return lastDuration * 1000;
  1647. } // if the playlist is unchanged since the last reload or last segment duration
  1648. // cannot be determined, try again after half the target duration
  1649. return (media.partTargetDuration || media.targetDuration || 10) * 500;
  1650. };
  1651. /**
  1652. * Load a playlist from a remote location
  1653. *
  1654. * @class PlaylistLoader
  1655. * @extends Stream
  1656. * @param {string|Object} src url or object of manifest
  1657. * @param {boolean} withCredentials the withCredentials xhr option
  1658. * @class
  1659. */
  1660. class PlaylistLoader extends EventTarget$1 {
  1661. constructor(src, vhs, options = {}) {
  1662. super();
  1663. if (!src) {
  1664. throw new Error('A non-empty playlist URL or object is required');
  1665. }
  1666. this.logger_ = logger('PlaylistLoader');
  1667. const {
  1668. withCredentials = false
  1669. } = options;
  1670. this.src = src;
  1671. this.vhs_ = vhs;
  1672. this.withCredentials = withCredentials;
  1673. this.addDateRangesToTextTrack_ = options.addDateRangesToTextTrack;
  1674. const vhsOptions = vhs.options_;
  1675. this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
  1676. this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
  1677. this.llhls = vhsOptions && vhsOptions.llhls;
  1678. this.dateRangesStorage_ = new DateRangesStorage(); // initialize the loader state
  1679. this.state = 'HAVE_NOTHING'; // live playlist staleness timeout
  1680. this.handleMediaupdatetimeout_ = this.handleMediaupdatetimeout_.bind(this);
  1681. this.on('mediaupdatetimeout', this.handleMediaupdatetimeout_);
  1682. this.on('loadedplaylist', this.handleLoadedPlaylist_.bind(this));
  1683. }
  1684. handleLoadedPlaylist_() {
  1685. const mediaPlaylist = this.media();
  1686. if (!mediaPlaylist) {
  1687. return;
  1688. }
  1689. this.dateRangesStorage_.setOffset(mediaPlaylist.segments);
  1690. this.dateRangesStorage_.setPendingDateRanges(mediaPlaylist.dateRanges);
  1691. const availableDateRanges = this.dateRangesStorage_.getDateRangesToProcess();
  1692. if (!availableDateRanges.length || !this.addDateRangesToTextTrack_) {
  1693. return;
  1694. }
  1695. this.addDateRangesToTextTrack_(availableDateRanges);
  1696. }
  1697. handleMediaupdatetimeout_() {
  1698. if (this.state !== 'HAVE_METADATA') {
  1699. // only refresh the media playlist if no other activity is going on
  1700. return;
  1701. }
  1702. const media = this.media();
  1703. let uri = resolveUrl(this.main.uri, media.uri);
  1704. if (this.llhls) {
  1705. uri = addLLHLSQueryDirectives(uri, media);
  1706. }
  1707. this.state = 'HAVE_CURRENT_METADATA';
  1708. this.request = this.vhs_.xhr({
  1709. uri,
  1710. withCredentials: this.withCredentials
  1711. }, (error, req) => {
  1712. // disposed
  1713. if (!this.request) {
  1714. return;
  1715. }
  1716. if (error) {
  1717. return this.playlistRequestError(this.request, this.media(), 'HAVE_METADATA');
  1718. }
  1719. this.haveMetadata({
  1720. playlistString: this.request.responseText,
  1721. url: this.media().uri,
  1722. id: this.media().id
  1723. });
  1724. });
  1725. }
  1726. playlistRequestError(xhr, playlist, startingState) {
  1727. const {
  1728. uri,
  1729. id
  1730. } = playlist; // any in-flight request is now finished
  1731. this.request = null;
  1732. if (startingState) {
  1733. this.state = startingState;
  1734. }
  1735. this.error = {
  1736. playlist: this.main.playlists[id],
  1737. status: xhr.status,
  1738. message: `HLS playlist request error at URL: ${uri}.`,
  1739. responseText: xhr.responseText,
  1740. code: xhr.status >= 500 ? 4 : 2
  1741. };
  1742. this.trigger('error');
  1743. }
  1744. parseManifest_({
  1745. url,
  1746. manifestString
  1747. }) {
  1748. return parseManifest({
  1749. onwarn: ({
  1750. message
  1751. }) => this.logger_(`m3u8-parser warn for ${url}: ${message}`),
  1752. oninfo: ({
  1753. message
  1754. }) => this.logger_(`m3u8-parser info for ${url}: ${message}`),
  1755. manifestString,
  1756. customTagParsers: this.customTagParsers,
  1757. customTagMappers: this.customTagMappers,
  1758. llhls: this.llhls
  1759. });
  1760. }
  1761. /**
  1762. * Update the playlist loader's state in response to a new or updated playlist.
  1763. *
  1764. * @param {string} [playlistString]
  1765. * Playlist string (if playlistObject is not provided)
  1766. * @param {Object} [playlistObject]
  1767. * Playlist object (if playlistString is not provided)
  1768. * @param {string} url
  1769. * URL of playlist
  1770. * @param {string} id
  1771. * ID to use for playlist
  1772. */
  1773. haveMetadata({
  1774. playlistString,
  1775. playlistObject,
  1776. url,
  1777. id
  1778. }) {
  1779. // any in-flight request is now finished
  1780. this.request = null;
  1781. this.state = 'HAVE_METADATA';
  1782. const playlist = playlistObject || this.parseManifest_({
  1783. url,
  1784. manifestString: playlistString
  1785. });
  1786. playlist.lastRequest = Date.now();
  1787. setupMediaPlaylist({
  1788. playlist,
  1789. uri: url,
  1790. id
  1791. }); // merge this playlist into the main manifest
  1792. const update = updateMain$1(this.main, playlist);
  1793. this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
  1794. this.pendingMedia_ = null;
  1795. if (update) {
  1796. this.main = update;
  1797. this.media_ = this.main.playlists[id];
  1798. } else {
  1799. this.trigger('playlistunchanged');
  1800. }
  1801. this.updateMediaUpdateTimeout_(refreshDelay(this.media(), !!update));
  1802. this.trigger('loadedplaylist');
  1803. }
  1804. /**
  1805. * Abort any outstanding work and clean up.
  1806. */
  1807. dispose() {
  1808. this.trigger('dispose');
  1809. this.stopRequest();
  1810. window$1.clearTimeout(this.mediaUpdateTimeout);
  1811. window$1.clearTimeout(this.finalRenditionTimeout);
  1812. this.dateRangesStorage_ = new DateRangesStorage();
  1813. this.off();
  1814. }
  1815. stopRequest() {
  1816. if (this.request) {
  1817. const oldRequest = this.request;
  1818. this.request = null;
  1819. oldRequest.onreadystatechange = null;
  1820. oldRequest.abort();
  1821. }
  1822. }
  1823. /**
  1824. * When called without any arguments, returns the currently
  1825. * active media playlist. When called with a single argument,
  1826. * triggers the playlist loader to asynchronously switch to the
  1827. * specified media playlist. Calling this method while the
  1828. * loader is in the HAVE_NOTHING causes an error to be emitted
  1829. * but otherwise has no effect.
  1830. *
  1831. * @param {Object=} playlist the parsed media playlist
  1832. * object to switch to
  1833. * @param {boolean=} shouldDelay whether we should delay the request by half target duration
  1834. *
  1835. * @return {Playlist} the current loaded media
  1836. */
  1837. media(playlist, shouldDelay) {
  1838. // getter
  1839. if (!playlist) {
  1840. return this.media_;
  1841. } // setter
  1842. if (this.state === 'HAVE_NOTHING') {
  1843. throw new Error('Cannot switch media playlist from ' + this.state);
  1844. } // find the playlist object if the target playlist has been
  1845. // specified by URI
  1846. if (typeof playlist === 'string') {
  1847. if (!this.main.playlists[playlist]) {
  1848. throw new Error('Unknown playlist URI: ' + playlist);
  1849. }
  1850. playlist = this.main.playlists[playlist];
  1851. }
  1852. window$1.clearTimeout(this.finalRenditionTimeout);
  1853. if (shouldDelay) {
  1854. const delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;
  1855. this.finalRenditionTimeout = window$1.setTimeout(this.media.bind(this, playlist, false), delay);
  1856. return;
  1857. }
  1858. const startingState = this.state;
  1859. const mediaChange = !this.media_ || playlist.id !== this.media_.id;
  1860. const mainPlaylistRef = this.main.playlists[playlist.id]; // switch to fully loaded playlists immediately
  1861. if (mainPlaylistRef && mainPlaylistRef.endList || // handle the case of a playlist object (e.g., if using vhs-json with a resolved
  1862. // media playlist or, for the case of demuxed audio, a resolved audio media group)
  1863. playlist.endList && playlist.segments.length) {
  1864. // abort outstanding playlist requests
  1865. if (this.request) {
  1866. this.request.onreadystatechange = null;
  1867. this.request.abort();
  1868. this.request = null;
  1869. }
  1870. this.state = 'HAVE_METADATA';
  1871. this.media_ = playlist; // trigger media change if the active media has been updated
  1872. if (mediaChange) {
  1873. this.trigger('mediachanging');
  1874. if (startingState === 'HAVE_MAIN_MANIFEST') {
  1875. // The initial playlist was a main manifest, and the first media selected was
  1876. // also provided (in the form of a resolved playlist object) as part of the
  1877. // source object (rather than just a URL). Therefore, since the media playlist
  1878. // doesn't need to be requested, loadedmetadata won't trigger as part of the
  1879. // normal flow, and needs an explicit trigger here.
  1880. this.trigger('loadedmetadata');
  1881. } else {
  1882. this.trigger('mediachange');
  1883. }
  1884. }
  1885. return;
  1886. } // We update/set the timeout here so that live playlists
  1887. // that are not a media change will "start" the loader as expected.
  1888. // We expect that this function will start the media update timeout
  1889. // cycle again. This also prevents a playlist switch failure from
  1890. // causing us to stall during live.
  1891. this.updateMediaUpdateTimeout_(refreshDelay(playlist, true)); // switching to the active playlist is a no-op
  1892. if (!mediaChange) {
  1893. return;
  1894. }
  1895. this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request
  1896. if (this.request) {
  1897. if (playlist.resolvedUri === this.request.url) {
  1898. // requesting to switch to the same playlist multiple times
  1899. // has no effect after the first
  1900. return;
  1901. }
  1902. this.request.onreadystatechange = null;
  1903. this.request.abort();
  1904. this.request = null;
  1905. } // request the new playlist
  1906. if (this.media_) {
  1907. this.trigger('mediachanging');
  1908. }
  1909. this.pendingMedia_ = playlist;
  1910. this.request = this.vhs_.xhr({
  1911. uri: playlist.resolvedUri,
  1912. withCredentials: this.withCredentials
  1913. }, (error, req) => {
  1914. // disposed
  1915. if (!this.request) {
  1916. return;
  1917. }
  1918. playlist.lastRequest = Date.now();
  1919. playlist.resolvedUri = resolveManifestRedirect(playlist.resolvedUri, req);
  1920. if (error) {
  1921. return this.playlistRequestError(this.request, playlist, startingState);
  1922. }
  1923. this.haveMetadata({
  1924. playlistString: req.responseText,
  1925. url: playlist.uri,
  1926. id: playlist.id
  1927. }); // fire loadedmetadata the first time a media playlist is loaded
  1928. if (startingState === 'HAVE_MAIN_MANIFEST') {
  1929. this.trigger('loadedmetadata');
  1930. } else {
  1931. this.trigger('mediachange');
  1932. }
  1933. });
  1934. }
  1935. /**
  1936. * pause loading of the playlist
  1937. */
  1938. pause() {
  1939. if (this.mediaUpdateTimeout) {
  1940. window$1.clearTimeout(this.mediaUpdateTimeout);
  1941. this.mediaUpdateTimeout = null;
  1942. }
  1943. this.stopRequest();
  1944. if (this.state === 'HAVE_NOTHING') {
  1945. // If we pause the loader before any data has been retrieved, its as if we never
  1946. // started, so reset to an unstarted state.
  1947. this.started = false;
  1948. } // Need to restore state now that no activity is happening
  1949. if (this.state === 'SWITCHING_MEDIA') {
  1950. // if the loader was in the process of switching media, it should either return to
  1951. // HAVE_MAIN_MANIFEST or HAVE_METADATA depending on if the loader has loaded a media
  1952. // playlist yet. This is determined by the existence of loader.media_
  1953. if (this.media_) {
  1954. this.state = 'HAVE_METADATA';
  1955. } else {
  1956. this.state = 'HAVE_MAIN_MANIFEST';
  1957. }
  1958. } else if (this.state === 'HAVE_CURRENT_METADATA') {
  1959. this.state = 'HAVE_METADATA';
  1960. }
  1961. }
  1962. /**
  1963. * start loading of the playlist
  1964. */
  1965. load(shouldDelay) {
  1966. if (this.mediaUpdateTimeout) {
  1967. window$1.clearTimeout(this.mediaUpdateTimeout);
  1968. this.mediaUpdateTimeout = null;
  1969. }
  1970. const media = this.media();
  1971. if (shouldDelay) {
  1972. const delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;
  1973. this.mediaUpdateTimeout = window$1.setTimeout(() => {
  1974. this.mediaUpdateTimeout = null;
  1975. this.load();
  1976. }, delay);
  1977. return;
  1978. }
  1979. if (!this.started) {
  1980. this.start();
  1981. return;
  1982. }
  1983. if (media && !media.endList) {
  1984. this.trigger('mediaupdatetimeout');
  1985. } else {
  1986. this.trigger('loadedplaylist');
  1987. }
  1988. }
  1989. updateMediaUpdateTimeout_(delay) {
  1990. if (this.mediaUpdateTimeout) {
  1991. window$1.clearTimeout(this.mediaUpdateTimeout);
  1992. this.mediaUpdateTimeout = null;
  1993. } // we only have use mediaupdatetimeout for live playlists.
  1994. if (!this.media() || this.media().endList) {
  1995. return;
  1996. }
  1997. this.mediaUpdateTimeout = window$1.setTimeout(() => {
  1998. this.mediaUpdateTimeout = null;
  1999. this.trigger('mediaupdatetimeout');
  2000. this.updateMediaUpdateTimeout_(delay);
  2001. }, delay);
  2002. }
  2003. /**
  2004. * start loading of the playlist
  2005. */
  2006. start() {
  2007. this.started = true;
  2008. if (typeof this.src === 'object') {
  2009. // in the case of an entirely constructed manifest object (meaning there's no actual
  2010. // manifest on a server), default the uri to the page's href
  2011. if (!this.src.uri) {
  2012. this.src.uri = window$1.location.href;
  2013. } // resolvedUri is added on internally after the initial request. Since there's no
  2014. // request for pre-resolved manifests, add on resolvedUri here.
  2015. this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first
  2016. // request can be skipped (since the top level of the manifest, at a minimum, is
  2017. // already available as a parsed manifest object). However, if the manifest object
  2018. // represents a main playlist, some media playlists may need to be resolved before
  2019. // the starting segment list is available. Therefore, go directly to setup of the
  2020. // initial playlist, and let the normal flow continue from there.
  2021. //
  2022. // Note that the call to setup is asynchronous, as other sections of VHS may assume
  2023. // that the first request is asynchronous.
  2024. setTimeout(() => {
  2025. this.setupInitialPlaylist(this.src);
  2026. }, 0);
  2027. return;
  2028. } // request the specified URL
  2029. this.request = this.vhs_.xhr({
  2030. uri: this.src,
  2031. withCredentials: this.withCredentials
  2032. }, (error, req) => {
  2033. // disposed
  2034. if (!this.request) {
  2035. return;
  2036. } // clear the loader's request reference
  2037. this.request = null;
  2038. if (error) {
  2039. this.error = {
  2040. status: req.status,
  2041. message: `HLS playlist request error at URL: ${this.src}.`,
  2042. responseText: req.responseText,
  2043. // MEDIA_ERR_NETWORK
  2044. code: 2
  2045. };
  2046. if (this.state === 'HAVE_NOTHING') {
  2047. this.started = false;
  2048. }
  2049. return this.trigger('error');
  2050. }
  2051. this.src = resolveManifestRedirect(this.src, req);
  2052. const manifest = this.parseManifest_({
  2053. manifestString: req.responseText,
  2054. url: this.src
  2055. });
  2056. this.setupInitialPlaylist(manifest);
  2057. });
  2058. }
  2059. srcUri() {
  2060. return typeof this.src === 'string' ? this.src : this.src.uri;
  2061. }
  2062. /**
  2063. * Given a manifest object that's either a main or media playlist, trigger the proper
  2064. * events and set the state of the playlist loader.
  2065. *
  2066. * If the manifest object represents a main playlist, `loadedplaylist` will be
  2067. * triggered to allow listeners to select a playlist. If none is selected, the loader
  2068. * will default to the first one in the playlists array.
  2069. *
  2070. * If the manifest object represents a media playlist, `loadedplaylist` will be
  2071. * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
  2072. *
  2073. * In the case of a media playlist, a main playlist object wrapper with one playlist
  2074. * will be created so that all logic can handle playlists in the same fashion (as an
  2075. * assumed manifest object schema).
  2076. *
  2077. * @param {Object} manifest
  2078. * The parsed manifest object
  2079. */
  2080. setupInitialPlaylist(manifest) {
  2081. this.state = 'HAVE_MAIN_MANIFEST';
  2082. if (manifest.playlists) {
  2083. this.main = manifest;
  2084. addPropertiesToMain(this.main, this.srcUri()); // If the initial main playlist has playlists wtih segments already resolved,
  2085. // then resolve URIs in advance, as they are usually done after a playlist request,
  2086. // which may not happen if the playlist is resolved.
  2087. manifest.playlists.forEach(playlist => {
  2088. playlist.segments = getAllSegments(playlist);
  2089. playlist.segments.forEach(segment => {
  2090. resolveSegmentUris(segment, playlist.resolvedUri);
  2091. });
  2092. });
  2093. this.trigger('loadedplaylist');
  2094. if (!this.request) {
  2095. // no media playlist was specifically selected so start
  2096. // from the first listed one
  2097. this.media(this.main.playlists[0]);
  2098. }
  2099. return;
  2100. } // In order to support media playlists passed in as vhs-json, the case where the uri
  2101. // is not provided as part of the manifest should be considered, and an appropriate
  2102. // default used.
  2103. const uri = this.srcUri() || window$1.location.href;
  2104. this.main = mainForMedia(manifest, uri);
  2105. this.haveMetadata({
  2106. playlistObject: manifest,
  2107. url: uri,
  2108. id: this.main.playlists[0].id
  2109. });
  2110. this.trigger('loadedmetadata');
  2111. }
  2112. /**
  2113. * Updates or deletes a preexisting pathway clone.
  2114. * Ensures that all playlists related to the old pathway clone are
  2115. * either updated or deleted.
  2116. *
  2117. * @param {Object} clone On update, the pathway clone object for the newly updated pathway clone.
  2118. * On delete, the old pathway clone object to be deleted.
  2119. * @param {boolean} isUpdate True if the pathway is to be updated,
  2120. * false if it is meant to be deleted.
  2121. */
  2122. updateOrDeleteClone(clone, isUpdate) {
  2123. const main = this.main;
  2124. const pathway = clone.ID;
  2125. let i = main.playlists.length; // Iterate backwards through the playlist so we can remove playlists if necessary.
  2126. while (i--) {
  2127. const p = main.playlists[i];
  2128. if (p.attributes['PATHWAY-ID'] === pathway) {
  2129. const oldPlaylistUri = p.resolvedUri;
  2130. const oldPlaylistId = p.id; // update the indexed playlist and add new playlists by ID and URI
  2131. if (isUpdate) {
  2132. const newPlaylistUri = this.createCloneURI_(p.resolvedUri, clone);
  2133. const newPlaylistId = createPlaylistID(pathway, newPlaylistUri);
  2134. const attributes = this.createCloneAttributes_(pathway, p.attributes);
  2135. const updatedPlaylist = this.createClonePlaylist_(p, newPlaylistId, clone, attributes);
  2136. main.playlists[i] = updatedPlaylist;
  2137. main.playlists[newPlaylistId] = updatedPlaylist;
  2138. main.playlists[newPlaylistUri] = updatedPlaylist;
  2139. } else {
  2140. // Remove the indexed playlist.
  2141. main.playlists.splice(i, 1);
  2142. } // Remove playlists by the old ID and URI.
  2143. delete main.playlists[oldPlaylistId];
  2144. delete main.playlists[oldPlaylistUri];
  2145. }
  2146. }
  2147. this.updateOrDeleteCloneMedia(clone, isUpdate);
  2148. }
  2149. /**
  2150. * Updates or deletes media data based on the pathway clone object.
  2151. * Due to the complexity of the media groups and playlists, in all cases
  2152. * we remove all of the old media groups and playlists.
  2153. * On updates, we then create new media groups and playlists based on the
  2154. * new pathway clone object.
  2155. *
  2156. * @param {Object} clone The pathway clone object for the newly updated pathway clone.
  2157. * @param {boolean} isUpdate True if the pathway is to be updated,
  2158. * false if it is meant to be deleted.
  2159. */
  2160. updateOrDeleteCloneMedia(clone, isUpdate) {
  2161. const main = this.main;
  2162. const id = clone.ID;
  2163. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(mediaType => {
  2164. if (!main.mediaGroups[mediaType] || !main.mediaGroups[mediaType][id]) {
  2165. return;
  2166. }
  2167. for (const groupKey in main.mediaGroups[mediaType]) {
  2168. // Remove all media playlists for the media group for this pathway clone.
  2169. if (groupKey === id) {
  2170. for (const labelKey in main.mediaGroups[mediaType][groupKey]) {
  2171. const oldMedia = main.mediaGroups[mediaType][groupKey][labelKey];
  2172. oldMedia.playlists.forEach((p, i) => {
  2173. const oldMediaPlaylist = main.playlists[p.id];
  2174. const oldPlaylistId = oldMediaPlaylist.id;
  2175. const oldPlaylistUri = oldMediaPlaylist.resolvedUri;
  2176. delete main.playlists[oldPlaylistId];
  2177. delete main.playlists[oldPlaylistUri];
  2178. });
  2179. } // Delete the old media group.
  2180. delete main.mediaGroups[mediaType][groupKey];
  2181. }
  2182. }
  2183. }); // Create the new media groups and playlists if there is an update.
  2184. if (isUpdate) {
  2185. this.createClonedMediaGroups_(clone);
  2186. }
  2187. }
  2188. /**
  2189. * Given a pathway clone object, clones all necessary playlists.
  2190. *
  2191. * @param {Object} clone The pathway clone object.
  2192. * @param {Object} basePlaylist The original playlist to clone from.
  2193. */
  2194. addClonePathway(clone, basePlaylist = {}) {
  2195. const main = this.main;
  2196. const index = main.playlists.length;
  2197. const uri = this.createCloneURI_(basePlaylist.resolvedUri, clone);
  2198. const playlistId = createPlaylistID(clone.ID, uri);
  2199. const attributes = this.createCloneAttributes_(clone.ID, basePlaylist.attributes);
  2200. const playlist = this.createClonePlaylist_(basePlaylist, playlistId, clone, attributes);
  2201. main.playlists[index] = playlist; // add playlist by ID and URI
  2202. main.playlists[playlistId] = playlist;
  2203. main.playlists[uri] = playlist;
  2204. this.createClonedMediaGroups_(clone);
  2205. }
  2206. /**
  2207. * Given a pathway clone object we create clones of all media.
  2208. * In this function, all necessary information and updated playlists
  2209. * are added to the `mediaGroup` object.
  2210. * Playlists are also added to the `playlists` array so the media groups
  2211. * will be properly linked.
  2212. *
  2213. * @param {Object} clone The pathway clone object.
  2214. */
  2215. createClonedMediaGroups_(clone) {
  2216. const id = clone.ID;
  2217. const baseID = clone['BASE-ID'];
  2218. const main = this.main;
  2219. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(mediaType => {
  2220. // If the media type doesn't exist, or there is already a clone, skip
  2221. // to the next media type.
  2222. if (!main.mediaGroups[mediaType] || main.mediaGroups[mediaType][id]) {
  2223. return;
  2224. }
  2225. for (const groupKey in main.mediaGroups[mediaType]) {
  2226. if (groupKey === baseID) {
  2227. // Create the group.
  2228. main.mediaGroups[mediaType][id] = {};
  2229. } else {
  2230. // There is no need to iterate over label keys in this case.
  2231. continue;
  2232. }
  2233. for (const labelKey in main.mediaGroups[mediaType][groupKey]) {
  2234. const oldMedia = main.mediaGroups[mediaType][groupKey][labelKey];
  2235. main.mediaGroups[mediaType][id][labelKey] = _extends({}, oldMedia);
  2236. const newMedia = main.mediaGroups[mediaType][id][labelKey]; // update URIs on the media
  2237. const newUri = this.createCloneURI_(oldMedia.resolvedUri, clone);
  2238. newMedia.resolvedUri = newUri;
  2239. newMedia.uri = newUri; // Reset playlists in the new media group.
  2240. newMedia.playlists = []; // Create new playlists in the newly cloned media group.
  2241. oldMedia.playlists.forEach((p, i) => {
  2242. const oldMediaPlaylist = main.playlists[p.id];
  2243. const group = groupID(mediaType, id, labelKey);
  2244. const newPlaylistID = createPlaylistID(id, group); // Check to see if it already exists
  2245. if (oldMediaPlaylist && !main.playlists[newPlaylistID]) {
  2246. const newMediaPlaylist = this.createClonePlaylist_(oldMediaPlaylist, newPlaylistID, clone);
  2247. const newPlaylistUri = newMediaPlaylist.resolvedUri;
  2248. main.playlists[newPlaylistID] = newMediaPlaylist;
  2249. main.playlists[newPlaylistUri] = newMediaPlaylist;
  2250. }
  2251. newMedia.playlists[i] = this.createClonePlaylist_(p, newPlaylistID, clone);
  2252. });
  2253. }
  2254. }
  2255. });
  2256. }
  2257. /**
  2258. * Using the original playlist to be cloned, and the pathway clone object
  2259. * information, we create a new playlist.
  2260. *
  2261. * @param {Object} basePlaylist The original playlist to be cloned from.
  2262. * @param {string} id The desired id of the newly cloned playlist.
  2263. * @param {Object} clone The pathway clone object.
  2264. * @param {Object} attributes An optional object to populate the `attributes` property in the playlist.
  2265. *
  2266. * @return {Object} The combined cloned playlist.
  2267. */
  2268. createClonePlaylist_(basePlaylist, id, clone, attributes) {
  2269. const uri = this.createCloneURI_(basePlaylist.resolvedUri, clone);
  2270. const newProps = {
  2271. resolvedUri: uri,
  2272. uri,
  2273. id
  2274. }; // Remove all segments from previous playlist in the clone.
  2275. if (basePlaylist.segments) {
  2276. newProps.segments = [];
  2277. }
  2278. if (attributes) {
  2279. newProps.attributes = attributes;
  2280. }
  2281. return merge(basePlaylist, newProps);
  2282. }
  2283. /**
  2284. * Generates an updated URI for a cloned pathway based on the original
  2285. * pathway's URI and the paramaters from the pathway clone object in the
  2286. * content steering server response.
  2287. *
  2288. * @param {string} baseUri URI to be updated in the cloned pathway.
  2289. * @param {Object} clone The pathway clone object.
  2290. *
  2291. * @return {string} The updated URI for the cloned pathway.
  2292. */
  2293. createCloneURI_(baseURI, clone) {
  2294. const uri = new URL(baseURI);
  2295. uri.hostname = clone['URI-REPLACEMENT'].HOST;
  2296. const params = clone['URI-REPLACEMENT'].PARAMS; // Add params to the cloned URL.
  2297. for (const key of Object.keys(params)) {
  2298. uri.searchParams.set(key, params[key]);
  2299. }
  2300. return uri.href;
  2301. }
  2302. /**
  2303. * Helper function to create the attributes needed for the new clone.
  2304. * This mainly adds the necessary media attributes.
  2305. *
  2306. * @param {string} id The pathway clone object ID.
  2307. * @param {Object} oldAttributes The old attributes to compare to.
  2308. * @return {Object} The new attributes to add to the playlist.
  2309. */
  2310. createCloneAttributes_(id, oldAttributes) {
  2311. const attributes = {
  2312. ['PATHWAY-ID']: id
  2313. };
  2314. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(mediaType => {
  2315. if (oldAttributes[mediaType]) {
  2316. attributes[mediaType] = id;
  2317. }
  2318. });
  2319. return attributes;
  2320. }
  2321. /**
  2322. * Returns the key ID set from a playlist
  2323. *
  2324. * @param {playlist} playlist to fetch the key ID set from.
  2325. * @return a Set of 32 digit hex strings that represent the unique keyIds for that playlist.
  2326. */
  2327. getKeyIdSet(playlist) {
  2328. if (playlist.contentProtection) {
  2329. const keyIds = new Set();
  2330. for (const keysystem in playlist.contentProtection) {
  2331. const keyId = playlist.contentProtection[keysystem].attributes.keyId;
  2332. if (keyId) {
  2333. keyIds.add(keyId.toLowerCase());
  2334. }
  2335. }
  2336. return keyIds;
  2337. }
  2338. }
  2339. }
  2340. /**
  2341. * @file xhr.js
  2342. */
  2343. const {
  2344. xhr: videojsXHR
  2345. } = videojs;
  2346. const callbackWrapper = function (request, error, response, callback) {
  2347. const reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
  2348. if (!error && reqResponse) {
  2349. request.responseTime = Date.now();
  2350. request.roundTripTime = request.responseTime - request.requestTime;
  2351. request.bytesReceived = reqResponse.byteLength || reqResponse.length;
  2352. if (!request.bandwidth) {
  2353. request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
  2354. }
  2355. }
  2356. if (response.headers) {
  2357. request.responseHeaders = response.headers;
  2358. } // videojs.xhr now uses a specific code on the error
  2359. // object to signal that a request has timed out instead
  2360. // of setting a boolean on the request object
  2361. if (error && error.code === 'ETIMEDOUT') {
  2362. request.timedout = true;
  2363. } // videojs.xhr no longer considers status codes outside of 200 and 0
  2364. // (for file uris) to be errors, but the old XHR did, so emulate that
  2365. // behavior. Status 206 may be used in response to byterange requests.
  2366. if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
  2367. error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));
  2368. }
  2369. callback(error, request);
  2370. };
  2371. /**
  2372. * Iterates over the request hooks Set and calls them in order
  2373. *
  2374. * @param {Set} hooks the hook Set to iterate over
  2375. * @param {Object} options the request options to pass to the xhr wrapper
  2376. * @return the callback hook function return value, the modified or new options Object.
  2377. */
  2378. const callAllRequestHooks = (requestSet, options) => {
  2379. if (!requestSet || !requestSet.size) {
  2380. return;
  2381. }
  2382. let newOptions = options;
  2383. requestSet.forEach(requestCallback => {
  2384. newOptions = requestCallback(newOptions);
  2385. });
  2386. return newOptions;
  2387. };
  2388. /**
  2389. * Iterates over the response hooks Set and calls them in order.
  2390. *
  2391. * @param {Set} hooks the hook Set to iterate over
  2392. * @param {Object} request the xhr request object
  2393. * @param {Object} error the xhr error object
  2394. * @param {Object} response the xhr response object
  2395. */
  2396. const callAllResponseHooks = (responseSet, request, error, response) => {
  2397. if (!responseSet || !responseSet.size) {
  2398. return;
  2399. }
  2400. responseSet.forEach(responseCallback => {
  2401. responseCallback(request, error, response);
  2402. });
  2403. };
  2404. const xhrFactory = function () {
  2405. const xhr = function XhrFunction(options, callback) {
  2406. // Add a default timeout
  2407. options = merge({
  2408. timeout: 45e3
  2409. }, options); // Allow an optional user-specified function to modify the option
  2410. // object before we construct the xhr request
  2411. // TODO: Remove beforeRequest in the next major release.
  2412. const beforeRequest = XhrFunction.beforeRequest || videojs.Vhs.xhr.beforeRequest; // onRequest and onResponse hooks as a Set, at either the player or global level.
  2413. // TODO: new Set added here for beforeRequest alias. Remove this when beforeRequest is removed.
  2414. const _requestCallbackSet = XhrFunction._requestCallbackSet || videojs.Vhs.xhr._requestCallbackSet || new Set();
  2415. const _responseCallbackSet = XhrFunction._responseCallbackSet || videojs.Vhs.xhr._responseCallbackSet;
  2416. if (beforeRequest && typeof beforeRequest === 'function') {
  2417. videojs.log.warn('beforeRequest is deprecated, use onRequest instead.');
  2418. _requestCallbackSet.add(beforeRequest);
  2419. } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
  2420. // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
  2421. const xhrMethod = videojs.Vhs.xhr.original === true ? videojsXHR : videojs.Vhs.xhr; // call all registered onRequest hooks, assign new options.
  2422. const beforeRequestOptions = callAllRequestHooks(_requestCallbackSet, options); // Remove the beforeRequest function from the hooks set so stale beforeRequest functions are not called.
  2423. _requestCallbackSet.delete(beforeRequest); // xhrMethod will call XMLHttpRequest.open and XMLHttpRequest.send
  2424. const request = xhrMethod(beforeRequestOptions || options, function (error, response) {
  2425. // call all registered onResponse hooks
  2426. callAllResponseHooks(_responseCallbackSet, request, error, response);
  2427. return callbackWrapper(request, error, response, callback);
  2428. });
  2429. const originalAbort = request.abort;
  2430. request.abort = function () {
  2431. request.aborted = true;
  2432. return originalAbort.apply(request, arguments);
  2433. };
  2434. request.uri = options.uri;
  2435. request.requestTime = Date.now();
  2436. return request;
  2437. };
  2438. xhr.original = true;
  2439. return xhr;
  2440. };
  2441. /**
  2442. * Turns segment byterange into a string suitable for use in
  2443. * HTTP Range requests
  2444. *
  2445. * @param {Object} byterange - an object with two values defining the start and end
  2446. * of a byte-range
  2447. */
  2448. const byterangeStr = function (byterange) {
  2449. // `byterangeEnd` is one less than `offset + length` because the HTTP range
  2450. // header uses inclusive ranges
  2451. let byterangeEnd;
  2452. const byterangeStart = byterange.offset;
  2453. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  2454. byterangeEnd = window$1.BigInt(byterange.offset) + window$1.BigInt(byterange.length) - window$1.BigInt(1);
  2455. } else {
  2456. byterangeEnd = byterange.offset + byterange.length - 1;
  2457. }
  2458. return 'bytes=' + byterangeStart + '-' + byterangeEnd;
  2459. };
  2460. /**
  2461. * Defines headers for use in the xhr request for a particular segment.
  2462. *
  2463. * @param {Object} segment - a simplified copy of the segmentInfo object
  2464. * from SegmentLoader
  2465. */
  2466. const segmentXhrHeaders = function (segment) {
  2467. const headers = {};
  2468. if (segment.byterange) {
  2469. headers.Range = byterangeStr(segment.byterange);
  2470. }
  2471. return headers;
  2472. };
  2473. /**
  2474. * @file bin-utils.js
  2475. */
  2476. /**
  2477. * convert a TimeRange to text
  2478. *
  2479. * @param {TimeRange} range the timerange to use for conversion
  2480. * @param {number} i the iterator on the range to convert
  2481. * @return {string} the range in string format
  2482. */
  2483. const textRange = function (range, i) {
  2484. return range.start(i) + '-' + range.end(i);
  2485. };
  2486. /**
  2487. * format a number as hex string
  2488. *
  2489. * @param {number} e The number
  2490. * @param {number} i the iterator
  2491. * @return {string} the hex formatted number as a string
  2492. */
  2493. const formatHexString = function (e, i) {
  2494. const value = e.toString(16);
  2495. return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
  2496. };
  2497. const formatAsciiString = function (e) {
  2498. if (e >= 0x20 && e < 0x7e) {
  2499. return String.fromCharCode(e);
  2500. }
  2501. return '.';
  2502. };
  2503. /**
  2504. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  2505. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  2506. *
  2507. * @param {Object} message
  2508. * Object of properties and values to send to the web worker
  2509. * @return {Object}
  2510. * Modified message with TypedArray values expanded
  2511. * @function createTransferableMessage
  2512. */
  2513. const createTransferableMessage = function (message) {
  2514. const transferable = {};
  2515. Object.keys(message).forEach(key => {
  2516. const value = message[key];
  2517. if (isArrayBufferView(value)) {
  2518. transferable[key] = {
  2519. bytes: value.buffer,
  2520. byteOffset: value.byteOffset,
  2521. byteLength: value.byteLength
  2522. };
  2523. } else {
  2524. transferable[key] = value;
  2525. }
  2526. });
  2527. return transferable;
  2528. };
  2529. /**
  2530. * Returns a unique string identifier for a media initialization
  2531. * segment.
  2532. *
  2533. * @param {Object} initSegment
  2534. * the init segment object.
  2535. *
  2536. * @return {string} the generated init segment id
  2537. */
  2538. const initSegmentId = function (initSegment) {
  2539. const byterange = initSegment.byterange || {
  2540. length: Infinity,
  2541. offset: 0
  2542. };
  2543. return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
  2544. };
  2545. /**
  2546. * Returns a unique string identifier for a media segment key.
  2547. *
  2548. * @param {Object} key the encryption key
  2549. * @return {string} the unique id for the media segment key.
  2550. */
  2551. const segmentKeyId = function (key) {
  2552. return key.resolvedUri;
  2553. };
  2554. /**
  2555. * utils to help dump binary data to the console
  2556. *
  2557. * @param {Array|TypedArray} data
  2558. * data to dump to a string
  2559. *
  2560. * @return {string} the data as a hex string.
  2561. */
  2562. const hexDump = data => {
  2563. const bytes = Array.prototype.slice.call(data);
  2564. const step = 16;
  2565. let result = '';
  2566. let hex;
  2567. let ascii;
  2568. for (let j = 0; j < bytes.length / step; j++) {
  2569. hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
  2570. ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
  2571. result += hex + ' ' + ascii + '\n';
  2572. }
  2573. return result;
  2574. };
  2575. const tagDump = ({
  2576. bytes
  2577. }) => hexDump(bytes);
  2578. const textRanges = ranges => {
  2579. let result = '';
  2580. let i;
  2581. for (i = 0; i < ranges.length; i++) {
  2582. result += textRange(ranges, i) + ' ';
  2583. }
  2584. return result;
  2585. };
  2586. var utils = /*#__PURE__*/Object.freeze({
  2587. __proto__: null,
  2588. createTransferableMessage: createTransferableMessage,
  2589. initSegmentId: initSegmentId,
  2590. segmentKeyId: segmentKeyId,
  2591. hexDump: hexDump,
  2592. tagDump: tagDump,
  2593. textRanges: textRanges
  2594. });
  2595. // TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
  2596. // 25% was arbitrarily chosen, and may need to be refined over time.
  2597. const SEGMENT_END_FUDGE_PERCENT = 0.25;
  2598. /**
  2599. * Converts a player time (any time that can be gotten/set from player.currentTime(),
  2600. * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
  2601. * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
  2602. *
  2603. * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
  2604. * point" (a point where we have a mapping from program time to player time, with player
  2605. * time being the post transmux start of the segment).
  2606. *
  2607. * For more details, see [this doc](../../docs/program-time-from-player-time.md).
  2608. *
  2609. * @param {number} playerTime the player time
  2610. * @param {Object} segment the segment which contains the player time
  2611. * @return {Date} program time
  2612. */
  2613. const playerTimeToProgramTime = (playerTime, segment) => {
  2614. if (!segment.dateTimeObject) {
  2615. // Can't convert without an "anchor point" for the program time (i.e., a time that can
  2616. // be used to map the start of a segment with a real world time).
  2617. return null;
  2618. }
  2619. const transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
  2620. const transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended
  2621. const startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
  2622. const offsetFromSegmentStart = playerTime - startOfSegment;
  2623. return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
  2624. };
  2625. const originalSegmentVideoDuration = videoTimingInfo => {
  2626. return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
  2627. };
  2628. /**
  2629. * Finds a segment that contains the time requested given as an ISO-8601 string. The
  2630. * returned segment might be an estimate or an accurate match.
  2631. *
  2632. * @param {string} programTime The ISO-8601 programTime to find a match for
  2633. * @param {Object} playlist A playlist object to search within
  2634. */
  2635. const findSegmentForProgramTime = (programTime, playlist) => {
  2636. // Assumptions:
  2637. // - verifyProgramDateTimeTags has already been run
  2638. // - live streams have been started
  2639. let dateTimeObject;
  2640. try {
  2641. dateTimeObject = new Date(programTime);
  2642. } catch (e) {
  2643. return null;
  2644. }
  2645. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  2646. return null;
  2647. }
  2648. let segment = playlist.segments[0];
  2649. if (dateTimeObject < new Date(segment.dateTimeObject)) {
  2650. // Requested time is before stream start.
  2651. return null;
  2652. }
  2653. for (let i = 0; i < playlist.segments.length - 1; i++) {
  2654. segment = playlist.segments[i];
  2655. const nextSegmentStart = new Date(playlist.segments[i + 1].dateTimeObject);
  2656. if (dateTimeObject < nextSegmentStart) {
  2657. break;
  2658. }
  2659. }
  2660. const lastSegment = playlist.segments[playlist.segments.length - 1];
  2661. const lastSegmentStart = lastSegment.dateTimeObject;
  2662. const lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
  2663. const lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
  2664. if (dateTimeObject > lastSegmentEnd) {
  2665. // Beyond the end of the stream, or our best guess of the end of the stream.
  2666. return null;
  2667. }
  2668. if (dateTimeObject > new Date(lastSegmentStart)) {
  2669. segment = lastSegment;
  2670. }
  2671. return {
  2672. segment,
  2673. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
  2674. // Although, given that all segments have accurate date time objects, the segment
  2675. // selected should be accurate, unless the video has been transmuxed at some point
  2676. // (determined by the presence of the videoTimingInfo object), the segment's "player
  2677. // time" (the start time in the player) can't be considered accurate.
  2678. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  2679. };
  2680. };
  2681. /**
  2682. * Finds a segment that contains the given player time(in seconds).
  2683. *
  2684. * @param {number} time The player time to find a match for
  2685. * @param {Object} playlist A playlist object to search within
  2686. */
  2687. const findSegmentForPlayerTime = (time, playlist) => {
  2688. // Assumptions:
  2689. // - there will always be a segment.duration
  2690. // - we can start from zero
  2691. // - segments are in time order
  2692. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  2693. return null;
  2694. }
  2695. let segmentEnd = 0;
  2696. let segment;
  2697. for (let i = 0; i < playlist.segments.length; i++) {
  2698. segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and
  2699. // should contain the most accurate values we have for the segment's player times.
  2700. //
  2701. // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
  2702. // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
  2703. // calculate an end value.
  2704. segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
  2705. if (time <= segmentEnd) {
  2706. break;
  2707. }
  2708. }
  2709. const lastSegment = playlist.segments[playlist.segments.length - 1];
  2710. if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
  2711. // The time requested is beyond the stream end.
  2712. return null;
  2713. }
  2714. if (time > segmentEnd) {
  2715. // The time is within or beyond the last segment.
  2716. //
  2717. // Check to see if the time is beyond a reasonable guess of the end of the stream.
  2718. if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
  2719. // Technically, because the duration value is only an estimate, the time may still
  2720. // exist in the last segment, however, there isn't enough information to make even
  2721. // a reasonable estimate.
  2722. return null;
  2723. }
  2724. segment = lastSegment;
  2725. }
  2726. return {
  2727. segment,
  2728. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
  2729. // Because videoTimingInfo is only set after transmux, it is the only way to get
  2730. // accurate timing values.
  2731. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  2732. };
  2733. };
  2734. /**
  2735. * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
  2736. * If the offset returned is positive, the programTime occurs after the
  2737. * comparisonTimestamp.
  2738. * If the offset is negative, the programTime occurs before the comparisonTimestamp.
  2739. *
  2740. * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
  2741. * @param {string} programTime The programTime as an ISO-8601 string
  2742. * @return {number} offset
  2743. */
  2744. const getOffsetFromTimestamp = (comparisonTimeStamp, programTime) => {
  2745. let segmentDateTime;
  2746. let programDateTime;
  2747. try {
  2748. segmentDateTime = new Date(comparisonTimeStamp);
  2749. programDateTime = new Date(programTime);
  2750. } catch (e) {// TODO handle error
  2751. }
  2752. const segmentTimeEpoch = segmentDateTime.getTime();
  2753. const programTimeEpoch = programDateTime.getTime();
  2754. return (programTimeEpoch - segmentTimeEpoch) / 1000;
  2755. };
  2756. /**
  2757. * Checks that all segments in this playlist have programDateTime tags.
  2758. *
  2759. * @param {Object} playlist A playlist object
  2760. */
  2761. const verifyProgramDateTimeTags = playlist => {
  2762. if (!playlist.segments || playlist.segments.length === 0) {
  2763. return false;
  2764. }
  2765. for (let i = 0; i < playlist.segments.length; i++) {
  2766. const segment = playlist.segments[i];
  2767. if (!segment.dateTimeObject) {
  2768. return false;
  2769. }
  2770. }
  2771. return true;
  2772. };
  2773. /**
  2774. * Returns the programTime of the media given a playlist and a playerTime.
  2775. * The playlist must have programDateTime tags for a programDateTime tag to be returned.
  2776. * If the segments containing the time requested have not been buffered yet, an estimate
  2777. * may be returned to the callback.
  2778. *
  2779. * @param {Object} args
  2780. * @param {Object} args.playlist A playlist object to search within
  2781. * @param {number} time A playerTime in seconds
  2782. * @param {Function} callback(err, programTime)
  2783. * @return {string} err.message A detailed error message
  2784. * @return {Object} programTime
  2785. * @return {number} programTime.mediaSeconds The streamTime in seconds
  2786. * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
  2787. */
  2788. const getProgramTime = ({
  2789. playlist,
  2790. time = undefined,
  2791. callback
  2792. }) => {
  2793. if (!callback) {
  2794. throw new Error('getProgramTime: callback must be provided');
  2795. }
  2796. if (!playlist || time === undefined) {
  2797. return callback({
  2798. message: 'getProgramTime: playlist and time must be provided'
  2799. });
  2800. }
  2801. const matchedSegment = findSegmentForPlayerTime(time, playlist);
  2802. if (!matchedSegment) {
  2803. return callback({
  2804. message: 'valid programTime was not found'
  2805. });
  2806. }
  2807. if (matchedSegment.type === 'estimate') {
  2808. return callback({
  2809. message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',
  2810. seekTime: matchedSegment.estimatedStart
  2811. });
  2812. }
  2813. const programTimeObject = {
  2814. mediaSeconds: time
  2815. };
  2816. const programTime = playerTimeToProgramTime(time, matchedSegment.segment);
  2817. if (programTime) {
  2818. programTimeObject.programDateTime = programTime.toISOString();
  2819. }
  2820. return callback(null, programTimeObject);
  2821. };
  2822. /**
  2823. * Seeks in the player to a time that matches the given programTime ISO-8601 string.
  2824. *
  2825. * @param {Object} args
  2826. * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
  2827. * @param {Object} args.playlist A playlist to look within
  2828. * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
  2829. * @param {Function} args.seekTo A method to perform a seek
  2830. * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
  2831. * @param {Object} args.tech The tech to seek on
  2832. * @param {Function} args.callback(err, newTime) A callback to return the new time to
  2833. * @return {string} err.message A detailed error message
  2834. * @return {number} newTime The exact time that was seeked to in seconds
  2835. */
  2836. const seekToProgramTime = ({
  2837. programTime,
  2838. playlist,
  2839. retryCount = 2,
  2840. seekTo,
  2841. pauseAfterSeek = true,
  2842. tech,
  2843. callback
  2844. }) => {
  2845. if (!callback) {
  2846. throw new Error('seekToProgramTime: callback must be provided');
  2847. }
  2848. if (typeof programTime === 'undefined' || !playlist || !seekTo) {
  2849. return callback({
  2850. message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
  2851. });
  2852. }
  2853. if (!playlist.endList && !tech.hasStarted_) {
  2854. return callback({
  2855. message: 'player must be playing a live stream to start buffering'
  2856. });
  2857. }
  2858. if (!verifyProgramDateTimeTags(playlist)) {
  2859. return callback({
  2860. message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
  2861. });
  2862. }
  2863. const matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match
  2864. if (!matchedSegment) {
  2865. return callback({
  2866. message: `${programTime} was not found in the stream`
  2867. });
  2868. }
  2869. const segment = matchedSegment.segment;
  2870. const mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
  2871. if (matchedSegment.type === 'estimate') {
  2872. // we've run out of retries
  2873. if (retryCount === 0) {
  2874. return callback({
  2875. message: `${programTime} is not buffered yet. Try again`
  2876. });
  2877. }
  2878. seekTo(matchedSegment.estimatedStart + mediaOffset);
  2879. tech.one('seeked', () => {
  2880. seekToProgramTime({
  2881. programTime,
  2882. playlist,
  2883. retryCount: retryCount - 1,
  2884. seekTo,
  2885. pauseAfterSeek,
  2886. tech,
  2887. callback
  2888. });
  2889. });
  2890. return;
  2891. } // Since the segment.start value is determined from the buffered end or ending time
  2892. // of the prior segment, the seekToTime doesn't need to account for any transmuxer
  2893. // modifications.
  2894. const seekToTime = segment.start + mediaOffset;
  2895. const seekedCallback = () => {
  2896. return callback(null, tech.currentTime());
  2897. }; // listen for seeked event
  2898. tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state
  2899. if (pauseAfterSeek) {
  2900. tech.pause();
  2901. }
  2902. seekTo(seekToTime);
  2903. };
  2904. // which will only happen if the request is complete.
  2905. const callbackOnCompleted = (request, cb) => {
  2906. if (request.readyState === 4) {
  2907. return cb();
  2908. }
  2909. return;
  2910. };
  2911. const containerRequest = (uri, xhr, cb) => {
  2912. let bytes = [];
  2913. let id3Offset;
  2914. let finished = false;
  2915. const endRequestAndCallback = function (err, req, type, _bytes) {
  2916. req.abort();
  2917. finished = true;
  2918. return cb(err, req, type, _bytes);
  2919. };
  2920. const progressListener = function (error, request) {
  2921. if (finished) {
  2922. return;
  2923. }
  2924. if (error) {
  2925. return endRequestAndCallback(error, request, '', bytes);
  2926. } // grap the new part of content that was just downloaded
  2927. const newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes
  2928. bytes = concatTypedArrays(bytes, stringToBytes(newPart, true));
  2929. id3Offset = id3Offset || getId3Offset(bytes); // we need at least 10 bytes to determine a type
  2930. // or we need at least two bytes after an id3Offset
  2931. if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
  2932. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  2933. }
  2934. const type = detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data
  2935. // to see the second sync byte, wait until we have enough data
  2936. // before declaring it ts
  2937. if (type === 'ts' && bytes.length < 188) {
  2938. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  2939. } // this may be an unsynced ts segment
  2940. // wait for 376 bytes before detecting no container
  2941. if (!type && bytes.length < 376) {
  2942. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  2943. }
  2944. return endRequestAndCallback(null, request, type, bytes);
  2945. };
  2946. const options = {
  2947. uri,
  2948. beforeSend(request) {
  2949. // this forces the browser to pass the bytes to us unprocessed
  2950. request.overrideMimeType('text/plain; charset=x-user-defined');
  2951. request.addEventListener('progress', function ({
  2952. total,
  2953. loaded
  2954. }) {
  2955. return callbackWrapper(request, null, {
  2956. statusCode: request.status
  2957. }, progressListener);
  2958. });
  2959. }
  2960. };
  2961. const request = xhr(options, function (error, response) {
  2962. return callbackWrapper(request, error, response, progressListener);
  2963. });
  2964. return request;
  2965. };
  2966. const {
  2967. EventTarget
  2968. } = videojs;
  2969. const dashPlaylistUnchanged = function (a, b) {
  2970. if (!isPlaylistUnchanged(a, b)) {
  2971. return false;
  2972. } // for dash the above check will often return true in scenarios where
  2973. // the playlist actually has changed because mediaSequence isn't a
  2974. // dash thing, and we often set it to 1. So if the playlists have the same amount
  2975. // of segments we return true.
  2976. // So for dash we need to make sure that the underlying segments are different.
  2977. // if sidx changed then the playlists are different.
  2978. if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
  2979. return false;
  2980. } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
  2981. return false;
  2982. } // one or the other does not have segments
  2983. // there was a change.
  2984. if (a.segments && !b.segments || !a.segments && b.segments) {
  2985. return false;
  2986. } // neither has segments nothing changed
  2987. if (!a.segments && !b.segments) {
  2988. return true;
  2989. } // check segments themselves
  2990. for (let i = 0; i < a.segments.length; i++) {
  2991. const aSegment = a.segments[i];
  2992. const bSegment = b.segments[i]; // if uris are different between segments there was a change
  2993. if (aSegment.uri !== bSegment.uri) {
  2994. return false;
  2995. } // neither segment has a byterange, there will be no byterange change.
  2996. if (!aSegment.byterange && !bSegment.byterange) {
  2997. continue;
  2998. }
  2999. const aByterange = aSegment.byterange;
  3000. const bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.
  3001. if (aByterange && !bByterange || !aByterange && bByterange) {
  3002. return false;
  3003. } // if both segments have byterange with different offsets, there was a change.
  3004. if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
  3005. return false;
  3006. }
  3007. } // if everything was the same with segments, this is the same playlist.
  3008. return true;
  3009. };
  3010. /**
  3011. * Use the representation IDs from the mpd object to create groupIDs, the NAME is set to mandatory representation
  3012. * ID in the parser. This allows for continuous playout across periods with the same representation IDs
  3013. * (continuous periods as defined in DASH-IF 3.2.12). This is assumed in the mpd-parser as well. If we want to support
  3014. * periods without continuous playback this function may need modification as well as the parser.
  3015. */
  3016. const dashGroupId = (type, group, label, playlist) => {
  3017. // If the manifest somehow does not have an ID (non-dash compliant), use the label.
  3018. const playlistId = playlist.attributes.NAME || label;
  3019. return `placeholder-uri-${type}-${group}-${playlistId}`;
  3020. };
  3021. /**
  3022. * Parses the main XML string and updates playlist URI references.
  3023. *
  3024. * @param {Object} config
  3025. * Object of arguments
  3026. * @param {string} config.mainXml
  3027. * The mpd XML
  3028. * @param {string} config.srcUrl
  3029. * The mpd URL
  3030. * @param {Date} config.clientOffset
  3031. * A time difference between server and client
  3032. * @param {Object} config.sidxMapping
  3033. * SIDX mappings for moof/mdat URIs and byte ranges
  3034. * @return {Object}
  3035. * The parsed mpd manifest object
  3036. */
  3037. const parseMainXml = ({
  3038. mainXml,
  3039. srcUrl,
  3040. clientOffset,
  3041. sidxMapping,
  3042. previousManifest
  3043. }) => {
  3044. const manifest = parse(mainXml, {
  3045. manifestUri: srcUrl,
  3046. clientOffset,
  3047. sidxMapping,
  3048. previousManifest
  3049. });
  3050. addPropertiesToMain(manifest, srcUrl, dashGroupId);
  3051. return manifest;
  3052. };
  3053. /**
  3054. * Removes any mediaGroup labels that no longer exist in the newMain
  3055. *
  3056. * @param {Object} update
  3057. * The previous mpd object being updated
  3058. * @param {Object} newMain
  3059. * The new mpd object
  3060. */
  3061. const removeOldMediaGroupLabels = (update, newMain) => {
  3062. forEachMediaGroup(update, (properties, type, group, label) => {
  3063. if (!(label in newMain.mediaGroups[type][group])) {
  3064. delete update.mediaGroups[type][group][label];
  3065. }
  3066. });
  3067. };
  3068. /**
  3069. * Returns a new main manifest that is the result of merging an updated main manifest
  3070. * into the original version.
  3071. *
  3072. * @param {Object} oldMain
  3073. * The old parsed mpd object
  3074. * @param {Object} newMain
  3075. * The updated parsed mpd object
  3076. * @return {Object}
  3077. * A new object representing the original main manifest with the updated media
  3078. * playlists merged in
  3079. */
  3080. const updateMain = (oldMain, newMain, sidxMapping) => {
  3081. let noChanges = true;
  3082. let update = merge(oldMain, {
  3083. // These are top level properties that can be updated
  3084. duration: newMain.duration,
  3085. minimumUpdatePeriod: newMain.minimumUpdatePeriod,
  3086. timelineStarts: newMain.timelineStarts
  3087. }); // First update the playlists in playlist list
  3088. for (let i = 0; i < newMain.playlists.length; i++) {
  3089. const playlist = newMain.playlists[i];
  3090. if (playlist.sidx) {
  3091. const sidxKey = generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
  3092. if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
  3093. addSidxSegmentsToPlaylist(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
  3094. }
  3095. }
  3096. const playlistUpdate = updateMain$1(update, playlist, dashPlaylistUnchanged);
  3097. if (playlistUpdate) {
  3098. update = playlistUpdate;
  3099. noChanges = false;
  3100. }
  3101. } // Then update media group playlists
  3102. forEachMediaGroup(newMain, (properties, type, group, label) => {
  3103. if (properties.playlists && properties.playlists.length) {
  3104. const id = properties.playlists[0].id;
  3105. const playlistUpdate = updateMain$1(update, properties.playlists[0], dashPlaylistUnchanged);
  3106. if (playlistUpdate) {
  3107. update = playlistUpdate; // add new mediaGroup label if it doesn't exist and assign the new mediaGroup.
  3108. if (!(label in update.mediaGroups[type][group])) {
  3109. update.mediaGroups[type][group][label] = properties;
  3110. } // update the playlist reference within media groups
  3111. update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
  3112. noChanges = false;
  3113. }
  3114. }
  3115. }); // remove mediaGroup labels and references that no longer exist in the newMain
  3116. removeOldMediaGroupLabels(update, newMain);
  3117. if (newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  3118. noChanges = false;
  3119. }
  3120. if (noChanges) {
  3121. return null;
  3122. }
  3123. return update;
  3124. }; // SIDX should be equivalent if the URI and byteranges of the SIDX match.
  3125. // If the SIDXs have maps, the two maps should match,
  3126. // both `a` and `b` missing SIDXs is considered matching.
  3127. // If `a` or `b` but not both have a map, they aren't matching.
  3128. const equivalentSidx = (a, b) => {
  3129. const neitherMap = Boolean(!a.map && !b.map);
  3130. const equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
  3131. return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
  3132. }; // exported for testing
  3133. const compareSidxEntry = (playlists, oldSidxMapping) => {
  3134. const newSidxMapping = {};
  3135. for (const id in playlists) {
  3136. const playlist = playlists[id];
  3137. const currentSidxInfo = playlist.sidx;
  3138. if (currentSidxInfo) {
  3139. const key = generateSidxKey(currentSidxInfo);
  3140. if (!oldSidxMapping[key]) {
  3141. break;
  3142. }
  3143. const savedSidxInfo = oldSidxMapping[key].sidxInfo;
  3144. if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
  3145. newSidxMapping[key] = oldSidxMapping[key];
  3146. }
  3147. }
  3148. }
  3149. return newSidxMapping;
  3150. };
  3151. /**
  3152. * A function that filters out changed items as they need to be requested separately.
  3153. *
  3154. * The method is exported for testing
  3155. *
  3156. * @param {Object} main the parsed mpd XML returned via mpd-parser
  3157. * @param {Object} oldSidxMapping the SIDX to compare against
  3158. */
  3159. const filterChangedSidxMappings = (main, oldSidxMapping) => {
  3160. const videoSidx = compareSidxEntry(main.playlists, oldSidxMapping);
  3161. let mediaGroupSidx = videoSidx;
  3162. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  3163. if (properties.playlists && properties.playlists.length) {
  3164. const playlists = properties.playlists;
  3165. mediaGroupSidx = merge(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
  3166. }
  3167. });
  3168. return mediaGroupSidx;
  3169. };
  3170. class DashPlaylistLoader extends EventTarget {
  3171. // DashPlaylistLoader must accept either a src url or a playlist because subsequent
  3172. // playlist loader setups from media groups will expect to be able to pass a playlist
  3173. // (since there aren't external URLs to media playlists with DASH)
  3174. constructor(srcUrlOrPlaylist, vhs, options = {}, mainPlaylistLoader) {
  3175. super();
  3176. this.mainPlaylistLoader_ = mainPlaylistLoader || this;
  3177. if (!mainPlaylistLoader) {
  3178. this.isMain_ = true;
  3179. }
  3180. const {
  3181. withCredentials = false
  3182. } = options;
  3183. this.vhs_ = vhs;
  3184. this.withCredentials = withCredentials;
  3185. this.addMetadataToTextTrack = options.addMetadataToTextTrack;
  3186. if (!srcUrlOrPlaylist) {
  3187. throw new Error('A non-empty playlist URL or object is required');
  3188. } // event naming?
  3189. this.on('minimumUpdatePeriod', () => {
  3190. this.refreshXml_();
  3191. }); // live playlist staleness timeout
  3192. this.on('mediaupdatetimeout', () => {
  3193. this.refreshMedia_(this.media().id);
  3194. });
  3195. this.state = 'HAVE_NOTHING';
  3196. this.loadedPlaylists_ = {};
  3197. this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state
  3198. // The mainPlaylistLoader will be created with a string
  3199. if (this.isMain_) {
  3200. this.mainPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes
  3201. // once multi-period is refactored
  3202. this.mainPlaylistLoader_.sidxMapping_ = {};
  3203. } else {
  3204. this.childPlaylist_ = srcUrlOrPlaylist;
  3205. }
  3206. }
  3207. requestErrored_(err, request, startingState) {
  3208. // disposed
  3209. if (!this.request) {
  3210. return true;
  3211. } // pending request is cleared
  3212. this.request = null;
  3213. if (err) {
  3214. // use the provided error object or create one
  3215. // based on the request/response
  3216. this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
  3217. status: request.status,
  3218. message: 'DASH request error at URL: ' + request.uri,
  3219. response: request.response,
  3220. // MEDIA_ERR_NETWORK
  3221. code: 2
  3222. };
  3223. if (startingState) {
  3224. this.state = startingState;
  3225. }
  3226. this.trigger('error');
  3227. return true;
  3228. }
  3229. }
  3230. /**
  3231. * Verify that the container of the sidx segment can be parsed
  3232. * and if it can, get and parse that segment.
  3233. */
  3234. addSidxSegments_(playlist, startingState, cb) {
  3235. const sidxKey = playlist.sidx && generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
  3236. if (!playlist.sidx || !sidxKey || this.mainPlaylistLoader_.sidxMapping_[sidxKey]) {
  3237. // keep this function async
  3238. this.mediaRequest_ = window$1.setTimeout(() => cb(false), 0);
  3239. return;
  3240. } // resolve the segment URL relative to the playlist
  3241. const uri = resolveManifestRedirect(playlist.sidx.resolvedUri);
  3242. const fin = (err, request) => {
  3243. if (this.requestErrored_(err, request, startingState)) {
  3244. return;
  3245. }
  3246. const sidxMapping = this.mainPlaylistLoader_.sidxMapping_;
  3247. let sidx;
  3248. try {
  3249. sidx = parseSidx(toUint8(request.response).subarray(8));
  3250. } catch (e) {
  3251. // sidx parsing failed.
  3252. this.requestErrored_(e, request, startingState);
  3253. return;
  3254. }
  3255. sidxMapping[sidxKey] = {
  3256. sidxInfo: playlist.sidx,
  3257. sidx
  3258. };
  3259. addSidxSegmentsToPlaylist(playlist, sidx, playlist.sidx.resolvedUri);
  3260. return cb(true);
  3261. };
  3262. this.request = containerRequest(uri, this.vhs_.xhr, (err, request, container, bytes) => {
  3263. if (err) {
  3264. return fin(err, request);
  3265. }
  3266. if (!container || container !== 'mp4') {
  3267. return fin({
  3268. status: request.status,
  3269. message: `Unsupported ${container || 'unknown'} container type for sidx segment at URL: ${uri}`,
  3270. // response is just bytes in this case
  3271. // but we really don't want to return that.
  3272. response: '',
  3273. playlist,
  3274. internal: true,
  3275. playlistExclusionDuration: Infinity,
  3276. // MEDIA_ERR_NETWORK
  3277. code: 2
  3278. }, request);
  3279. } // if we already downloaded the sidx bytes in the container request, use them
  3280. const {
  3281. offset,
  3282. length
  3283. } = playlist.sidx.byterange;
  3284. if (bytes.length >= length + offset) {
  3285. return fin(err, {
  3286. response: bytes.subarray(offset, offset + length),
  3287. status: request.status,
  3288. uri: request.uri
  3289. });
  3290. } // otherwise request sidx bytes
  3291. this.request = this.vhs_.xhr({
  3292. uri,
  3293. responseType: 'arraybuffer',
  3294. headers: segmentXhrHeaders({
  3295. byterange: playlist.sidx.byterange
  3296. })
  3297. }, fin);
  3298. });
  3299. }
  3300. dispose() {
  3301. this.trigger('dispose');
  3302. this.stopRequest();
  3303. this.loadedPlaylists_ = {};
  3304. window$1.clearTimeout(this.minimumUpdatePeriodTimeout_);
  3305. window$1.clearTimeout(this.mediaRequest_);
  3306. window$1.clearTimeout(this.mediaUpdateTimeout);
  3307. this.mediaUpdateTimeout = null;
  3308. this.mediaRequest_ = null;
  3309. this.minimumUpdatePeriodTimeout_ = null;
  3310. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  3311. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  3312. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  3313. }
  3314. this.off();
  3315. }
  3316. hasPendingRequest() {
  3317. return this.request || this.mediaRequest_;
  3318. }
  3319. stopRequest() {
  3320. if (this.request) {
  3321. const oldRequest = this.request;
  3322. this.request = null;
  3323. oldRequest.onreadystatechange = null;
  3324. oldRequest.abort();
  3325. }
  3326. }
  3327. media(playlist) {
  3328. // getter
  3329. if (!playlist) {
  3330. return this.media_;
  3331. } // setter
  3332. if (this.state === 'HAVE_NOTHING') {
  3333. throw new Error('Cannot switch media playlist from ' + this.state);
  3334. }
  3335. const startingState = this.state; // find the playlist object if the target playlist has been specified by URI
  3336. if (typeof playlist === 'string') {
  3337. if (!this.mainPlaylistLoader_.main.playlists[playlist]) {
  3338. throw new Error('Unknown playlist URI: ' + playlist);
  3339. }
  3340. playlist = this.mainPlaylistLoader_.main.playlists[playlist];
  3341. }
  3342. const mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
  3343. if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
  3344. this.state = 'HAVE_METADATA';
  3345. this.media_ = playlist; // trigger media change if the active media has been updated
  3346. if (mediaChange) {
  3347. this.trigger('mediachanging');
  3348. this.trigger('mediachange');
  3349. }
  3350. return;
  3351. } // switching to the active playlist is a no-op
  3352. if (!mediaChange) {
  3353. return;
  3354. } // switching from an already loaded playlist
  3355. if (this.media_) {
  3356. this.trigger('mediachanging');
  3357. }
  3358. this.addSidxSegments_(playlist, startingState, sidxChanged => {
  3359. // everything is ready just continue to haveMetadata
  3360. this.haveMetadata({
  3361. startingState,
  3362. playlist
  3363. });
  3364. });
  3365. }
  3366. haveMetadata({
  3367. startingState,
  3368. playlist
  3369. }) {
  3370. this.state = 'HAVE_METADATA';
  3371. this.loadedPlaylists_[playlist.id] = playlist;
  3372. this.mediaRequest_ = null; // This will trigger loadedplaylist
  3373. this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
  3374. // to resolve setup of media groups
  3375. if (startingState === 'HAVE_MAIN_MANIFEST') {
  3376. this.trigger('loadedmetadata');
  3377. } else {
  3378. // trigger media change if the active media has been updated
  3379. this.trigger('mediachange');
  3380. }
  3381. }
  3382. pause() {
  3383. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  3384. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  3385. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  3386. }
  3387. this.stopRequest();
  3388. window$1.clearTimeout(this.mediaUpdateTimeout);
  3389. this.mediaUpdateTimeout = null;
  3390. if (this.isMain_) {
  3391. window$1.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_);
  3392. this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
  3393. }
  3394. if (this.state === 'HAVE_NOTHING') {
  3395. // If we pause the loader before any data has been retrieved, its as if we never
  3396. // started, so reset to an unstarted state.
  3397. this.started = false;
  3398. }
  3399. }
  3400. load(isFinalRendition) {
  3401. window$1.clearTimeout(this.mediaUpdateTimeout);
  3402. this.mediaUpdateTimeout = null;
  3403. const media = this.media();
  3404. if (isFinalRendition) {
  3405. const delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;
  3406. this.mediaUpdateTimeout = window$1.setTimeout(() => this.load(), delay);
  3407. return;
  3408. } // because the playlists are internal to the manifest, load should either load the
  3409. // main manifest, or do nothing but trigger an event
  3410. if (!this.started) {
  3411. this.start();
  3412. return;
  3413. }
  3414. if (media && !media.endList) {
  3415. // Check to see if this is the main loader and the MUP was cleared (this happens
  3416. // when the loader was paused). `media` should be set at this point since one is always
  3417. // set during `start()`.
  3418. if (this.isMain_ && !this.minimumUpdatePeriodTimeout_) {
  3419. // Trigger minimumUpdatePeriod to refresh the main manifest
  3420. this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
  3421. this.updateMinimumUpdatePeriodTimeout_();
  3422. }
  3423. this.trigger('mediaupdatetimeout');
  3424. } else {
  3425. this.trigger('loadedplaylist');
  3426. }
  3427. }
  3428. start() {
  3429. this.started = true; // We don't need to request the main manifest again
  3430. // Call this asynchronously to match the xhr request behavior below
  3431. if (!this.isMain_) {
  3432. this.mediaRequest_ = window$1.setTimeout(() => this.haveMain_(), 0);
  3433. return;
  3434. }
  3435. this.requestMain_((req, mainChanged) => {
  3436. this.haveMain_();
  3437. if (!this.hasPendingRequest() && !this.media_) {
  3438. this.media(this.mainPlaylistLoader_.main.playlists[0]);
  3439. }
  3440. });
  3441. }
  3442. requestMain_(cb) {
  3443. this.request = this.vhs_.xhr({
  3444. uri: this.mainPlaylistLoader_.srcUrl,
  3445. withCredentials: this.withCredentials
  3446. }, (error, req) => {
  3447. if (this.requestErrored_(error, req)) {
  3448. if (this.state === 'HAVE_NOTHING') {
  3449. this.started = false;
  3450. }
  3451. return;
  3452. }
  3453. const mainChanged = req.responseText !== this.mainPlaylistLoader_.mainXml_;
  3454. this.mainPlaylistLoader_.mainXml_ = req.responseText;
  3455. if (req.responseHeaders && req.responseHeaders.date) {
  3456. this.mainLoaded_ = Date.parse(req.responseHeaders.date);
  3457. } else {
  3458. this.mainLoaded_ = Date.now();
  3459. }
  3460. this.mainPlaylistLoader_.srcUrl = resolveManifestRedirect(this.mainPlaylistLoader_.srcUrl, req);
  3461. if (mainChanged) {
  3462. this.handleMain_();
  3463. this.syncClientServerClock_(() => {
  3464. return cb(req, mainChanged);
  3465. });
  3466. return;
  3467. }
  3468. return cb(req, mainChanged);
  3469. });
  3470. }
  3471. /**
  3472. * Parses the main xml for UTCTiming node to sync the client clock to the server
  3473. * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
  3474. *
  3475. * @param {Function} done
  3476. * Function to call when clock sync has completed
  3477. */
  3478. syncClientServerClock_(done) {
  3479. const utcTiming = parseUTCTiming(this.mainPlaylistLoader_.mainXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the
  3480. // server clock
  3481. if (utcTiming === null) {
  3482. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  3483. return done();
  3484. }
  3485. if (utcTiming.method === 'DIRECT') {
  3486. this.mainPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
  3487. return done();
  3488. }
  3489. this.request = this.vhs_.xhr({
  3490. uri: resolveUrl(this.mainPlaylistLoader_.srcUrl, utcTiming.value),
  3491. method: utcTiming.method,
  3492. withCredentials: this.withCredentials
  3493. }, (error, req) => {
  3494. // disposed
  3495. if (!this.request) {
  3496. return;
  3497. }
  3498. if (error) {
  3499. // sync request failed, fall back to using date header from mpd
  3500. // TODO: log warning
  3501. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  3502. return done();
  3503. }
  3504. let serverTime;
  3505. if (utcTiming.method === 'HEAD') {
  3506. if (!req.responseHeaders || !req.responseHeaders.date) {
  3507. // expected date header not preset, fall back to using date header from mpd
  3508. // TODO: log warning
  3509. serverTime = this.mainLoaded_;
  3510. } else {
  3511. serverTime = Date.parse(req.responseHeaders.date);
  3512. }
  3513. } else {
  3514. serverTime = Date.parse(req.responseText);
  3515. }
  3516. this.mainPlaylistLoader_.clientOffset_ = serverTime - Date.now();
  3517. done();
  3518. });
  3519. }
  3520. haveMain_() {
  3521. this.state = 'HAVE_MAIN_MANIFEST';
  3522. if (this.isMain_) {
  3523. // We have the main playlist at this point, so
  3524. // trigger this to allow PlaylistController
  3525. // to make an initial playlist selection
  3526. this.trigger('loadedplaylist');
  3527. } else if (!this.media_) {
  3528. // no media playlist was specifically selected so select
  3529. // the one the child playlist loader was created with
  3530. this.media(this.childPlaylist_);
  3531. }
  3532. }
  3533. handleMain_() {
  3534. // clear media request
  3535. this.mediaRequest_ = null;
  3536. const oldMain = this.mainPlaylistLoader_.main;
  3537. let newMain = parseMainXml({
  3538. mainXml: this.mainPlaylistLoader_.mainXml_,
  3539. srcUrl: this.mainPlaylistLoader_.srcUrl,
  3540. clientOffset: this.mainPlaylistLoader_.clientOffset_,
  3541. sidxMapping: this.mainPlaylistLoader_.sidxMapping_,
  3542. previousManifest: oldMain
  3543. }); // if we have an old main to compare the new main against
  3544. if (oldMain) {
  3545. newMain = updateMain(oldMain, newMain, this.mainPlaylistLoader_.sidxMapping_);
  3546. } // only update main if we have a new main
  3547. this.mainPlaylistLoader_.main = newMain ? newMain : oldMain;
  3548. const location = this.mainPlaylistLoader_.main.locations && this.mainPlaylistLoader_.main.locations[0];
  3549. if (location && location !== this.mainPlaylistLoader_.srcUrl) {
  3550. this.mainPlaylistLoader_.srcUrl = location;
  3551. }
  3552. if (!oldMain || newMain && newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  3553. this.updateMinimumUpdatePeriodTimeout_();
  3554. }
  3555. this.addEventStreamToMetadataTrack_(newMain);
  3556. return Boolean(newMain);
  3557. }
  3558. updateMinimumUpdatePeriodTimeout_() {
  3559. const mpl = this.mainPlaylistLoader_; // cancel any pending creation of mup on media
  3560. // a new one will be added if needed.
  3561. if (mpl.createMupOnMedia_) {
  3562. mpl.off('loadedmetadata', mpl.createMupOnMedia_);
  3563. mpl.createMupOnMedia_ = null;
  3564. } // clear any pending timeouts
  3565. if (mpl.minimumUpdatePeriodTimeout_) {
  3566. window$1.clearTimeout(mpl.minimumUpdatePeriodTimeout_);
  3567. mpl.minimumUpdatePeriodTimeout_ = null;
  3568. }
  3569. let mup = mpl.main && mpl.main.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current
  3570. // MPD has no future validity, so a new one will need to be acquired when new
  3571. // media segments are to be made available. Thus, we use the target duration
  3572. // in this case
  3573. if (mup === 0) {
  3574. if (mpl.media()) {
  3575. mup = mpl.media().targetDuration * 1000;
  3576. } else {
  3577. mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
  3578. mpl.one('loadedmetadata', mpl.createMupOnMedia_);
  3579. }
  3580. } // if minimumUpdatePeriod is invalid or <= zero, which
  3581. // can happen when a live video becomes VOD. skip timeout
  3582. // creation.
  3583. if (typeof mup !== 'number' || mup <= 0) {
  3584. if (mup < 0) {
  3585. this.logger_(`found invalid minimumUpdatePeriod of ${mup}, not setting a timeout`);
  3586. }
  3587. return;
  3588. }
  3589. this.createMUPTimeout_(mup);
  3590. }
  3591. createMUPTimeout_(mup) {
  3592. const mpl = this.mainPlaylistLoader_;
  3593. mpl.minimumUpdatePeriodTimeout_ = window$1.setTimeout(() => {
  3594. mpl.minimumUpdatePeriodTimeout_ = null;
  3595. mpl.trigger('minimumUpdatePeriod');
  3596. mpl.createMUPTimeout_(mup);
  3597. }, mup);
  3598. }
  3599. /**
  3600. * Sends request to refresh the main xml and updates the parsed main manifest
  3601. */
  3602. refreshXml_() {
  3603. this.requestMain_((req, mainChanged) => {
  3604. if (!mainChanged) {
  3605. return;
  3606. }
  3607. if (this.media_) {
  3608. this.media_ = this.mainPlaylistLoader_.main.playlists[this.media_.id];
  3609. } // This will filter out updated sidx info from the mapping
  3610. this.mainPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.sidxMapping_);
  3611. this.addSidxSegments_(this.media(), this.state, sidxChanged => {
  3612. // TODO: do we need to reload the current playlist?
  3613. this.refreshMedia_(this.media().id);
  3614. });
  3615. });
  3616. }
  3617. /**
  3618. * Refreshes the media playlist by re-parsing the main xml and updating playlist
  3619. * references. If this is an alternate loader, the updated parsed manifest is retrieved
  3620. * from the main loader.
  3621. */
  3622. refreshMedia_(mediaID) {
  3623. if (!mediaID) {
  3624. throw new Error('refreshMedia_ must take a media id');
  3625. } // for main we have to reparse the main xml
  3626. // to re-create segments based on current timing values
  3627. // which may change media. We only skip updating the main manifest
  3628. // if this is the first time this.media_ is being set.
  3629. // as main was just parsed in that case.
  3630. if (this.media_ && this.isMain_) {
  3631. this.handleMain_();
  3632. }
  3633. const playlists = this.mainPlaylistLoader_.main.playlists;
  3634. const mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
  3635. if (mediaChanged) {
  3636. this.media_ = playlists[mediaID];
  3637. } else {
  3638. this.trigger('playlistunchanged');
  3639. }
  3640. if (!this.mediaUpdateTimeout) {
  3641. const createMediaUpdateTimeout = () => {
  3642. if (this.media().endList) {
  3643. return;
  3644. }
  3645. this.mediaUpdateTimeout = window$1.setTimeout(() => {
  3646. this.trigger('mediaupdatetimeout');
  3647. createMediaUpdateTimeout();
  3648. }, refreshDelay(this.media(), Boolean(mediaChanged)));
  3649. };
  3650. createMediaUpdateTimeout();
  3651. }
  3652. this.trigger('loadedplaylist');
  3653. }
  3654. /**
  3655. * Takes eventstream data from a parsed DASH manifest and adds it to the metadata text track.
  3656. *
  3657. * @param {manifest} newMain the newly parsed manifest
  3658. */
  3659. addEventStreamToMetadataTrack_(newMain) {
  3660. // Only add new event stream metadata if we have a new manifest.
  3661. if (newMain && this.mainPlaylistLoader_.main.eventStream) {
  3662. // convert EventStream to ID3-like data.
  3663. const metadataArray = this.mainPlaylistLoader_.main.eventStream.map(eventStreamNode => {
  3664. return {
  3665. cueTime: eventStreamNode.start,
  3666. frames: [{
  3667. data: eventStreamNode.messageData
  3668. }]
  3669. };
  3670. });
  3671. this.addMetadataToTextTrack('EventStream', metadataArray, this.mainPlaylistLoader_.main.duration);
  3672. }
  3673. }
  3674. /**
  3675. * Returns the key ID set from a playlist
  3676. *
  3677. * @param {playlist} playlist to fetch the key ID set from.
  3678. * @return a Set of 32 digit hex strings that represent the unique keyIds for that playlist.
  3679. */
  3680. getKeyIdSet(playlist) {
  3681. if (playlist.contentProtection) {
  3682. const keyIds = new Set();
  3683. for (const keysystem in playlist.contentProtection) {
  3684. const defaultKID = playlist.contentProtection[keysystem].attributes['cenc:default_KID'];
  3685. if (defaultKID) {
  3686. // DASH keyIds are separated by dashes.
  3687. keyIds.add(defaultKID.replace(/-/g, '').toLowerCase());
  3688. }
  3689. }
  3690. return keyIds;
  3691. }
  3692. }
  3693. }
  3694. var Config = {
  3695. GOAL_BUFFER_LENGTH: 30,
  3696. MAX_GOAL_BUFFER_LENGTH: 60,
  3697. BACK_BUFFER_LENGTH: 30,
  3698. GOAL_BUFFER_LENGTH_RATE: 1,
  3699. // 0.5 MB/s
  3700. INITIAL_BANDWIDTH: 4194304,
  3701. // A fudge factor to apply to advertised playlist bitrates to account for
  3702. // temporary flucations in client bandwidth
  3703. BANDWIDTH_VARIANCE: 1.2,
  3704. // How much of the buffer must be filled before we consider upswitching
  3705. BUFFER_LOW_WATER_LINE: 0,
  3706. MAX_BUFFER_LOW_WATER_LINE: 30,
  3707. // TODO: Remove this when experimentalBufferBasedABR is removed
  3708. EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
  3709. BUFFER_LOW_WATER_LINE_RATE: 1,
  3710. // If the buffer is greater than the high water line, we won't switch down
  3711. BUFFER_HIGH_WATER_LINE: 30
  3712. };
  3713. const stringToArrayBuffer = string => {
  3714. const view = new Uint8Array(new ArrayBuffer(string.length));
  3715. for (let i = 0; i < string.length; i++) {
  3716. view[i] = string.charCodeAt(i);
  3717. }
  3718. return view.buffer;
  3719. };
  3720. /* global Blob, BlobBuilder, Worker */
  3721. // unify worker interface
  3722. const browserWorkerPolyFill = function (workerObj) {
  3723. // node only supports on/off
  3724. workerObj.on = workerObj.addEventListener;
  3725. workerObj.off = workerObj.removeEventListener;
  3726. return workerObj;
  3727. };
  3728. const createObjectURL = function (str) {
  3729. try {
  3730. return URL.createObjectURL(new Blob([str], {
  3731. type: 'application/javascript'
  3732. }));
  3733. } catch (e) {
  3734. const blob = new BlobBuilder();
  3735. blob.append(str);
  3736. return URL.createObjectURL(blob.getBlob());
  3737. }
  3738. };
  3739. const factory = function (code) {
  3740. return function () {
  3741. const objectUrl = createObjectURL(code);
  3742. const worker = browserWorkerPolyFill(new Worker(objectUrl));
  3743. worker.objURL = objectUrl;
  3744. const terminate = worker.terminate;
  3745. worker.on = worker.addEventListener;
  3746. worker.off = worker.removeEventListener;
  3747. worker.terminate = function () {
  3748. URL.revokeObjectURL(objectUrl);
  3749. return terminate.call(this);
  3750. };
  3751. return worker;
  3752. };
  3753. };
  3754. const transform = function (code) {
  3755. return `var browserWorkerPolyFill = ${browserWorkerPolyFill.toString()};\n` + 'browserWorkerPolyFill(self);\n' + code;
  3756. };
  3757. const getWorkerString = function (fn) {
  3758. return fn.toString().replace(/^function.+?{/, '').slice(0, -1);
  3759. };
  3760. /* rollup-plugin-worker-factory start for worker!/home/runner/work/http-streaming/http-streaming/src/transmuxer-worker.js */
  3761. const workerCode$1 = transform(getWorkerString(function () {
  3762. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  3763. /**
  3764. * mux.js
  3765. *
  3766. * Copyright (c) Brightcove
  3767. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  3768. *
  3769. * A lightweight readable stream implemention that handles event dispatching.
  3770. * Objects that inherit from streams should call init in their constructors.
  3771. */
  3772. var Stream$8 = function () {
  3773. this.init = function () {
  3774. var listeners = {};
  3775. /**
  3776. * Add a listener for a specified event type.
  3777. * @param type {string} the event name
  3778. * @param listener {function} the callback to be invoked when an event of
  3779. * the specified type occurs
  3780. */
  3781. this.on = function (type, listener) {
  3782. if (!listeners[type]) {
  3783. listeners[type] = [];
  3784. }
  3785. listeners[type] = listeners[type].concat(listener);
  3786. };
  3787. /**
  3788. * Remove a listener for a specified event type.
  3789. * @param type {string} the event name
  3790. * @param listener {function} a function previously registered for this
  3791. * type of event through `on`
  3792. */
  3793. this.off = function (type, listener) {
  3794. var index;
  3795. if (!listeners[type]) {
  3796. return false;
  3797. }
  3798. index = listeners[type].indexOf(listener);
  3799. listeners[type] = listeners[type].slice();
  3800. listeners[type].splice(index, 1);
  3801. return index > -1;
  3802. };
  3803. /**
  3804. * Trigger an event of the specified type on this stream. Any additional
  3805. * arguments to this function are passed as parameters to event listeners.
  3806. * @param type {string} the event name
  3807. */
  3808. this.trigger = function (type) {
  3809. var callbacks, i, length, args;
  3810. callbacks = listeners[type];
  3811. if (!callbacks) {
  3812. return;
  3813. } // Slicing the arguments on every invocation of this method
  3814. // can add a significant amount of overhead. Avoid the
  3815. // intermediate object creation for the common case of a
  3816. // single callback argument
  3817. if (arguments.length === 2) {
  3818. length = callbacks.length;
  3819. for (i = 0; i < length; ++i) {
  3820. callbacks[i].call(this, arguments[1]);
  3821. }
  3822. } else {
  3823. args = [];
  3824. i = arguments.length;
  3825. for (i = 1; i < arguments.length; ++i) {
  3826. args.push(arguments[i]);
  3827. }
  3828. length = callbacks.length;
  3829. for (i = 0; i < length; ++i) {
  3830. callbacks[i].apply(this, args);
  3831. }
  3832. }
  3833. };
  3834. /**
  3835. * Destroys the stream and cleans up.
  3836. */
  3837. this.dispose = function () {
  3838. listeners = {};
  3839. };
  3840. };
  3841. };
  3842. /**
  3843. * Forwards all `data` events on this stream to the destination stream. The
  3844. * destination stream should provide a method `push` to receive the data
  3845. * events as they arrive.
  3846. * @param destination {stream} the stream that will receive all `data` events
  3847. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  3848. * when the current stream emits a 'done' event
  3849. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  3850. */
  3851. Stream$8.prototype.pipe = function (destination) {
  3852. this.on('data', function (data) {
  3853. destination.push(data);
  3854. });
  3855. this.on('done', function (flushSource) {
  3856. destination.flush(flushSource);
  3857. });
  3858. this.on('partialdone', function (flushSource) {
  3859. destination.partialFlush(flushSource);
  3860. });
  3861. this.on('endedtimeline', function (flushSource) {
  3862. destination.endTimeline(flushSource);
  3863. });
  3864. this.on('reset', function (flushSource) {
  3865. destination.reset(flushSource);
  3866. });
  3867. return destination;
  3868. }; // Default stream functions that are expected to be overridden to perform
  3869. // actual work. These are provided by the prototype as a sort of no-op
  3870. // implementation so that we don't have to check for their existence in the
  3871. // `pipe` function above.
  3872. Stream$8.prototype.push = function (data) {
  3873. this.trigger('data', data);
  3874. };
  3875. Stream$8.prototype.flush = function (flushSource) {
  3876. this.trigger('done', flushSource);
  3877. };
  3878. Stream$8.prototype.partialFlush = function (flushSource) {
  3879. this.trigger('partialdone', flushSource);
  3880. };
  3881. Stream$8.prototype.endTimeline = function (flushSource) {
  3882. this.trigger('endedtimeline', flushSource);
  3883. };
  3884. Stream$8.prototype.reset = function (flushSource) {
  3885. this.trigger('reset', flushSource);
  3886. };
  3887. var stream = Stream$8;
  3888. var MAX_UINT32$1 = Math.pow(2, 32);
  3889. var getUint64$3 = function (uint8) {
  3890. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  3891. var value;
  3892. if (dv.getBigUint64) {
  3893. value = dv.getBigUint64(0);
  3894. if (value < Number.MAX_SAFE_INTEGER) {
  3895. return Number(value);
  3896. }
  3897. return value;
  3898. }
  3899. return dv.getUint32(0) * MAX_UINT32$1 + dv.getUint32(4);
  3900. };
  3901. var numbers = {
  3902. getUint64: getUint64$3,
  3903. MAX_UINT32: MAX_UINT32$1
  3904. };
  3905. /**
  3906. * mux.js
  3907. *
  3908. * Copyright (c) Brightcove
  3909. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  3910. *
  3911. * Functions that generate fragmented MP4s suitable for use with Media
  3912. * Source Extensions.
  3913. */
  3914. var MAX_UINT32 = numbers.MAX_UINT32;
  3915. 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
  3916. (function () {
  3917. var i;
  3918. types = {
  3919. avc1: [],
  3920. // codingname
  3921. avcC: [],
  3922. btrt: [],
  3923. dinf: [],
  3924. dref: [],
  3925. esds: [],
  3926. ftyp: [],
  3927. hdlr: [],
  3928. mdat: [],
  3929. mdhd: [],
  3930. mdia: [],
  3931. mfhd: [],
  3932. minf: [],
  3933. moof: [],
  3934. moov: [],
  3935. mp4a: [],
  3936. // codingname
  3937. mvex: [],
  3938. mvhd: [],
  3939. pasp: [],
  3940. sdtp: [],
  3941. smhd: [],
  3942. stbl: [],
  3943. stco: [],
  3944. stsc: [],
  3945. stsd: [],
  3946. stsz: [],
  3947. stts: [],
  3948. styp: [],
  3949. tfdt: [],
  3950. tfhd: [],
  3951. traf: [],
  3952. trak: [],
  3953. trun: [],
  3954. trex: [],
  3955. tkhd: [],
  3956. vmhd: []
  3957. }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  3958. // don't throw an error
  3959. if (typeof Uint8Array === 'undefined') {
  3960. return;
  3961. }
  3962. for (i in types) {
  3963. if (types.hasOwnProperty(i)) {
  3964. types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  3965. }
  3966. }
  3967. MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
  3968. AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
  3969. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  3970. VIDEO_HDLR = new Uint8Array([0x00, // version 0
  3971. 0x00, 0x00, 0x00, // flags
  3972. 0x00, 0x00, 0x00, 0x00, // pre_defined
  3973. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  3974. 0x00, 0x00, 0x00, 0x00, // reserved
  3975. 0x00, 0x00, 0x00, 0x00, // reserved
  3976. 0x00, 0x00, 0x00, 0x00, // reserved
  3977. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  3978. ]);
  3979. AUDIO_HDLR = new Uint8Array([0x00, // version 0
  3980. 0x00, 0x00, 0x00, // flags
  3981. 0x00, 0x00, 0x00, 0x00, // pre_defined
  3982. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  3983. 0x00, 0x00, 0x00, 0x00, // reserved
  3984. 0x00, 0x00, 0x00, 0x00, // reserved
  3985. 0x00, 0x00, 0x00, 0x00, // reserved
  3986. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  3987. ]);
  3988. HDLR_TYPES = {
  3989. video: VIDEO_HDLR,
  3990. audio: AUDIO_HDLR
  3991. };
  3992. DREF = new Uint8Array([0x00, // version 0
  3993. 0x00, 0x00, 0x00, // flags
  3994. 0x00, 0x00, 0x00, 0x01, // entry_count
  3995. 0x00, 0x00, 0x00, 0x0c, // entry_size
  3996. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  3997. 0x00, // version 0
  3998. 0x00, 0x00, 0x01 // entry_flags
  3999. ]);
  4000. SMHD = new Uint8Array([0x00, // version
  4001. 0x00, 0x00, 0x00, // flags
  4002. 0x00, 0x00, // balance, 0 means centered
  4003. 0x00, 0x00 // reserved
  4004. ]);
  4005. STCO = new Uint8Array([0x00, // version
  4006. 0x00, 0x00, 0x00, // flags
  4007. 0x00, 0x00, 0x00, 0x00 // entry_count
  4008. ]);
  4009. STSC = STCO;
  4010. STSZ = new Uint8Array([0x00, // version
  4011. 0x00, 0x00, 0x00, // flags
  4012. 0x00, 0x00, 0x00, 0x00, // sample_size
  4013. 0x00, 0x00, 0x00, 0x00 // sample_count
  4014. ]);
  4015. STTS = STCO;
  4016. VMHD = new Uint8Array([0x00, // version
  4017. 0x00, 0x00, 0x01, // flags
  4018. 0x00, 0x00, // graphicsmode
  4019. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  4020. ]);
  4021. })();
  4022. box = function (type) {
  4023. var payload = [],
  4024. size = 0,
  4025. i,
  4026. result,
  4027. view;
  4028. for (i = 1; i < arguments.length; i++) {
  4029. payload.push(arguments[i]);
  4030. }
  4031. i = payload.length; // calculate the total size we need to allocate
  4032. while (i--) {
  4033. size += payload[i].byteLength;
  4034. }
  4035. result = new Uint8Array(size + 8);
  4036. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  4037. view.setUint32(0, result.byteLength);
  4038. result.set(type, 4); // copy the payload into the result
  4039. for (i = 0, size = 8; i < payload.length; i++) {
  4040. result.set(payload[i], size);
  4041. size += payload[i].byteLength;
  4042. }
  4043. return result;
  4044. };
  4045. dinf = function () {
  4046. return box(types.dinf, box(types.dref, DREF));
  4047. };
  4048. esds = function (track) {
  4049. return box(types.esds, new Uint8Array([0x00, // version
  4050. 0x00, 0x00, 0x00, // flags
  4051. // ES_Descriptor
  4052. 0x03, // tag, ES_DescrTag
  4053. 0x19, // length
  4054. 0x00, 0x00, // ES_ID
  4055. 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
  4056. // DecoderConfigDescriptor
  4057. 0x04, // tag, DecoderConfigDescrTag
  4058. 0x11, // length
  4059. 0x40, // object type
  4060. 0x15, // streamType
  4061. 0x00, 0x06, 0x00, // bufferSizeDB
  4062. 0x00, 0x00, 0xda, 0xc0, // maxBitrate
  4063. 0x00, 0x00, 0xda, 0xc0, // avgBitrate
  4064. // DecoderSpecificInfo
  4065. 0x05, // tag, DecoderSpecificInfoTag
  4066. 0x02, // length
  4067. // ISO/IEC 14496-3, AudioSpecificConfig
  4068. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  4069. track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
  4070. ]));
  4071. };
  4072. ftyp = function () {
  4073. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  4074. };
  4075. hdlr = function (type) {
  4076. return box(types.hdlr, HDLR_TYPES[type]);
  4077. };
  4078. mdat = function (data) {
  4079. return box(types.mdat, data);
  4080. };
  4081. mdhd = function (track) {
  4082. var result = new Uint8Array([0x00, // version 0
  4083. 0x00, 0x00, 0x00, // flags
  4084. 0x00, 0x00, 0x00, 0x02, // creation_time
  4085. 0x00, 0x00, 0x00, 0x03, // modification_time
  4086. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  4087. track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF, // duration
  4088. 0x55, 0xc4, // 'und' language (undetermined)
  4089. 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
  4090. // defined. The sample rate can be parsed out of an ADTS header, for
  4091. // instance.
  4092. if (track.samplerate) {
  4093. result[12] = track.samplerate >>> 24 & 0xFF;
  4094. result[13] = track.samplerate >>> 16 & 0xFF;
  4095. result[14] = track.samplerate >>> 8 & 0xFF;
  4096. result[15] = track.samplerate & 0xFF;
  4097. }
  4098. return box(types.mdhd, result);
  4099. };
  4100. mdia = function (track) {
  4101. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  4102. };
  4103. mfhd = function (sequenceNumber) {
  4104. return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
  4105. (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
  4106. ]));
  4107. };
  4108. minf = function (track) {
  4109. return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
  4110. };
  4111. moof = function (sequenceNumber, tracks) {
  4112. var trackFragments = [],
  4113. i = tracks.length; // build traf boxes for each track fragment
  4114. while (i--) {
  4115. trackFragments[i] = traf(tracks[i]);
  4116. }
  4117. return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
  4118. };
  4119. /**
  4120. * Returns a movie box.
  4121. * @param tracks {array} the tracks associated with this movie
  4122. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  4123. */
  4124. moov = function (tracks) {
  4125. var i = tracks.length,
  4126. boxes = [];
  4127. while (i--) {
  4128. boxes[i] = trak(tracks[i]);
  4129. }
  4130. return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
  4131. };
  4132. mvex = function (tracks) {
  4133. var i = tracks.length,
  4134. boxes = [];
  4135. while (i--) {
  4136. boxes[i] = trex(tracks[i]);
  4137. }
  4138. return box.apply(null, [types.mvex].concat(boxes));
  4139. };
  4140. mvhd = function (duration) {
  4141. var bytes = new Uint8Array([0x00, // version 0
  4142. 0x00, 0x00, 0x00, // flags
  4143. 0x00, 0x00, 0x00, 0x01, // creation_time
  4144. 0x00, 0x00, 0x00, 0x02, // modification_time
  4145. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  4146. (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF, // duration
  4147. 0x00, 0x01, 0x00, 0x00, // 1.0 rate
  4148. 0x01, 0x00, // 1.0 volume
  4149. 0x00, 0x00, // reserved
  4150. 0x00, 0x00, 0x00, 0x00, // reserved
  4151. 0x00, 0x00, 0x00, 0x00, // reserved
  4152. 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
  4153. 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
  4154. 0xff, 0xff, 0xff, 0xff // next_track_ID
  4155. ]);
  4156. return box(types.mvhd, bytes);
  4157. };
  4158. sdtp = function (track) {
  4159. var samples = track.samples || [],
  4160. bytes = new Uint8Array(4 + samples.length),
  4161. flags,
  4162. i; // leave the full box header (4 bytes) all zero
  4163. // write the sample table
  4164. for (i = 0; i < samples.length; i++) {
  4165. flags = samples[i].flags;
  4166. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  4167. }
  4168. return box(types.sdtp, bytes);
  4169. };
  4170. stbl = function (track) {
  4171. return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
  4172. };
  4173. (function () {
  4174. var videoSample, audioSample;
  4175. stsd = function (track) {
  4176. return box(types.stsd, new Uint8Array([0x00, // version 0
  4177. 0x00, 0x00, 0x00, // flags
  4178. 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
  4179. };
  4180. videoSample = function (track) {
  4181. var sps = track.sps || [],
  4182. pps = track.pps || [],
  4183. sequenceParameterSets = [],
  4184. pictureParameterSets = [],
  4185. i,
  4186. avc1Box; // assemble the SPSs
  4187. for (i = 0; i < sps.length; i++) {
  4188. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  4189. sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
  4190. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  4191. } // assemble the PPSs
  4192. for (i = 0; i < pps.length; i++) {
  4193. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  4194. pictureParameterSets.push(pps[i].byteLength & 0xFF);
  4195. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  4196. }
  4197. avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  4198. 0x00, 0x01, // data_reference_index
  4199. 0x00, 0x00, // pre_defined
  4200. 0x00, 0x00, // reserved
  4201. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  4202. (track.width & 0xff00) >> 8, track.width & 0xff, // width
  4203. (track.height & 0xff00) >> 8, track.height & 0xff, // height
  4204. 0x00, 0x48, 0x00, 0x00, // horizresolution
  4205. 0x00, 0x48, 0x00, 0x00, // vertresolution
  4206. 0x00, 0x00, 0x00, 0x00, // reserved
  4207. 0x00, 0x01, // frame_count
  4208. 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
  4209. 0x00, 0x18, // depth = 24
  4210. 0x11, 0x11 // pre_defined = -1
  4211. ]), box(types.avcC, new Uint8Array([0x01, // configurationVersion
  4212. track.profileIdc, // AVCProfileIndication
  4213. track.profileCompatibility, // profile_compatibility
  4214. track.levelIdc, // AVCLevelIndication
  4215. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  4216. ].concat([sps.length], // numOfSequenceParameterSets
  4217. sequenceParameterSets, // "SPS"
  4218. [pps.length], // numOfPictureParameterSets
  4219. pictureParameterSets // "PPS"
  4220. ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  4221. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  4222. 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
  4223. ]))];
  4224. if (track.sarRatio) {
  4225. var hSpacing = track.sarRatio[0],
  4226. vSpacing = track.sarRatio[1];
  4227. 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])));
  4228. }
  4229. return box.apply(null, avc1Box);
  4230. };
  4231. audioSample = function (track) {
  4232. return box(types.mp4a, new Uint8Array([// SampleEntry, ISO/IEC 14496-12
  4233. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  4234. 0x00, 0x01, // data_reference_index
  4235. // AudioSampleEntry, ISO/IEC 14496-12
  4236. 0x00, 0x00, 0x00, 0x00, // reserved
  4237. 0x00, 0x00, 0x00, 0x00, // reserved
  4238. (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff, // channelcount
  4239. (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff, // samplesize
  4240. 0x00, 0x00, // pre_defined
  4241. 0x00, 0x00, // reserved
  4242. (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
  4243. // MP4AudioSampleEntry, ISO/IEC 14496-14
  4244. ]), esds(track));
  4245. };
  4246. })();
  4247. tkhd = function (track) {
  4248. var result = new Uint8Array([0x00, // version 0
  4249. 0x00, 0x00, 0x07, // flags
  4250. 0x00, 0x00, 0x00, 0x00, // creation_time
  4251. 0x00, 0x00, 0x00, 0x00, // modification_time
  4252. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  4253. 0x00, 0x00, 0x00, 0x00, // reserved
  4254. (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF, // duration
  4255. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  4256. 0x00, 0x00, // layer
  4257. 0x00, 0x00, // alternate_group
  4258. 0x01, 0x00, // non-audio track volume
  4259. 0x00, 0x00, // reserved
  4260. 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
  4261. (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00, // width
  4262. (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
  4263. ]);
  4264. return box(types.tkhd, result);
  4265. };
  4266. /**
  4267. * Generate a track fragment (traf) box. A traf box collects metadata
  4268. * about tracks in a movie fragment (moof) box.
  4269. */
  4270. traf = function (track) {
  4271. var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
  4272. trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00, // version 0
  4273. 0x00, 0x00, 0x3a, // flags
  4274. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  4275. 0x00, 0x00, 0x00, 0x01, // sample_description_index
  4276. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  4277. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  4278. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  4279. ]));
  4280. upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / MAX_UINT32);
  4281. lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % MAX_UINT32);
  4282. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01, // version 1
  4283. 0x00, 0x00, 0x00, // flags
  4284. // baseMediaDecodeTime
  4285. 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
  4286. // the containing moof to the first payload byte of the associated
  4287. // mdat
  4288. dataOffset = 32 + // tfhd
  4289. 20 + // tfdt
  4290. 8 + // traf header
  4291. 16 + // mfhd
  4292. 8 + // moof header
  4293. 8; // mdat header
  4294. // audio tracks require less metadata
  4295. if (track.type === 'audio') {
  4296. trackFragmentRun = trun$1(track, dataOffset);
  4297. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
  4298. } // video tracks should contain an independent and disposable samples
  4299. // box (sdtp)
  4300. // generate one and adjust offsets to match
  4301. sampleDependencyTable = sdtp(track);
  4302. trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
  4303. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
  4304. };
  4305. /**
  4306. * Generate a track box.
  4307. * @param track {object} a track definition
  4308. * @return {Uint8Array} the track box
  4309. */
  4310. trak = function (track) {
  4311. track.duration = track.duration || 0xffffffff;
  4312. return box(types.trak, tkhd(track), mdia(track));
  4313. };
  4314. trex = function (track) {
  4315. var result = new Uint8Array([0x00, // version 0
  4316. 0x00, 0x00, 0x00, // flags
  4317. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  4318. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  4319. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  4320. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  4321. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  4322. ]); // the last two bytes of default_sample_flags is the sample
  4323. // degradation priority, a hint about the importance of this sample
  4324. // relative to others. Lower the degradation priority for all sample
  4325. // types other than video.
  4326. if (track.type !== 'video') {
  4327. result[result.length - 1] = 0x00;
  4328. }
  4329. return box(types.trex, result);
  4330. };
  4331. (function () {
  4332. var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
  4333. // duration is present for the first sample, it will be present for
  4334. // all subsequent samples.
  4335. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  4336. trunHeader = function (samples, offset) {
  4337. var durationPresent = 0,
  4338. sizePresent = 0,
  4339. flagsPresent = 0,
  4340. compositionTimeOffset = 0; // trun flag constants
  4341. if (samples.length) {
  4342. if (samples[0].duration !== undefined) {
  4343. durationPresent = 0x1;
  4344. }
  4345. if (samples[0].size !== undefined) {
  4346. sizePresent = 0x2;
  4347. }
  4348. if (samples[0].flags !== undefined) {
  4349. flagsPresent = 0x4;
  4350. }
  4351. if (samples[0].compositionTimeOffset !== undefined) {
  4352. compositionTimeOffset = 0x8;
  4353. }
  4354. }
  4355. return [0x00, // version 0
  4356. 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01, // flags
  4357. (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF, // sample_count
  4358. (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
  4359. ];
  4360. };
  4361. videoTrun = function (track, offset) {
  4362. var bytesOffest, bytes, header, samples, sample, i;
  4363. samples = track.samples || [];
  4364. offset += 8 + 12 + 16 * samples.length;
  4365. header = trunHeader(samples, offset);
  4366. bytes = new Uint8Array(header.length + samples.length * 16);
  4367. bytes.set(header);
  4368. bytesOffest = header.length;
  4369. for (i = 0; i < samples.length; i++) {
  4370. sample = samples[i];
  4371. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  4372. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  4373. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  4374. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  4375. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  4376. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  4377. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  4378. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  4379. bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
  4380. bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
  4381. bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
  4382. bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
  4383. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
  4384. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
  4385. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
  4386. bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
  4387. }
  4388. return box(types.trun, bytes);
  4389. };
  4390. audioTrun = function (track, offset) {
  4391. var bytes, bytesOffest, header, samples, sample, i;
  4392. samples = track.samples || [];
  4393. offset += 8 + 12 + 8 * samples.length;
  4394. header = trunHeader(samples, offset);
  4395. bytes = new Uint8Array(header.length + samples.length * 8);
  4396. bytes.set(header);
  4397. bytesOffest = header.length;
  4398. for (i = 0; i < samples.length; i++) {
  4399. sample = samples[i];
  4400. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  4401. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  4402. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  4403. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  4404. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  4405. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  4406. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  4407. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  4408. }
  4409. return box(types.trun, bytes);
  4410. };
  4411. trun$1 = function (track, offset) {
  4412. if (track.type === 'audio') {
  4413. return audioTrun(track, offset);
  4414. }
  4415. return videoTrun(track, offset);
  4416. };
  4417. })();
  4418. var mp4Generator = {
  4419. ftyp: ftyp,
  4420. mdat: mdat,
  4421. moof: moof,
  4422. moov: moov,
  4423. initSegment: function (tracks) {
  4424. var fileType = ftyp(),
  4425. movie = moov(tracks),
  4426. result;
  4427. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  4428. result.set(fileType);
  4429. result.set(movie, fileType.byteLength);
  4430. return result;
  4431. }
  4432. };
  4433. /**
  4434. * mux.js
  4435. *
  4436. * Copyright (c) Brightcove
  4437. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4438. */
  4439. // composed of the nal units that make up that frame
  4440. // Also keep track of cummulative data about the frame from the nal units such
  4441. // as the frame duration, starting pts, etc.
  4442. var groupNalsIntoFrames = function (nalUnits) {
  4443. var i,
  4444. currentNal,
  4445. currentFrame = [],
  4446. frames = []; // TODO added for LHLS, make sure this is OK
  4447. frames.byteLength = 0;
  4448. frames.nalCount = 0;
  4449. frames.duration = 0;
  4450. currentFrame.byteLength = 0;
  4451. for (i = 0; i < nalUnits.length; i++) {
  4452. currentNal = nalUnits[i]; // Split on 'aud'-type nal units
  4453. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  4454. // Since the very first nal unit is expected to be an AUD
  4455. // only push to the frames array when currentFrame is not empty
  4456. if (currentFrame.length) {
  4457. currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
  4458. frames.byteLength += currentFrame.byteLength;
  4459. frames.nalCount += currentFrame.length;
  4460. frames.duration += currentFrame.duration;
  4461. frames.push(currentFrame);
  4462. }
  4463. currentFrame = [currentNal];
  4464. currentFrame.byteLength = currentNal.data.byteLength;
  4465. currentFrame.pts = currentNal.pts;
  4466. currentFrame.dts = currentNal.dts;
  4467. } else {
  4468. // Specifically flag key frames for ease of use later
  4469. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  4470. currentFrame.keyFrame = true;
  4471. }
  4472. currentFrame.duration = currentNal.dts - currentFrame.dts;
  4473. currentFrame.byteLength += currentNal.data.byteLength;
  4474. currentFrame.push(currentNal);
  4475. }
  4476. } // For the last frame, use the duration of the previous frame if we
  4477. // have nothing better to go on
  4478. if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
  4479. currentFrame.duration = frames[frames.length - 1].duration;
  4480. } // Push the final frame
  4481. // TODO added for LHLS, make sure this is OK
  4482. frames.byteLength += currentFrame.byteLength;
  4483. frames.nalCount += currentFrame.length;
  4484. frames.duration += currentFrame.duration;
  4485. frames.push(currentFrame);
  4486. return frames;
  4487. }; // Convert an array of frames into an array of Gop with each Gop being composed
  4488. // of the frames that make up that Gop
  4489. // Also keep track of cummulative data about the Gop from the frames such as the
  4490. // Gop duration, starting pts, etc.
  4491. var groupFramesIntoGops = function (frames) {
  4492. var i,
  4493. currentFrame,
  4494. currentGop = [],
  4495. gops = []; // We must pre-set some of the values on the Gop since we
  4496. // keep running totals of these values
  4497. currentGop.byteLength = 0;
  4498. currentGop.nalCount = 0;
  4499. currentGop.duration = 0;
  4500. currentGop.pts = frames[0].pts;
  4501. currentGop.dts = frames[0].dts; // store some metadata about all the Gops
  4502. gops.byteLength = 0;
  4503. gops.nalCount = 0;
  4504. gops.duration = 0;
  4505. gops.pts = frames[0].pts;
  4506. gops.dts = frames[0].dts;
  4507. for (i = 0; i < frames.length; i++) {
  4508. currentFrame = frames[i];
  4509. if (currentFrame.keyFrame) {
  4510. // Since the very first frame is expected to be an keyframe
  4511. // only push to the gops array when currentGop is not empty
  4512. if (currentGop.length) {
  4513. gops.push(currentGop);
  4514. gops.byteLength += currentGop.byteLength;
  4515. gops.nalCount += currentGop.nalCount;
  4516. gops.duration += currentGop.duration;
  4517. }
  4518. currentGop = [currentFrame];
  4519. currentGop.nalCount = currentFrame.length;
  4520. currentGop.byteLength = currentFrame.byteLength;
  4521. currentGop.pts = currentFrame.pts;
  4522. currentGop.dts = currentFrame.dts;
  4523. currentGop.duration = currentFrame.duration;
  4524. } else {
  4525. currentGop.duration += currentFrame.duration;
  4526. currentGop.nalCount += currentFrame.length;
  4527. currentGop.byteLength += currentFrame.byteLength;
  4528. currentGop.push(currentFrame);
  4529. }
  4530. }
  4531. if (gops.length && currentGop.duration <= 0) {
  4532. currentGop.duration = gops[gops.length - 1].duration;
  4533. }
  4534. gops.byteLength += currentGop.byteLength;
  4535. gops.nalCount += currentGop.nalCount;
  4536. gops.duration += currentGop.duration; // push the final Gop
  4537. gops.push(currentGop);
  4538. return gops;
  4539. };
  4540. /*
  4541. * Search for the first keyframe in the GOPs and throw away all frames
  4542. * until that keyframe. Then extend the duration of the pulled keyframe
  4543. * and pull the PTS and DTS of the keyframe so that it covers the time
  4544. * range of the frames that were disposed.
  4545. *
  4546. * @param {Array} gops video GOPs
  4547. * @returns {Array} modified video GOPs
  4548. */
  4549. var extendFirstKeyFrame = function (gops) {
  4550. var currentGop;
  4551. if (!gops[0][0].keyFrame && gops.length > 1) {
  4552. // Remove the first GOP
  4553. currentGop = gops.shift();
  4554. gops.byteLength -= currentGop.byteLength;
  4555. gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
  4556. // first gop to cover the time period of the
  4557. // frames we just removed
  4558. gops[0][0].dts = currentGop.dts;
  4559. gops[0][0].pts = currentGop.pts;
  4560. gops[0][0].duration += currentGop.duration;
  4561. }
  4562. return gops;
  4563. };
  4564. /**
  4565. * Default sample object
  4566. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  4567. */
  4568. var createDefaultSample = function () {
  4569. return {
  4570. size: 0,
  4571. flags: {
  4572. isLeading: 0,
  4573. dependsOn: 1,
  4574. isDependedOn: 0,
  4575. hasRedundancy: 0,
  4576. degradationPriority: 0,
  4577. isNonSyncSample: 1
  4578. }
  4579. };
  4580. };
  4581. /*
  4582. * Collates information from a video frame into an object for eventual
  4583. * entry into an MP4 sample table.
  4584. *
  4585. * @param {Object} frame the video frame
  4586. * @param {Number} dataOffset the byte offset to position the sample
  4587. * @return {Object} object containing sample table info for a frame
  4588. */
  4589. var sampleForFrame = function (frame, dataOffset) {
  4590. var sample = createDefaultSample();
  4591. sample.dataOffset = dataOffset;
  4592. sample.compositionTimeOffset = frame.pts - frame.dts;
  4593. sample.duration = frame.duration;
  4594. sample.size = 4 * frame.length; // Space for nal unit size
  4595. sample.size += frame.byteLength;
  4596. if (frame.keyFrame) {
  4597. sample.flags.dependsOn = 2;
  4598. sample.flags.isNonSyncSample = 0;
  4599. }
  4600. return sample;
  4601. }; // generate the track's sample table from an array of gops
  4602. var generateSampleTable$1 = function (gops, baseDataOffset) {
  4603. var h,
  4604. i,
  4605. sample,
  4606. currentGop,
  4607. currentFrame,
  4608. dataOffset = baseDataOffset || 0,
  4609. samples = [];
  4610. for (h = 0; h < gops.length; h++) {
  4611. currentGop = gops[h];
  4612. for (i = 0; i < currentGop.length; i++) {
  4613. currentFrame = currentGop[i];
  4614. sample = sampleForFrame(currentFrame, dataOffset);
  4615. dataOffset += sample.size;
  4616. samples.push(sample);
  4617. }
  4618. }
  4619. return samples;
  4620. }; // generate the track's raw mdat data from an array of gops
  4621. var concatenateNalData = function (gops) {
  4622. var h,
  4623. i,
  4624. j,
  4625. currentGop,
  4626. currentFrame,
  4627. currentNal,
  4628. dataOffset = 0,
  4629. nalsByteLength = gops.byteLength,
  4630. numberOfNals = gops.nalCount,
  4631. totalByteLength = nalsByteLength + 4 * numberOfNals,
  4632. data = new Uint8Array(totalByteLength),
  4633. view = new DataView(data.buffer); // For each Gop..
  4634. for (h = 0; h < gops.length; h++) {
  4635. currentGop = gops[h]; // For each Frame..
  4636. for (i = 0; i < currentGop.length; i++) {
  4637. currentFrame = currentGop[i]; // For each NAL..
  4638. for (j = 0; j < currentFrame.length; j++) {
  4639. currentNal = currentFrame[j];
  4640. view.setUint32(dataOffset, currentNal.data.byteLength);
  4641. dataOffset += 4;
  4642. data.set(currentNal.data, dataOffset);
  4643. dataOffset += currentNal.data.byteLength;
  4644. }
  4645. }
  4646. }
  4647. return data;
  4648. }; // generate the track's sample table from a frame
  4649. var generateSampleTableForFrame = function (frame, baseDataOffset) {
  4650. var sample,
  4651. dataOffset = baseDataOffset || 0,
  4652. samples = [];
  4653. sample = sampleForFrame(frame, dataOffset);
  4654. samples.push(sample);
  4655. return samples;
  4656. }; // generate the track's raw mdat data from a frame
  4657. var concatenateNalDataForFrame = function (frame) {
  4658. var i,
  4659. currentNal,
  4660. dataOffset = 0,
  4661. nalsByteLength = frame.byteLength,
  4662. numberOfNals = frame.length,
  4663. totalByteLength = nalsByteLength + 4 * numberOfNals,
  4664. data = new Uint8Array(totalByteLength),
  4665. view = new DataView(data.buffer); // For each NAL..
  4666. for (i = 0; i < frame.length; i++) {
  4667. currentNal = frame[i];
  4668. view.setUint32(dataOffset, currentNal.data.byteLength);
  4669. dataOffset += 4;
  4670. data.set(currentNal.data, dataOffset);
  4671. dataOffset += currentNal.data.byteLength;
  4672. }
  4673. return data;
  4674. };
  4675. var frameUtils$1 = {
  4676. groupNalsIntoFrames: groupNalsIntoFrames,
  4677. groupFramesIntoGops: groupFramesIntoGops,
  4678. extendFirstKeyFrame: extendFirstKeyFrame,
  4679. generateSampleTable: generateSampleTable$1,
  4680. concatenateNalData: concatenateNalData,
  4681. generateSampleTableForFrame: generateSampleTableForFrame,
  4682. concatenateNalDataForFrame: concatenateNalDataForFrame
  4683. };
  4684. /**
  4685. * mux.js
  4686. *
  4687. * Copyright (c) Brightcove
  4688. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4689. */
  4690. var highPrefix = [33, 16, 5, 32, 164, 27];
  4691. var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  4692. var zeroFill = function (count) {
  4693. var a = [];
  4694. while (count--) {
  4695. a.push(0);
  4696. }
  4697. return a;
  4698. };
  4699. var makeTable = function (metaTable) {
  4700. return Object.keys(metaTable).reduce(function (obj, key) {
  4701. obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
  4702. return arr.concat(part);
  4703. }, []));
  4704. return obj;
  4705. }, {});
  4706. };
  4707. var silence;
  4708. var silence_1 = function () {
  4709. if (!silence) {
  4710. // Frames-of-silence to use for filling in missing AAC frames
  4711. var coneOfSilence = {
  4712. 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
  4713. 88200: [highPrefix, [231], zeroFill(170), [56]],
  4714. 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
  4715. 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
  4716. 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
  4717. 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
  4718. 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
  4719. 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
  4720. 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]],
  4721. 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]],
  4722. 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
  4723. };
  4724. silence = makeTable(coneOfSilence);
  4725. }
  4726. return silence;
  4727. };
  4728. /**
  4729. * mux.js
  4730. *
  4731. * Copyright (c) Brightcove
  4732. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4733. */
  4734. var ONE_SECOND_IN_TS$4 = 90000,
  4735. // 90kHz clock
  4736. secondsToVideoTs,
  4737. secondsToAudioTs,
  4738. videoTsToSeconds,
  4739. audioTsToSeconds,
  4740. audioTsToVideoTs,
  4741. videoTsToAudioTs,
  4742. metadataTsToSeconds;
  4743. secondsToVideoTs = function (seconds) {
  4744. return seconds * ONE_SECOND_IN_TS$4;
  4745. };
  4746. secondsToAudioTs = function (seconds, sampleRate) {
  4747. return seconds * sampleRate;
  4748. };
  4749. videoTsToSeconds = function (timestamp) {
  4750. return timestamp / ONE_SECOND_IN_TS$4;
  4751. };
  4752. audioTsToSeconds = function (timestamp, sampleRate) {
  4753. return timestamp / sampleRate;
  4754. };
  4755. audioTsToVideoTs = function (timestamp, sampleRate) {
  4756. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  4757. };
  4758. videoTsToAudioTs = function (timestamp, sampleRate) {
  4759. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  4760. };
  4761. /**
  4762. * Adjust ID3 tag or caption timing information by the timeline pts values
  4763. * (if keepOriginalTimestamps is false) and convert to seconds
  4764. */
  4765. metadataTsToSeconds = function (timestamp, timelineStartPts, keepOriginalTimestamps) {
  4766. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  4767. };
  4768. var clock$2 = {
  4769. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
  4770. secondsToVideoTs: secondsToVideoTs,
  4771. secondsToAudioTs: secondsToAudioTs,
  4772. videoTsToSeconds: videoTsToSeconds,
  4773. audioTsToSeconds: audioTsToSeconds,
  4774. audioTsToVideoTs: audioTsToVideoTs,
  4775. videoTsToAudioTs: videoTsToAudioTs,
  4776. metadataTsToSeconds: metadataTsToSeconds
  4777. };
  4778. /**
  4779. * mux.js
  4780. *
  4781. * Copyright (c) Brightcove
  4782. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4783. */
  4784. var coneOfSilence = silence_1;
  4785. var clock$1 = clock$2;
  4786. /**
  4787. * Sum the `byteLength` properties of the data in each AAC frame
  4788. */
  4789. var sumFrameByteLengths = function (array) {
  4790. var i,
  4791. currentObj,
  4792. sum = 0; // sum the byteLength's all each nal unit in the frame
  4793. for (i = 0; i < array.length; i++) {
  4794. currentObj = array[i];
  4795. sum += currentObj.data.byteLength;
  4796. }
  4797. return sum;
  4798. }; // Possibly pad (prefix) the audio track with silence if appending this track
  4799. // would lead to the introduction of a gap in the audio buffer
  4800. var prefixWithSilence = function (track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
  4801. var baseMediaDecodeTimeTs,
  4802. frameDuration = 0,
  4803. audioGapDuration = 0,
  4804. audioFillFrameCount = 0,
  4805. audioFillDuration = 0,
  4806. silentFrame,
  4807. i,
  4808. firstFrame;
  4809. if (!frames.length) {
  4810. return;
  4811. }
  4812. baseMediaDecodeTimeTs = clock$1.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
  4813. frameDuration = Math.ceil(clock$1.ONE_SECOND_IN_TS / (track.samplerate / 1024));
  4814. if (audioAppendStartTs && videoBaseMediaDecodeTime) {
  4815. // insert the shortest possible amount (audio gap or audio to video gap)
  4816. audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
  4817. audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
  4818. audioFillDuration = audioFillFrameCount * frameDuration;
  4819. } // don't attempt to fill gaps smaller than a single frame or larger
  4820. // than a half second
  4821. if (audioFillFrameCount < 1 || audioFillDuration > clock$1.ONE_SECOND_IN_TS / 2) {
  4822. return;
  4823. }
  4824. silentFrame = coneOfSilence()[track.samplerate];
  4825. if (!silentFrame) {
  4826. // we don't have a silent frame pregenerated for the sample rate, so use a frame
  4827. // from the content instead
  4828. silentFrame = frames[0].data;
  4829. }
  4830. for (i = 0; i < audioFillFrameCount; i++) {
  4831. firstFrame = frames[0];
  4832. frames.splice(0, 0, {
  4833. data: silentFrame,
  4834. dts: firstFrame.dts - frameDuration,
  4835. pts: firstFrame.pts - frameDuration
  4836. });
  4837. }
  4838. track.baseMediaDecodeTime -= Math.floor(clock$1.videoTsToAudioTs(audioFillDuration, track.samplerate));
  4839. return audioFillDuration;
  4840. }; // If the audio segment extends before the earliest allowed dts
  4841. // value, remove AAC frames until starts at or after the earliest
  4842. // allowed DTS so that we don't end up with a negative baseMedia-
  4843. // DecodeTime for the audio track
  4844. var trimAdtsFramesByEarliestDts = function (adtsFrames, track, earliestAllowedDts) {
  4845. if (track.minSegmentDts >= earliestAllowedDts) {
  4846. return adtsFrames;
  4847. } // We will need to recalculate the earliest segment Dts
  4848. track.minSegmentDts = Infinity;
  4849. return adtsFrames.filter(function (currentFrame) {
  4850. // If this is an allowed frame, keep it and record it's Dts
  4851. if (currentFrame.dts >= earliestAllowedDts) {
  4852. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  4853. track.minSegmentPts = track.minSegmentDts;
  4854. return true;
  4855. } // Otherwise, discard it
  4856. return false;
  4857. });
  4858. }; // generate the track's raw mdat data from an array of frames
  4859. var generateSampleTable = function (frames) {
  4860. var i,
  4861. currentFrame,
  4862. samples = [];
  4863. for (i = 0; i < frames.length; i++) {
  4864. currentFrame = frames[i];
  4865. samples.push({
  4866. size: currentFrame.data.byteLength,
  4867. duration: 1024 // For AAC audio, all samples contain 1024 samples
  4868. });
  4869. }
  4870. return samples;
  4871. }; // generate the track's sample table from an array of frames
  4872. var concatenateFrameData = function (frames) {
  4873. var i,
  4874. currentFrame,
  4875. dataOffset = 0,
  4876. data = new Uint8Array(sumFrameByteLengths(frames));
  4877. for (i = 0; i < frames.length; i++) {
  4878. currentFrame = frames[i];
  4879. data.set(currentFrame.data, dataOffset);
  4880. dataOffset += currentFrame.data.byteLength;
  4881. }
  4882. return data;
  4883. };
  4884. var audioFrameUtils$1 = {
  4885. prefixWithSilence: prefixWithSilence,
  4886. trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  4887. generateSampleTable: generateSampleTable,
  4888. concatenateFrameData: concatenateFrameData
  4889. };
  4890. /**
  4891. * mux.js
  4892. *
  4893. * Copyright (c) Brightcove
  4894. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4895. */
  4896. var ONE_SECOND_IN_TS$3 = clock$2.ONE_SECOND_IN_TS;
  4897. /**
  4898. * Store information about the start and end of the track and the
  4899. * duration for each frame/sample we process in order to calculate
  4900. * the baseMediaDecodeTime
  4901. */
  4902. var collectDtsInfo = function (track, data) {
  4903. if (typeof data.pts === 'number') {
  4904. if (track.timelineStartInfo.pts === undefined) {
  4905. track.timelineStartInfo.pts = data.pts;
  4906. }
  4907. if (track.minSegmentPts === undefined) {
  4908. track.minSegmentPts = data.pts;
  4909. } else {
  4910. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  4911. }
  4912. if (track.maxSegmentPts === undefined) {
  4913. track.maxSegmentPts = data.pts;
  4914. } else {
  4915. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  4916. }
  4917. }
  4918. if (typeof data.dts === 'number') {
  4919. if (track.timelineStartInfo.dts === undefined) {
  4920. track.timelineStartInfo.dts = data.dts;
  4921. }
  4922. if (track.minSegmentDts === undefined) {
  4923. track.minSegmentDts = data.dts;
  4924. } else {
  4925. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  4926. }
  4927. if (track.maxSegmentDts === undefined) {
  4928. track.maxSegmentDts = data.dts;
  4929. } else {
  4930. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  4931. }
  4932. }
  4933. };
  4934. /**
  4935. * Clear values used to calculate the baseMediaDecodeTime between
  4936. * tracks
  4937. */
  4938. var clearDtsInfo = function (track) {
  4939. delete track.minSegmentDts;
  4940. delete track.maxSegmentDts;
  4941. delete track.minSegmentPts;
  4942. delete track.maxSegmentPts;
  4943. };
  4944. /**
  4945. * Calculate the track's baseMediaDecodeTime based on the earliest
  4946. * DTS the transmuxer has ever seen and the minimum DTS for the
  4947. * current track
  4948. * @param track {object} track metadata configuration
  4949. * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
  4950. * in the source; false to adjust the first segment to start at 0.
  4951. */
  4952. var calculateTrackBaseMediaDecodeTime = function (track, keepOriginalTimestamps) {
  4953. var baseMediaDecodeTime,
  4954. scale,
  4955. minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
  4956. if (!keepOriginalTimestamps) {
  4957. minSegmentDts -= track.timelineStartInfo.dts;
  4958. } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  4959. // we want the start of the first segment to be placed
  4960. baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
  4961. baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
  4962. baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
  4963. if (track.type === 'audio') {
  4964. // Audio has a different clock equal to the sampling_rate so we need to
  4965. // scale the PTS values into the clock rate of the track
  4966. scale = track.samplerate / ONE_SECOND_IN_TS$3;
  4967. baseMediaDecodeTime *= scale;
  4968. baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  4969. }
  4970. return baseMediaDecodeTime;
  4971. };
  4972. var trackDecodeInfo$1 = {
  4973. clearDtsInfo: clearDtsInfo,
  4974. calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  4975. collectDtsInfo: collectDtsInfo
  4976. };
  4977. /**
  4978. * mux.js
  4979. *
  4980. * Copyright (c) Brightcove
  4981. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4982. *
  4983. * Reads in-band caption information from a video elementary
  4984. * stream. Captions must follow the CEA-708 standard for injection
  4985. * into an MPEG-2 transport streams.
  4986. * @see https://en.wikipedia.org/wiki/CEA-708
  4987. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  4988. */
  4989. // payload type field to indicate how they are to be
  4990. // interpreted. CEAS-708 caption content is always transmitted with
  4991. // payload type 0x04.
  4992. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  4993. RBSP_TRAILING_BITS = 128;
  4994. /**
  4995. * Parse a supplemental enhancement information (SEI) NAL unit.
  4996. * Stops parsing once a message of type ITU T T35 has been found.
  4997. *
  4998. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  4999. * @return {object} the parsed SEI payload
  5000. * @see Rec. ITU-T H.264, 7.3.2.3.1
  5001. */
  5002. var parseSei = function (bytes) {
  5003. var i = 0,
  5004. result = {
  5005. payloadType: -1,
  5006. payloadSize: 0
  5007. },
  5008. payloadType = 0,
  5009. payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
  5010. while (i < bytes.byteLength) {
  5011. // stop once we have hit the end of the sei_rbsp
  5012. if (bytes[i] === RBSP_TRAILING_BITS) {
  5013. break;
  5014. } // Parse payload type
  5015. while (bytes[i] === 0xFF) {
  5016. payloadType += 255;
  5017. i++;
  5018. }
  5019. payloadType += bytes[i++]; // Parse payload size
  5020. while (bytes[i] === 0xFF) {
  5021. payloadSize += 255;
  5022. i++;
  5023. }
  5024. payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
  5025. // there can only ever be one caption message in a frame's sei
  5026. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  5027. var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
  5028. if (userIdentifier === 'GA94') {
  5029. result.payloadType = payloadType;
  5030. result.payloadSize = payloadSize;
  5031. result.payload = bytes.subarray(i, i + payloadSize);
  5032. break;
  5033. } else {
  5034. result.payload = void 0;
  5035. }
  5036. } // skip the payload and parse the next message
  5037. i += payloadSize;
  5038. payloadType = 0;
  5039. payloadSize = 0;
  5040. }
  5041. return result;
  5042. }; // see ANSI/SCTE 128-1 (2013), section 8.1
  5043. var parseUserData = function (sei) {
  5044. // itu_t_t35_contry_code must be 181 (United States) for
  5045. // captions
  5046. if (sei.payload[0] !== 181) {
  5047. return null;
  5048. } // itu_t_t35_provider_code should be 49 (ATSC) for captions
  5049. if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
  5050. return null;
  5051. } // the user_identifier should be "GA94" to indicate ATSC1 data
  5052. if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
  5053. return null;
  5054. } // finally, user_data_type_code should be 0x03 for caption data
  5055. if (sei.payload[7] !== 0x03) {
  5056. return null;
  5057. } // return the user_data_type_structure and strip the trailing
  5058. // marker bits
  5059. return sei.payload.subarray(8, sei.payload.length - 1);
  5060. }; // see CEA-708-D, section 4.4
  5061. var parseCaptionPackets = function (pts, userData) {
  5062. var results = [],
  5063. i,
  5064. count,
  5065. offset,
  5066. data; // if this is just filler, return immediately
  5067. if (!(userData[0] & 0x40)) {
  5068. return results;
  5069. } // parse out the cc_data_1 and cc_data_2 fields
  5070. count = userData[0] & 0x1f;
  5071. for (i = 0; i < count; i++) {
  5072. offset = i * 3;
  5073. data = {
  5074. type: userData[offset + 2] & 0x03,
  5075. pts: pts
  5076. }; // capture cc data when cc_valid is 1
  5077. if (userData[offset + 2] & 0x04) {
  5078. data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
  5079. results.push(data);
  5080. }
  5081. }
  5082. return results;
  5083. };
  5084. var discardEmulationPreventionBytes$1 = function (data) {
  5085. var length = data.byteLength,
  5086. emulationPreventionBytesPositions = [],
  5087. i = 1,
  5088. newLength,
  5089. newData; // Find all `Emulation Prevention Bytes`
  5090. while (i < length - 2) {
  5091. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  5092. emulationPreventionBytesPositions.push(i + 2);
  5093. i += 2;
  5094. } else {
  5095. i++;
  5096. }
  5097. } // If no Emulation Prevention Bytes were found just return the original
  5098. // array
  5099. if (emulationPreventionBytesPositions.length === 0) {
  5100. return data;
  5101. } // Create a new array to hold the NAL unit data
  5102. newLength = length - emulationPreventionBytesPositions.length;
  5103. newData = new Uint8Array(newLength);
  5104. var sourceIndex = 0;
  5105. for (i = 0; i < newLength; sourceIndex++, i++) {
  5106. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  5107. // Skip this byte
  5108. sourceIndex++; // Remove this position index
  5109. emulationPreventionBytesPositions.shift();
  5110. }
  5111. newData[i] = data[sourceIndex];
  5112. }
  5113. return newData;
  5114. }; // exports
  5115. var captionPacketParser = {
  5116. parseSei: parseSei,
  5117. parseUserData: parseUserData,
  5118. parseCaptionPackets: parseCaptionPackets,
  5119. discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
  5120. USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
  5121. };
  5122. /**
  5123. * mux.js
  5124. *
  5125. * Copyright (c) Brightcove
  5126. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  5127. *
  5128. * Reads in-band caption information from a video elementary
  5129. * stream. Captions must follow the CEA-708 standard for injection
  5130. * into an MPEG-2 transport streams.
  5131. * @see https://en.wikipedia.org/wiki/CEA-708
  5132. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  5133. */
  5134. // Link To Transport
  5135. // -----------------
  5136. var Stream$7 = stream;
  5137. var cea708Parser = captionPacketParser;
  5138. var CaptionStream$2 = function (options) {
  5139. options = options || {};
  5140. CaptionStream$2.prototype.init.call(this); // parse708captions flag, default to true
  5141. this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
  5142. this.captionPackets_ = [];
  5143. this.ccStreams_ = [new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
  5144. new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
  5145. new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
  5146. new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  5147. ];
  5148. if (this.parse708captions_) {
  5149. this.cc708Stream_ = new Cea708Stream({
  5150. captionServices: options.captionServices
  5151. }); // eslint-disable-line no-use-before-define
  5152. }
  5153. this.reset(); // forward data and done events from CCs to this CaptionStream
  5154. this.ccStreams_.forEach(function (cc) {
  5155. cc.on('data', this.trigger.bind(this, 'data'));
  5156. cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
  5157. cc.on('done', this.trigger.bind(this, 'done'));
  5158. }, this);
  5159. if (this.parse708captions_) {
  5160. this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
  5161. this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
  5162. this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
  5163. }
  5164. };
  5165. CaptionStream$2.prototype = new Stream$7();
  5166. CaptionStream$2.prototype.push = function (event) {
  5167. var sei, userData, newCaptionPackets; // only examine SEI NALs
  5168. if (event.nalUnitType !== 'sei_rbsp') {
  5169. return;
  5170. } // parse the sei
  5171. sei = cea708Parser.parseSei(event.escapedRBSP); // no payload data, skip
  5172. if (!sei.payload) {
  5173. return;
  5174. } // ignore everything but user_data_registered_itu_t_t35
  5175. if (sei.payloadType !== cea708Parser.USER_DATA_REGISTERED_ITU_T_T35) {
  5176. return;
  5177. } // parse out the user data payload
  5178. userData = cea708Parser.parseUserData(sei); // ignore unrecognized userData
  5179. if (!userData) {
  5180. return;
  5181. } // Sometimes, the same segment # will be downloaded twice. To stop the
  5182. // caption data from being processed twice, we track the latest dts we've
  5183. // received and ignore everything with a dts before that. However, since
  5184. // data for a specific dts can be split across packets on either side of
  5185. // a segment boundary, we need to make sure we *don't* ignore the packets
  5186. // from the *next* segment that have dts === this.latestDts_. By constantly
  5187. // tracking the number of packets received with dts === this.latestDts_, we
  5188. // know how many should be ignored once we start receiving duplicates.
  5189. if (event.dts < this.latestDts_) {
  5190. // We've started getting older data, so set the flag.
  5191. this.ignoreNextEqualDts_ = true;
  5192. return;
  5193. } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
  5194. this.numSameDts_--;
  5195. if (!this.numSameDts_) {
  5196. // We've received the last duplicate packet, time to start processing again
  5197. this.ignoreNextEqualDts_ = false;
  5198. }
  5199. return;
  5200. } // parse out CC data packets and save them for later
  5201. newCaptionPackets = cea708Parser.parseCaptionPackets(event.pts, userData);
  5202. this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  5203. if (this.latestDts_ !== event.dts) {
  5204. this.numSameDts_ = 0;
  5205. }
  5206. this.numSameDts_++;
  5207. this.latestDts_ = event.dts;
  5208. };
  5209. CaptionStream$2.prototype.flushCCStreams = function (flushType) {
  5210. this.ccStreams_.forEach(function (cc) {
  5211. return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  5212. }, this);
  5213. };
  5214. CaptionStream$2.prototype.flushStream = function (flushType) {
  5215. // make sure we actually parsed captions before proceeding
  5216. if (!this.captionPackets_.length) {
  5217. this.flushCCStreams(flushType);
  5218. return;
  5219. } // In Chrome, the Array#sort function is not stable so add a
  5220. // presortIndex that we can use to ensure we get a stable-sort
  5221. this.captionPackets_.forEach(function (elem, idx) {
  5222. elem.presortIndex = idx;
  5223. }); // sort caption byte-pairs based on their PTS values
  5224. this.captionPackets_.sort(function (a, b) {
  5225. if (a.pts === b.pts) {
  5226. return a.presortIndex - b.presortIndex;
  5227. }
  5228. return a.pts - b.pts;
  5229. });
  5230. this.captionPackets_.forEach(function (packet) {
  5231. if (packet.type < 2) {
  5232. // Dispatch packet to the right Cea608Stream
  5233. this.dispatchCea608Packet(packet);
  5234. } else {
  5235. // Dispatch packet to the Cea708Stream
  5236. this.dispatchCea708Packet(packet);
  5237. }
  5238. }, this);
  5239. this.captionPackets_.length = 0;
  5240. this.flushCCStreams(flushType);
  5241. };
  5242. CaptionStream$2.prototype.flush = function () {
  5243. return this.flushStream('flush');
  5244. }; // Only called if handling partial data
  5245. CaptionStream$2.prototype.partialFlush = function () {
  5246. return this.flushStream('partialFlush');
  5247. };
  5248. CaptionStream$2.prototype.reset = function () {
  5249. this.latestDts_ = null;
  5250. this.ignoreNextEqualDts_ = false;
  5251. this.numSameDts_ = 0;
  5252. this.activeCea608Channel_ = [null, null];
  5253. this.ccStreams_.forEach(function (ccStream) {
  5254. ccStream.reset();
  5255. });
  5256. }; // From the CEA-608 spec:
  5257. /*
  5258. * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
  5259. * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
  5260. * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
  5261. * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
  5262. * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
  5263. * to switch to captioning or Text.
  5264. */
  5265. // With that in mind, we ignore any data between an XDS control code and a
  5266. // subsequent closed-captioning control code.
  5267. CaptionStream$2.prototype.dispatchCea608Packet = function (packet) {
  5268. // NOTE: packet.type is the CEA608 field
  5269. if (this.setsTextOrXDSActive(packet)) {
  5270. this.activeCea608Channel_[packet.type] = null;
  5271. } else if (this.setsChannel1Active(packet)) {
  5272. this.activeCea608Channel_[packet.type] = 0;
  5273. } else if (this.setsChannel2Active(packet)) {
  5274. this.activeCea608Channel_[packet.type] = 1;
  5275. }
  5276. if (this.activeCea608Channel_[packet.type] === null) {
  5277. // If we haven't received anything to set the active channel, or the
  5278. // packets are Text/XDS data, discard the data; we don't want jumbled
  5279. // captions
  5280. return;
  5281. }
  5282. this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  5283. };
  5284. CaptionStream$2.prototype.setsChannel1Active = function (packet) {
  5285. return (packet.ccData & 0x7800) === 0x1000;
  5286. };
  5287. CaptionStream$2.prototype.setsChannel2Active = function (packet) {
  5288. return (packet.ccData & 0x7800) === 0x1800;
  5289. };
  5290. CaptionStream$2.prototype.setsTextOrXDSActive = function (packet) {
  5291. return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
  5292. };
  5293. CaptionStream$2.prototype.dispatchCea708Packet = function (packet) {
  5294. if (this.parse708captions_) {
  5295. this.cc708Stream_.push(packet);
  5296. }
  5297. }; // ----------------------
  5298. // Session to Application
  5299. // ----------------------
  5300. // This hash maps special and extended character codes to their
  5301. // proper Unicode equivalent. The first one-byte key is just a
  5302. // non-standard character code. The two-byte keys that follow are
  5303. // the extended CEA708 character codes, along with the preceding
  5304. // 0x10 extended character byte to distinguish these codes from
  5305. // non-extended character codes. Every CEA708 character code that
  5306. // is not in this object maps directly to a standard unicode
  5307. // character code.
  5308. // The transparent space and non-breaking transparent space are
  5309. // technically not fully supported since there is no code to
  5310. // make them transparent, so they have normal non-transparent
  5311. // stand-ins.
  5312. // The special closed caption (CC) character isn't a standard
  5313. // unicode character, so a fairly similar unicode character was
  5314. // chosen in it's place.
  5315. var CHARACTER_TRANSLATION_708 = {
  5316. 0x7f: 0x266a,
  5317. // ♪
  5318. 0x1020: 0x20,
  5319. // Transparent Space
  5320. 0x1021: 0xa0,
  5321. // Nob-breaking Transparent Space
  5322. 0x1025: 0x2026,
  5323. // …
  5324. 0x102a: 0x0160,
  5325. // Š
  5326. 0x102c: 0x0152,
  5327. // Œ
  5328. 0x1030: 0x2588,
  5329. // █
  5330. 0x1031: 0x2018,
  5331. // ‘
  5332. 0x1032: 0x2019,
  5333. // ’
  5334. 0x1033: 0x201c,
  5335. // “
  5336. 0x1034: 0x201d,
  5337. // ”
  5338. 0x1035: 0x2022,
  5339. // •
  5340. 0x1039: 0x2122,
  5341. // ™
  5342. 0x103a: 0x0161,
  5343. // š
  5344. 0x103c: 0x0153,
  5345. // œ
  5346. 0x103d: 0x2120,
  5347. // ℠
  5348. 0x103f: 0x0178,
  5349. // Ÿ
  5350. 0x1076: 0x215b,
  5351. // ⅛
  5352. 0x1077: 0x215c,
  5353. // ⅜
  5354. 0x1078: 0x215d,
  5355. // ⅝
  5356. 0x1079: 0x215e,
  5357. // ⅞
  5358. 0x107a: 0x23d0,
  5359. // ⏐
  5360. 0x107b: 0x23a4,
  5361. // ⎤
  5362. 0x107c: 0x23a3,
  5363. // ⎣
  5364. 0x107d: 0x23af,
  5365. // ⎯
  5366. 0x107e: 0x23a6,
  5367. // ⎦
  5368. 0x107f: 0x23a1,
  5369. // ⎡
  5370. 0x10a0: 0x3138 // ㄸ (CC char)
  5371. };
  5372. var get708CharFromCode = function (code) {
  5373. var newCode = CHARACTER_TRANSLATION_708[code] || code;
  5374. if (code & 0x1000 && code === newCode) {
  5375. // Invalid extended code
  5376. return '';
  5377. }
  5378. return String.fromCharCode(newCode);
  5379. };
  5380. var within708TextBlock = function (b) {
  5381. return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
  5382. };
  5383. var Cea708Window = function (windowNum) {
  5384. this.windowNum = windowNum;
  5385. this.reset();
  5386. };
  5387. Cea708Window.prototype.reset = function () {
  5388. this.clearText();
  5389. this.pendingNewLine = false;
  5390. this.winAttr = {};
  5391. this.penAttr = {};
  5392. this.penLoc = {};
  5393. this.penColor = {}; // These default values are arbitrary,
  5394. // defineWindow will usually override them
  5395. this.visible = 0;
  5396. this.rowLock = 0;
  5397. this.columnLock = 0;
  5398. this.priority = 0;
  5399. this.relativePositioning = 0;
  5400. this.anchorVertical = 0;
  5401. this.anchorHorizontal = 0;
  5402. this.anchorPoint = 0;
  5403. this.rowCount = 1;
  5404. this.virtualRowCount = this.rowCount + 1;
  5405. this.columnCount = 41;
  5406. this.windowStyle = 0;
  5407. this.penStyle = 0;
  5408. };
  5409. Cea708Window.prototype.getText = function () {
  5410. return this.rows.join('\n');
  5411. };
  5412. Cea708Window.prototype.clearText = function () {
  5413. this.rows = [''];
  5414. this.rowIdx = 0;
  5415. };
  5416. Cea708Window.prototype.newLine = function (pts) {
  5417. if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
  5418. this.beforeRowOverflow(pts);
  5419. }
  5420. if (this.rows.length > 0) {
  5421. this.rows.push('');
  5422. this.rowIdx++;
  5423. } // Show all virtual rows since there's no visible scrolling
  5424. while (this.rows.length > this.virtualRowCount) {
  5425. this.rows.shift();
  5426. this.rowIdx--;
  5427. }
  5428. };
  5429. Cea708Window.prototype.isEmpty = function () {
  5430. if (this.rows.length === 0) {
  5431. return true;
  5432. } else if (this.rows.length === 1) {
  5433. return this.rows[0] === '';
  5434. }
  5435. return false;
  5436. };
  5437. Cea708Window.prototype.addText = function (text) {
  5438. this.rows[this.rowIdx] += text;
  5439. };
  5440. Cea708Window.prototype.backspace = function () {
  5441. if (!this.isEmpty()) {
  5442. var row = this.rows[this.rowIdx];
  5443. this.rows[this.rowIdx] = row.substr(0, row.length - 1);
  5444. }
  5445. };
  5446. var Cea708Service = function (serviceNum, encoding, stream) {
  5447. this.serviceNum = serviceNum;
  5448. this.text = '';
  5449. this.currentWindow = new Cea708Window(-1);
  5450. this.windows = [];
  5451. this.stream = stream; // Try to setup a TextDecoder if an `encoding` value was provided
  5452. if (typeof encoding === 'string') {
  5453. this.createTextDecoder(encoding);
  5454. }
  5455. };
  5456. /**
  5457. * Initialize service windows
  5458. * Must be run before service use
  5459. *
  5460. * @param {Integer} pts PTS value
  5461. * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
  5462. */
  5463. Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
  5464. this.startPts = pts;
  5465. for (var win = 0; win < 8; win++) {
  5466. this.windows[win] = new Cea708Window(win);
  5467. if (typeof beforeRowOverflow === 'function') {
  5468. this.windows[win].beforeRowOverflow = beforeRowOverflow;
  5469. }
  5470. }
  5471. };
  5472. /**
  5473. * Set current window of service to be affected by commands
  5474. *
  5475. * @param {Integer} windowNum Window number
  5476. */
  5477. Cea708Service.prototype.setCurrentWindow = function (windowNum) {
  5478. this.currentWindow = this.windows[windowNum];
  5479. };
  5480. /**
  5481. * Try to create a TextDecoder if it is natively supported
  5482. */
  5483. Cea708Service.prototype.createTextDecoder = function (encoding) {
  5484. if (typeof TextDecoder === 'undefined') {
  5485. this.stream.trigger('log', {
  5486. level: 'warn',
  5487. message: 'The `encoding` option is unsupported without TextDecoder support'
  5488. });
  5489. } else {
  5490. try {
  5491. this.textDecoder_ = new TextDecoder(encoding);
  5492. } catch (error) {
  5493. this.stream.trigger('log', {
  5494. level: 'warn',
  5495. message: 'TextDecoder could not be created with ' + encoding + ' encoding. ' + error
  5496. });
  5497. }
  5498. }
  5499. };
  5500. var Cea708Stream = function (options) {
  5501. options = options || {};
  5502. Cea708Stream.prototype.init.call(this);
  5503. var self = this;
  5504. var captionServices = options.captionServices || {};
  5505. var captionServiceEncodings = {};
  5506. var serviceProps; // Get service encodings from captionServices option block
  5507. Object.keys(captionServices).forEach(serviceName => {
  5508. serviceProps = captionServices[serviceName];
  5509. if (/^SERVICE/.test(serviceName)) {
  5510. captionServiceEncodings[serviceName] = serviceProps.encoding;
  5511. }
  5512. });
  5513. this.serviceEncodings = captionServiceEncodings;
  5514. this.current708Packet = null;
  5515. this.services = {};
  5516. this.push = function (packet) {
  5517. if (packet.type === 3) {
  5518. // 708 packet start
  5519. self.new708Packet();
  5520. self.add708Bytes(packet);
  5521. } else {
  5522. if (self.current708Packet === null) {
  5523. // This should only happen at the start of a file if there's no packet start.
  5524. self.new708Packet();
  5525. }
  5526. self.add708Bytes(packet);
  5527. }
  5528. };
  5529. };
  5530. Cea708Stream.prototype = new Stream$7();
  5531. /**
  5532. * Push current 708 packet, create new 708 packet.
  5533. */
  5534. Cea708Stream.prototype.new708Packet = function () {
  5535. if (this.current708Packet !== null) {
  5536. this.push708Packet();
  5537. }
  5538. this.current708Packet = {
  5539. data: [],
  5540. ptsVals: []
  5541. };
  5542. };
  5543. /**
  5544. * Add pts and both bytes from packet into current 708 packet.
  5545. */
  5546. Cea708Stream.prototype.add708Bytes = function (packet) {
  5547. var data = packet.ccData;
  5548. var byte0 = data >>> 8;
  5549. var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
  5550. // that service blocks will always line up with byte pairs.
  5551. this.current708Packet.ptsVals.push(packet.pts);
  5552. this.current708Packet.data.push(byte0);
  5553. this.current708Packet.data.push(byte1);
  5554. };
  5555. /**
  5556. * Parse completed 708 packet into service blocks and push each service block.
  5557. */
  5558. Cea708Stream.prototype.push708Packet = function () {
  5559. var packet708 = this.current708Packet;
  5560. var packetData = packet708.data;
  5561. var serviceNum = null;
  5562. var blockSize = null;
  5563. var i = 0;
  5564. var b = packetData[i++];
  5565. packet708.seq = b >> 6;
  5566. packet708.sizeCode = b & 0x3f; // 0b00111111;
  5567. for (; i < packetData.length; i++) {
  5568. b = packetData[i++];
  5569. serviceNum = b >> 5;
  5570. blockSize = b & 0x1f; // 0b00011111
  5571. if (serviceNum === 7 && blockSize > 0) {
  5572. // Extended service num
  5573. b = packetData[i++];
  5574. serviceNum = b;
  5575. }
  5576. this.pushServiceBlock(serviceNum, i, blockSize);
  5577. if (blockSize > 0) {
  5578. i += blockSize - 1;
  5579. }
  5580. }
  5581. };
  5582. /**
  5583. * Parse service block, execute commands, read text.
  5584. *
  5585. * Note: While many of these commands serve important purposes,
  5586. * many others just parse out the parameters or attributes, but
  5587. * nothing is done with them because this is not a full and complete
  5588. * implementation of the entire 708 spec.
  5589. *
  5590. * @param {Integer} serviceNum Service number
  5591. * @param {Integer} start Start index of the 708 packet data
  5592. * @param {Integer} size Block size
  5593. */
  5594. Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
  5595. var b;
  5596. var i = start;
  5597. var packetData = this.current708Packet.data;
  5598. var service = this.services[serviceNum];
  5599. if (!service) {
  5600. service = this.initService(serviceNum, i);
  5601. }
  5602. for (; i < start + size && i < packetData.length; i++) {
  5603. b = packetData[i];
  5604. if (within708TextBlock(b)) {
  5605. i = this.handleText(i, service);
  5606. } else if (b === 0x18) {
  5607. i = this.multiByteCharacter(i, service);
  5608. } else if (b === 0x10) {
  5609. i = this.extendedCommands(i, service);
  5610. } else if (0x80 <= b && b <= 0x87) {
  5611. i = this.setCurrentWindow(i, service);
  5612. } else if (0x98 <= b && b <= 0x9f) {
  5613. i = this.defineWindow(i, service);
  5614. } else if (b === 0x88) {
  5615. i = this.clearWindows(i, service);
  5616. } else if (b === 0x8c) {
  5617. i = this.deleteWindows(i, service);
  5618. } else if (b === 0x89) {
  5619. i = this.displayWindows(i, service);
  5620. } else if (b === 0x8a) {
  5621. i = this.hideWindows(i, service);
  5622. } else if (b === 0x8b) {
  5623. i = this.toggleWindows(i, service);
  5624. } else if (b === 0x97) {
  5625. i = this.setWindowAttributes(i, service);
  5626. } else if (b === 0x90) {
  5627. i = this.setPenAttributes(i, service);
  5628. } else if (b === 0x91) {
  5629. i = this.setPenColor(i, service);
  5630. } else if (b === 0x92) {
  5631. i = this.setPenLocation(i, service);
  5632. } else if (b === 0x8f) {
  5633. service = this.reset(i, service);
  5634. } else if (b === 0x08) {
  5635. // BS: Backspace
  5636. service.currentWindow.backspace();
  5637. } else if (b === 0x0c) {
  5638. // FF: Form feed
  5639. service.currentWindow.clearText();
  5640. } else if (b === 0x0d) {
  5641. // CR: Carriage return
  5642. service.currentWindow.pendingNewLine = true;
  5643. } else if (b === 0x0e) {
  5644. // HCR: Horizontal carriage return
  5645. service.currentWindow.clearText();
  5646. } else if (b === 0x8d) {
  5647. // DLY: Delay, nothing to do
  5648. i++;
  5649. } else ;
  5650. }
  5651. };
  5652. /**
  5653. * Execute an extended command
  5654. *
  5655. * @param {Integer} i Current index in the 708 packet
  5656. * @param {Service} service The service object to be affected
  5657. * @return {Integer} New index after parsing
  5658. */
  5659. Cea708Stream.prototype.extendedCommands = function (i, service) {
  5660. var packetData = this.current708Packet.data;
  5661. var b = packetData[++i];
  5662. if (within708TextBlock(b)) {
  5663. i = this.handleText(i, service, {
  5664. isExtended: true
  5665. });
  5666. }
  5667. return i;
  5668. };
  5669. /**
  5670. * Get PTS value of a given byte index
  5671. *
  5672. * @param {Integer} byteIndex Index of the byte
  5673. * @return {Integer} PTS
  5674. */
  5675. Cea708Stream.prototype.getPts = function (byteIndex) {
  5676. // There's 1 pts value per 2 bytes
  5677. return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
  5678. };
  5679. /**
  5680. * Initializes a service
  5681. *
  5682. * @param {Integer} serviceNum Service number
  5683. * @return {Service} Initialized service object
  5684. */
  5685. Cea708Stream.prototype.initService = function (serviceNum, i) {
  5686. var serviceName = 'SERVICE' + serviceNum;
  5687. var self = this;
  5688. var serviceName;
  5689. var encoding;
  5690. if (serviceName in this.serviceEncodings) {
  5691. encoding = this.serviceEncodings[serviceName];
  5692. }
  5693. this.services[serviceNum] = new Cea708Service(serviceNum, encoding, self);
  5694. this.services[serviceNum].init(this.getPts(i), function (pts) {
  5695. self.flushDisplayed(pts, self.services[serviceNum]);
  5696. });
  5697. return this.services[serviceNum];
  5698. };
  5699. /**
  5700. * Execute text writing to current window
  5701. *
  5702. * @param {Integer} i Current index in the 708 packet
  5703. * @param {Service} service The service object to be affected
  5704. * @return {Integer} New index after parsing
  5705. */
  5706. Cea708Stream.prototype.handleText = function (i, service, options) {
  5707. var isExtended = options && options.isExtended;
  5708. var isMultiByte = options && options.isMultiByte;
  5709. var packetData = this.current708Packet.data;
  5710. var extended = isExtended ? 0x1000 : 0x0000;
  5711. var currentByte = packetData[i];
  5712. var nextByte = packetData[i + 1];
  5713. var win = service.currentWindow;
  5714. var char;
  5715. var charCodeArray; // Converts an array of bytes to a unicode hex string.
  5716. function toHexString(byteArray) {
  5717. return byteArray.map(byte => {
  5718. return ('0' + (byte & 0xFF).toString(16)).slice(-2);
  5719. }).join('');
  5720. }
  5721. if (isMultiByte) {
  5722. charCodeArray = [currentByte, nextByte];
  5723. i++;
  5724. } else {
  5725. charCodeArray = [currentByte];
  5726. } // Use the TextDecoder if one was created for this service
  5727. if (service.textDecoder_ && !isExtended) {
  5728. char = service.textDecoder_.decode(new Uint8Array(charCodeArray));
  5729. } else {
  5730. // We assume any multi-byte char without a decoder is unicode.
  5731. if (isMultiByte) {
  5732. const unicode = toHexString(charCodeArray); // Takes a unicode hex string and creates a single character.
  5733. char = String.fromCharCode(parseInt(unicode, 16));
  5734. } else {
  5735. char = get708CharFromCode(extended | currentByte);
  5736. }
  5737. }
  5738. if (win.pendingNewLine && !win.isEmpty()) {
  5739. win.newLine(this.getPts(i));
  5740. }
  5741. win.pendingNewLine = false;
  5742. win.addText(char);
  5743. return i;
  5744. };
  5745. /**
  5746. * Handle decoding of multibyte character
  5747. *
  5748. * @param {Integer} i Current index in the 708 packet
  5749. * @param {Service} service The service object to be affected
  5750. * @return {Integer} New index after parsing
  5751. */
  5752. Cea708Stream.prototype.multiByteCharacter = function (i, service) {
  5753. var packetData = this.current708Packet.data;
  5754. var firstByte = packetData[i + 1];
  5755. var secondByte = packetData[i + 2];
  5756. if (within708TextBlock(firstByte) && within708TextBlock(secondByte)) {
  5757. i = this.handleText(++i, service, {
  5758. isMultiByte: true
  5759. });
  5760. }
  5761. return i;
  5762. };
  5763. /**
  5764. * Parse and execute the CW# command.
  5765. *
  5766. * Set the current window.
  5767. *
  5768. * @param {Integer} i Current index in the 708 packet
  5769. * @param {Service} service The service object to be affected
  5770. * @return {Integer} New index after parsing
  5771. */
  5772. Cea708Stream.prototype.setCurrentWindow = function (i, service) {
  5773. var packetData = this.current708Packet.data;
  5774. var b = packetData[i];
  5775. var windowNum = b & 0x07;
  5776. service.setCurrentWindow(windowNum);
  5777. return i;
  5778. };
  5779. /**
  5780. * Parse and execute the DF# command.
  5781. *
  5782. * Define a window and set it as the current window.
  5783. *
  5784. * @param {Integer} i Current index in the 708 packet
  5785. * @param {Service} service The service object to be affected
  5786. * @return {Integer} New index after parsing
  5787. */
  5788. Cea708Stream.prototype.defineWindow = function (i, service) {
  5789. var packetData = this.current708Packet.data;
  5790. var b = packetData[i];
  5791. var windowNum = b & 0x07;
  5792. service.setCurrentWindow(windowNum);
  5793. var win = service.currentWindow;
  5794. b = packetData[++i];
  5795. win.visible = (b & 0x20) >> 5; // v
  5796. win.rowLock = (b & 0x10) >> 4; // rl
  5797. win.columnLock = (b & 0x08) >> 3; // cl
  5798. win.priority = b & 0x07; // p
  5799. b = packetData[++i];
  5800. win.relativePositioning = (b & 0x80) >> 7; // rp
  5801. win.anchorVertical = b & 0x7f; // av
  5802. b = packetData[++i];
  5803. win.anchorHorizontal = b; // ah
  5804. b = packetData[++i];
  5805. win.anchorPoint = (b & 0xf0) >> 4; // ap
  5806. win.rowCount = b & 0x0f; // rc
  5807. b = packetData[++i];
  5808. win.columnCount = b & 0x3f; // cc
  5809. b = packetData[++i];
  5810. win.windowStyle = (b & 0x38) >> 3; // ws
  5811. win.penStyle = b & 0x07; // ps
  5812. // The spec says there are (rowCount+1) "virtual rows"
  5813. win.virtualRowCount = win.rowCount + 1;
  5814. return i;
  5815. };
  5816. /**
  5817. * Parse and execute the SWA command.
  5818. *
  5819. * Set attributes of the current window.
  5820. *
  5821. * @param {Integer} i Current index in the 708 packet
  5822. * @param {Service} service The service object to be affected
  5823. * @return {Integer} New index after parsing
  5824. */
  5825. Cea708Stream.prototype.setWindowAttributes = function (i, service) {
  5826. var packetData = this.current708Packet.data;
  5827. var b = packetData[i];
  5828. var winAttr = service.currentWindow.winAttr;
  5829. b = packetData[++i];
  5830. winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
  5831. winAttr.fillRed = (b & 0x30) >> 4; // fr
  5832. winAttr.fillGreen = (b & 0x0c) >> 2; // fg
  5833. winAttr.fillBlue = b & 0x03; // fb
  5834. b = packetData[++i];
  5835. winAttr.borderType = (b & 0xc0) >> 6; // bt
  5836. winAttr.borderRed = (b & 0x30) >> 4; // br
  5837. winAttr.borderGreen = (b & 0x0c) >> 2; // bg
  5838. winAttr.borderBlue = b & 0x03; // bb
  5839. b = packetData[++i];
  5840. winAttr.borderType += (b & 0x80) >> 5; // bt
  5841. winAttr.wordWrap = (b & 0x40) >> 6; // ww
  5842. winAttr.printDirection = (b & 0x30) >> 4; // pd
  5843. winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
  5844. winAttr.justify = b & 0x03; // j
  5845. b = packetData[++i];
  5846. winAttr.effectSpeed = (b & 0xf0) >> 4; // es
  5847. winAttr.effectDirection = (b & 0x0c) >> 2; // ed
  5848. winAttr.displayEffect = b & 0x03; // de
  5849. return i;
  5850. };
  5851. /**
  5852. * Gather text from all displayed windows and push a caption to output.
  5853. *
  5854. * @param {Integer} i Current index in the 708 packet
  5855. * @param {Service} service The service object to be affected
  5856. */
  5857. Cea708Stream.prototype.flushDisplayed = function (pts, service) {
  5858. var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
  5859. // display text in the correct order, but sample files so far have not shown any issue.
  5860. for (var winId = 0; winId < 8; winId++) {
  5861. if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
  5862. displayedText.push(service.windows[winId].getText());
  5863. }
  5864. }
  5865. service.endPts = pts;
  5866. service.text = displayedText.join('\n\n');
  5867. this.pushCaption(service);
  5868. service.startPts = pts;
  5869. };
  5870. /**
  5871. * Push a caption to output if the caption contains text.
  5872. *
  5873. * @param {Service} service The service object to be affected
  5874. */
  5875. Cea708Stream.prototype.pushCaption = function (service) {
  5876. if (service.text !== '') {
  5877. this.trigger('data', {
  5878. startPts: service.startPts,
  5879. endPts: service.endPts,
  5880. text: service.text,
  5881. stream: 'cc708_' + service.serviceNum
  5882. });
  5883. service.text = '';
  5884. service.startPts = service.endPts;
  5885. }
  5886. };
  5887. /**
  5888. * Parse and execute the DSW command.
  5889. *
  5890. * Set visible property of windows based on the parsed bitmask.
  5891. *
  5892. * @param {Integer} i Current index in the 708 packet
  5893. * @param {Service} service The service object to be affected
  5894. * @return {Integer} New index after parsing
  5895. */
  5896. Cea708Stream.prototype.displayWindows = function (i, service) {
  5897. var packetData = this.current708Packet.data;
  5898. var b = packetData[++i];
  5899. var pts = this.getPts(i);
  5900. this.flushDisplayed(pts, service);
  5901. for (var winId = 0; winId < 8; winId++) {
  5902. if (b & 0x01 << winId) {
  5903. service.windows[winId].visible = 1;
  5904. }
  5905. }
  5906. return i;
  5907. };
  5908. /**
  5909. * Parse and execute the HDW command.
  5910. *
  5911. * Set visible property of windows based on the parsed bitmask.
  5912. *
  5913. * @param {Integer} i Current index in the 708 packet
  5914. * @param {Service} service The service object to be affected
  5915. * @return {Integer} New index after parsing
  5916. */
  5917. Cea708Stream.prototype.hideWindows = function (i, service) {
  5918. var packetData = this.current708Packet.data;
  5919. var b = packetData[++i];
  5920. var pts = this.getPts(i);
  5921. this.flushDisplayed(pts, service);
  5922. for (var winId = 0; winId < 8; winId++) {
  5923. if (b & 0x01 << winId) {
  5924. service.windows[winId].visible = 0;
  5925. }
  5926. }
  5927. return i;
  5928. };
  5929. /**
  5930. * Parse and execute the TGW command.
  5931. *
  5932. * Set visible property of windows based on the parsed bitmask.
  5933. *
  5934. * @param {Integer} i Current index in the 708 packet
  5935. * @param {Service} service The service object to be affected
  5936. * @return {Integer} New index after parsing
  5937. */
  5938. Cea708Stream.prototype.toggleWindows = function (i, service) {
  5939. var packetData = this.current708Packet.data;
  5940. var b = packetData[++i];
  5941. var pts = this.getPts(i);
  5942. this.flushDisplayed(pts, service);
  5943. for (var winId = 0; winId < 8; winId++) {
  5944. if (b & 0x01 << winId) {
  5945. service.windows[winId].visible ^= 1;
  5946. }
  5947. }
  5948. return i;
  5949. };
  5950. /**
  5951. * Parse and execute the CLW command.
  5952. *
  5953. * Clear text of windows based on the parsed bitmask.
  5954. *
  5955. * @param {Integer} i Current index in the 708 packet
  5956. * @param {Service} service The service object to be affected
  5957. * @return {Integer} New index after parsing
  5958. */
  5959. Cea708Stream.prototype.clearWindows = function (i, service) {
  5960. var packetData = this.current708Packet.data;
  5961. var b = packetData[++i];
  5962. var pts = this.getPts(i);
  5963. this.flushDisplayed(pts, service);
  5964. for (var winId = 0; winId < 8; winId++) {
  5965. if (b & 0x01 << winId) {
  5966. service.windows[winId].clearText();
  5967. }
  5968. }
  5969. return i;
  5970. };
  5971. /**
  5972. * Parse and execute the DLW command.
  5973. *
  5974. * Re-initialize windows based on the parsed bitmask.
  5975. *
  5976. * @param {Integer} i Current index in the 708 packet
  5977. * @param {Service} service The service object to be affected
  5978. * @return {Integer} New index after parsing
  5979. */
  5980. Cea708Stream.prototype.deleteWindows = function (i, service) {
  5981. var packetData = this.current708Packet.data;
  5982. var b = packetData[++i];
  5983. var pts = this.getPts(i);
  5984. this.flushDisplayed(pts, service);
  5985. for (var winId = 0; winId < 8; winId++) {
  5986. if (b & 0x01 << winId) {
  5987. service.windows[winId].reset();
  5988. }
  5989. }
  5990. return i;
  5991. };
  5992. /**
  5993. * Parse and execute the SPA command.
  5994. *
  5995. * Set pen attributes of the current window.
  5996. *
  5997. * @param {Integer} i Current index in the 708 packet
  5998. * @param {Service} service The service object to be affected
  5999. * @return {Integer} New index after parsing
  6000. */
  6001. Cea708Stream.prototype.setPenAttributes = function (i, service) {
  6002. var packetData = this.current708Packet.data;
  6003. var b = packetData[i];
  6004. var penAttr = service.currentWindow.penAttr;
  6005. b = packetData[++i];
  6006. penAttr.textTag = (b & 0xf0) >> 4; // tt
  6007. penAttr.offset = (b & 0x0c) >> 2; // o
  6008. penAttr.penSize = b & 0x03; // s
  6009. b = packetData[++i];
  6010. penAttr.italics = (b & 0x80) >> 7; // i
  6011. penAttr.underline = (b & 0x40) >> 6; // u
  6012. penAttr.edgeType = (b & 0x38) >> 3; // et
  6013. penAttr.fontStyle = b & 0x07; // fs
  6014. return i;
  6015. };
  6016. /**
  6017. * Parse and execute the SPC command.
  6018. *
  6019. * Set pen color of the current window.
  6020. *
  6021. * @param {Integer} i Current index in the 708 packet
  6022. * @param {Service} service The service object to be affected
  6023. * @return {Integer} New index after parsing
  6024. */
  6025. Cea708Stream.prototype.setPenColor = function (i, service) {
  6026. var packetData = this.current708Packet.data;
  6027. var b = packetData[i];
  6028. var penColor = service.currentWindow.penColor;
  6029. b = packetData[++i];
  6030. penColor.fgOpacity = (b & 0xc0) >> 6; // fo
  6031. penColor.fgRed = (b & 0x30) >> 4; // fr
  6032. penColor.fgGreen = (b & 0x0c) >> 2; // fg
  6033. penColor.fgBlue = b & 0x03; // fb
  6034. b = packetData[++i];
  6035. penColor.bgOpacity = (b & 0xc0) >> 6; // bo
  6036. penColor.bgRed = (b & 0x30) >> 4; // br
  6037. penColor.bgGreen = (b & 0x0c) >> 2; // bg
  6038. penColor.bgBlue = b & 0x03; // bb
  6039. b = packetData[++i];
  6040. penColor.edgeRed = (b & 0x30) >> 4; // er
  6041. penColor.edgeGreen = (b & 0x0c) >> 2; // eg
  6042. penColor.edgeBlue = b & 0x03; // eb
  6043. return i;
  6044. };
  6045. /**
  6046. * Parse and execute the SPL command.
  6047. *
  6048. * Set pen location of the current window.
  6049. *
  6050. * @param {Integer} i Current index in the 708 packet
  6051. * @param {Service} service The service object to be affected
  6052. * @return {Integer} New index after parsing
  6053. */
  6054. Cea708Stream.prototype.setPenLocation = function (i, service) {
  6055. var packetData = this.current708Packet.data;
  6056. var b = packetData[i];
  6057. var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
  6058. service.currentWindow.pendingNewLine = true;
  6059. b = packetData[++i];
  6060. penLoc.row = b & 0x0f; // r
  6061. b = packetData[++i];
  6062. penLoc.column = b & 0x3f; // c
  6063. return i;
  6064. };
  6065. /**
  6066. * Execute the RST command.
  6067. *
  6068. * Reset service to a clean slate. Re-initialize.
  6069. *
  6070. * @param {Integer} i Current index in the 708 packet
  6071. * @param {Service} service The service object to be affected
  6072. * @return {Service} Re-initialized service
  6073. */
  6074. Cea708Stream.prototype.reset = function (i, service) {
  6075. var pts = this.getPts(i);
  6076. this.flushDisplayed(pts, service);
  6077. return this.initService(service.serviceNum, i);
  6078. }; // This hash maps non-ASCII, special, and extended character codes to their
  6079. // proper Unicode equivalent. The first keys that are only a single byte
  6080. // are the non-standard ASCII characters, which simply map the CEA608 byte
  6081. // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
  6082. // character codes, but have their MSB bitmasked with 0x03 so that a lookup
  6083. // can be performed regardless of the field and data channel on which the
  6084. // character code was received.
  6085. var CHARACTER_TRANSLATION = {
  6086. 0x2a: 0xe1,
  6087. // á
  6088. 0x5c: 0xe9,
  6089. // é
  6090. 0x5e: 0xed,
  6091. // í
  6092. 0x5f: 0xf3,
  6093. // ó
  6094. 0x60: 0xfa,
  6095. // ú
  6096. 0x7b: 0xe7,
  6097. // ç
  6098. 0x7c: 0xf7,
  6099. // ÷
  6100. 0x7d: 0xd1,
  6101. // Ñ
  6102. 0x7e: 0xf1,
  6103. // ñ
  6104. 0x7f: 0x2588,
  6105. // █
  6106. 0x0130: 0xae,
  6107. // ®
  6108. 0x0131: 0xb0,
  6109. // °
  6110. 0x0132: 0xbd,
  6111. // ½
  6112. 0x0133: 0xbf,
  6113. // ¿
  6114. 0x0134: 0x2122,
  6115. // ™
  6116. 0x0135: 0xa2,
  6117. // ¢
  6118. 0x0136: 0xa3,
  6119. // £
  6120. 0x0137: 0x266a,
  6121. // ♪
  6122. 0x0138: 0xe0,
  6123. // à
  6124. 0x0139: 0xa0,
  6125. //
  6126. 0x013a: 0xe8,
  6127. // è
  6128. 0x013b: 0xe2,
  6129. // â
  6130. 0x013c: 0xea,
  6131. // ê
  6132. 0x013d: 0xee,
  6133. // î
  6134. 0x013e: 0xf4,
  6135. // ô
  6136. 0x013f: 0xfb,
  6137. // û
  6138. 0x0220: 0xc1,
  6139. // Á
  6140. 0x0221: 0xc9,
  6141. // É
  6142. 0x0222: 0xd3,
  6143. // Ó
  6144. 0x0223: 0xda,
  6145. // Ú
  6146. 0x0224: 0xdc,
  6147. // Ü
  6148. 0x0225: 0xfc,
  6149. // ü
  6150. 0x0226: 0x2018,
  6151. // ‘
  6152. 0x0227: 0xa1,
  6153. // ¡
  6154. 0x0228: 0x2a,
  6155. // *
  6156. 0x0229: 0x27,
  6157. // '
  6158. 0x022a: 0x2014,
  6159. // —
  6160. 0x022b: 0xa9,
  6161. // ©
  6162. 0x022c: 0x2120,
  6163. // ℠
  6164. 0x022d: 0x2022,
  6165. // •
  6166. 0x022e: 0x201c,
  6167. // “
  6168. 0x022f: 0x201d,
  6169. // ”
  6170. 0x0230: 0xc0,
  6171. // À
  6172. 0x0231: 0xc2,
  6173. // Â
  6174. 0x0232: 0xc7,
  6175. // Ç
  6176. 0x0233: 0xc8,
  6177. // È
  6178. 0x0234: 0xca,
  6179. // Ê
  6180. 0x0235: 0xcb,
  6181. // Ë
  6182. 0x0236: 0xeb,
  6183. // ë
  6184. 0x0237: 0xce,
  6185. // Î
  6186. 0x0238: 0xcf,
  6187. // Ï
  6188. 0x0239: 0xef,
  6189. // ï
  6190. 0x023a: 0xd4,
  6191. // Ô
  6192. 0x023b: 0xd9,
  6193. // Ù
  6194. 0x023c: 0xf9,
  6195. // ù
  6196. 0x023d: 0xdb,
  6197. // Û
  6198. 0x023e: 0xab,
  6199. // «
  6200. 0x023f: 0xbb,
  6201. // »
  6202. 0x0320: 0xc3,
  6203. // Ã
  6204. 0x0321: 0xe3,
  6205. // ã
  6206. 0x0322: 0xcd,
  6207. // Í
  6208. 0x0323: 0xcc,
  6209. // Ì
  6210. 0x0324: 0xec,
  6211. // ì
  6212. 0x0325: 0xd2,
  6213. // Ò
  6214. 0x0326: 0xf2,
  6215. // ò
  6216. 0x0327: 0xd5,
  6217. // Õ
  6218. 0x0328: 0xf5,
  6219. // õ
  6220. 0x0329: 0x7b,
  6221. // {
  6222. 0x032a: 0x7d,
  6223. // }
  6224. 0x032b: 0x5c,
  6225. // \
  6226. 0x032c: 0x5e,
  6227. // ^
  6228. 0x032d: 0x5f,
  6229. // _
  6230. 0x032e: 0x7c,
  6231. // |
  6232. 0x032f: 0x7e,
  6233. // ~
  6234. 0x0330: 0xc4,
  6235. // Ä
  6236. 0x0331: 0xe4,
  6237. // ä
  6238. 0x0332: 0xd6,
  6239. // Ö
  6240. 0x0333: 0xf6,
  6241. // ö
  6242. 0x0334: 0xdf,
  6243. // ß
  6244. 0x0335: 0xa5,
  6245. // ¥
  6246. 0x0336: 0xa4,
  6247. // ¤
  6248. 0x0337: 0x2502,
  6249. // │
  6250. 0x0338: 0xc5,
  6251. // Å
  6252. 0x0339: 0xe5,
  6253. // å
  6254. 0x033a: 0xd8,
  6255. // Ø
  6256. 0x033b: 0xf8,
  6257. // ø
  6258. 0x033c: 0x250c,
  6259. // ┌
  6260. 0x033d: 0x2510,
  6261. // ┐
  6262. 0x033e: 0x2514,
  6263. // └
  6264. 0x033f: 0x2518 // ┘
  6265. };
  6266. var getCharFromCode = function (code) {
  6267. if (code === null) {
  6268. return '';
  6269. }
  6270. code = CHARACTER_TRANSLATION[code] || code;
  6271. return String.fromCharCode(code);
  6272. }; // the index of the last row in a CEA-608 display buffer
  6273. var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
  6274. // getting it through bit logic.
  6275. 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
  6276. // cells. The "bottom" row is the last element in the outer array.
  6277. // We keep track of positioning information as we go by storing the
  6278. // number of indentations and the tab offset in this buffer.
  6279. var createDisplayBuffer = function () {
  6280. var result = [],
  6281. i = BOTTOM_ROW + 1;
  6282. while (i--) {
  6283. result.push({
  6284. text: '',
  6285. indent: 0,
  6286. offset: 0
  6287. });
  6288. }
  6289. return result;
  6290. };
  6291. var Cea608Stream = function (field, dataChannel) {
  6292. Cea608Stream.prototype.init.call(this);
  6293. this.field_ = field || 0;
  6294. this.dataChannel_ = dataChannel || 0;
  6295. this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
  6296. this.setConstants();
  6297. this.reset();
  6298. this.push = function (packet) {
  6299. var data, swap, char0, char1, text; // remove the parity bits
  6300. data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
  6301. if (data === this.lastControlCode_) {
  6302. this.lastControlCode_ = null;
  6303. return;
  6304. } // Store control codes
  6305. if ((data & 0xf000) === 0x1000) {
  6306. this.lastControlCode_ = data;
  6307. } else if (data !== this.PADDING_) {
  6308. this.lastControlCode_ = null;
  6309. }
  6310. char0 = data >>> 8;
  6311. char1 = data & 0xff;
  6312. if (data === this.PADDING_) {
  6313. return;
  6314. } else if (data === this.RESUME_CAPTION_LOADING_) {
  6315. this.mode_ = 'popOn';
  6316. } else if (data === this.END_OF_CAPTION_) {
  6317. // If an EOC is received while in paint-on mode, the displayed caption
  6318. // text should be swapped to non-displayed memory as if it was a pop-on
  6319. // caption. Because of that, we should explicitly switch back to pop-on
  6320. // mode
  6321. this.mode_ = 'popOn';
  6322. this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
  6323. this.flushDisplayed(packet.pts); // flip memory
  6324. swap = this.displayed_;
  6325. this.displayed_ = this.nonDisplayed_;
  6326. this.nonDisplayed_ = swap; // start measuring the time to display the caption
  6327. this.startPts_ = packet.pts;
  6328. } else if (data === this.ROLL_UP_2_ROWS_) {
  6329. this.rollUpRows_ = 2;
  6330. this.setRollUp(packet.pts);
  6331. } else if (data === this.ROLL_UP_3_ROWS_) {
  6332. this.rollUpRows_ = 3;
  6333. this.setRollUp(packet.pts);
  6334. } else if (data === this.ROLL_UP_4_ROWS_) {
  6335. this.rollUpRows_ = 4;
  6336. this.setRollUp(packet.pts);
  6337. } else if (data === this.CARRIAGE_RETURN_) {
  6338. this.clearFormatting(packet.pts);
  6339. this.flushDisplayed(packet.pts);
  6340. this.shiftRowsUp_();
  6341. this.startPts_ = packet.pts;
  6342. } else if (data === this.BACKSPACE_) {
  6343. if (this.mode_ === 'popOn') {
  6344. this.nonDisplayed_[this.row_].text = this.nonDisplayed_[this.row_].text.slice(0, -1);
  6345. } else {
  6346. this.displayed_[this.row_].text = this.displayed_[this.row_].text.slice(0, -1);
  6347. }
  6348. } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
  6349. this.flushDisplayed(packet.pts);
  6350. this.displayed_ = createDisplayBuffer();
  6351. } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
  6352. this.nonDisplayed_ = createDisplayBuffer();
  6353. } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
  6354. if (this.mode_ !== 'paintOn') {
  6355. // NOTE: This should be removed when proper caption positioning is
  6356. // implemented
  6357. this.flushDisplayed(packet.pts);
  6358. this.displayed_ = createDisplayBuffer();
  6359. }
  6360. this.mode_ = 'paintOn';
  6361. this.startPts_ = packet.pts; // Append special characters to caption text
  6362. } else if (this.isSpecialCharacter(char0, char1)) {
  6363. // Bitmask char0 so that we can apply character transformations
  6364. // regardless of field and data channel.
  6365. // Then byte-shift to the left and OR with char1 so we can pass the
  6366. // entire character code to `getCharFromCode`.
  6367. char0 = (char0 & 0x03) << 8;
  6368. text = getCharFromCode(char0 | char1);
  6369. this[this.mode_](packet.pts, text);
  6370. this.column_++; // Append extended characters to caption text
  6371. } else if (this.isExtCharacter(char0, char1)) {
  6372. // Extended characters always follow their "non-extended" equivalents.
  6373. // IE if a "è" is desired, you'll always receive "eè"; non-compliant
  6374. // decoders are supposed to drop the "è", while compliant decoders
  6375. // backspace the "e" and insert "è".
  6376. // Delete the previous character
  6377. if (this.mode_ === 'popOn') {
  6378. this.nonDisplayed_[this.row_].text = this.nonDisplayed_[this.row_].text.slice(0, -1);
  6379. } else {
  6380. this.displayed_[this.row_].text = this.displayed_[this.row_].text.slice(0, -1);
  6381. } // Bitmask char0 so that we can apply character transformations
  6382. // regardless of field and data channel.
  6383. // Then byte-shift to the left and OR with char1 so we can pass the
  6384. // entire character code to `getCharFromCode`.
  6385. char0 = (char0 & 0x03) << 8;
  6386. text = getCharFromCode(char0 | char1);
  6387. this[this.mode_](packet.pts, text);
  6388. this.column_++; // Process mid-row codes
  6389. } else if (this.isMidRowCode(char0, char1)) {
  6390. // Attributes are not additive, so clear all formatting
  6391. this.clearFormatting(packet.pts); // According to the standard, mid-row codes
  6392. // should be replaced with spaces, so add one now
  6393. this[this.mode_](packet.pts, ' ');
  6394. this.column_++;
  6395. if ((char1 & 0xe) === 0xe) {
  6396. this.addFormatting(packet.pts, ['i']);
  6397. }
  6398. if ((char1 & 0x1) === 0x1) {
  6399. this.addFormatting(packet.pts, ['u']);
  6400. } // Detect offset control codes and adjust cursor
  6401. } else if (this.isOffsetControlCode(char0, char1)) {
  6402. // Cursor position is set by indent PAC (see below) in 4-column
  6403. // increments, with an additional offset code of 1-3 to reach any
  6404. // of the 32 columns specified by CEA-608. So all we need to do
  6405. // here is increment the column cursor by the given offset.
  6406. const offset = char1 & 0x03; // For an offest value 1-3, set the offset for that caption
  6407. // in the non-displayed array.
  6408. this.nonDisplayed_[this.row_].offset = offset;
  6409. this.column_ += offset; // Detect PACs (Preamble Address Codes)
  6410. } else if (this.isPAC(char0, char1)) {
  6411. // There's no logic for PAC -> row mapping, so we have to just
  6412. // find the row code in an array and use its index :(
  6413. var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
  6414. if (this.mode_ === 'rollUp') {
  6415. // This implies that the base row is incorrectly set.
  6416. // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
  6417. // of roll-up rows set.
  6418. if (row - this.rollUpRows_ + 1 < 0) {
  6419. row = this.rollUpRows_ - 1;
  6420. }
  6421. this.setRollUp(packet.pts, row);
  6422. }
  6423. if (row !== this.row_) {
  6424. // formatting is only persistent for current row
  6425. this.clearFormatting(packet.pts);
  6426. this.row_ = row;
  6427. } // All PACs can apply underline, so detect and apply
  6428. // (All odd-numbered second bytes set underline)
  6429. if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
  6430. this.addFormatting(packet.pts, ['u']);
  6431. }
  6432. if ((data & 0x10) === 0x10) {
  6433. // We've got an indent level code. Each successive even number
  6434. // increments the column cursor by 4, so we can get the desired
  6435. // column position by bit-shifting to the right (to get n/2)
  6436. // and multiplying by 4.
  6437. const indentations = (data & 0xe) >> 1;
  6438. this.column_ = indentations * 4; // add to the number of indentations for positioning
  6439. this.nonDisplayed_[this.row_].indent += indentations;
  6440. }
  6441. if (this.isColorPAC(char1)) {
  6442. // it's a color code, though we only support white, which
  6443. // can be either normal or italicized. white italics can be
  6444. // either 0x4e or 0x6e depending on the row, so we just
  6445. // bitwise-and with 0xe to see if italics should be turned on
  6446. if ((char1 & 0xe) === 0xe) {
  6447. this.addFormatting(packet.pts, ['i']);
  6448. }
  6449. } // We have a normal character in char0, and possibly one in char1
  6450. } else if (this.isNormalChar(char0)) {
  6451. if (char1 === 0x00) {
  6452. char1 = null;
  6453. }
  6454. text = getCharFromCode(char0);
  6455. text += getCharFromCode(char1);
  6456. this[this.mode_](packet.pts, text);
  6457. this.column_ += text.length;
  6458. } // finish data processing
  6459. };
  6460. };
  6461. Cea608Stream.prototype = new Stream$7(); // Trigger a cue point that captures the current state of the
  6462. // display buffer
  6463. Cea608Stream.prototype.flushDisplayed = function (pts) {
  6464. const logWarning = index => {
  6465. this.trigger('log', {
  6466. level: 'warn',
  6467. message: 'Skipping a malformed 608 caption at index ' + index + '.'
  6468. });
  6469. };
  6470. const content = [];
  6471. this.displayed_.forEach((row, i) => {
  6472. if (row && row.text && row.text.length) {
  6473. try {
  6474. // remove spaces from the start and end of the string
  6475. row.text = row.text.trim();
  6476. } catch (e) {
  6477. // Ordinarily, this shouldn't happen. However, caption
  6478. // parsing errors should not throw exceptions and
  6479. // break playback.
  6480. logWarning(i);
  6481. } // See the below link for more details on the following fields:
  6482. // https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#positioning-in-cea-608
  6483. if (row.text.length) {
  6484. content.push({
  6485. // The text to be displayed in the caption from this specific row, with whitespace removed.
  6486. text: row.text,
  6487. // Value between 1 and 15 representing the PAC row used to calculate line height.
  6488. line: i + 1,
  6489. // A number representing the indent position by percentage (CEA-608 PAC indent code).
  6490. // The value will be a number between 10 and 80. Offset is used to add an aditional
  6491. // value to the position if necessary.
  6492. position: 10 + Math.min(70, row.indent * 10) + row.offset * 2.5
  6493. });
  6494. }
  6495. } else if (row === undefined || row === null) {
  6496. logWarning(i);
  6497. }
  6498. });
  6499. if (content.length) {
  6500. this.trigger('data', {
  6501. startPts: this.startPts_,
  6502. endPts: pts,
  6503. content,
  6504. stream: this.name_
  6505. });
  6506. }
  6507. };
  6508. /**
  6509. * Zero out the data, used for startup and on seek
  6510. */
  6511. Cea608Stream.prototype.reset = function () {
  6512. this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
  6513. // actually display captions. If a caption is shifted to a row
  6514. // with a lower index than this, it is cleared from the display
  6515. // buffer
  6516. this.topRow_ = 0;
  6517. this.startPts_ = 0;
  6518. this.displayed_ = createDisplayBuffer();
  6519. this.nonDisplayed_ = createDisplayBuffer();
  6520. this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
  6521. this.column_ = 0;
  6522. this.row_ = BOTTOM_ROW;
  6523. this.rollUpRows_ = 2; // This variable holds currently-applied formatting
  6524. this.formatting_ = [];
  6525. };
  6526. /**
  6527. * Sets up control code and related constants for this instance
  6528. */
  6529. Cea608Stream.prototype.setConstants = function () {
  6530. // The following attributes have these uses:
  6531. // ext_ : char0 for mid-row codes, and the base for extended
  6532. // chars (ext_+0, ext_+1, and ext_+2 are char0s for
  6533. // extended codes)
  6534. // control_: char0 for control codes, except byte-shifted to the
  6535. // left so that we can do this.control_ | CONTROL_CODE
  6536. // offset_: char0 for tab offset codes
  6537. //
  6538. // It's also worth noting that control codes, and _only_ control codes,
  6539. // differ between field 1 and field2. Field 2 control codes are always
  6540. // their field 1 value plus 1. That's why there's the "| field" on the
  6541. // control value.
  6542. if (this.dataChannel_ === 0) {
  6543. this.BASE_ = 0x10;
  6544. this.EXT_ = 0x11;
  6545. this.CONTROL_ = (0x14 | this.field_) << 8;
  6546. this.OFFSET_ = 0x17;
  6547. } else if (this.dataChannel_ === 1) {
  6548. this.BASE_ = 0x18;
  6549. this.EXT_ = 0x19;
  6550. this.CONTROL_ = (0x1c | this.field_) << 8;
  6551. this.OFFSET_ = 0x1f;
  6552. } // Constants for the LSByte command codes recognized by Cea608Stream. This
  6553. // list is not exhaustive. For a more comprehensive listing and semantics see
  6554. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  6555. // Padding
  6556. this.PADDING_ = 0x0000; // Pop-on Mode
  6557. this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
  6558. this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
  6559. this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
  6560. this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
  6561. this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
  6562. this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
  6563. this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
  6564. this.BACKSPACE_ = this.CONTROL_ | 0x21;
  6565. this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
  6566. this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
  6567. };
  6568. /**
  6569. * Detects if the 2-byte packet data is a special character
  6570. *
  6571. * Special characters have a second byte in the range 0x30 to 0x3f,
  6572. * with the first byte being 0x11 (for data channel 1) or 0x19 (for
  6573. * data channel 2).
  6574. *
  6575. * @param {Integer} char0 The first byte
  6576. * @param {Integer} char1 The second byte
  6577. * @return {Boolean} Whether the 2 bytes are an special character
  6578. */
  6579. Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
  6580. return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
  6581. };
  6582. /**
  6583. * Detects if the 2-byte packet data is an extended character
  6584. *
  6585. * Extended characters have a second byte in the range 0x20 to 0x3f,
  6586. * with the first byte being 0x12 or 0x13 (for data channel 1) or
  6587. * 0x1a or 0x1b (for data channel 2).
  6588. *
  6589. * @param {Integer} char0 The first byte
  6590. * @param {Integer} char1 The second byte
  6591. * @return {Boolean} Whether the 2 bytes are an extended character
  6592. */
  6593. Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
  6594. return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
  6595. };
  6596. /**
  6597. * Detects if the 2-byte packet is a mid-row code
  6598. *
  6599. * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
  6600. * the first byte being 0x11 (for data channel 1) or 0x19 (for data
  6601. * channel 2).
  6602. *
  6603. * @param {Integer} char0 The first byte
  6604. * @param {Integer} char1 The second byte
  6605. * @return {Boolean} Whether the 2 bytes are a mid-row code
  6606. */
  6607. Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
  6608. return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
  6609. };
  6610. /**
  6611. * Detects if the 2-byte packet is an offset control code
  6612. *
  6613. * Offset control codes have a second byte in the range 0x21 to 0x23,
  6614. * with the first byte being 0x17 (for data channel 1) or 0x1f (for
  6615. * data channel 2).
  6616. *
  6617. * @param {Integer} char0 The first byte
  6618. * @param {Integer} char1 The second byte
  6619. * @return {Boolean} Whether the 2 bytes are an offset control code
  6620. */
  6621. Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
  6622. return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
  6623. };
  6624. /**
  6625. * Detects if the 2-byte packet is a Preamble Address Code
  6626. *
  6627. * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
  6628. * or 0x18 to 0x1f (for data channel 2), with the second byte in the
  6629. * range 0x40 to 0x7f.
  6630. *
  6631. * @param {Integer} char0 The first byte
  6632. * @param {Integer} char1 The second byte
  6633. * @return {Boolean} Whether the 2 bytes are a PAC
  6634. */
  6635. Cea608Stream.prototype.isPAC = function (char0, char1) {
  6636. return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
  6637. };
  6638. /**
  6639. * Detects if a packet's second byte is in the range of a PAC color code
  6640. *
  6641. * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
  6642. * 0x60 to 0x6f.
  6643. *
  6644. * @param {Integer} char1 The second byte
  6645. * @return {Boolean} Whether the byte is a color PAC
  6646. */
  6647. Cea608Stream.prototype.isColorPAC = function (char1) {
  6648. return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
  6649. };
  6650. /**
  6651. * Detects if a single byte is in the range of a normal character
  6652. *
  6653. * Normal text bytes are in the range 0x20 to 0x7f.
  6654. *
  6655. * @param {Integer} char The byte
  6656. * @return {Boolean} Whether the byte is a normal character
  6657. */
  6658. Cea608Stream.prototype.isNormalChar = function (char) {
  6659. return char >= 0x20 && char <= 0x7f;
  6660. };
  6661. /**
  6662. * Configures roll-up
  6663. *
  6664. * @param {Integer} pts Current PTS
  6665. * @param {Integer} newBaseRow Used by PACs to slide the current window to
  6666. * a new position
  6667. */
  6668. Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
  6669. // Reset the base row to the bottom row when switching modes
  6670. if (this.mode_ !== 'rollUp') {
  6671. this.row_ = BOTTOM_ROW;
  6672. this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
  6673. this.flushDisplayed(pts);
  6674. this.nonDisplayed_ = createDisplayBuffer();
  6675. this.displayed_ = createDisplayBuffer();
  6676. }
  6677. if (newBaseRow !== undefined && newBaseRow !== this.row_) {
  6678. // move currently displayed captions (up or down) to the new base row
  6679. for (var i = 0; i < this.rollUpRows_; i++) {
  6680. this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
  6681. this.displayed_[this.row_ - i] = {
  6682. text: '',
  6683. indent: 0,
  6684. offset: 0
  6685. };
  6686. }
  6687. }
  6688. if (newBaseRow === undefined) {
  6689. newBaseRow = this.row_;
  6690. }
  6691. this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  6692. }; // Adds the opening HTML tag for the passed character to the caption text,
  6693. // and keeps track of it for later closing
  6694. Cea608Stream.prototype.addFormatting = function (pts, format) {
  6695. this.formatting_ = this.formatting_.concat(format);
  6696. var text = format.reduce(function (text, format) {
  6697. return text + '<' + format + '>';
  6698. }, '');
  6699. this[this.mode_](pts, text);
  6700. }; // Adds HTML closing tags for current formatting to caption text and
  6701. // clears remembered formatting
  6702. Cea608Stream.prototype.clearFormatting = function (pts) {
  6703. if (!this.formatting_.length) {
  6704. return;
  6705. }
  6706. var text = this.formatting_.reverse().reduce(function (text, format) {
  6707. return text + '</' + format + '>';
  6708. }, '');
  6709. this.formatting_ = [];
  6710. this[this.mode_](pts, text);
  6711. }; // Mode Implementations
  6712. Cea608Stream.prototype.popOn = function (pts, text) {
  6713. var baseRow = this.nonDisplayed_[this.row_].text; // buffer characters
  6714. baseRow += text;
  6715. this.nonDisplayed_[this.row_].text = baseRow;
  6716. };
  6717. Cea608Stream.prototype.rollUp = function (pts, text) {
  6718. var baseRow = this.displayed_[this.row_].text;
  6719. baseRow += text;
  6720. this.displayed_[this.row_].text = baseRow;
  6721. };
  6722. Cea608Stream.prototype.shiftRowsUp_ = function () {
  6723. var i; // clear out inactive rows
  6724. for (i = 0; i < this.topRow_; i++) {
  6725. this.displayed_[i] = {
  6726. text: '',
  6727. indent: 0,
  6728. offset: 0
  6729. };
  6730. }
  6731. for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
  6732. this.displayed_[i] = {
  6733. text: '',
  6734. indent: 0,
  6735. offset: 0
  6736. };
  6737. } // shift displayed rows up
  6738. for (i = this.topRow_; i < this.row_; i++) {
  6739. this.displayed_[i] = this.displayed_[i + 1];
  6740. } // clear out the bottom row
  6741. this.displayed_[this.row_] = {
  6742. text: '',
  6743. indent: 0,
  6744. offset: 0
  6745. };
  6746. };
  6747. Cea608Stream.prototype.paintOn = function (pts, text) {
  6748. var baseRow = this.displayed_[this.row_].text;
  6749. baseRow += text;
  6750. this.displayed_[this.row_].text = baseRow;
  6751. }; // exports
  6752. var captionStream = {
  6753. CaptionStream: CaptionStream$2,
  6754. Cea608Stream: Cea608Stream,
  6755. Cea708Stream: Cea708Stream
  6756. };
  6757. /**
  6758. * mux.js
  6759. *
  6760. * Copyright (c) Brightcove
  6761. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6762. */
  6763. var streamTypes = {
  6764. H264_STREAM_TYPE: 0x1B,
  6765. ADTS_STREAM_TYPE: 0x0F,
  6766. METADATA_STREAM_TYPE: 0x15
  6767. };
  6768. /**
  6769. * mux.js
  6770. *
  6771. * Copyright (c) Brightcove
  6772. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6773. *
  6774. * Accepts program elementary stream (PES) data events and corrects
  6775. * decode and presentation time stamps to account for a rollover
  6776. * of the 33 bit value.
  6777. */
  6778. var Stream$6 = stream;
  6779. var MAX_TS = 8589934592;
  6780. var RO_THRESH = 4294967296;
  6781. var TYPE_SHARED = 'shared';
  6782. var handleRollover$1 = function (value, reference) {
  6783. var direction = 1;
  6784. if (value > reference) {
  6785. // If the current timestamp value is greater than our reference timestamp and we detect a
  6786. // timestamp rollover, this means the roll over is happening in the opposite direction.
  6787. // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
  6788. // point will be set to a small number, e.g. 1. The user then seeks backwards over the
  6789. // rollover point. In loading this segment, the timestamp values will be very large,
  6790. // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
  6791. // the time stamp to be `value - 2^33`.
  6792. direction = -1;
  6793. } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  6794. // cause an incorrect adjustment.
  6795. while (Math.abs(reference - value) > RO_THRESH) {
  6796. value += direction * MAX_TS;
  6797. }
  6798. return value;
  6799. };
  6800. var TimestampRolloverStream$1 = function (type) {
  6801. var lastDTS, referenceDTS;
  6802. TimestampRolloverStream$1.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
  6803. // video and audio. We could use `undefined` here, but having a string
  6804. // makes debugging a little clearer.
  6805. this.type_ = type || TYPE_SHARED;
  6806. this.push = function (data) {
  6807. /**
  6808. * Rollover stream expects data from elementary stream.
  6809. * Elementary stream can push forward 2 types of data
  6810. * - Parsed Video/Audio/Timed-metadata PES (packetized elementary stream) packets
  6811. * - Tracks metadata from PMT (Program Map Table)
  6812. * Rollover stream expects pts/dts info to be available, since it stores lastDTS
  6813. * We should ignore non-PES packets since they may override lastDTS to undefined.
  6814. * lastDTS is important to signal the next segments
  6815. * about rollover from the previous segments.
  6816. */
  6817. if (data.type === 'metadata') {
  6818. this.trigger('data', data);
  6819. return;
  6820. } // Any "shared" rollover streams will accept _all_ data. Otherwise,
  6821. // streams will only accept data that matches their type.
  6822. if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
  6823. return;
  6824. }
  6825. if (referenceDTS === undefined) {
  6826. referenceDTS = data.dts;
  6827. }
  6828. data.dts = handleRollover$1(data.dts, referenceDTS);
  6829. data.pts = handleRollover$1(data.pts, referenceDTS);
  6830. lastDTS = data.dts;
  6831. this.trigger('data', data);
  6832. };
  6833. this.flush = function () {
  6834. referenceDTS = lastDTS;
  6835. this.trigger('done');
  6836. };
  6837. this.endTimeline = function () {
  6838. this.flush();
  6839. this.trigger('endedtimeline');
  6840. };
  6841. this.discontinuity = function () {
  6842. referenceDTS = void 0;
  6843. lastDTS = void 0;
  6844. };
  6845. this.reset = function () {
  6846. this.discontinuity();
  6847. this.trigger('reset');
  6848. };
  6849. };
  6850. TimestampRolloverStream$1.prototype = new Stream$6();
  6851. var timestampRolloverStream = {
  6852. TimestampRolloverStream: TimestampRolloverStream$1,
  6853. handleRollover: handleRollover$1
  6854. }; // Once IE11 support is dropped, this function should be removed.
  6855. var typedArrayIndexOf$1 = (typedArray, element, fromIndex) => {
  6856. if (!typedArray) {
  6857. return -1;
  6858. }
  6859. var currentIndex = fromIndex;
  6860. for (; currentIndex < typedArray.length; currentIndex++) {
  6861. if (typedArray[currentIndex] === element) {
  6862. return currentIndex;
  6863. }
  6864. }
  6865. return -1;
  6866. };
  6867. var typedArray = {
  6868. typedArrayIndexOf: typedArrayIndexOf$1
  6869. };
  6870. /**
  6871. * mux.js
  6872. *
  6873. * Copyright (c) Brightcove
  6874. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6875. *
  6876. * Tools for parsing ID3 frame data
  6877. * @see http://id3.org/id3v2.3.0
  6878. */
  6879. var typedArrayIndexOf = typedArray.typedArrayIndexOf,
  6880. // Frames that allow different types of text encoding contain a text
  6881. // encoding description byte [ID3v2.4.0 section 4.]
  6882. textEncodingDescriptionByte = {
  6883. Iso88591: 0x00,
  6884. // ISO-8859-1, terminated with \0.
  6885. Utf16: 0x01,
  6886. // UTF-16 encoded Unicode BOM, terminated with \0\0
  6887. Utf16be: 0x02,
  6888. // UTF-16BE encoded Unicode, without BOM, terminated with \0\0
  6889. Utf8: 0x03 // UTF-8 encoded Unicode, terminated with \0
  6890. },
  6891. // return a percent-encoded representation of the specified byte range
  6892. // @see http://en.wikipedia.org/wiki/Percent-encoding
  6893. percentEncode$1 = function (bytes, start, end) {
  6894. var i,
  6895. result = '';
  6896. for (i = start; i < end; i++) {
  6897. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  6898. }
  6899. return result;
  6900. },
  6901. // return the string representation of the specified byte range,
  6902. // interpreted as UTf-8.
  6903. parseUtf8 = function (bytes, start, end) {
  6904. return decodeURIComponent(percentEncode$1(bytes, start, end));
  6905. },
  6906. // return the string representation of the specified byte range,
  6907. // interpreted as ISO-8859-1.
  6908. parseIso88591$1 = function (bytes, start, end) {
  6909. return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
  6910. },
  6911. parseSyncSafeInteger$1 = function (data) {
  6912. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  6913. },
  6914. frameParsers = {
  6915. 'APIC': function (frame) {
  6916. var i = 1,
  6917. mimeTypeEndIndex,
  6918. descriptionEndIndex,
  6919. LINK_MIME_TYPE = '-->';
  6920. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  6921. // ignore frames with unrecognized character encodings
  6922. return;
  6923. } // parsing fields [ID3v2.4.0 section 4.14.]
  6924. mimeTypeEndIndex = typedArrayIndexOf(frame.data, 0, i);
  6925. if (mimeTypeEndIndex < 0) {
  6926. // malformed frame
  6927. return;
  6928. } // parsing Mime type field (terminated with \0)
  6929. frame.mimeType = parseIso88591$1(frame.data, i, mimeTypeEndIndex);
  6930. i = mimeTypeEndIndex + 1; // parsing 1-byte Picture Type field
  6931. frame.pictureType = frame.data[i];
  6932. i++;
  6933. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, i);
  6934. if (descriptionEndIndex < 0) {
  6935. // malformed frame
  6936. return;
  6937. } // parsing Description field (terminated with \0)
  6938. frame.description = parseUtf8(frame.data, i, descriptionEndIndex);
  6939. i = descriptionEndIndex + 1;
  6940. if (frame.mimeType === LINK_MIME_TYPE) {
  6941. // parsing Picture Data field as URL (always represented as ISO-8859-1 [ID3v2.4.0 section 4.])
  6942. frame.url = parseIso88591$1(frame.data, i, frame.data.length);
  6943. } else {
  6944. // parsing Picture Data field as binary data
  6945. frame.pictureData = frame.data.subarray(i, frame.data.length);
  6946. }
  6947. },
  6948. 'T*': function (frame) {
  6949. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  6950. // ignore frames with unrecognized character encodings
  6951. return;
  6952. } // parse text field, do not include null terminator in the frame value
  6953. // frames that allow different types of encoding contain terminated text [ID3v2.4.0 section 4.]
  6954. 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.]
  6955. frame.values = frame.value.split('\0');
  6956. },
  6957. 'TXXX': function (frame) {
  6958. var descriptionEndIndex;
  6959. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  6960. // ignore frames with unrecognized character encodings
  6961. return;
  6962. }
  6963. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  6964. if (descriptionEndIndex === -1) {
  6965. return;
  6966. } // parse the text fields
  6967. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // do not include the null terminator in the tag value
  6968. // frames that allow different types of encoding contain terminated text
  6969. // [ID3v2.4.0 section 4.]
  6970. frame.value = parseUtf8(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0*$/, '');
  6971. frame.data = frame.value;
  6972. },
  6973. 'W*': function (frame) {
  6974. // parse URL field; URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  6975. // if the value is followed by a string termination all the following information should be ignored [ID3v2.4.0 section 4.3]
  6976. frame.url = parseIso88591$1(frame.data, 0, frame.data.length).replace(/\0.*$/, '');
  6977. },
  6978. 'WXXX': function (frame) {
  6979. var descriptionEndIndex;
  6980. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  6981. // ignore frames with unrecognized character encodings
  6982. return;
  6983. }
  6984. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  6985. if (descriptionEndIndex === -1) {
  6986. return;
  6987. } // parse the description and URL fields
  6988. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  6989. // if the value is followed by a string termination all the following information
  6990. // should be ignored [ID3v2.4.0 section 4.3]
  6991. frame.url = parseIso88591$1(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0.*$/, '');
  6992. },
  6993. 'PRIV': function (frame) {
  6994. var i;
  6995. for (i = 0; i < frame.data.length; i++) {
  6996. if (frame.data[i] === 0) {
  6997. // parse the description and URL fields
  6998. frame.owner = parseIso88591$1(frame.data, 0, i);
  6999. break;
  7000. }
  7001. }
  7002. frame.privateData = frame.data.subarray(i + 1);
  7003. frame.data = frame.privateData;
  7004. }
  7005. };
  7006. var parseId3Frames$1 = function (data) {
  7007. var frameSize,
  7008. frameHeader,
  7009. frameStart = 10,
  7010. tagSize = 0,
  7011. frames = []; // If we don't have enough data for a header, 10 bytes,
  7012. // or 'ID3' in the first 3 bytes this is not a valid ID3 tag.
  7013. if (data.length < 10 || data[0] !== 'I'.charCodeAt(0) || data[1] !== 'D'.charCodeAt(0) || data[2] !== '3'.charCodeAt(0)) {
  7014. return;
  7015. } // the frame size is transmitted as a 28-bit integer in the
  7016. // last four bytes of the ID3 header.
  7017. // The most significant bit of each byte is dropped and the
  7018. // results concatenated to recover the actual value.
  7019. tagSize = parseSyncSafeInteger$1(data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  7020. // convenient for our comparisons to include it
  7021. tagSize += 10; // check bit 6 of byte 5 for the extended header flag.
  7022. var hasExtendedHeader = data[5] & 0x40;
  7023. if (hasExtendedHeader) {
  7024. // advance the frame start past the extended header
  7025. frameStart += 4; // header size field
  7026. frameStart += parseSyncSafeInteger$1(data.subarray(10, 14));
  7027. tagSize -= parseSyncSafeInteger$1(data.subarray(16, 20)); // clip any padding off the end
  7028. } // parse one or more ID3 frames
  7029. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  7030. do {
  7031. // determine the number of bytes in this frame
  7032. frameSize = parseSyncSafeInteger$1(data.subarray(frameStart + 4, frameStart + 8));
  7033. if (frameSize < 1) {
  7034. break;
  7035. }
  7036. frameHeader = String.fromCharCode(data[frameStart], data[frameStart + 1], data[frameStart + 2], data[frameStart + 3]);
  7037. var frame = {
  7038. id: frameHeader,
  7039. data: data.subarray(frameStart + 10, frameStart + frameSize + 10)
  7040. };
  7041. frame.key = frame.id; // parse frame values
  7042. if (frameParsers[frame.id]) {
  7043. // use frame specific parser
  7044. frameParsers[frame.id](frame);
  7045. } else if (frame.id[0] === 'T') {
  7046. // use text frame generic parser
  7047. frameParsers['T*'](frame);
  7048. } else if (frame.id[0] === 'W') {
  7049. // use URL link frame generic parser
  7050. frameParsers['W*'](frame);
  7051. }
  7052. frames.push(frame);
  7053. frameStart += 10; // advance past the frame header
  7054. frameStart += frameSize; // advance past the frame body
  7055. } while (frameStart < tagSize);
  7056. return frames;
  7057. };
  7058. var parseId3 = {
  7059. parseId3Frames: parseId3Frames$1,
  7060. parseSyncSafeInteger: parseSyncSafeInteger$1,
  7061. frameParsers: frameParsers
  7062. };
  7063. /**
  7064. * mux.js
  7065. *
  7066. * Copyright (c) Brightcove
  7067. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  7068. *
  7069. * Accepts program elementary stream (PES) data events and parses out
  7070. * ID3 metadata from them, if present.
  7071. * @see http://id3.org/id3v2.3.0
  7072. */
  7073. var Stream$5 = stream,
  7074. StreamTypes$3 = streamTypes,
  7075. id3 = parseId3,
  7076. MetadataStream;
  7077. MetadataStream = function (options) {
  7078. var settings = {
  7079. // the bytes of the program-level descriptor field in MP2T
  7080. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  7081. // program element descriptors"
  7082. descriptor: options && options.descriptor
  7083. },
  7084. // the total size in bytes of the ID3 tag being parsed
  7085. tagSize = 0,
  7086. // tag data that is not complete enough to be parsed
  7087. buffer = [],
  7088. // the total number of bytes currently in the buffer
  7089. bufferSize = 0,
  7090. i;
  7091. MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
  7092. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  7093. this.dispatchType = StreamTypes$3.METADATA_STREAM_TYPE.toString(16);
  7094. if (settings.descriptor) {
  7095. for (i = 0; i < settings.descriptor.length; i++) {
  7096. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  7097. }
  7098. }
  7099. this.push = function (chunk) {
  7100. var tag, frameStart, frameSize, frame, i, frameHeader;
  7101. if (chunk.type !== 'timed-metadata') {
  7102. return;
  7103. } // if data_alignment_indicator is set in the PES header,
  7104. // we must have the start of a new ID3 tag. Assume anything
  7105. // remaining in the buffer was malformed and throw it out
  7106. if (chunk.dataAlignmentIndicator) {
  7107. bufferSize = 0;
  7108. buffer.length = 0;
  7109. } // ignore events that don't look like ID3 data
  7110. 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))) {
  7111. this.trigger('log', {
  7112. level: 'warn',
  7113. message: 'Skipping unrecognized metadata packet'
  7114. });
  7115. return;
  7116. } // add this chunk to the data we've collected so far
  7117. buffer.push(chunk);
  7118. bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
  7119. if (buffer.length === 1) {
  7120. // the frame size is transmitted as a 28-bit integer in the
  7121. // last four bytes of the ID3 header.
  7122. // The most significant bit of each byte is dropped and the
  7123. // results concatenated to recover the actual value.
  7124. tagSize = id3.parseSyncSafeInteger(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  7125. // convenient for our comparisons to include it
  7126. tagSize += 10;
  7127. } // if the entire frame has not arrived, wait for more data
  7128. if (bufferSize < tagSize) {
  7129. return;
  7130. } // collect the entire frame so it can be parsed
  7131. tag = {
  7132. data: new Uint8Array(tagSize),
  7133. frames: [],
  7134. pts: buffer[0].pts,
  7135. dts: buffer[0].dts
  7136. };
  7137. for (i = 0; i < tagSize;) {
  7138. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  7139. i += buffer[0].data.byteLength;
  7140. bufferSize -= buffer[0].data.byteLength;
  7141. buffer.shift();
  7142. } // find the start of the first frame and the end of the tag
  7143. frameStart = 10;
  7144. if (tag.data[5] & 0x40) {
  7145. // advance the frame start past the extended header
  7146. frameStart += 4; // header size field
  7147. frameStart += id3.parseSyncSafeInteger(tag.data.subarray(10, 14)); // clip any padding off the end
  7148. tagSize -= id3.parseSyncSafeInteger(tag.data.subarray(16, 20));
  7149. } // parse one or more ID3 frames
  7150. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  7151. do {
  7152. // determine the number of bytes in this frame
  7153. frameSize = id3.parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
  7154. if (frameSize < 1) {
  7155. this.trigger('log', {
  7156. level: 'warn',
  7157. message: 'Malformed ID3 frame encountered. Skipping remaining metadata parsing.'
  7158. }); // If the frame is malformed, don't parse any further frames but allow previous valid parsed frames
  7159. // to be sent along.
  7160. break;
  7161. }
  7162. frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
  7163. frame = {
  7164. id: frameHeader,
  7165. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  7166. };
  7167. frame.key = frame.id; // parse frame values
  7168. if (id3.frameParsers[frame.id]) {
  7169. // use frame specific parser
  7170. id3.frameParsers[frame.id](frame);
  7171. } else if (frame.id[0] === 'T') {
  7172. // use text frame generic parser
  7173. id3.frameParsers['T*'](frame);
  7174. } else if (frame.id[0] === 'W') {
  7175. // use URL link frame generic parser
  7176. id3.frameParsers['W*'](frame);
  7177. } // handle the special PRIV frame used to indicate the start
  7178. // time for raw AAC data
  7179. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  7180. var d = frame.data,
  7181. size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  7182. size *= 4;
  7183. size += d[7] & 0x03;
  7184. frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
  7185. // on the value of this frame
  7186. // we couldn't have known the appropriate pts and dts before
  7187. // parsing this ID3 tag so set those values now
  7188. if (tag.pts === undefined && tag.dts === undefined) {
  7189. tag.pts = frame.timeStamp;
  7190. tag.dts = frame.timeStamp;
  7191. }
  7192. this.trigger('timestamp', frame);
  7193. }
  7194. tag.frames.push(frame);
  7195. frameStart += 10; // advance past the frame header
  7196. frameStart += frameSize; // advance past the frame body
  7197. } while (frameStart < tagSize);
  7198. this.trigger('data', tag);
  7199. };
  7200. };
  7201. MetadataStream.prototype = new Stream$5();
  7202. var metadataStream = MetadataStream;
  7203. /**
  7204. * mux.js
  7205. *
  7206. * Copyright (c) Brightcove
  7207. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  7208. *
  7209. * A stream-based mp2t to mp4 converter. This utility can be used to
  7210. * deliver mp4s to a SourceBuffer on platforms that support native
  7211. * Media Source Extensions.
  7212. */
  7213. var Stream$4 = stream,
  7214. CaptionStream$1 = captionStream,
  7215. StreamTypes$2 = streamTypes,
  7216. TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
  7217. var TransportPacketStream, TransportParseStream, ElementaryStream; // constants
  7218. var MP2T_PACKET_LENGTH$1 = 188,
  7219. // bytes
  7220. SYNC_BYTE$1 = 0x47;
  7221. /**
  7222. * Splits an incoming stream of binary data into MPEG-2 Transport
  7223. * Stream packets.
  7224. */
  7225. TransportPacketStream = function () {
  7226. var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),
  7227. bytesInBuffer = 0;
  7228. TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
  7229. /**
  7230. * Split a stream of data into M2TS packets
  7231. **/
  7232. this.push = function (bytes) {
  7233. var startIndex = 0,
  7234. endIndex = MP2T_PACKET_LENGTH$1,
  7235. everything; // If there are bytes remaining from the last segment, prepend them to the
  7236. // bytes that were pushed in
  7237. if (bytesInBuffer) {
  7238. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  7239. everything.set(buffer.subarray(0, bytesInBuffer));
  7240. everything.set(bytes, bytesInBuffer);
  7241. bytesInBuffer = 0;
  7242. } else {
  7243. everything = bytes;
  7244. } // While we have enough data for a packet
  7245. while (endIndex < everything.byteLength) {
  7246. // Look for a pair of start and end sync bytes in the data..
  7247. if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
  7248. // We found a packet so emit it and jump one whole packet forward in
  7249. // the stream
  7250. this.trigger('data', everything.subarray(startIndex, endIndex));
  7251. startIndex += MP2T_PACKET_LENGTH$1;
  7252. endIndex += MP2T_PACKET_LENGTH$1;
  7253. continue;
  7254. } // If we get here, we have somehow become de-synchronized and we need to step
  7255. // forward one byte at a time until we find a pair of sync bytes that denote
  7256. // a packet
  7257. startIndex++;
  7258. endIndex++;
  7259. } // If there was some data left over at the end of the segment that couldn't
  7260. // possibly be a whole packet, keep it because it might be the start of a packet
  7261. // that continues in the next segment
  7262. if (startIndex < everything.byteLength) {
  7263. buffer.set(everything.subarray(startIndex), 0);
  7264. bytesInBuffer = everything.byteLength - startIndex;
  7265. }
  7266. };
  7267. /**
  7268. * Passes identified M2TS packets to the TransportParseStream to be parsed
  7269. **/
  7270. this.flush = function () {
  7271. // If the buffer contains a whole packet when we are being flushed, emit it
  7272. // and empty the buffer. Otherwise hold onto the data because it may be
  7273. // important for decoding the next segment
  7274. if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
  7275. this.trigger('data', buffer);
  7276. bytesInBuffer = 0;
  7277. }
  7278. this.trigger('done');
  7279. };
  7280. this.endTimeline = function () {
  7281. this.flush();
  7282. this.trigger('endedtimeline');
  7283. };
  7284. this.reset = function () {
  7285. bytesInBuffer = 0;
  7286. this.trigger('reset');
  7287. };
  7288. };
  7289. TransportPacketStream.prototype = new Stream$4();
  7290. /**
  7291. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  7292. * forms of the individual transport stream packets.
  7293. */
  7294. TransportParseStream = function () {
  7295. var parsePsi, parsePat, parsePmt, self;
  7296. TransportParseStream.prototype.init.call(this);
  7297. self = this;
  7298. this.packetsWaitingForPmt = [];
  7299. this.programMapTable = undefined;
  7300. parsePsi = function (payload, psi) {
  7301. var offset = 0; // PSI packets may be split into multiple sections and those
  7302. // sections may be split into multiple packets. If a PSI
  7303. // section starts in this packet, the payload_unit_start_indicator
  7304. // will be true and the first byte of the payload will indicate
  7305. // the offset from the current position to the start of the
  7306. // section.
  7307. if (psi.payloadUnitStartIndicator) {
  7308. offset += payload[offset] + 1;
  7309. }
  7310. if (psi.type === 'pat') {
  7311. parsePat(payload.subarray(offset), psi);
  7312. } else {
  7313. parsePmt(payload.subarray(offset), psi);
  7314. }
  7315. };
  7316. parsePat = function (payload, pat) {
  7317. pat.section_number = payload[7]; // eslint-disable-line camelcase
  7318. pat.last_section_number = payload[8]; // eslint-disable-line camelcase
  7319. // skip the PSI header and parse the first PMT entry
  7320. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  7321. pat.pmtPid = self.pmtPid;
  7322. };
  7323. /**
  7324. * Parse out the relevant fields of a Program Map Table (PMT).
  7325. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  7326. * packet. The first byte in this array should be the table_id
  7327. * field.
  7328. * @param pmt {object} the object that should be decorated with
  7329. * fields parsed from the PMT.
  7330. */
  7331. parsePmt = function (payload, pmt) {
  7332. var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
  7333. // take effect. We don't believe this should ever be the case
  7334. // for HLS but we'll ignore "forward" PMT declarations if we see
  7335. // them. Future PMT declarations have the current_next_indicator
  7336. // set to zero.
  7337. if (!(payload[5] & 0x01)) {
  7338. return;
  7339. } // overwrite any existing program map table
  7340. self.programMapTable = {
  7341. video: null,
  7342. audio: null,
  7343. 'timed-metadata': {}
  7344. }; // the mapping table ends at the end of the current section
  7345. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  7346. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  7347. // long the program info descriptors are
  7348. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
  7349. offset = 12 + programInfoLength;
  7350. while (offset < tableEnd) {
  7351. var streamType = payload[offset];
  7352. var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
  7353. // TODO: should this be done for metadata too? for now maintain behavior of
  7354. // multiple metadata streams
  7355. if (streamType === StreamTypes$2.H264_STREAM_TYPE && self.programMapTable.video === null) {
  7356. self.programMapTable.video = pid;
  7357. } else if (streamType === StreamTypes$2.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
  7358. self.programMapTable.audio = pid;
  7359. } else if (streamType === StreamTypes$2.METADATA_STREAM_TYPE) {
  7360. // map pid to stream type for metadata streams
  7361. self.programMapTable['timed-metadata'][pid] = streamType;
  7362. } // move to the next table entry
  7363. // skip past the elementary stream descriptors, if present
  7364. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  7365. } // record the map on the packet as well
  7366. pmt.programMapTable = self.programMapTable;
  7367. };
  7368. /**
  7369. * Deliver a new MP2T packet to the next stream in the pipeline.
  7370. */
  7371. this.push = function (packet) {
  7372. var result = {},
  7373. offset = 4;
  7374. result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
  7375. result.pid = packet[1] & 0x1f;
  7376. result.pid <<= 8;
  7377. result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
  7378. // fifth byte of the TS packet header. The adaptation field is
  7379. // used to add stuffing to PES packets that don't fill a complete
  7380. // TS packet, and to specify some forms of timing and control data
  7381. // that we do not currently use.
  7382. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  7383. offset += packet[offset] + 1;
  7384. } // parse the rest of the packet based on the type
  7385. if (result.pid === 0) {
  7386. result.type = 'pat';
  7387. parsePsi(packet.subarray(offset), result);
  7388. this.trigger('data', result);
  7389. } else if (result.pid === this.pmtPid) {
  7390. result.type = 'pmt';
  7391. parsePsi(packet.subarray(offset), result);
  7392. this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
  7393. while (this.packetsWaitingForPmt.length) {
  7394. this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
  7395. }
  7396. } else if (this.programMapTable === undefined) {
  7397. // When we have not seen a PMT yet, defer further processing of
  7398. // PES packets until one has been parsed
  7399. this.packetsWaitingForPmt.push([packet, offset, result]);
  7400. } else {
  7401. this.processPes_(packet, offset, result);
  7402. }
  7403. };
  7404. this.processPes_ = function (packet, offset, result) {
  7405. // set the appropriate stream type
  7406. if (result.pid === this.programMapTable.video) {
  7407. result.streamType = StreamTypes$2.H264_STREAM_TYPE;
  7408. } else if (result.pid === this.programMapTable.audio) {
  7409. result.streamType = StreamTypes$2.ADTS_STREAM_TYPE;
  7410. } else {
  7411. // if not video or audio, it is timed-metadata or unknown
  7412. // if unknown, streamType will be undefined
  7413. result.streamType = this.programMapTable['timed-metadata'][result.pid];
  7414. }
  7415. result.type = 'pes';
  7416. result.data = packet.subarray(offset);
  7417. this.trigger('data', result);
  7418. };
  7419. };
  7420. TransportParseStream.prototype = new Stream$4();
  7421. TransportParseStream.STREAM_TYPES = {
  7422. h264: 0x1b,
  7423. adts: 0x0f
  7424. };
  7425. /**
  7426. * Reconsistutes program elementary stream (PES) packets from parsed
  7427. * transport stream packets. That is, if you pipe an
  7428. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  7429. * events will be events which capture the bytes for individual PES
  7430. * packets plus relevant metadata that has been extracted from the
  7431. * container.
  7432. */
  7433. ElementaryStream = function () {
  7434. var self = this,
  7435. segmentHadPmt = false,
  7436. // PES packet fragments
  7437. video = {
  7438. data: [],
  7439. size: 0
  7440. },
  7441. audio = {
  7442. data: [],
  7443. size: 0
  7444. },
  7445. timedMetadata = {
  7446. data: [],
  7447. size: 0
  7448. },
  7449. programMapTable,
  7450. parsePes = function (payload, pes) {
  7451. var ptsDtsFlags;
  7452. const startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
  7453. pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
  7454. // that are frame data that is continuing from the previous fragment. This
  7455. // is to check that the pes data is the start of a new pes payload
  7456. if (startPrefix !== 1) {
  7457. return;
  7458. } // get the packet length, this will be 0 for video
  7459. pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
  7460. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
  7461. // and a DTS value. Determine what combination of values is
  7462. // available to work with.
  7463. ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  7464. // performs all bitwise operations on 32-bit integers but javascript
  7465. // supports a much greater range (52-bits) of integer using standard
  7466. // mathematical operations.
  7467. // We construct a 31-bit value using bitwise operators over the 31
  7468. // most significant bits and then multiply by 4 (equal to a left-shift
  7469. // of 2) before we add the final 2 least significant bits of the
  7470. // timestamp (equal to an OR.)
  7471. if (ptsDtsFlags & 0xC0) {
  7472. // the PTS and DTS are not written out directly. For information
  7473. // on how they are encoded, see
  7474. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  7475. pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
  7476. pes.pts *= 4; // Left shift by 2
  7477. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  7478. pes.dts = pes.pts;
  7479. if (ptsDtsFlags & 0x40) {
  7480. pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
  7481. pes.dts *= 4; // Left shift by 2
  7482. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  7483. }
  7484. } // the data section starts immediately after the PES header.
  7485. // pes_header_data_length specifies the number of header bytes
  7486. // that follow the last byte of the field.
  7487. pes.data = payload.subarray(9 + payload[8]);
  7488. },
  7489. /**
  7490. * Pass completely parsed PES packets to the next stream in the pipeline
  7491. **/
  7492. flushStream = function (stream, type, forceFlush) {
  7493. var packetData = new Uint8Array(stream.size),
  7494. event = {
  7495. type: type
  7496. },
  7497. i = 0,
  7498. offset = 0,
  7499. packetFlushable = false,
  7500. fragment; // do nothing if there is not enough buffered data for a complete
  7501. // PES header
  7502. if (!stream.data.length || stream.size < 9) {
  7503. return;
  7504. }
  7505. event.trackId = stream.data[0].pid; // reassemble the packet
  7506. for (i = 0; i < stream.data.length; i++) {
  7507. fragment = stream.data[i];
  7508. packetData.set(fragment.data, offset);
  7509. offset += fragment.data.byteLength;
  7510. } // parse assembled packet's PES header
  7511. parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
  7512. // check that there is enough stream data to fill the packet
  7513. packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
  7514. if (forceFlush || packetFlushable) {
  7515. stream.size = 0;
  7516. stream.data.length = 0;
  7517. } // only emit packets that are complete. this is to avoid assembling
  7518. // incomplete PES packets due to poor segmentation
  7519. if (packetFlushable) {
  7520. self.trigger('data', event);
  7521. }
  7522. };
  7523. ElementaryStream.prototype.init.call(this);
  7524. /**
  7525. * Identifies M2TS packet types and parses PES packets using metadata
  7526. * parsed from the PMT
  7527. **/
  7528. this.push = function (data) {
  7529. ({
  7530. pat: function () {// we have to wait for the PMT to arrive as well before we
  7531. // have any meaningful metadata
  7532. },
  7533. pes: function () {
  7534. var stream, streamType;
  7535. switch (data.streamType) {
  7536. case StreamTypes$2.H264_STREAM_TYPE:
  7537. stream = video;
  7538. streamType = 'video';
  7539. break;
  7540. case StreamTypes$2.ADTS_STREAM_TYPE:
  7541. stream = audio;
  7542. streamType = 'audio';
  7543. break;
  7544. case StreamTypes$2.METADATA_STREAM_TYPE:
  7545. stream = timedMetadata;
  7546. streamType = 'timed-metadata';
  7547. break;
  7548. default:
  7549. // ignore unknown stream types
  7550. return;
  7551. } // if a new packet is starting, we can flush the completed
  7552. // packet
  7553. if (data.payloadUnitStartIndicator) {
  7554. flushStream(stream, streamType, true);
  7555. } // buffer this fragment until we are sure we've received the
  7556. // complete payload
  7557. stream.data.push(data);
  7558. stream.size += data.data.byteLength;
  7559. },
  7560. pmt: function () {
  7561. var event = {
  7562. type: 'metadata',
  7563. tracks: []
  7564. };
  7565. programMapTable = data.programMapTable; // translate audio and video streams to tracks
  7566. if (programMapTable.video !== null) {
  7567. event.tracks.push({
  7568. timelineStartInfo: {
  7569. baseMediaDecodeTime: 0
  7570. },
  7571. id: +programMapTable.video,
  7572. codec: 'avc',
  7573. type: 'video'
  7574. });
  7575. }
  7576. if (programMapTable.audio !== null) {
  7577. event.tracks.push({
  7578. timelineStartInfo: {
  7579. baseMediaDecodeTime: 0
  7580. },
  7581. id: +programMapTable.audio,
  7582. codec: 'adts',
  7583. type: 'audio'
  7584. });
  7585. }
  7586. segmentHadPmt = true;
  7587. self.trigger('data', event);
  7588. }
  7589. })[data.type]();
  7590. };
  7591. this.reset = function () {
  7592. video.size = 0;
  7593. video.data.length = 0;
  7594. audio.size = 0;
  7595. audio.data.length = 0;
  7596. this.trigger('reset');
  7597. };
  7598. /**
  7599. * Flush any remaining input. Video PES packets may be of variable
  7600. * length. Normally, the start of a new video packet can trigger the
  7601. * finalization of the previous packet. That is not possible if no
  7602. * more video is forthcoming, however. In that case, some other
  7603. * mechanism (like the end of the file) has to be employed. When it is
  7604. * clear that no additional data is forthcoming, calling this method
  7605. * will flush the buffered packets.
  7606. */
  7607. this.flushStreams_ = function () {
  7608. // !!THIS ORDER IS IMPORTANT!!
  7609. // video first then audio
  7610. flushStream(video, 'video');
  7611. flushStream(audio, 'audio');
  7612. flushStream(timedMetadata, 'timed-metadata');
  7613. };
  7614. this.flush = function () {
  7615. // if on flush we haven't had a pmt emitted
  7616. // and we have a pmt to emit. emit the pmt
  7617. // so that we trigger a trackinfo downstream.
  7618. if (!segmentHadPmt && programMapTable) {
  7619. var pmt = {
  7620. type: 'metadata',
  7621. tracks: []
  7622. }; // translate audio and video streams to tracks
  7623. if (programMapTable.video !== null) {
  7624. pmt.tracks.push({
  7625. timelineStartInfo: {
  7626. baseMediaDecodeTime: 0
  7627. },
  7628. id: +programMapTable.video,
  7629. codec: 'avc',
  7630. type: 'video'
  7631. });
  7632. }
  7633. if (programMapTable.audio !== null) {
  7634. pmt.tracks.push({
  7635. timelineStartInfo: {
  7636. baseMediaDecodeTime: 0
  7637. },
  7638. id: +programMapTable.audio,
  7639. codec: 'adts',
  7640. type: 'audio'
  7641. });
  7642. }
  7643. self.trigger('data', pmt);
  7644. }
  7645. segmentHadPmt = false;
  7646. this.flushStreams_();
  7647. this.trigger('done');
  7648. };
  7649. };
  7650. ElementaryStream.prototype = new Stream$4();
  7651. var m2ts$1 = {
  7652. PAT_PID: 0x0000,
  7653. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
  7654. TransportPacketStream: TransportPacketStream,
  7655. TransportParseStream: TransportParseStream,
  7656. ElementaryStream: ElementaryStream,
  7657. TimestampRolloverStream: TimestampRolloverStream,
  7658. CaptionStream: CaptionStream$1.CaptionStream,
  7659. Cea608Stream: CaptionStream$1.Cea608Stream,
  7660. Cea708Stream: CaptionStream$1.Cea708Stream,
  7661. MetadataStream: metadataStream
  7662. };
  7663. for (var type in StreamTypes$2) {
  7664. if (StreamTypes$2.hasOwnProperty(type)) {
  7665. m2ts$1[type] = StreamTypes$2[type];
  7666. }
  7667. }
  7668. var m2ts_1 = m2ts$1;
  7669. /**
  7670. * mux.js
  7671. *
  7672. * Copyright (c) Brightcove
  7673. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  7674. */
  7675. var Stream$3 = stream;
  7676. var ONE_SECOND_IN_TS$2 = clock$2.ONE_SECOND_IN_TS;
  7677. var AdtsStream$1;
  7678. var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  7679. /*
  7680. * Accepts a ElementaryStream and emits data events with parsed
  7681. * AAC Audio Frames of the individual packets. Input audio in ADTS
  7682. * format is unpacked and re-emitted as AAC frames.
  7683. *
  7684. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  7685. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  7686. */
  7687. AdtsStream$1 = function (handlePartialSegments) {
  7688. var buffer,
  7689. frameNum = 0;
  7690. AdtsStream$1.prototype.init.call(this);
  7691. this.skipWarn_ = function (start, end) {
  7692. this.trigger('log', {
  7693. level: 'warn',
  7694. message: `adts skiping bytes ${start} to ${end} in frame ${frameNum} outside syncword`
  7695. });
  7696. };
  7697. this.push = function (packet) {
  7698. var i = 0,
  7699. frameLength,
  7700. protectionSkipBytes,
  7701. oldBuffer,
  7702. sampleCount,
  7703. adtsFrameDuration;
  7704. if (!handlePartialSegments) {
  7705. frameNum = 0;
  7706. }
  7707. if (packet.type !== 'audio') {
  7708. // ignore non-audio data
  7709. return;
  7710. } // Prepend any data in the buffer to the input data so that we can parse
  7711. // aac frames the cross a PES packet boundary
  7712. if (buffer && buffer.length) {
  7713. oldBuffer = buffer;
  7714. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  7715. buffer.set(oldBuffer);
  7716. buffer.set(packet.data, oldBuffer.byteLength);
  7717. } else {
  7718. buffer = packet.data;
  7719. } // unpack any ADTS frames which have been fully received
  7720. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  7721. var skip; // We use i + 7 here because we want to be able to parse the entire header.
  7722. // If we don't have enough bytes to do that, then we definitely won't have a full frame.
  7723. while (i + 7 < buffer.length) {
  7724. // Look for the start of an ADTS header..
  7725. if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
  7726. if (typeof skip !== 'number') {
  7727. skip = i;
  7728. } // If a valid header was not found, jump one forward and attempt to
  7729. // find a valid ADTS header starting at the next byte
  7730. i++;
  7731. continue;
  7732. }
  7733. if (typeof skip === 'number') {
  7734. this.skipWarn_(skip, i);
  7735. skip = null;
  7736. } // The protection skip bit tells us if we have 2 bytes of CRC data at the
  7737. // end of the ADTS header
  7738. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
  7739. // end of the sync sequence
  7740. // NOTE: frame length includes the size of the header
  7741. frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
  7742. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  7743. 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,
  7744. // then we have to wait for more data
  7745. if (buffer.byteLength - i < frameLength) {
  7746. break;
  7747. } // Otherwise, deliver the complete AAC frame
  7748. this.trigger('data', {
  7749. pts: packet.pts + frameNum * adtsFrameDuration,
  7750. dts: packet.dts + frameNum * adtsFrameDuration,
  7751. sampleCount: sampleCount,
  7752. audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
  7753. channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
  7754. samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
  7755. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  7756. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  7757. samplesize: 16,
  7758. // data is the frame without it's header
  7759. data: buffer.subarray(i + 7 + protectionSkipBytes, i + frameLength)
  7760. });
  7761. frameNum++;
  7762. i += frameLength;
  7763. }
  7764. if (typeof skip === 'number') {
  7765. this.skipWarn_(skip, i);
  7766. skip = null;
  7767. } // remove processed bytes from the buffer.
  7768. buffer = buffer.subarray(i);
  7769. };
  7770. this.flush = function () {
  7771. frameNum = 0;
  7772. this.trigger('done');
  7773. };
  7774. this.reset = function () {
  7775. buffer = void 0;
  7776. this.trigger('reset');
  7777. };
  7778. this.endTimeline = function () {
  7779. buffer = void 0;
  7780. this.trigger('endedtimeline');
  7781. };
  7782. };
  7783. AdtsStream$1.prototype = new Stream$3();
  7784. var adts = AdtsStream$1;
  7785. /**
  7786. * mux.js
  7787. *
  7788. * Copyright (c) Brightcove
  7789. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  7790. */
  7791. var ExpGolomb$1;
  7792. /**
  7793. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  7794. * scheme used by h264.
  7795. */
  7796. ExpGolomb$1 = function (workingData) {
  7797. var // the number of bytes left to examine in workingData
  7798. workingBytesAvailable = workingData.byteLength,
  7799. // the current word being examined
  7800. workingWord = 0,
  7801. // :uint
  7802. // the number of bits left to examine in the current word
  7803. workingBitsAvailable = 0; // :uint;
  7804. // ():uint
  7805. this.length = function () {
  7806. return 8 * workingBytesAvailable;
  7807. }; // ():uint
  7808. this.bitsAvailable = function () {
  7809. return 8 * workingBytesAvailable + workingBitsAvailable;
  7810. }; // ():void
  7811. this.loadWord = function () {
  7812. var position = workingData.byteLength - workingBytesAvailable,
  7813. workingBytes = new Uint8Array(4),
  7814. availableBytes = Math.min(4, workingBytesAvailable);
  7815. if (availableBytes === 0) {
  7816. throw new Error('no bytes available');
  7817. }
  7818. workingBytes.set(workingData.subarray(position, position + availableBytes));
  7819. workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
  7820. workingBitsAvailable = availableBytes * 8;
  7821. workingBytesAvailable -= availableBytes;
  7822. }; // (count:int):void
  7823. this.skipBits = function (count) {
  7824. var skipBytes; // :int
  7825. if (workingBitsAvailable > count) {
  7826. workingWord <<= count;
  7827. workingBitsAvailable -= count;
  7828. } else {
  7829. count -= workingBitsAvailable;
  7830. skipBytes = Math.floor(count / 8);
  7831. count -= skipBytes * 8;
  7832. workingBytesAvailable -= skipBytes;
  7833. this.loadWord();
  7834. workingWord <<= count;
  7835. workingBitsAvailable -= count;
  7836. }
  7837. }; // (size:int):uint
  7838. this.readBits = function (size) {
  7839. var bits = Math.min(workingBitsAvailable, size),
  7840. // :uint
  7841. valu = workingWord >>> 32 - bits; // :uint
  7842. // if size > 31, handle error
  7843. workingBitsAvailable -= bits;
  7844. if (workingBitsAvailable > 0) {
  7845. workingWord <<= bits;
  7846. } else if (workingBytesAvailable > 0) {
  7847. this.loadWord();
  7848. }
  7849. bits = size - bits;
  7850. if (bits > 0) {
  7851. return valu << bits | this.readBits(bits);
  7852. }
  7853. return valu;
  7854. }; // ():uint
  7855. this.skipLeadingZeros = function () {
  7856. var leadingZeroCount; // :uint
  7857. for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
  7858. if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
  7859. // the first bit of working word is 1
  7860. workingWord <<= leadingZeroCount;
  7861. workingBitsAvailable -= leadingZeroCount;
  7862. return leadingZeroCount;
  7863. }
  7864. } // we exhausted workingWord and still have not found a 1
  7865. this.loadWord();
  7866. return leadingZeroCount + this.skipLeadingZeros();
  7867. }; // ():void
  7868. this.skipUnsignedExpGolomb = function () {
  7869. this.skipBits(1 + this.skipLeadingZeros());
  7870. }; // ():void
  7871. this.skipExpGolomb = function () {
  7872. this.skipBits(1 + this.skipLeadingZeros());
  7873. }; // ():uint
  7874. this.readUnsignedExpGolomb = function () {
  7875. var clz = this.skipLeadingZeros(); // :uint
  7876. return this.readBits(clz + 1) - 1;
  7877. }; // ():int
  7878. this.readExpGolomb = function () {
  7879. var valu = this.readUnsignedExpGolomb(); // :int
  7880. if (0x01 & valu) {
  7881. // the number is odd if the low order bit is set
  7882. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  7883. }
  7884. return -1 * (valu >>> 1); // divide by two then make it negative
  7885. }; // Some convenience functions
  7886. // :Boolean
  7887. this.readBoolean = function () {
  7888. return this.readBits(1) === 1;
  7889. }; // ():int
  7890. this.readUnsignedByte = function () {
  7891. return this.readBits(8);
  7892. };
  7893. this.loadWord();
  7894. };
  7895. var expGolomb = ExpGolomb$1;
  7896. /**
  7897. * mux.js
  7898. *
  7899. * Copyright (c) Brightcove
  7900. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  7901. */
  7902. var Stream$2 = stream;
  7903. var ExpGolomb = expGolomb;
  7904. var H264Stream$1, NalByteStream;
  7905. var PROFILES_WITH_OPTIONAL_SPS_DATA;
  7906. /**
  7907. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  7908. */
  7909. NalByteStream = function () {
  7910. var syncPoint = 0,
  7911. i,
  7912. buffer;
  7913. NalByteStream.prototype.init.call(this);
  7914. /*
  7915. * Scans a byte stream and triggers a data event with the NAL units found.
  7916. * @param {Object} data Event received from H264Stream
  7917. * @param {Uint8Array} data.data The h264 byte stream to be scanned
  7918. *
  7919. * @see H264Stream.push
  7920. */
  7921. this.push = function (data) {
  7922. var swapBuffer;
  7923. if (!buffer) {
  7924. buffer = data.data;
  7925. } else {
  7926. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  7927. swapBuffer.set(buffer);
  7928. swapBuffer.set(data.data, buffer.byteLength);
  7929. buffer = swapBuffer;
  7930. }
  7931. var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
  7932. // scan for NAL unit boundaries
  7933. // a match looks like this:
  7934. // 0 0 1 .. NAL .. 0 0 1
  7935. // ^ sync point ^ i
  7936. // or this:
  7937. // 0 0 1 .. NAL .. 0 0 0
  7938. // ^ sync point ^ i
  7939. // advance the sync point to a NAL start, if necessary
  7940. for (; syncPoint < len - 3; syncPoint++) {
  7941. if (buffer[syncPoint + 2] === 1) {
  7942. // the sync point is properly aligned
  7943. i = syncPoint + 5;
  7944. break;
  7945. }
  7946. }
  7947. while (i < len) {
  7948. // look at the current byte to determine if we've hit the end of
  7949. // a NAL unit boundary
  7950. switch (buffer[i]) {
  7951. case 0:
  7952. // skip past non-sync sequences
  7953. if (buffer[i - 1] !== 0) {
  7954. i += 2;
  7955. break;
  7956. } else if (buffer[i - 2] !== 0) {
  7957. i++;
  7958. break;
  7959. } // deliver the NAL unit if it isn't empty
  7960. if (syncPoint + 3 !== i - 2) {
  7961. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  7962. } // drop trailing zeroes
  7963. do {
  7964. i++;
  7965. } while (buffer[i] !== 1 && i < len);
  7966. syncPoint = i - 2;
  7967. i += 3;
  7968. break;
  7969. case 1:
  7970. // skip past non-sync sequences
  7971. if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
  7972. i += 3;
  7973. break;
  7974. } // deliver the NAL unit
  7975. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  7976. syncPoint = i - 2;
  7977. i += 3;
  7978. break;
  7979. default:
  7980. // the current byte isn't a one or zero, so it cannot be part
  7981. // of a sync sequence
  7982. i += 3;
  7983. break;
  7984. }
  7985. } // filter out the NAL units that were delivered
  7986. buffer = buffer.subarray(syncPoint);
  7987. i -= syncPoint;
  7988. syncPoint = 0;
  7989. };
  7990. this.reset = function () {
  7991. buffer = null;
  7992. syncPoint = 0;
  7993. this.trigger('reset');
  7994. };
  7995. this.flush = function () {
  7996. // deliver the last buffered NAL unit
  7997. if (buffer && buffer.byteLength > 3) {
  7998. this.trigger('data', buffer.subarray(syncPoint + 3));
  7999. } // reset the stream state
  8000. buffer = null;
  8001. syncPoint = 0;
  8002. this.trigger('done');
  8003. };
  8004. this.endTimeline = function () {
  8005. this.flush();
  8006. this.trigger('endedtimeline');
  8007. };
  8008. };
  8009. NalByteStream.prototype = new Stream$2(); // values of profile_idc that indicate additional fields are included in the SPS
  8010. // see Recommendation ITU-T H.264 (4/2013),
  8011. // 7.3.2.1.1 Sequence parameter set data syntax
  8012. PROFILES_WITH_OPTIONAL_SPS_DATA = {
  8013. 100: true,
  8014. 110: true,
  8015. 122: true,
  8016. 244: true,
  8017. 44: true,
  8018. 83: true,
  8019. 86: true,
  8020. 118: true,
  8021. 128: true,
  8022. // TODO: the three profiles below don't
  8023. // appear to have sps data in the specificiation anymore?
  8024. 138: true,
  8025. 139: true,
  8026. 134: true
  8027. };
  8028. /**
  8029. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  8030. * events.
  8031. */
  8032. H264Stream$1 = function () {
  8033. var nalByteStream = new NalByteStream(),
  8034. self,
  8035. trackId,
  8036. currentPts,
  8037. currentDts,
  8038. discardEmulationPreventionBytes,
  8039. readSequenceParameterSet,
  8040. skipScalingList;
  8041. H264Stream$1.prototype.init.call(this);
  8042. self = this;
  8043. /*
  8044. * Pushes a packet from a stream onto the NalByteStream
  8045. *
  8046. * @param {Object} packet - A packet received from a stream
  8047. * @param {Uint8Array} packet.data - The raw bytes of the packet
  8048. * @param {Number} packet.dts - Decode timestamp of the packet
  8049. * @param {Number} packet.pts - Presentation timestamp of the packet
  8050. * @param {Number} packet.trackId - The id of the h264 track this packet came from
  8051. * @param {('video'|'audio')} packet.type - The type of packet
  8052. *
  8053. */
  8054. this.push = function (packet) {
  8055. if (packet.type !== 'video') {
  8056. return;
  8057. }
  8058. trackId = packet.trackId;
  8059. currentPts = packet.pts;
  8060. currentDts = packet.dts;
  8061. nalByteStream.push(packet);
  8062. };
  8063. /*
  8064. * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
  8065. * for the NALUs to the next stream component.
  8066. * Also, preprocess caption and sequence parameter NALUs.
  8067. *
  8068. * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
  8069. * @see NalByteStream.push
  8070. */
  8071. nalByteStream.on('data', function (data) {
  8072. var event = {
  8073. trackId: trackId,
  8074. pts: currentPts,
  8075. dts: currentDts,
  8076. data: data,
  8077. nalUnitTypeCode: data[0] & 0x1f
  8078. };
  8079. switch (event.nalUnitTypeCode) {
  8080. case 0x05:
  8081. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  8082. break;
  8083. case 0x06:
  8084. event.nalUnitType = 'sei_rbsp';
  8085. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  8086. break;
  8087. case 0x07:
  8088. event.nalUnitType = 'seq_parameter_set_rbsp';
  8089. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  8090. event.config = readSequenceParameterSet(event.escapedRBSP);
  8091. break;
  8092. case 0x08:
  8093. event.nalUnitType = 'pic_parameter_set_rbsp';
  8094. break;
  8095. case 0x09:
  8096. event.nalUnitType = 'access_unit_delimiter_rbsp';
  8097. break;
  8098. } // This triggers data on the H264Stream
  8099. self.trigger('data', event);
  8100. });
  8101. nalByteStream.on('done', function () {
  8102. self.trigger('done');
  8103. });
  8104. nalByteStream.on('partialdone', function () {
  8105. self.trigger('partialdone');
  8106. });
  8107. nalByteStream.on('reset', function () {
  8108. self.trigger('reset');
  8109. });
  8110. nalByteStream.on('endedtimeline', function () {
  8111. self.trigger('endedtimeline');
  8112. });
  8113. this.flush = function () {
  8114. nalByteStream.flush();
  8115. };
  8116. this.partialFlush = function () {
  8117. nalByteStream.partialFlush();
  8118. };
  8119. this.reset = function () {
  8120. nalByteStream.reset();
  8121. };
  8122. this.endTimeline = function () {
  8123. nalByteStream.endTimeline();
  8124. };
  8125. /**
  8126. * Advance the ExpGolomb decoder past a scaling list. The scaling
  8127. * list is optionally transmitted as part of a sequence parameter
  8128. * set and is not relevant to transmuxing.
  8129. * @param count {number} the number of entries in this scaling list
  8130. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  8131. * start of a scaling list
  8132. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  8133. */
  8134. skipScalingList = function (count, expGolombDecoder) {
  8135. var lastScale = 8,
  8136. nextScale = 8,
  8137. j,
  8138. deltaScale;
  8139. for (j = 0; j < count; j++) {
  8140. if (nextScale !== 0) {
  8141. deltaScale = expGolombDecoder.readExpGolomb();
  8142. nextScale = (lastScale + deltaScale + 256) % 256;
  8143. }
  8144. lastScale = nextScale === 0 ? lastScale : nextScale;
  8145. }
  8146. };
  8147. /**
  8148. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  8149. * Sequence Payload"
  8150. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  8151. * unit
  8152. * @return {Uint8Array} the RBSP without any Emulation
  8153. * Prevention Bytes
  8154. */
  8155. discardEmulationPreventionBytes = function (data) {
  8156. var length = data.byteLength,
  8157. emulationPreventionBytesPositions = [],
  8158. i = 1,
  8159. newLength,
  8160. newData; // Find all `Emulation Prevention Bytes`
  8161. while (i < length - 2) {
  8162. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  8163. emulationPreventionBytesPositions.push(i + 2);
  8164. i += 2;
  8165. } else {
  8166. i++;
  8167. }
  8168. } // If no Emulation Prevention Bytes were found just return the original
  8169. // array
  8170. if (emulationPreventionBytesPositions.length === 0) {
  8171. return data;
  8172. } // Create a new array to hold the NAL unit data
  8173. newLength = length - emulationPreventionBytesPositions.length;
  8174. newData = new Uint8Array(newLength);
  8175. var sourceIndex = 0;
  8176. for (i = 0; i < newLength; sourceIndex++, i++) {
  8177. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  8178. // Skip this byte
  8179. sourceIndex++; // Remove this position index
  8180. emulationPreventionBytesPositions.shift();
  8181. }
  8182. newData[i] = data[sourceIndex];
  8183. }
  8184. return newData;
  8185. };
  8186. /**
  8187. * Read a sequence parameter set and return some interesting video
  8188. * properties. A sequence parameter set is the H264 metadata that
  8189. * describes the properties of upcoming video frames.
  8190. * @param data {Uint8Array} the bytes of a sequence parameter set
  8191. * @return {object} an object with configuration parsed from the
  8192. * sequence parameter set, including the dimensions of the
  8193. * associated video frames.
  8194. */
  8195. readSequenceParameterSet = function (data) {
  8196. var frameCropLeftOffset = 0,
  8197. frameCropRightOffset = 0,
  8198. frameCropTopOffset = 0,
  8199. frameCropBottomOffset = 0,
  8200. expGolombDecoder,
  8201. profileIdc,
  8202. levelIdc,
  8203. profileCompatibility,
  8204. chromaFormatIdc,
  8205. picOrderCntType,
  8206. numRefFramesInPicOrderCntCycle,
  8207. picWidthInMbsMinus1,
  8208. picHeightInMapUnitsMinus1,
  8209. frameMbsOnlyFlag,
  8210. scalingListCount,
  8211. sarRatio = [1, 1],
  8212. aspectRatioIdc,
  8213. i;
  8214. expGolombDecoder = new ExpGolomb(data);
  8215. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  8216. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  8217. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  8218. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  8219. // some profiles have more optional data we don't need
  8220. if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
  8221. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  8222. if (chromaFormatIdc === 3) {
  8223. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  8224. }
  8225. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  8226. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  8227. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  8228. if (expGolombDecoder.readBoolean()) {
  8229. // seq_scaling_matrix_present_flag
  8230. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  8231. for (i = 0; i < scalingListCount; i++) {
  8232. if (expGolombDecoder.readBoolean()) {
  8233. // seq_scaling_list_present_flag[ i ]
  8234. if (i < 6) {
  8235. skipScalingList(16, expGolombDecoder);
  8236. } else {
  8237. skipScalingList(64, expGolombDecoder);
  8238. }
  8239. }
  8240. }
  8241. }
  8242. }
  8243. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  8244. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  8245. if (picOrderCntType === 0) {
  8246. expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
  8247. } else if (picOrderCntType === 1) {
  8248. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  8249. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  8250. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  8251. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  8252. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  8253. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  8254. }
  8255. }
  8256. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  8257. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  8258. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  8259. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  8260. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  8261. if (frameMbsOnlyFlag === 0) {
  8262. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  8263. }
  8264. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  8265. if (expGolombDecoder.readBoolean()) {
  8266. // frame_cropping_flag
  8267. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  8268. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  8269. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  8270. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  8271. }
  8272. if (expGolombDecoder.readBoolean()) {
  8273. // vui_parameters_present_flag
  8274. if (expGolombDecoder.readBoolean()) {
  8275. // aspect_ratio_info_present_flag
  8276. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  8277. switch (aspectRatioIdc) {
  8278. case 1:
  8279. sarRatio = [1, 1];
  8280. break;
  8281. case 2:
  8282. sarRatio = [12, 11];
  8283. break;
  8284. case 3:
  8285. sarRatio = [10, 11];
  8286. break;
  8287. case 4:
  8288. sarRatio = [16, 11];
  8289. break;
  8290. case 5:
  8291. sarRatio = [40, 33];
  8292. break;
  8293. case 6:
  8294. sarRatio = [24, 11];
  8295. break;
  8296. case 7:
  8297. sarRatio = [20, 11];
  8298. break;
  8299. case 8:
  8300. sarRatio = [32, 11];
  8301. break;
  8302. case 9:
  8303. sarRatio = [80, 33];
  8304. break;
  8305. case 10:
  8306. sarRatio = [18, 11];
  8307. break;
  8308. case 11:
  8309. sarRatio = [15, 11];
  8310. break;
  8311. case 12:
  8312. sarRatio = [64, 33];
  8313. break;
  8314. case 13:
  8315. sarRatio = [160, 99];
  8316. break;
  8317. case 14:
  8318. sarRatio = [4, 3];
  8319. break;
  8320. case 15:
  8321. sarRatio = [3, 2];
  8322. break;
  8323. case 16:
  8324. sarRatio = [2, 1];
  8325. break;
  8326. case 255:
  8327. {
  8328. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
  8329. break;
  8330. }
  8331. }
  8332. if (sarRatio) {
  8333. sarRatio[0] / sarRatio[1];
  8334. }
  8335. }
  8336. }
  8337. return {
  8338. profileIdc: profileIdc,
  8339. levelIdc: levelIdc,
  8340. profileCompatibility: profileCompatibility,
  8341. width: (picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2,
  8342. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
  8343. // sar is sample aspect ratio
  8344. sarRatio: sarRatio
  8345. };
  8346. };
  8347. };
  8348. H264Stream$1.prototype = new Stream$2();
  8349. var h264 = {
  8350. H264Stream: H264Stream$1,
  8351. NalByteStream: NalByteStream
  8352. };
  8353. /**
  8354. * mux.js
  8355. *
  8356. * Copyright (c) Brightcove
  8357. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8358. *
  8359. * Utilities to detect basic properties and metadata about Aac data.
  8360. */
  8361. var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  8362. var parseId3TagSize = function (header, byteIndex) {
  8363. var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
  8364. flags = header[byteIndex + 5],
  8365. footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
  8366. returnSize = returnSize >= 0 ? returnSize : 0;
  8367. if (footerPresent) {
  8368. return returnSize + 20;
  8369. }
  8370. return returnSize + 10;
  8371. };
  8372. var getId3Offset = function (data, offset) {
  8373. if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
  8374. return offset;
  8375. }
  8376. offset += parseId3TagSize(data, offset);
  8377. return getId3Offset(data, offset);
  8378. }; // TODO: use vhs-utils
  8379. var isLikelyAacData$1 = function (data) {
  8380. var offset = getId3Offset(data, 0);
  8381. return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 && // verify that the 2 layer bits are 0, aka this
  8382. // is not mp3 data but aac data.
  8383. (data[offset + 1] & 0x16) === 0x10;
  8384. };
  8385. var parseSyncSafeInteger = function (data) {
  8386. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  8387. }; // return a percent-encoded representation of the specified byte range
  8388. // @see http://en.wikipedia.org/wiki/Percent-encoding
  8389. var percentEncode = function (bytes, start, end) {
  8390. var i,
  8391. result = '';
  8392. for (i = start; i < end; i++) {
  8393. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  8394. }
  8395. return result;
  8396. }; // return the string representation of the specified byte range,
  8397. // interpreted as ISO-8859-1.
  8398. var parseIso88591 = function (bytes, start, end) {
  8399. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  8400. };
  8401. var parseAdtsSize = function (header, byteIndex) {
  8402. var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  8403. middle = header[byteIndex + 4] << 3,
  8404. highTwo = header[byteIndex + 3] & 0x3 << 11;
  8405. return highTwo | middle | lowThree;
  8406. };
  8407. var parseType$4 = function (header, byteIndex) {
  8408. if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
  8409. return 'timed-metadata';
  8410. } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
  8411. return 'audio';
  8412. }
  8413. return null;
  8414. };
  8415. var parseSampleRate = function (packet) {
  8416. var i = 0;
  8417. while (i + 5 < packet.length) {
  8418. if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
  8419. // If a valid header was not found, jump one forward and attempt to
  8420. // find a valid ADTS header starting at the next byte
  8421. i++;
  8422. continue;
  8423. }
  8424. return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
  8425. }
  8426. return null;
  8427. };
  8428. var parseAacTimestamp = function (packet) {
  8429. var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
  8430. frameStart = 10;
  8431. if (packet[5] & 0x40) {
  8432. // advance the frame start past the extended header
  8433. frameStart += 4; // header size field
  8434. frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
  8435. } // parse one or more ID3 frames
  8436. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  8437. do {
  8438. // determine the number of bytes in this frame
  8439. frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
  8440. if (frameSize < 1) {
  8441. return null;
  8442. }
  8443. frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
  8444. if (frameHeader === 'PRIV') {
  8445. frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
  8446. for (var i = 0; i < frame.byteLength; i++) {
  8447. if (frame[i] === 0) {
  8448. var owner = parseIso88591(frame, 0, i);
  8449. if (owner === 'com.apple.streaming.transportStreamTimestamp') {
  8450. var d = frame.subarray(i + 1);
  8451. var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  8452. size *= 4;
  8453. size += d[7] & 0x03;
  8454. return size;
  8455. }
  8456. break;
  8457. }
  8458. }
  8459. }
  8460. frameStart += 10; // advance past the frame header
  8461. frameStart += frameSize; // advance past the frame body
  8462. } while (frameStart < packet.byteLength);
  8463. return null;
  8464. };
  8465. var utils = {
  8466. isLikelyAacData: isLikelyAacData$1,
  8467. parseId3TagSize: parseId3TagSize,
  8468. parseAdtsSize: parseAdtsSize,
  8469. parseType: parseType$4,
  8470. parseSampleRate: parseSampleRate,
  8471. parseAacTimestamp: parseAacTimestamp
  8472. };
  8473. /**
  8474. * mux.js
  8475. *
  8476. * Copyright (c) Brightcove
  8477. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8478. *
  8479. * A stream-based aac to mp4 converter. This utility can be used to
  8480. * deliver mp4s to a SourceBuffer on platforms that support native
  8481. * Media Source Extensions.
  8482. */
  8483. var Stream$1 = stream;
  8484. var aacUtils = utils; // Constants
  8485. var AacStream$1;
  8486. /**
  8487. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  8488. */
  8489. AacStream$1 = function () {
  8490. var everything = new Uint8Array(),
  8491. timeStamp = 0;
  8492. AacStream$1.prototype.init.call(this);
  8493. this.setTimestamp = function (timestamp) {
  8494. timeStamp = timestamp;
  8495. };
  8496. this.push = function (bytes) {
  8497. var frameSize = 0,
  8498. byteIndex = 0,
  8499. bytesLeft,
  8500. chunk,
  8501. packet,
  8502. tempLength; // If there are bytes remaining from the last segment, prepend them to the
  8503. // bytes that were pushed in
  8504. if (everything.length) {
  8505. tempLength = everything.length;
  8506. everything = new Uint8Array(bytes.byteLength + tempLength);
  8507. everything.set(everything.subarray(0, tempLength));
  8508. everything.set(bytes, tempLength);
  8509. } else {
  8510. everything = bytes;
  8511. }
  8512. while (everything.length - byteIndex >= 3) {
  8513. if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
  8514. // Exit early because we don't have enough to parse
  8515. // the ID3 tag header
  8516. if (everything.length - byteIndex < 10) {
  8517. break;
  8518. } // check framesize
  8519. frameSize = aacUtils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  8520. // to emit a full packet
  8521. // Add to byteIndex to support multiple ID3 tags in sequence
  8522. if (byteIndex + frameSize > everything.length) {
  8523. break;
  8524. }
  8525. chunk = {
  8526. type: 'timed-metadata',
  8527. data: everything.subarray(byteIndex, byteIndex + frameSize)
  8528. };
  8529. this.trigger('data', chunk);
  8530. byteIndex += frameSize;
  8531. continue;
  8532. } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
  8533. // Exit early because we don't have enough to parse
  8534. // the ADTS frame header
  8535. if (everything.length - byteIndex < 7) {
  8536. break;
  8537. }
  8538. frameSize = aacUtils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  8539. // to emit a full packet
  8540. if (byteIndex + frameSize > everything.length) {
  8541. break;
  8542. }
  8543. packet = {
  8544. type: 'audio',
  8545. data: everything.subarray(byteIndex, byteIndex + frameSize),
  8546. pts: timeStamp,
  8547. dts: timeStamp
  8548. };
  8549. this.trigger('data', packet);
  8550. byteIndex += frameSize;
  8551. continue;
  8552. }
  8553. byteIndex++;
  8554. }
  8555. bytesLeft = everything.length - byteIndex;
  8556. if (bytesLeft > 0) {
  8557. everything = everything.subarray(byteIndex);
  8558. } else {
  8559. everything = new Uint8Array();
  8560. }
  8561. };
  8562. this.reset = function () {
  8563. everything = new Uint8Array();
  8564. this.trigger('reset');
  8565. };
  8566. this.endTimeline = function () {
  8567. everything = new Uint8Array();
  8568. this.trigger('endedtimeline');
  8569. };
  8570. };
  8571. AacStream$1.prototype = new Stream$1();
  8572. var aac = AacStream$1;
  8573. var AUDIO_PROPERTIES$1 = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
  8574. var audioProperties = AUDIO_PROPERTIES$1;
  8575. var VIDEO_PROPERTIES$1 = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
  8576. var videoProperties = VIDEO_PROPERTIES$1;
  8577. /**
  8578. * mux.js
  8579. *
  8580. * Copyright (c) Brightcove
  8581. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8582. *
  8583. * A stream-based mp2t to mp4 converter. This utility can be used to
  8584. * deliver mp4s to a SourceBuffer on platforms that support native
  8585. * Media Source Extensions.
  8586. */
  8587. var Stream = stream;
  8588. var mp4 = mp4Generator;
  8589. var frameUtils = frameUtils$1;
  8590. var audioFrameUtils = audioFrameUtils$1;
  8591. var trackDecodeInfo = trackDecodeInfo$1;
  8592. var m2ts = m2ts_1;
  8593. var clock = clock$2;
  8594. var AdtsStream = adts;
  8595. var H264Stream = h264.H264Stream;
  8596. var AacStream = aac;
  8597. var isLikelyAacData = utils.isLikelyAacData;
  8598. var ONE_SECOND_IN_TS$1 = clock$2.ONE_SECOND_IN_TS;
  8599. var AUDIO_PROPERTIES = audioProperties;
  8600. var VIDEO_PROPERTIES = videoProperties; // object types
  8601. var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;
  8602. var retriggerForStream = function (key, event) {
  8603. event.stream = key;
  8604. this.trigger('log', event);
  8605. };
  8606. var addPipelineLogRetriggers = function (transmuxer, pipeline) {
  8607. var keys = Object.keys(pipeline);
  8608. for (var i = 0; i < keys.length; i++) {
  8609. var key = keys[i]; // skip non-stream keys and headOfPipeline
  8610. // which is just a duplicate
  8611. if (key === 'headOfPipeline' || !pipeline[key].on) {
  8612. continue;
  8613. }
  8614. pipeline[key].on('log', retriggerForStream.bind(transmuxer, key));
  8615. }
  8616. };
  8617. /**
  8618. * Compare two arrays (even typed) for same-ness
  8619. */
  8620. var arrayEquals = function (a, b) {
  8621. var i;
  8622. if (a.length !== b.length) {
  8623. return false;
  8624. } // compare the value of each element in the array
  8625. for (i = 0; i < a.length; i++) {
  8626. if (a[i] !== b[i]) {
  8627. return false;
  8628. }
  8629. }
  8630. return true;
  8631. };
  8632. var generateSegmentTimingInfo = function (baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
  8633. var ptsOffsetFromDts = startPts - startDts,
  8634. decodeDuration = endDts - startDts,
  8635. presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
  8636. // however, the player time values will reflect a start from the baseMediaDecodeTime.
  8637. // In order to provide relevant values for the player times, base timing info on the
  8638. // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  8639. return {
  8640. start: {
  8641. dts: baseMediaDecodeTime,
  8642. pts: baseMediaDecodeTime + ptsOffsetFromDts
  8643. },
  8644. end: {
  8645. dts: baseMediaDecodeTime + decodeDuration,
  8646. pts: baseMediaDecodeTime + presentationDuration
  8647. },
  8648. prependedContentDuration: prependedContentDuration,
  8649. baseMediaDecodeTime: baseMediaDecodeTime
  8650. };
  8651. };
  8652. /**
  8653. * Constructs a single-track, ISO BMFF media segment from AAC data
  8654. * events. The output of this stream can be fed to a SourceBuffer
  8655. * configured with a suitable initialization segment.
  8656. * @param track {object} track metadata configuration
  8657. * @param options {object} transmuxer options object
  8658. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  8659. * in the source; false to adjust the first segment to start at 0.
  8660. */
  8661. AudioSegmentStream = function (track, options) {
  8662. var adtsFrames = [],
  8663. sequenceNumber,
  8664. earliestAllowedDts = 0,
  8665. audioAppendStartTs = 0,
  8666. videoBaseMediaDecodeTime = Infinity;
  8667. options = options || {};
  8668. sequenceNumber = options.firstSequenceNumber || 0;
  8669. AudioSegmentStream.prototype.init.call(this);
  8670. this.push = function (data) {
  8671. trackDecodeInfo.collectDtsInfo(track, data);
  8672. if (track) {
  8673. AUDIO_PROPERTIES.forEach(function (prop) {
  8674. track[prop] = data[prop];
  8675. });
  8676. } // buffer audio data until end() is called
  8677. adtsFrames.push(data);
  8678. };
  8679. this.setEarliestDts = function (earliestDts) {
  8680. earliestAllowedDts = earliestDts;
  8681. };
  8682. this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  8683. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  8684. };
  8685. this.setAudioAppendStart = function (timestamp) {
  8686. audioAppendStartTs = timestamp;
  8687. };
  8688. this.flush = function () {
  8689. var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
  8690. if (adtsFrames.length === 0) {
  8691. this.trigger('done', 'AudioSegmentStream');
  8692. return;
  8693. }
  8694. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
  8695. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
  8696. videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
  8697. // samples (that is, adts frames) in the audio data
  8698. track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
  8699. mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));
  8700. adtsFrames = [];
  8701. moof = mp4.moof(sequenceNumber, [track]);
  8702. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
  8703. sequenceNumber++;
  8704. boxes.set(moof);
  8705. boxes.set(mdat, moof.byteLength);
  8706. trackDecodeInfo.clearDtsInfo(track);
  8707. frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
  8708. // tests) on adding the timingInfo event. However, it seems unlikely that there's a
  8709. // valid use-case where an init segment/data should be triggered without associated
  8710. // frames. Leaving for now, but should be looked into.
  8711. if (frames.length) {
  8712. segmentDuration = frames.length * frameDuration;
  8713. this.trigger('segmentTimingInfo', generateSegmentTimingInfo( // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
  8714. // frame info is in video clock cycles. Convert to match expectation of
  8715. // listeners (that all timestamps will be based on video clock cycles).
  8716. clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate), // frame times are already in video clock, as is segment duration
  8717. frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
  8718. this.trigger('timingInfo', {
  8719. start: frames[0].pts,
  8720. end: frames[0].pts + segmentDuration
  8721. });
  8722. }
  8723. this.trigger('data', {
  8724. track: track,
  8725. boxes: boxes
  8726. });
  8727. this.trigger('done', 'AudioSegmentStream');
  8728. };
  8729. this.reset = function () {
  8730. trackDecodeInfo.clearDtsInfo(track);
  8731. adtsFrames = [];
  8732. this.trigger('reset');
  8733. };
  8734. };
  8735. AudioSegmentStream.prototype = new Stream();
  8736. /**
  8737. * Constructs a single-track, ISO BMFF media segment from H264 data
  8738. * events. The output of this stream can be fed to a SourceBuffer
  8739. * configured with a suitable initialization segment.
  8740. * @param track {object} track metadata configuration
  8741. * @param options {object} transmuxer options object
  8742. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  8743. * gopsToAlignWith list when attempting to align gop pts
  8744. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  8745. * in the source; false to adjust the first segment to start at 0.
  8746. */
  8747. VideoSegmentStream = function (track, options) {
  8748. var sequenceNumber,
  8749. nalUnits = [],
  8750. gopsToAlignWith = [],
  8751. config,
  8752. pps;
  8753. options = options || {};
  8754. sequenceNumber = options.firstSequenceNumber || 0;
  8755. VideoSegmentStream.prototype.init.call(this);
  8756. delete track.minPTS;
  8757. this.gopCache_ = [];
  8758. /**
  8759. * Constructs a ISO BMFF segment given H264 nalUnits
  8760. * @param {Object} nalUnit A data event representing a nalUnit
  8761. * @param {String} nalUnit.nalUnitType
  8762. * @param {Object} nalUnit.config Properties for a mp4 track
  8763. * @param {Uint8Array} nalUnit.data The nalUnit bytes
  8764. * @see lib/codecs/h264.js
  8765. **/
  8766. this.push = function (nalUnit) {
  8767. trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
  8768. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  8769. config = nalUnit.config;
  8770. track.sps = [nalUnit.data];
  8771. VIDEO_PROPERTIES.forEach(function (prop) {
  8772. track[prop] = config[prop];
  8773. }, this);
  8774. }
  8775. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
  8776. pps = nalUnit.data;
  8777. track.pps = [nalUnit.data];
  8778. } // buffer video until flush() is called
  8779. nalUnits.push(nalUnit);
  8780. };
  8781. /**
  8782. * Pass constructed ISO BMFF track and boxes on to the
  8783. * next stream in the pipeline
  8784. **/
  8785. this.flush = function () {
  8786. var frames,
  8787. gopForFusion,
  8788. gops,
  8789. moof,
  8790. mdat,
  8791. boxes,
  8792. prependedContentDuration = 0,
  8793. firstGop,
  8794. lastGop; // Throw away nalUnits at the start of the byte stream until
  8795. // we find the first AUD
  8796. while (nalUnits.length) {
  8797. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  8798. break;
  8799. }
  8800. nalUnits.shift();
  8801. } // Return early if no video data has been observed
  8802. if (nalUnits.length === 0) {
  8803. this.resetStream_();
  8804. this.trigger('done', 'VideoSegmentStream');
  8805. return;
  8806. } // Organize the raw nal-units into arrays that represent
  8807. // higher-level constructs such as frames and gops
  8808. // (group-of-pictures)
  8809. frames = frameUtils.groupNalsIntoFrames(nalUnits);
  8810. gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
  8811. // a problem since MSE (on Chrome) requires a leading keyframe.
  8812. //
  8813. // We have two approaches to repairing this situation:
  8814. // 1) GOP-FUSION:
  8815. // This is where we keep track of the GOPS (group-of-pictures)
  8816. // from previous fragments and attempt to find one that we can
  8817. // prepend to the current fragment in order to create a valid
  8818. // fragment.
  8819. // 2) KEYFRAME-PULLING:
  8820. // Here we search for the first keyframe in the fragment and
  8821. // throw away all the frames between the start of the fragment
  8822. // and that keyframe. We then extend the duration and pull the
  8823. // PTS of the keyframe forward so that it covers the time range
  8824. // of the frames that were disposed of.
  8825. //
  8826. // #1 is far prefereable over #2 which can cause "stuttering" but
  8827. // requires more things to be just right.
  8828. if (!gops[0][0].keyFrame) {
  8829. // Search for a gop for fusion from our gopCache
  8830. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  8831. if (gopForFusion) {
  8832. // in order to provide more accurate timing information about the segment, save
  8833. // the number of seconds prepended to the original segment due to GOP fusion
  8834. prependedContentDuration = gopForFusion.duration;
  8835. gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
  8836. // new gop at the beginning
  8837. gops.byteLength += gopForFusion.byteLength;
  8838. gops.nalCount += gopForFusion.nalCount;
  8839. gops.pts = gopForFusion.pts;
  8840. gops.dts = gopForFusion.dts;
  8841. gops.duration += gopForFusion.duration;
  8842. } else {
  8843. // If we didn't find a candidate gop fall back to keyframe-pulling
  8844. gops = frameUtils.extendFirstKeyFrame(gops);
  8845. }
  8846. } // Trim gops to align with gopsToAlignWith
  8847. if (gopsToAlignWith.length) {
  8848. var alignedGops;
  8849. if (options.alignGopsAtEnd) {
  8850. alignedGops = this.alignGopsAtEnd_(gops);
  8851. } else {
  8852. alignedGops = this.alignGopsAtStart_(gops);
  8853. }
  8854. if (!alignedGops) {
  8855. // save all the nals in the last GOP into the gop cache
  8856. this.gopCache_.unshift({
  8857. gop: gops.pop(),
  8858. pps: track.pps,
  8859. sps: track.sps
  8860. }); // Keep a maximum of 6 GOPs in the cache
  8861. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  8862. nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
  8863. this.resetStream_();
  8864. this.trigger('done', 'VideoSegmentStream');
  8865. return;
  8866. } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
  8867. // when recalculated before sending off to CoalesceStream
  8868. trackDecodeInfo.clearDtsInfo(track);
  8869. gops = alignedGops;
  8870. }
  8871. trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
  8872. // samples (that is, frames) in the video data
  8873. track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
  8874. mdat = mp4.mdat(frameUtils.concatenateNalData(gops));
  8875. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
  8876. this.trigger('processedGopsInfo', gops.map(function (gop) {
  8877. return {
  8878. pts: gop.pts,
  8879. dts: gop.dts,
  8880. byteLength: gop.byteLength
  8881. };
  8882. }));
  8883. firstGop = gops[0];
  8884. lastGop = gops[gops.length - 1];
  8885. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
  8886. this.trigger('timingInfo', {
  8887. start: gops[0].pts,
  8888. end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
  8889. }); // save all the nals in the last GOP into the gop cache
  8890. this.gopCache_.unshift({
  8891. gop: gops.pop(),
  8892. pps: track.pps,
  8893. sps: track.sps
  8894. }); // Keep a maximum of 6 GOPs in the cache
  8895. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  8896. nalUnits = [];
  8897. this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
  8898. this.trigger('timelineStartInfo', track.timelineStartInfo);
  8899. moof = mp4.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
  8900. // throwing away hundreds of media segment fragments
  8901. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
  8902. sequenceNumber++;
  8903. boxes.set(moof);
  8904. boxes.set(mdat, moof.byteLength);
  8905. this.trigger('data', {
  8906. track: track,
  8907. boxes: boxes
  8908. });
  8909. this.resetStream_(); // Continue with the flush process now
  8910. this.trigger('done', 'VideoSegmentStream');
  8911. };
  8912. this.reset = function () {
  8913. this.resetStream_();
  8914. nalUnits = [];
  8915. this.gopCache_.length = 0;
  8916. gopsToAlignWith.length = 0;
  8917. this.trigger('reset');
  8918. };
  8919. this.resetStream_ = function () {
  8920. trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
  8921. // for instance, when we are rendition switching
  8922. config = undefined;
  8923. pps = undefined;
  8924. }; // Search for a candidate Gop for gop-fusion from the gop cache and
  8925. // return it or return null if no good candidate was found
  8926. this.getGopForFusion_ = function (nalUnit) {
  8927. var halfSecond = 45000,
  8928. // Half-a-second in a 90khz clock
  8929. allowableOverlap = 10000,
  8930. // About 3 frames @ 30fps
  8931. nearestDistance = Infinity,
  8932. dtsDistance,
  8933. nearestGopObj,
  8934. currentGop,
  8935. currentGopObj,
  8936. i; // Search for the GOP nearest to the beginning of this nal unit
  8937. for (i = 0; i < this.gopCache_.length; i++) {
  8938. currentGopObj = this.gopCache_[i];
  8939. currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
  8940. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  8941. continue;
  8942. } // Reject Gops that would require a negative baseMediaDecodeTime
  8943. if (currentGop.dts < track.timelineStartInfo.dts) {
  8944. continue;
  8945. } // The distance between the end of the gop and the start of the nalUnit
  8946. dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
  8947. // a half-second of the nal unit
  8948. if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
  8949. // Always use the closest GOP we found if there is more than
  8950. // one candidate
  8951. if (!nearestGopObj || nearestDistance > dtsDistance) {
  8952. nearestGopObj = currentGopObj;
  8953. nearestDistance = dtsDistance;
  8954. }
  8955. }
  8956. }
  8957. if (nearestGopObj) {
  8958. return nearestGopObj.gop;
  8959. }
  8960. return null;
  8961. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  8962. // of gopsToAlignWith starting from the START of the list
  8963. this.alignGopsAtStart_ = function (gops) {
  8964. var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
  8965. byteLength = gops.byteLength;
  8966. nalCount = gops.nalCount;
  8967. duration = gops.duration;
  8968. alignIndex = gopIndex = 0;
  8969. while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
  8970. align = gopsToAlignWith[alignIndex];
  8971. gop = gops[gopIndex];
  8972. if (align.pts === gop.pts) {
  8973. break;
  8974. }
  8975. if (gop.pts > align.pts) {
  8976. // this current gop starts after the current gop we want to align on, so increment
  8977. // align index
  8978. alignIndex++;
  8979. continue;
  8980. } // current gop starts before the current gop we want to align on. so increment gop
  8981. // index
  8982. gopIndex++;
  8983. byteLength -= gop.byteLength;
  8984. nalCount -= gop.nalCount;
  8985. duration -= gop.duration;
  8986. }
  8987. if (gopIndex === 0) {
  8988. // no gops to trim
  8989. return gops;
  8990. }
  8991. if (gopIndex === gops.length) {
  8992. // all gops trimmed, skip appending all gops
  8993. return null;
  8994. }
  8995. alignedGops = gops.slice(gopIndex);
  8996. alignedGops.byteLength = byteLength;
  8997. alignedGops.duration = duration;
  8998. alignedGops.nalCount = nalCount;
  8999. alignedGops.pts = alignedGops[0].pts;
  9000. alignedGops.dts = alignedGops[0].dts;
  9001. return alignedGops;
  9002. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  9003. // of gopsToAlignWith starting from the END of the list
  9004. this.alignGopsAtEnd_ = function (gops) {
  9005. var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
  9006. alignIndex = gopsToAlignWith.length - 1;
  9007. gopIndex = gops.length - 1;
  9008. alignEndIndex = null;
  9009. matchFound = false;
  9010. while (alignIndex >= 0 && gopIndex >= 0) {
  9011. align = gopsToAlignWith[alignIndex];
  9012. gop = gops[gopIndex];
  9013. if (align.pts === gop.pts) {
  9014. matchFound = true;
  9015. break;
  9016. }
  9017. if (align.pts > gop.pts) {
  9018. alignIndex--;
  9019. continue;
  9020. }
  9021. if (alignIndex === gopsToAlignWith.length - 1) {
  9022. // gop.pts is greater than the last alignment candidate. If no match is found
  9023. // by the end of this loop, we still want to append gops that come after this
  9024. // point
  9025. alignEndIndex = gopIndex;
  9026. }
  9027. gopIndex--;
  9028. }
  9029. if (!matchFound && alignEndIndex === null) {
  9030. return null;
  9031. }
  9032. var trimIndex;
  9033. if (matchFound) {
  9034. trimIndex = gopIndex;
  9035. } else {
  9036. trimIndex = alignEndIndex;
  9037. }
  9038. if (trimIndex === 0) {
  9039. return gops;
  9040. }
  9041. var alignedGops = gops.slice(trimIndex);
  9042. var metadata = alignedGops.reduce(function (total, gop) {
  9043. total.byteLength += gop.byteLength;
  9044. total.duration += gop.duration;
  9045. total.nalCount += gop.nalCount;
  9046. return total;
  9047. }, {
  9048. byteLength: 0,
  9049. duration: 0,
  9050. nalCount: 0
  9051. });
  9052. alignedGops.byteLength = metadata.byteLength;
  9053. alignedGops.duration = metadata.duration;
  9054. alignedGops.nalCount = metadata.nalCount;
  9055. alignedGops.pts = alignedGops[0].pts;
  9056. alignedGops.dts = alignedGops[0].dts;
  9057. return alignedGops;
  9058. };
  9059. this.alignGopsWith = function (newGopsToAlignWith) {
  9060. gopsToAlignWith = newGopsToAlignWith;
  9061. };
  9062. };
  9063. VideoSegmentStream.prototype = new Stream();
  9064. /**
  9065. * A Stream that can combine multiple streams (ie. audio & video)
  9066. * into a single output segment for MSE. Also supports audio-only
  9067. * and video-only streams.
  9068. * @param options {object} transmuxer options object
  9069. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  9070. * in the source; false to adjust the first segment to start at media timeline start.
  9071. */
  9072. CoalesceStream = function (options, metadataStream) {
  9073. // Number of Tracks per output segment
  9074. // If greater than 1, we combine multiple
  9075. // tracks into a single segment
  9076. this.numberOfTracks = 0;
  9077. this.metadataStream = metadataStream;
  9078. options = options || {};
  9079. if (typeof options.remux !== 'undefined') {
  9080. this.remuxTracks = !!options.remux;
  9081. } else {
  9082. this.remuxTracks = true;
  9083. }
  9084. if (typeof options.keepOriginalTimestamps === 'boolean') {
  9085. this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  9086. } else {
  9087. this.keepOriginalTimestamps = false;
  9088. }
  9089. this.pendingTracks = [];
  9090. this.videoTrack = null;
  9091. this.pendingBoxes = [];
  9092. this.pendingCaptions = [];
  9093. this.pendingMetadata = [];
  9094. this.pendingBytes = 0;
  9095. this.emittedTracks = 0;
  9096. CoalesceStream.prototype.init.call(this); // Take output from multiple
  9097. this.push = function (output) {
  9098. // buffer incoming captions until the associated video segment
  9099. // finishes
  9100. if (output.content || output.text) {
  9101. return this.pendingCaptions.push(output);
  9102. } // buffer incoming id3 tags until the final flush
  9103. if (output.frames) {
  9104. return this.pendingMetadata.push(output);
  9105. } // Add this track to the list of pending tracks and store
  9106. // important information required for the construction of
  9107. // the final segment
  9108. this.pendingTracks.push(output.track);
  9109. this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
  9110. // We unshift audio and push video because
  9111. // as of Chrome 75 when switching from
  9112. // one init segment to another if the video
  9113. // mdat does not appear after the audio mdat
  9114. // only audio will play for the duration of our transmux.
  9115. if (output.track.type === 'video') {
  9116. this.videoTrack = output.track;
  9117. this.pendingBoxes.push(output.boxes);
  9118. }
  9119. if (output.track.type === 'audio') {
  9120. this.audioTrack = output.track;
  9121. this.pendingBoxes.unshift(output.boxes);
  9122. }
  9123. };
  9124. };
  9125. CoalesceStream.prototype = new Stream();
  9126. CoalesceStream.prototype.flush = function (flushSource) {
  9127. var offset = 0,
  9128. event = {
  9129. captions: [],
  9130. captionStreams: {},
  9131. metadata: [],
  9132. info: {}
  9133. },
  9134. caption,
  9135. id3,
  9136. initSegment,
  9137. timelineStartPts = 0,
  9138. i;
  9139. if (this.pendingTracks.length < this.numberOfTracks) {
  9140. if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
  9141. // Return because we haven't received a flush from a data-generating
  9142. // portion of the segment (meaning that we have only recieved meta-data
  9143. // or captions.)
  9144. return;
  9145. } else if (this.remuxTracks) {
  9146. // Return until we have enough tracks from the pipeline to remux (if we
  9147. // are remuxing audio and video into a single MP4)
  9148. return;
  9149. } else if (this.pendingTracks.length === 0) {
  9150. // In the case where we receive a flush without any data having been
  9151. // received we consider it an emitted track for the purposes of coalescing
  9152. // `done` events.
  9153. // We do this for the case where there is an audio and video track in the
  9154. // segment but no audio data. (seen in several playlists with alternate
  9155. // audio tracks and no audio present in the main TS segments.)
  9156. this.emittedTracks++;
  9157. if (this.emittedTracks >= this.numberOfTracks) {
  9158. this.trigger('done');
  9159. this.emittedTracks = 0;
  9160. }
  9161. return;
  9162. }
  9163. }
  9164. if (this.videoTrack) {
  9165. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  9166. VIDEO_PROPERTIES.forEach(function (prop) {
  9167. event.info[prop] = this.videoTrack[prop];
  9168. }, this);
  9169. } else if (this.audioTrack) {
  9170. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  9171. AUDIO_PROPERTIES.forEach(function (prop) {
  9172. event.info[prop] = this.audioTrack[prop];
  9173. }, this);
  9174. }
  9175. if (this.videoTrack || this.audioTrack) {
  9176. if (this.pendingTracks.length === 1) {
  9177. event.type = this.pendingTracks[0].type;
  9178. } else {
  9179. event.type = 'combined';
  9180. }
  9181. this.emittedTracks += this.pendingTracks.length;
  9182. initSegment = mp4.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
  9183. event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
  9184. // and track definitions
  9185. event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
  9186. event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
  9187. for (i = 0; i < this.pendingBoxes.length; i++) {
  9188. event.data.set(this.pendingBoxes[i], offset);
  9189. offset += this.pendingBoxes[i].byteLength;
  9190. } // Translate caption PTS times into second offsets to match the
  9191. // video timeline for the segment, and add track info
  9192. for (i = 0; i < this.pendingCaptions.length; i++) {
  9193. caption = this.pendingCaptions[i];
  9194. caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
  9195. caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
  9196. event.captionStreams[caption.stream] = true;
  9197. event.captions.push(caption);
  9198. } // Translate ID3 frame PTS times into second offsets to match the
  9199. // video timeline for the segment
  9200. for (i = 0; i < this.pendingMetadata.length; i++) {
  9201. id3 = this.pendingMetadata[i];
  9202. id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
  9203. event.metadata.push(id3);
  9204. } // We add this to every single emitted segment even though we only need
  9205. // it for the first
  9206. event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
  9207. this.pendingTracks.length = 0;
  9208. this.videoTrack = null;
  9209. this.pendingBoxes.length = 0;
  9210. this.pendingCaptions.length = 0;
  9211. this.pendingBytes = 0;
  9212. this.pendingMetadata.length = 0; // Emit the built segment
  9213. // We include captions and ID3 tags for backwards compatibility,
  9214. // ideally we should send only video and audio in the data event
  9215. this.trigger('data', event); // Emit each caption to the outside world
  9216. // Ideally, this would happen immediately on parsing captions,
  9217. // but we need to ensure that video data is sent back first
  9218. // so that caption timing can be adjusted to match video timing
  9219. for (i = 0; i < event.captions.length; i++) {
  9220. caption = event.captions[i];
  9221. this.trigger('caption', caption);
  9222. } // Emit each id3 tag to the outside world
  9223. // Ideally, this would happen immediately on parsing the tag,
  9224. // but we need to ensure that video data is sent back first
  9225. // so that ID3 frame timing can be adjusted to match video timing
  9226. for (i = 0; i < event.metadata.length; i++) {
  9227. id3 = event.metadata[i];
  9228. this.trigger('id3Frame', id3);
  9229. }
  9230. } // Only emit `done` if all tracks have been flushed and emitted
  9231. if (this.emittedTracks >= this.numberOfTracks) {
  9232. this.trigger('done');
  9233. this.emittedTracks = 0;
  9234. }
  9235. };
  9236. CoalesceStream.prototype.setRemux = function (val) {
  9237. this.remuxTracks = val;
  9238. };
  9239. /**
  9240. * A Stream that expects MP2T binary data as input and produces
  9241. * corresponding media segments, suitable for use with Media Source
  9242. * Extension (MSE) implementations that support the ISO BMFF byte
  9243. * stream format, like Chrome.
  9244. */
  9245. Transmuxer = function (options) {
  9246. var self = this,
  9247. hasFlushed = true,
  9248. videoTrack,
  9249. audioTrack;
  9250. Transmuxer.prototype.init.call(this);
  9251. options = options || {};
  9252. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  9253. this.transmuxPipeline_ = {};
  9254. this.setupAacPipeline = function () {
  9255. var pipeline = {};
  9256. this.transmuxPipeline_ = pipeline;
  9257. pipeline.type = 'aac';
  9258. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  9259. pipeline.aacStream = new AacStream();
  9260. pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
  9261. pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
  9262. pipeline.adtsStream = new AdtsStream();
  9263. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  9264. pipeline.headOfPipeline = pipeline.aacStream;
  9265. pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
  9266. pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
  9267. pipeline.metadataStream.on('timestamp', function (frame) {
  9268. pipeline.aacStream.setTimestamp(frame.timeStamp);
  9269. });
  9270. pipeline.aacStream.on('data', function (data) {
  9271. if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
  9272. return;
  9273. }
  9274. audioTrack = audioTrack || {
  9275. timelineStartInfo: {
  9276. baseMediaDecodeTime: self.baseMediaDecodeTime
  9277. },
  9278. codec: 'adts',
  9279. type: 'audio'
  9280. }; // hook up the audio segment stream to the first track with aac data
  9281. pipeline.coalesceStream.numberOfTracks++;
  9282. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  9283. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  9284. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
  9285. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
  9286. self.trigger('trackinfo', {
  9287. hasAudio: !!audioTrack,
  9288. hasVideo: !!videoTrack
  9289. });
  9290. }); // Re-emit any data coming from the coalesce stream to the outside world
  9291. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
  9292. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  9293. addPipelineLogRetriggers(this, pipeline);
  9294. };
  9295. this.setupTsPipeline = function () {
  9296. var pipeline = {};
  9297. this.transmuxPipeline_ = pipeline;
  9298. pipeline.type = 'ts';
  9299. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  9300. pipeline.packetStream = new m2ts.TransportPacketStream();
  9301. pipeline.parseStream = new m2ts.TransportParseStream();
  9302. pipeline.elementaryStream = new m2ts.ElementaryStream();
  9303. pipeline.timestampRolloverStream = new m2ts.TimestampRolloverStream();
  9304. pipeline.adtsStream = new AdtsStream();
  9305. pipeline.h264Stream = new H264Stream();
  9306. pipeline.captionStream = new m2ts.CaptionStream(options);
  9307. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  9308. pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
  9309. pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
  9310. // demux the streams
  9311. pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
  9312. pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
  9313. pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
  9314. pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
  9315. pipeline.elementaryStream.on('data', function (data) {
  9316. var i;
  9317. if (data.type === 'metadata') {
  9318. i = data.tracks.length; // scan the tracks listed in the metadata
  9319. while (i--) {
  9320. if (!videoTrack && data.tracks[i].type === 'video') {
  9321. videoTrack = data.tracks[i];
  9322. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  9323. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  9324. audioTrack = data.tracks[i];
  9325. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  9326. }
  9327. } // hook up the video segment stream to the first track with h264 data
  9328. if (videoTrack && !pipeline.videoSegmentStream) {
  9329. pipeline.coalesceStream.numberOfTracks++;
  9330. pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack, options);
  9331. pipeline.videoSegmentStream.on('log', self.getLogTrigger_('videoSegmentStream'));
  9332. pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
  9333. // When video emits timelineStartInfo data after a flush, we forward that
  9334. // info to the AudioSegmentStream, if it exists, because video timeline
  9335. // data takes precedence. Do not do this if keepOriginalTimestamps is set,
  9336. // because this is a particularly subtle form of timestamp alteration.
  9337. if (audioTrack && !options.keepOriginalTimestamps) {
  9338. audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
  9339. // very earliest DTS we have seen in video because Chrome will
  9340. // interpret any video track with a baseMediaDecodeTime that is
  9341. // non-zero as a gap.
  9342. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
  9343. }
  9344. });
  9345. pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
  9346. pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
  9347. pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
  9348. if (audioTrack) {
  9349. pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
  9350. }
  9351. });
  9352. pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
  9353. pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
  9354. }
  9355. if (audioTrack && !pipeline.audioSegmentStream) {
  9356. // hook up the audio segment stream to the first track with aac data
  9357. pipeline.coalesceStream.numberOfTracks++;
  9358. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  9359. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  9360. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
  9361. pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
  9362. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
  9363. } // emit pmt info
  9364. self.trigger('trackinfo', {
  9365. hasAudio: !!audioTrack,
  9366. hasVideo: !!videoTrack
  9367. });
  9368. }
  9369. }); // Re-emit any data coming from the coalesce stream to the outside world
  9370. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  9371. pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
  9372. id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
  9373. self.trigger('id3Frame', id3Frame);
  9374. });
  9375. pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
  9376. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  9377. addPipelineLogRetriggers(this, pipeline);
  9378. }; // hook up the segment streams once track metadata is delivered
  9379. this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  9380. var pipeline = this.transmuxPipeline_;
  9381. if (!options.keepOriginalTimestamps) {
  9382. this.baseMediaDecodeTime = baseMediaDecodeTime;
  9383. }
  9384. if (audioTrack) {
  9385. audioTrack.timelineStartInfo.dts = undefined;
  9386. audioTrack.timelineStartInfo.pts = undefined;
  9387. trackDecodeInfo.clearDtsInfo(audioTrack);
  9388. if (pipeline.audioTimestampRolloverStream) {
  9389. pipeline.audioTimestampRolloverStream.discontinuity();
  9390. }
  9391. }
  9392. if (videoTrack) {
  9393. if (pipeline.videoSegmentStream) {
  9394. pipeline.videoSegmentStream.gopCache_ = [];
  9395. }
  9396. videoTrack.timelineStartInfo.dts = undefined;
  9397. videoTrack.timelineStartInfo.pts = undefined;
  9398. trackDecodeInfo.clearDtsInfo(videoTrack);
  9399. pipeline.captionStream.reset();
  9400. }
  9401. if (pipeline.timestampRolloverStream) {
  9402. pipeline.timestampRolloverStream.discontinuity();
  9403. }
  9404. };
  9405. this.setAudioAppendStart = function (timestamp) {
  9406. if (audioTrack) {
  9407. this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
  9408. }
  9409. };
  9410. this.setRemux = function (val) {
  9411. var pipeline = this.transmuxPipeline_;
  9412. options.remux = val;
  9413. if (pipeline && pipeline.coalesceStream) {
  9414. pipeline.coalesceStream.setRemux(val);
  9415. }
  9416. };
  9417. this.alignGopsWith = function (gopsToAlignWith) {
  9418. if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
  9419. this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
  9420. }
  9421. };
  9422. this.getLogTrigger_ = function (key) {
  9423. var self = this;
  9424. return function (event) {
  9425. event.stream = key;
  9426. self.trigger('log', event);
  9427. };
  9428. }; // feed incoming data to the front of the parsing pipeline
  9429. this.push = function (data) {
  9430. if (hasFlushed) {
  9431. var isAac = isLikelyAacData(data);
  9432. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  9433. this.setupAacPipeline();
  9434. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  9435. this.setupTsPipeline();
  9436. }
  9437. hasFlushed = false;
  9438. }
  9439. this.transmuxPipeline_.headOfPipeline.push(data);
  9440. }; // flush any buffered data
  9441. this.flush = function () {
  9442. hasFlushed = true; // Start at the top of the pipeline and flush all pending work
  9443. this.transmuxPipeline_.headOfPipeline.flush();
  9444. };
  9445. this.endTimeline = function () {
  9446. this.transmuxPipeline_.headOfPipeline.endTimeline();
  9447. };
  9448. this.reset = function () {
  9449. if (this.transmuxPipeline_.headOfPipeline) {
  9450. this.transmuxPipeline_.headOfPipeline.reset();
  9451. }
  9452. }; // Caption data has to be reset when seeking outside buffered range
  9453. this.resetCaptions = function () {
  9454. if (this.transmuxPipeline_.captionStream) {
  9455. this.transmuxPipeline_.captionStream.reset();
  9456. }
  9457. };
  9458. };
  9459. Transmuxer.prototype = new Stream();
  9460. var transmuxer = {
  9461. Transmuxer: Transmuxer,
  9462. VideoSegmentStream: VideoSegmentStream,
  9463. AudioSegmentStream: AudioSegmentStream,
  9464. AUDIO_PROPERTIES: AUDIO_PROPERTIES,
  9465. VIDEO_PROPERTIES: VIDEO_PROPERTIES,
  9466. // exported for testing
  9467. generateSegmentTimingInfo: generateSegmentTimingInfo
  9468. };
  9469. /**
  9470. * mux.js
  9471. *
  9472. * Copyright (c) Brightcove
  9473. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9474. */
  9475. var toUnsigned$3 = function (value) {
  9476. return value >>> 0;
  9477. };
  9478. var toHexString$1 = function (value) {
  9479. return ('00' + value.toString(16)).slice(-2);
  9480. };
  9481. var bin = {
  9482. toUnsigned: toUnsigned$3,
  9483. toHexString: toHexString$1
  9484. };
  9485. var parseType$3 = function (buffer) {
  9486. var result = '';
  9487. result += String.fromCharCode(buffer[0]);
  9488. result += String.fromCharCode(buffer[1]);
  9489. result += String.fromCharCode(buffer[2]);
  9490. result += String.fromCharCode(buffer[3]);
  9491. return result;
  9492. };
  9493. var parseType_1 = parseType$3;
  9494. var toUnsigned$2 = bin.toUnsigned;
  9495. var parseType$2 = parseType_1;
  9496. var findBox$2 = function (data, path) {
  9497. var results = [],
  9498. i,
  9499. size,
  9500. type,
  9501. end,
  9502. subresults;
  9503. if (!path.length) {
  9504. // short-circuit the search for empty paths
  9505. return null;
  9506. }
  9507. for (i = 0; i < data.byteLength;) {
  9508. size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
  9509. type = parseType$2(data.subarray(i + 4, i + 8));
  9510. end = size > 1 ? i + size : data.byteLength;
  9511. if (type === path[0]) {
  9512. if (path.length === 1) {
  9513. // this is the end of the path and we've found the box we were
  9514. // looking for
  9515. results.push(data.subarray(i + 8, end));
  9516. } else {
  9517. // recursively search for the next box along the path
  9518. subresults = findBox$2(data.subarray(i + 8, end), path.slice(1));
  9519. if (subresults.length) {
  9520. results = results.concat(subresults);
  9521. }
  9522. }
  9523. }
  9524. i = end;
  9525. } // we've finished searching all of data
  9526. return results;
  9527. };
  9528. var findBox_1 = findBox$2;
  9529. var toUnsigned$1 = bin.toUnsigned;
  9530. var getUint64$2 = numbers.getUint64;
  9531. var tfdt = function (data) {
  9532. var result = {
  9533. version: data[0],
  9534. flags: new Uint8Array(data.subarray(1, 4))
  9535. };
  9536. if (result.version === 1) {
  9537. result.baseMediaDecodeTime = getUint64$2(data.subarray(4));
  9538. } else {
  9539. result.baseMediaDecodeTime = toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
  9540. }
  9541. return result;
  9542. };
  9543. var parseTfdt$2 = tfdt;
  9544. var parseSampleFlags$1 = function (flags) {
  9545. return {
  9546. isLeading: (flags[0] & 0x0c) >>> 2,
  9547. dependsOn: flags[0] & 0x03,
  9548. isDependedOn: (flags[1] & 0xc0) >>> 6,
  9549. hasRedundancy: (flags[1] & 0x30) >>> 4,
  9550. paddingValue: (flags[1] & 0x0e) >>> 1,
  9551. isNonSyncSample: flags[1] & 0x01,
  9552. degradationPriority: flags[2] << 8 | flags[3]
  9553. };
  9554. };
  9555. var parseSampleFlags_1 = parseSampleFlags$1;
  9556. var parseSampleFlags = parseSampleFlags_1;
  9557. var trun = function (data) {
  9558. var result = {
  9559. version: data[0],
  9560. flags: new Uint8Array(data.subarray(1, 4)),
  9561. samples: []
  9562. },
  9563. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  9564. // Flag interpretation
  9565. dataOffsetPresent = result.flags[2] & 0x01,
  9566. // compare with 2nd byte of 0x1
  9567. firstSampleFlagsPresent = result.flags[2] & 0x04,
  9568. // compare with 2nd byte of 0x4
  9569. sampleDurationPresent = result.flags[1] & 0x01,
  9570. // compare with 2nd byte of 0x100
  9571. sampleSizePresent = result.flags[1] & 0x02,
  9572. // compare with 2nd byte of 0x200
  9573. sampleFlagsPresent = result.flags[1] & 0x04,
  9574. // compare with 2nd byte of 0x400
  9575. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
  9576. // compare with 2nd byte of 0x800
  9577. sampleCount = view.getUint32(4),
  9578. offset = 8,
  9579. sample;
  9580. if (dataOffsetPresent) {
  9581. // 32 bit signed integer
  9582. result.dataOffset = view.getInt32(offset);
  9583. offset += 4;
  9584. } // Overrides the flags for the first sample only. The order of
  9585. // optional values will be: duration, size, compositionTimeOffset
  9586. if (firstSampleFlagsPresent && sampleCount) {
  9587. sample = {
  9588. flags: parseSampleFlags(data.subarray(offset, offset + 4))
  9589. };
  9590. offset += 4;
  9591. if (sampleDurationPresent) {
  9592. sample.duration = view.getUint32(offset);
  9593. offset += 4;
  9594. }
  9595. if (sampleSizePresent) {
  9596. sample.size = view.getUint32(offset);
  9597. offset += 4;
  9598. }
  9599. if (sampleCompositionTimeOffsetPresent) {
  9600. if (result.version === 1) {
  9601. sample.compositionTimeOffset = view.getInt32(offset);
  9602. } else {
  9603. sample.compositionTimeOffset = view.getUint32(offset);
  9604. }
  9605. offset += 4;
  9606. }
  9607. result.samples.push(sample);
  9608. sampleCount--;
  9609. }
  9610. while (sampleCount--) {
  9611. sample = {};
  9612. if (sampleDurationPresent) {
  9613. sample.duration = view.getUint32(offset);
  9614. offset += 4;
  9615. }
  9616. if (sampleSizePresent) {
  9617. sample.size = view.getUint32(offset);
  9618. offset += 4;
  9619. }
  9620. if (sampleFlagsPresent) {
  9621. sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
  9622. offset += 4;
  9623. }
  9624. if (sampleCompositionTimeOffsetPresent) {
  9625. if (result.version === 1) {
  9626. sample.compositionTimeOffset = view.getInt32(offset);
  9627. } else {
  9628. sample.compositionTimeOffset = view.getUint32(offset);
  9629. }
  9630. offset += 4;
  9631. }
  9632. result.samples.push(sample);
  9633. }
  9634. return result;
  9635. };
  9636. var parseTrun$2 = trun;
  9637. var tfhd = function (data) {
  9638. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  9639. result = {
  9640. version: data[0],
  9641. flags: new Uint8Array(data.subarray(1, 4)),
  9642. trackId: view.getUint32(4)
  9643. },
  9644. baseDataOffsetPresent = result.flags[2] & 0x01,
  9645. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  9646. defaultSampleDurationPresent = result.flags[2] & 0x08,
  9647. defaultSampleSizePresent = result.flags[2] & 0x10,
  9648. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  9649. durationIsEmpty = result.flags[0] & 0x010000,
  9650. defaultBaseIsMoof = result.flags[0] & 0x020000,
  9651. i;
  9652. i = 8;
  9653. if (baseDataOffsetPresent) {
  9654. i += 4; // truncate top 4 bytes
  9655. // FIXME: should we read the full 64 bits?
  9656. result.baseDataOffset = view.getUint32(12);
  9657. i += 4;
  9658. }
  9659. if (sampleDescriptionIndexPresent) {
  9660. result.sampleDescriptionIndex = view.getUint32(i);
  9661. i += 4;
  9662. }
  9663. if (defaultSampleDurationPresent) {
  9664. result.defaultSampleDuration = view.getUint32(i);
  9665. i += 4;
  9666. }
  9667. if (defaultSampleSizePresent) {
  9668. result.defaultSampleSize = view.getUint32(i);
  9669. i += 4;
  9670. }
  9671. if (defaultSampleFlagsPresent) {
  9672. result.defaultSampleFlags = view.getUint32(i);
  9673. }
  9674. if (durationIsEmpty) {
  9675. result.durationIsEmpty = true;
  9676. }
  9677. if (!baseDataOffsetPresent && defaultBaseIsMoof) {
  9678. result.baseDataOffsetIsMoof = true;
  9679. }
  9680. return result;
  9681. };
  9682. var parseTfhd$2 = tfhd;
  9683. var win;
  9684. if (typeof window !== "undefined") {
  9685. win = window;
  9686. } else if (typeof commonjsGlobal !== "undefined") {
  9687. win = commonjsGlobal;
  9688. } else if (typeof self !== "undefined") {
  9689. win = self;
  9690. } else {
  9691. win = {};
  9692. }
  9693. var window_1 = win;
  9694. /**
  9695. * mux.js
  9696. *
  9697. * Copyright (c) Brightcove
  9698. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9699. *
  9700. * Reads in-band CEA-708 captions out of FMP4 segments.
  9701. * @see https://en.wikipedia.org/wiki/CEA-708
  9702. */
  9703. var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
  9704. var CaptionStream = captionStream.CaptionStream;
  9705. var findBox$1 = findBox_1;
  9706. var parseTfdt$1 = parseTfdt$2;
  9707. var parseTrun$1 = parseTrun$2;
  9708. var parseTfhd$1 = parseTfhd$2;
  9709. var window$2 = window_1;
  9710. /**
  9711. * Maps an offset in the mdat to a sample based on the the size of the samples.
  9712. * Assumes that `parseSamples` has been called first.
  9713. *
  9714. * @param {Number} offset - The offset into the mdat
  9715. * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  9716. * @return {?Object} The matching sample, or null if no match was found.
  9717. *
  9718. * @see ISO-BMFF-12/2015, Section 8.8.8
  9719. **/
  9720. var mapToSample = function (offset, samples) {
  9721. var approximateOffset = offset;
  9722. for (var i = 0; i < samples.length; i++) {
  9723. var sample = samples[i];
  9724. if (approximateOffset < sample.size) {
  9725. return sample;
  9726. }
  9727. approximateOffset -= sample.size;
  9728. }
  9729. return null;
  9730. };
  9731. /**
  9732. * Finds SEI nal units contained in a Media Data Box.
  9733. * Assumes that `parseSamples` has been called first.
  9734. *
  9735. * @param {Uint8Array} avcStream - The bytes of the mdat
  9736. * @param {Object[]} samples - The samples parsed out by `parseSamples`
  9737. * @param {Number} trackId - The trackId of this video track
  9738. * @return {Object[]} seiNals - the parsed SEI NALUs found.
  9739. * The contents of the seiNal should match what is expected by
  9740. * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  9741. *
  9742. * @see ISO-BMFF-12/2015, Section 8.1.1
  9743. * @see Rec. ITU-T H.264, 7.3.2.3.1
  9744. **/
  9745. var findSeiNals = function (avcStream, samples, trackId) {
  9746. var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  9747. result = {
  9748. logs: [],
  9749. seiNals: []
  9750. },
  9751. seiNal,
  9752. i,
  9753. length,
  9754. lastMatchedSample;
  9755. for (i = 0; i + 4 < avcStream.length; i += length) {
  9756. length = avcView.getUint32(i);
  9757. i += 4; // Bail if this doesn't appear to be an H264 stream
  9758. if (length <= 0) {
  9759. continue;
  9760. }
  9761. switch (avcStream[i] & 0x1F) {
  9762. case 0x06:
  9763. var data = avcStream.subarray(i + 1, i + 1 + length);
  9764. var matchingSample = mapToSample(i, samples);
  9765. seiNal = {
  9766. nalUnitType: 'sei_rbsp',
  9767. size: length,
  9768. data: data,
  9769. escapedRBSP: discardEmulationPreventionBytes(data),
  9770. trackId: trackId
  9771. };
  9772. if (matchingSample) {
  9773. seiNal.pts = matchingSample.pts;
  9774. seiNal.dts = matchingSample.dts;
  9775. lastMatchedSample = matchingSample;
  9776. } else if (lastMatchedSample) {
  9777. // If a matching sample cannot be found, use the last
  9778. // sample's values as they should be as close as possible
  9779. seiNal.pts = lastMatchedSample.pts;
  9780. seiNal.dts = lastMatchedSample.dts;
  9781. } else {
  9782. result.logs.push({
  9783. level: 'warn',
  9784. message: 'We\'ve encountered a nal unit without data at ' + i + ' for trackId ' + trackId + '. See mux.js#223.'
  9785. });
  9786. break;
  9787. }
  9788. result.seiNals.push(seiNal);
  9789. break;
  9790. }
  9791. }
  9792. return result;
  9793. };
  9794. /**
  9795. * Parses sample information out of Track Run Boxes and calculates
  9796. * the absolute presentation and decode timestamps of each sample.
  9797. *
  9798. * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  9799. * @param {Number|BigInt} baseMediaDecodeTime - base media decode time from tfdt
  9800. @see ISO-BMFF-12/2015, Section 8.8.12
  9801. * @param {Object} tfhd - The parsed Track Fragment Header
  9802. * @see inspect.parseTfhd
  9803. * @return {Object[]} the parsed samples
  9804. *
  9805. * @see ISO-BMFF-12/2015, Section 8.8.8
  9806. **/
  9807. var parseSamples = function (truns, baseMediaDecodeTime, tfhd) {
  9808. var currentDts = baseMediaDecodeTime;
  9809. var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  9810. var defaultSampleSize = tfhd.defaultSampleSize || 0;
  9811. var trackId = tfhd.trackId;
  9812. var allSamples = [];
  9813. truns.forEach(function (trun) {
  9814. // Note: We currently do not parse the sample table as well
  9815. // as the trun. It's possible some sources will require this.
  9816. // moov > trak > mdia > minf > stbl
  9817. var trackRun = parseTrun$1(trun);
  9818. var samples = trackRun.samples;
  9819. samples.forEach(function (sample) {
  9820. if (sample.duration === undefined) {
  9821. sample.duration = defaultSampleDuration;
  9822. }
  9823. if (sample.size === undefined) {
  9824. sample.size = defaultSampleSize;
  9825. }
  9826. sample.trackId = trackId;
  9827. sample.dts = currentDts;
  9828. if (sample.compositionTimeOffset === undefined) {
  9829. sample.compositionTimeOffset = 0;
  9830. }
  9831. if (typeof currentDts === 'bigint') {
  9832. sample.pts = currentDts + window$2.BigInt(sample.compositionTimeOffset);
  9833. currentDts += window$2.BigInt(sample.duration);
  9834. } else {
  9835. sample.pts = currentDts + sample.compositionTimeOffset;
  9836. currentDts += sample.duration;
  9837. }
  9838. });
  9839. allSamples = allSamples.concat(samples);
  9840. });
  9841. return allSamples;
  9842. };
  9843. /**
  9844. * Parses out caption nals from an FMP4 segment's video tracks.
  9845. *
  9846. * @param {Uint8Array} segment - The bytes of a single segment
  9847. * @param {Number} videoTrackId - The trackId of a video track in the segment
  9848. * @return {Object.<Number, Object[]>} A mapping of video trackId to
  9849. * a list of seiNals found in that track
  9850. **/
  9851. var parseCaptionNals = function (segment, videoTrackId) {
  9852. // To get the samples
  9853. var trafs = findBox$1(segment, ['moof', 'traf']); // To get SEI NAL units
  9854. var mdats = findBox$1(segment, ['mdat']);
  9855. var captionNals = {};
  9856. var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
  9857. mdats.forEach(function (mdat, index) {
  9858. var matchingTraf = trafs[index];
  9859. mdatTrafPairs.push({
  9860. mdat: mdat,
  9861. traf: matchingTraf
  9862. });
  9863. });
  9864. mdatTrafPairs.forEach(function (pair) {
  9865. var mdat = pair.mdat;
  9866. var traf = pair.traf;
  9867. var tfhd = findBox$1(traf, ['tfhd']); // Exactly 1 tfhd per traf
  9868. var headerInfo = parseTfhd$1(tfhd[0]);
  9869. var trackId = headerInfo.trackId;
  9870. var tfdt = findBox$1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
  9871. var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt$1(tfdt[0]).baseMediaDecodeTime : 0;
  9872. var truns = findBox$1(traf, ['trun']);
  9873. var samples;
  9874. var result; // Only parse video data for the chosen video track
  9875. if (videoTrackId === trackId && truns.length > 0) {
  9876. samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
  9877. result = findSeiNals(mdat, samples, trackId);
  9878. if (!captionNals[trackId]) {
  9879. captionNals[trackId] = {
  9880. seiNals: [],
  9881. logs: []
  9882. };
  9883. }
  9884. captionNals[trackId].seiNals = captionNals[trackId].seiNals.concat(result.seiNals);
  9885. captionNals[trackId].logs = captionNals[trackId].logs.concat(result.logs);
  9886. }
  9887. });
  9888. return captionNals;
  9889. };
  9890. /**
  9891. * Parses out inband captions from an MP4 container and returns
  9892. * caption objects that can be used by WebVTT and the TextTrack API.
  9893. * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  9894. * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  9895. * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  9896. *
  9897. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  9898. * @param {Number} trackId - The id of the video track to parse
  9899. * @param {Number} timescale - The timescale for the video track from the init segment
  9900. *
  9901. * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  9902. * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  9903. * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  9904. * @return {Object[]} parsedCaptions[].content - A list of individual caption segments
  9905. * @return {String} parsedCaptions[].content.text - The visible content of the caption segment
  9906. * @return {Number} parsedCaptions[].content.line - The line height from 1-15 for positioning of the caption segment
  9907. * @return {Number} parsedCaptions[].content.position - The column indent percentage for cue positioning from 10-80
  9908. **/
  9909. var parseEmbeddedCaptions = function (segment, trackId, timescale) {
  9910. var captionNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  9911. if (trackId === null) {
  9912. return null;
  9913. }
  9914. captionNals = parseCaptionNals(segment, trackId);
  9915. var trackNals = captionNals[trackId] || {};
  9916. return {
  9917. seiNals: trackNals.seiNals,
  9918. logs: trackNals.logs,
  9919. timescale: timescale
  9920. };
  9921. };
  9922. /**
  9923. * Converts SEI NALUs into captions that can be used by video.js
  9924. **/
  9925. var CaptionParser = function () {
  9926. var isInitialized = false;
  9927. var captionStream; // Stores segments seen before trackId and timescale are set
  9928. var segmentCache; // Stores video track ID of the track being parsed
  9929. var trackId; // Stores the timescale of the track being parsed
  9930. var timescale; // Stores captions parsed so far
  9931. var parsedCaptions; // Stores whether we are receiving partial data or not
  9932. var parsingPartial;
  9933. /**
  9934. * A method to indicate whether a CaptionParser has been initalized
  9935. * @returns {Boolean}
  9936. **/
  9937. this.isInitialized = function () {
  9938. return isInitialized;
  9939. };
  9940. /**
  9941. * Initializes the underlying CaptionStream, SEI NAL parsing
  9942. * and management, and caption collection
  9943. **/
  9944. this.init = function (options) {
  9945. captionStream = new CaptionStream();
  9946. isInitialized = true;
  9947. parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
  9948. captionStream.on('data', function (event) {
  9949. // Convert to seconds in the source's timescale
  9950. event.startTime = event.startPts / timescale;
  9951. event.endTime = event.endPts / timescale;
  9952. parsedCaptions.captions.push(event);
  9953. parsedCaptions.captionStreams[event.stream] = true;
  9954. });
  9955. captionStream.on('log', function (log) {
  9956. parsedCaptions.logs.push(log);
  9957. });
  9958. };
  9959. /**
  9960. * Determines if a new video track will be selected
  9961. * or if the timescale changed
  9962. * @return {Boolean}
  9963. **/
  9964. this.isNewInit = function (videoTrackIds, timescales) {
  9965. if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
  9966. return false;
  9967. }
  9968. return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
  9969. };
  9970. /**
  9971. * Parses out SEI captions and interacts with underlying
  9972. * CaptionStream to return dispatched captions
  9973. *
  9974. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  9975. * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
  9976. * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
  9977. * @see parseEmbeddedCaptions
  9978. * @see m2ts/caption-stream.js
  9979. **/
  9980. this.parse = function (segment, videoTrackIds, timescales) {
  9981. var parsedData;
  9982. if (!this.isInitialized()) {
  9983. return null; // This is not likely to be a video segment
  9984. } else if (!videoTrackIds || !timescales) {
  9985. return null;
  9986. } else if (this.isNewInit(videoTrackIds, timescales)) {
  9987. // Use the first video track only as there is no
  9988. // mechanism to switch to other video tracks
  9989. trackId = videoTrackIds[0];
  9990. timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
  9991. // data until we have one.
  9992. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  9993. } else if (trackId === null || !timescale) {
  9994. segmentCache.push(segment);
  9995. return null;
  9996. } // Now that a timescale and trackId is set, parse cached segments
  9997. while (segmentCache.length > 0) {
  9998. var cachedSegment = segmentCache.shift();
  9999. this.parse(cachedSegment, videoTrackIds, timescales);
  10000. }
  10001. parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
  10002. if (parsedData && parsedData.logs) {
  10003. parsedCaptions.logs = parsedCaptions.logs.concat(parsedData.logs);
  10004. }
  10005. if (parsedData === null || !parsedData.seiNals) {
  10006. if (parsedCaptions.logs.length) {
  10007. return {
  10008. logs: parsedCaptions.logs,
  10009. captions: [],
  10010. captionStreams: []
  10011. };
  10012. }
  10013. return null;
  10014. }
  10015. this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
  10016. this.flushStream();
  10017. return parsedCaptions;
  10018. };
  10019. /**
  10020. * Pushes SEI NALUs onto CaptionStream
  10021. * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
  10022. * Assumes that `parseCaptionNals` has been called first
  10023. * @see m2ts/caption-stream.js
  10024. **/
  10025. this.pushNals = function (nals) {
  10026. if (!this.isInitialized() || !nals || nals.length === 0) {
  10027. return null;
  10028. }
  10029. nals.forEach(function (nal) {
  10030. captionStream.push(nal);
  10031. });
  10032. };
  10033. /**
  10034. * Flushes underlying CaptionStream to dispatch processed, displayable captions
  10035. * @see m2ts/caption-stream.js
  10036. **/
  10037. this.flushStream = function () {
  10038. if (!this.isInitialized()) {
  10039. return null;
  10040. }
  10041. if (!parsingPartial) {
  10042. captionStream.flush();
  10043. } else {
  10044. captionStream.partialFlush();
  10045. }
  10046. };
  10047. /**
  10048. * Reset caption buckets for new data
  10049. **/
  10050. this.clearParsedCaptions = function () {
  10051. parsedCaptions.captions = [];
  10052. parsedCaptions.captionStreams = {};
  10053. parsedCaptions.logs = [];
  10054. };
  10055. /**
  10056. * Resets underlying CaptionStream
  10057. * @see m2ts/caption-stream.js
  10058. **/
  10059. this.resetCaptionStream = function () {
  10060. if (!this.isInitialized()) {
  10061. return null;
  10062. }
  10063. captionStream.reset();
  10064. };
  10065. /**
  10066. * Convenience method to clear all captions flushed from the
  10067. * CaptionStream and still being parsed
  10068. * @see m2ts/caption-stream.js
  10069. **/
  10070. this.clearAllCaptions = function () {
  10071. this.clearParsedCaptions();
  10072. this.resetCaptionStream();
  10073. };
  10074. /**
  10075. * Reset caption parser
  10076. **/
  10077. this.reset = function () {
  10078. segmentCache = [];
  10079. trackId = null;
  10080. timescale = null;
  10081. if (!parsedCaptions) {
  10082. parsedCaptions = {
  10083. captions: [],
  10084. // CC1, CC2, CC3, CC4
  10085. captionStreams: {},
  10086. logs: []
  10087. };
  10088. } else {
  10089. this.clearParsedCaptions();
  10090. }
  10091. this.resetCaptionStream();
  10092. };
  10093. this.reset();
  10094. };
  10095. var captionParser = CaptionParser;
  10096. /**
  10097. * Returns the first string in the data array ending with a null char '\0'
  10098. * @param {UInt8} data
  10099. * @returns the string with the null char
  10100. */
  10101. var uint8ToCString$1 = function (data) {
  10102. var index = 0;
  10103. var curChar = String.fromCharCode(data[index]);
  10104. var retString = '';
  10105. while (curChar !== '\0') {
  10106. retString += curChar;
  10107. index++;
  10108. curChar = String.fromCharCode(data[index]);
  10109. } // Add nullChar
  10110. retString += curChar;
  10111. return retString;
  10112. };
  10113. var string = {
  10114. uint8ToCString: uint8ToCString$1
  10115. };
  10116. var uint8ToCString = string.uint8ToCString;
  10117. var getUint64$1 = numbers.getUint64;
  10118. /**
  10119. * Based on: ISO/IEC 23009 Section: 5.10.3.3
  10120. * References:
  10121. * https://dashif-documents.azurewebsites.net/Events/master/event.html#emsg-format
  10122. * https://aomediacodec.github.io/id3-emsg/
  10123. *
  10124. * Takes emsg box data as a uint8 array and returns a emsg box object
  10125. * @param {UInt8Array} boxData data from emsg box
  10126. * @returns A parsed emsg box object
  10127. */
  10128. var parseEmsgBox = function (boxData) {
  10129. // version + flags
  10130. var offset = 4;
  10131. var version = boxData[0];
  10132. var scheme_id_uri, value, timescale, presentation_time, presentation_time_delta, event_duration, id, message_data;
  10133. if (version === 0) {
  10134. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  10135. offset += scheme_id_uri.length;
  10136. value = uint8ToCString(boxData.subarray(offset));
  10137. offset += value.length;
  10138. var dv = new DataView(boxData.buffer);
  10139. timescale = dv.getUint32(offset);
  10140. offset += 4;
  10141. presentation_time_delta = dv.getUint32(offset);
  10142. offset += 4;
  10143. event_duration = dv.getUint32(offset);
  10144. offset += 4;
  10145. id = dv.getUint32(offset);
  10146. offset += 4;
  10147. } else if (version === 1) {
  10148. var dv = new DataView(boxData.buffer);
  10149. timescale = dv.getUint32(offset);
  10150. offset += 4;
  10151. presentation_time = getUint64$1(boxData.subarray(offset));
  10152. offset += 8;
  10153. event_duration = dv.getUint32(offset);
  10154. offset += 4;
  10155. id = dv.getUint32(offset);
  10156. offset += 4;
  10157. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  10158. offset += scheme_id_uri.length;
  10159. value = uint8ToCString(boxData.subarray(offset));
  10160. offset += value.length;
  10161. }
  10162. message_data = new Uint8Array(boxData.subarray(offset, boxData.byteLength));
  10163. var emsgBox = {
  10164. scheme_id_uri,
  10165. value,
  10166. // if timescale is undefined or 0 set to 1
  10167. timescale: timescale ? timescale : 1,
  10168. presentation_time,
  10169. presentation_time_delta,
  10170. event_duration,
  10171. id,
  10172. message_data
  10173. };
  10174. return isValidEmsgBox(version, emsgBox) ? emsgBox : undefined;
  10175. };
  10176. /**
  10177. * Scales a presentation time or time delta with an offset with a provided timescale
  10178. * @param {number} presentationTime
  10179. * @param {number} timescale
  10180. * @param {number} timeDelta
  10181. * @param {number} offset
  10182. * @returns the scaled time as a number
  10183. */
  10184. var scaleTime = function (presentationTime, timescale, timeDelta, offset) {
  10185. return presentationTime || presentationTime === 0 ? presentationTime / timescale : offset + timeDelta / timescale;
  10186. };
  10187. /**
  10188. * Checks the emsg box data for validity based on the version
  10189. * @param {number} version of the emsg box to validate
  10190. * @param {Object} emsg the emsg data to validate
  10191. * @returns if the box is valid as a boolean
  10192. */
  10193. var isValidEmsgBox = function (version, emsg) {
  10194. var hasScheme = emsg.scheme_id_uri !== '\0';
  10195. var isValidV0Box = version === 0 && isDefined(emsg.presentation_time_delta) && hasScheme;
  10196. var isValidV1Box = version === 1 && isDefined(emsg.presentation_time) && hasScheme; // Only valid versions of emsg are 0 and 1
  10197. return !(version > 1) && isValidV0Box || isValidV1Box;
  10198. }; // Utility function to check if an object is defined
  10199. var isDefined = function (data) {
  10200. return data !== undefined || data !== null;
  10201. };
  10202. var emsg$1 = {
  10203. parseEmsgBox: parseEmsgBox,
  10204. scaleTime: scaleTime
  10205. };
  10206. /**
  10207. * mux.js
  10208. *
  10209. * Copyright (c) Brightcove
  10210. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  10211. *
  10212. * Utilities to detect basic properties and metadata about MP4s.
  10213. */
  10214. var toUnsigned = bin.toUnsigned;
  10215. var toHexString = bin.toHexString;
  10216. var findBox = findBox_1;
  10217. var parseType$1 = parseType_1;
  10218. var emsg = emsg$1;
  10219. var parseTfhd = parseTfhd$2;
  10220. var parseTrun = parseTrun$2;
  10221. var parseTfdt = parseTfdt$2;
  10222. var getUint64 = numbers.getUint64;
  10223. var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader, getEmsgID3;
  10224. var window$1 = window_1;
  10225. var parseId3Frames = parseId3.parseId3Frames;
  10226. /**
  10227. * Parses an MP4 initialization segment and extracts the timescale
  10228. * values for any declared tracks. Timescale values indicate the
  10229. * number of clock ticks per second to assume for time-based values
  10230. * elsewhere in the MP4.
  10231. *
  10232. * To determine the start time of an MP4, you need two pieces of
  10233. * information: the timescale unit and the earliest base media decode
  10234. * time. Multiple timescales can be specified within an MP4 but the
  10235. * base media decode time is always expressed in the timescale from
  10236. * the media header box for the track:
  10237. * ```
  10238. * moov > trak > mdia > mdhd.timescale
  10239. * ```
  10240. * @param init {Uint8Array} the bytes of the init segment
  10241. * @return {object} a hash of track ids to timescale values or null if
  10242. * the init segment is malformed.
  10243. */
  10244. timescale = function (init) {
  10245. var result = {},
  10246. traks = findBox(init, ['moov', 'trak']); // mdhd timescale
  10247. return traks.reduce(function (result, trak) {
  10248. var tkhd, version, index, id, mdhd;
  10249. tkhd = findBox(trak, ['tkhd'])[0];
  10250. if (!tkhd) {
  10251. return null;
  10252. }
  10253. version = tkhd[0];
  10254. index = version === 0 ? 12 : 20;
  10255. id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
  10256. mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  10257. if (!mdhd) {
  10258. return null;
  10259. }
  10260. version = mdhd[0];
  10261. index = version === 0 ? 12 : 20;
  10262. result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  10263. return result;
  10264. }, result);
  10265. };
  10266. /**
  10267. * Determine the base media decode start time, in seconds, for an MP4
  10268. * fragment. If multiple fragments are specified, the earliest time is
  10269. * returned.
  10270. *
  10271. * The base media decode time can be parsed from track fragment
  10272. * metadata:
  10273. * ```
  10274. * moof > traf > tfdt.baseMediaDecodeTime
  10275. * ```
  10276. * It requires the timescale value from the mdhd to interpret.
  10277. *
  10278. * @param timescale {object} a hash of track ids to timescale values.
  10279. * @return {number} the earliest base media decode start time for the
  10280. * fragment, in seconds
  10281. */
  10282. startTime = function (timescale, fragment) {
  10283. var trafs; // we need info from two childrend of each track fragment box
  10284. trafs = findBox(fragment, ['moof', 'traf']); // determine the start times for each track
  10285. var lowestTime = trafs.reduce(function (acc, traf) {
  10286. var tfhd = findBox(traf, ['tfhd'])[0]; // get the track id from the tfhd
  10287. var id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
  10288. var scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
  10289. var tfdt = findBox(traf, ['tfdt'])[0];
  10290. var dv = new DataView(tfdt.buffer, tfdt.byteOffset, tfdt.byteLength);
  10291. var baseTime; // version 1 is 64 bit
  10292. if (tfdt[0] === 1) {
  10293. baseTime = getUint64(tfdt.subarray(4, 12));
  10294. } else {
  10295. baseTime = dv.getUint32(4);
  10296. } // convert base time to seconds if it is a valid number.
  10297. let seconds;
  10298. if (typeof baseTime === 'bigint') {
  10299. seconds = baseTime / window$1.BigInt(scale);
  10300. } else if (typeof baseTime === 'number' && !isNaN(baseTime)) {
  10301. seconds = baseTime / scale;
  10302. }
  10303. if (seconds < Number.MAX_SAFE_INTEGER) {
  10304. seconds = Number(seconds);
  10305. }
  10306. if (seconds < acc) {
  10307. acc = seconds;
  10308. }
  10309. return acc;
  10310. }, Infinity);
  10311. return typeof lowestTime === 'bigint' || isFinite(lowestTime) ? lowestTime : 0;
  10312. };
  10313. /**
  10314. * Determine the composition start, in seconds, for an MP4
  10315. * fragment.
  10316. *
  10317. * The composition start time of a fragment can be calculated using the base
  10318. * media decode time, composition time offset, and timescale, as follows:
  10319. *
  10320. * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
  10321. *
  10322. * All of the aforementioned information is contained within a media fragment's
  10323. * `traf` box, except for timescale info, which comes from the initialization
  10324. * segment, so a track id (also contained within a `traf`) is also necessary to
  10325. * associate it with a timescale
  10326. *
  10327. *
  10328. * @param timescales {object} - a hash of track ids to timescale values.
  10329. * @param fragment {Unit8Array} - the bytes of a media segment
  10330. * @return {number} the composition start time for the fragment, in seconds
  10331. **/
  10332. compositionStartTime = function (timescales, fragment) {
  10333. var trafBoxes = findBox(fragment, ['moof', 'traf']);
  10334. var baseMediaDecodeTime = 0;
  10335. var compositionTimeOffset = 0;
  10336. var trackId;
  10337. if (trafBoxes && trafBoxes.length) {
  10338. // The spec states that track run samples contained within a `traf` box are contiguous, but
  10339. // it does not explicitly state whether the `traf` boxes themselves are contiguous.
  10340. // We will assume that they are, so we only need the first to calculate start time.
  10341. var tfhd = findBox(trafBoxes[0], ['tfhd'])[0];
  10342. var trun = findBox(trafBoxes[0], ['trun'])[0];
  10343. var tfdt = findBox(trafBoxes[0], ['tfdt'])[0];
  10344. if (tfhd) {
  10345. var parsedTfhd = parseTfhd(tfhd);
  10346. trackId = parsedTfhd.trackId;
  10347. }
  10348. if (tfdt) {
  10349. var parsedTfdt = parseTfdt(tfdt);
  10350. baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
  10351. }
  10352. if (trun) {
  10353. var parsedTrun = parseTrun(trun);
  10354. if (parsedTrun.samples && parsedTrun.samples.length) {
  10355. compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
  10356. }
  10357. }
  10358. } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
  10359. // specified.
  10360. var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
  10361. if (typeof baseMediaDecodeTime === 'bigint') {
  10362. compositionTimeOffset = window$1.BigInt(compositionTimeOffset);
  10363. timescale = window$1.BigInt(timescale);
  10364. }
  10365. var result = (baseMediaDecodeTime + compositionTimeOffset) / timescale;
  10366. if (typeof result === 'bigint' && result < Number.MAX_SAFE_INTEGER) {
  10367. result = Number(result);
  10368. }
  10369. return result;
  10370. };
  10371. /**
  10372. * Find the trackIds of the video tracks in this source.
  10373. * Found by parsing the Handler Reference and Track Header Boxes:
  10374. * moov > trak > mdia > hdlr
  10375. * moov > trak > tkhd
  10376. *
  10377. * @param {Uint8Array} init - The bytes of the init segment for this source
  10378. * @return {Number[]} A list of trackIds
  10379. *
  10380. * @see ISO-BMFF-12/2015, Section 8.4.3
  10381. **/
  10382. getVideoTrackIds = function (init) {
  10383. var traks = findBox(init, ['moov', 'trak']);
  10384. var videoTrackIds = [];
  10385. traks.forEach(function (trak) {
  10386. var hdlrs = findBox(trak, ['mdia', 'hdlr']);
  10387. var tkhds = findBox(trak, ['tkhd']);
  10388. hdlrs.forEach(function (hdlr, index) {
  10389. var handlerType = parseType$1(hdlr.subarray(8, 12));
  10390. var tkhd = tkhds[index];
  10391. var view;
  10392. var version;
  10393. var trackId;
  10394. if (handlerType === 'vide') {
  10395. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  10396. version = view.getUint8(0);
  10397. trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
  10398. videoTrackIds.push(trackId);
  10399. }
  10400. });
  10401. });
  10402. return videoTrackIds;
  10403. };
  10404. getTimescaleFromMediaHeader = function (mdhd) {
  10405. // mdhd is a FullBox, meaning it will have its own version as the first byte
  10406. var version = mdhd[0];
  10407. var index = version === 0 ? 12 : 20;
  10408. return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  10409. };
  10410. /**
  10411. * Get all the video, audio, and hint tracks from a non fragmented
  10412. * mp4 segment
  10413. */
  10414. getTracks = function (init) {
  10415. var traks = findBox(init, ['moov', 'trak']);
  10416. var tracks = [];
  10417. traks.forEach(function (trak) {
  10418. var track = {};
  10419. var tkhd = findBox(trak, ['tkhd'])[0];
  10420. var view, tkhdVersion; // id
  10421. if (tkhd) {
  10422. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  10423. tkhdVersion = view.getUint8(0);
  10424. track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
  10425. }
  10426. var hdlr = findBox(trak, ['mdia', 'hdlr'])[0]; // type
  10427. if (hdlr) {
  10428. var type = parseType$1(hdlr.subarray(8, 12));
  10429. if (type === 'vide') {
  10430. track.type = 'video';
  10431. } else if (type === 'soun') {
  10432. track.type = 'audio';
  10433. } else {
  10434. track.type = type;
  10435. }
  10436. } // codec
  10437. var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  10438. if (stsd) {
  10439. var sampleDescriptions = stsd.subarray(8); // gives the codec type string
  10440. track.codec = parseType$1(sampleDescriptions.subarray(4, 8));
  10441. var codecBox = findBox(sampleDescriptions, [track.codec])[0];
  10442. var codecConfig, codecConfigType;
  10443. if (codecBox) {
  10444. // https://tools.ietf.org/html/rfc6381#section-3.3
  10445. if (/^[asm]vc[1-9]$/i.test(track.codec)) {
  10446. // we don't need anything but the "config" parameter of the
  10447. // avc1 codecBox
  10448. codecConfig = codecBox.subarray(78);
  10449. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  10450. if (codecConfigType === 'avcC' && codecConfig.length > 11) {
  10451. track.codec += '.'; // left padded with zeroes for single digit hex
  10452. // profile idc
  10453. track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
  10454. track.codec += toHexString(codecConfig[10]); // level idc
  10455. track.codec += toHexString(codecConfig[11]);
  10456. } else {
  10457. // TODO: show a warning that we couldn't parse the codec
  10458. // and are using the default
  10459. track.codec = 'avc1.4d400d';
  10460. }
  10461. } else if (/^mp4[a,v]$/i.test(track.codec)) {
  10462. // we do not need anything but the streamDescriptor of the mp4a codecBox
  10463. codecConfig = codecBox.subarray(28);
  10464. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  10465. if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
  10466. track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
  10467. track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
  10468. } else {
  10469. // TODO: show a warning that we couldn't parse the codec
  10470. // and are using the default
  10471. track.codec = 'mp4a.40.2';
  10472. }
  10473. } else {
  10474. // flac, opus, etc
  10475. track.codec = track.codec.toLowerCase();
  10476. }
  10477. }
  10478. }
  10479. var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  10480. if (mdhd) {
  10481. track.timescale = getTimescaleFromMediaHeader(mdhd);
  10482. }
  10483. tracks.push(track);
  10484. });
  10485. return tracks;
  10486. };
  10487. /**
  10488. * Returns an array of emsg ID3 data from the provided segmentData.
  10489. * An offset can also be provided as the Latest Arrival Time to calculate
  10490. * the Event Start Time of v0 EMSG boxes.
  10491. * See: https://dashif-documents.azurewebsites.net/Events/master/event.html#Inband-event-timing
  10492. *
  10493. * @param {Uint8Array} segmentData the segment byte array.
  10494. * @param {number} offset the segment start time or Latest Arrival Time,
  10495. * @return {Object[]} an array of ID3 parsed from EMSG boxes
  10496. */
  10497. getEmsgID3 = function (segmentData, offset = 0) {
  10498. var emsgBoxes = findBox(segmentData, ['emsg']);
  10499. return emsgBoxes.map(data => {
  10500. var parsedBox = emsg.parseEmsgBox(new Uint8Array(data));
  10501. var parsedId3Frames = parseId3Frames(parsedBox.message_data);
  10502. return {
  10503. cueTime: emsg.scaleTime(parsedBox.presentation_time, parsedBox.timescale, parsedBox.presentation_time_delta, offset),
  10504. duration: emsg.scaleTime(parsedBox.event_duration, parsedBox.timescale),
  10505. frames: parsedId3Frames
  10506. };
  10507. });
  10508. };
  10509. var probe$2 = {
  10510. // export mp4 inspector's findBox and parseType for backwards compatibility
  10511. findBox: findBox,
  10512. parseType: parseType$1,
  10513. timescale: timescale,
  10514. startTime: startTime,
  10515. compositionStartTime: compositionStartTime,
  10516. videoTrackIds: getVideoTrackIds,
  10517. tracks: getTracks,
  10518. getTimescaleFromMediaHeader: getTimescaleFromMediaHeader,
  10519. getEmsgID3: getEmsgID3
  10520. };
  10521. /**
  10522. * mux.js
  10523. *
  10524. * Copyright (c) Brightcove
  10525. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  10526. *
  10527. * Utilities to detect basic properties and metadata about TS Segments.
  10528. */
  10529. var StreamTypes$1 = streamTypes;
  10530. var parsePid = function (packet) {
  10531. var pid = packet[1] & 0x1f;
  10532. pid <<= 8;
  10533. pid |= packet[2];
  10534. return pid;
  10535. };
  10536. var parsePayloadUnitStartIndicator = function (packet) {
  10537. return !!(packet[1] & 0x40);
  10538. };
  10539. var parseAdaptionField = function (packet) {
  10540. var offset = 0; // if an adaption field is present, its length is specified by the
  10541. // fifth byte of the TS packet header. The adaptation field is
  10542. // used to add stuffing to PES packets that don't fill a complete
  10543. // TS packet, and to specify some forms of timing and control data
  10544. // that we do not currently use.
  10545. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  10546. offset += packet[4] + 1;
  10547. }
  10548. return offset;
  10549. };
  10550. var parseType = function (packet, pmtPid) {
  10551. var pid = parsePid(packet);
  10552. if (pid === 0) {
  10553. return 'pat';
  10554. } else if (pid === pmtPid) {
  10555. return 'pmt';
  10556. } else if (pmtPid) {
  10557. return 'pes';
  10558. }
  10559. return null;
  10560. };
  10561. var parsePat = function (packet) {
  10562. var pusi = parsePayloadUnitStartIndicator(packet);
  10563. var offset = 4 + parseAdaptionField(packet);
  10564. if (pusi) {
  10565. offset += packet[offset] + 1;
  10566. }
  10567. return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
  10568. };
  10569. var parsePmt = function (packet) {
  10570. var programMapTable = {};
  10571. var pusi = parsePayloadUnitStartIndicator(packet);
  10572. var payloadOffset = 4 + parseAdaptionField(packet);
  10573. if (pusi) {
  10574. payloadOffset += packet[payloadOffset] + 1;
  10575. } // PMTs can be sent ahead of the time when they should actually
  10576. // take effect. We don't believe this should ever be the case
  10577. // for HLS but we'll ignore "forward" PMT declarations if we see
  10578. // them. Future PMT declarations have the current_next_indicator
  10579. // set to zero.
  10580. if (!(packet[payloadOffset + 5] & 0x01)) {
  10581. return;
  10582. }
  10583. var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section
  10584. sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
  10585. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  10586. // long the program info descriptors are
  10587. programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table
  10588. var offset = 12 + programInfoLength;
  10589. while (offset < tableEnd) {
  10590. var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type
  10591. programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
  10592. // skip past the elementary stream descriptors, if present
  10593. offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
  10594. }
  10595. return programMapTable;
  10596. };
  10597. var parsePesType = function (packet, programMapTable) {
  10598. var pid = parsePid(packet);
  10599. var type = programMapTable[pid];
  10600. switch (type) {
  10601. case StreamTypes$1.H264_STREAM_TYPE:
  10602. return 'video';
  10603. case StreamTypes$1.ADTS_STREAM_TYPE:
  10604. return 'audio';
  10605. case StreamTypes$1.METADATA_STREAM_TYPE:
  10606. return 'timed-metadata';
  10607. default:
  10608. return null;
  10609. }
  10610. };
  10611. var parsePesTime = function (packet) {
  10612. var pusi = parsePayloadUnitStartIndicator(packet);
  10613. if (!pusi) {
  10614. return null;
  10615. }
  10616. var offset = 4 + parseAdaptionField(packet);
  10617. if (offset >= packet.byteLength) {
  10618. // From the H 222.0 MPEG-TS spec
  10619. // "For transport stream packets carrying PES packets, stuffing is needed when there
  10620. // is insufficient PES packet data to completely fill the transport stream packet
  10621. // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
  10622. // the sum of the lengths of the data elements in it, so that the payload bytes
  10623. // remaining after the adaptation field exactly accommodates the available PES packet
  10624. // data."
  10625. //
  10626. // If the offset is >= the length of the packet, then the packet contains no data
  10627. // and instead is just adaption field stuffing bytes
  10628. return null;
  10629. }
  10630. var pes = null;
  10631. var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value
  10632. // and a DTS value. Determine what combination of values is
  10633. // available to work with.
  10634. ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  10635. // performs all bitwise operations on 32-bit integers but javascript
  10636. // supports a much greater range (52-bits) of integer using standard
  10637. // mathematical operations.
  10638. // We construct a 31-bit value using bitwise operators over the 31
  10639. // most significant bits and then multiply by 4 (equal to a left-shift
  10640. // of 2) before we add the final 2 least significant bits of the
  10641. // timestamp (equal to an OR.)
  10642. if (ptsDtsFlags & 0xC0) {
  10643. pes = {}; // the PTS and DTS are not written out directly. For information
  10644. // on how they are encoded, see
  10645. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  10646. 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;
  10647. pes.pts *= 4; // Left shift by 2
  10648. pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
  10649. pes.dts = pes.pts;
  10650. if (ptsDtsFlags & 0x40) {
  10651. 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;
  10652. pes.dts *= 4; // Left shift by 2
  10653. pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
  10654. }
  10655. }
  10656. return pes;
  10657. };
  10658. var parseNalUnitType = function (type) {
  10659. switch (type) {
  10660. case 0x05:
  10661. return 'slice_layer_without_partitioning_rbsp_idr';
  10662. case 0x06:
  10663. return 'sei_rbsp';
  10664. case 0x07:
  10665. return 'seq_parameter_set_rbsp';
  10666. case 0x08:
  10667. return 'pic_parameter_set_rbsp';
  10668. case 0x09:
  10669. return 'access_unit_delimiter_rbsp';
  10670. default:
  10671. return null;
  10672. }
  10673. };
  10674. var videoPacketContainsKeyFrame = function (packet) {
  10675. var offset = 4 + parseAdaptionField(packet);
  10676. var frameBuffer = packet.subarray(offset);
  10677. var frameI = 0;
  10678. var frameSyncPoint = 0;
  10679. var foundKeyFrame = false;
  10680. var nalType; // advance the sync point to a NAL start, if necessary
  10681. for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
  10682. if (frameBuffer[frameSyncPoint + 2] === 1) {
  10683. // the sync point is properly aligned
  10684. frameI = frameSyncPoint + 5;
  10685. break;
  10686. }
  10687. }
  10688. while (frameI < frameBuffer.byteLength) {
  10689. // look at the current byte to determine if we've hit the end of
  10690. // a NAL unit boundary
  10691. switch (frameBuffer[frameI]) {
  10692. case 0:
  10693. // skip past non-sync sequences
  10694. if (frameBuffer[frameI - 1] !== 0) {
  10695. frameI += 2;
  10696. break;
  10697. } else if (frameBuffer[frameI - 2] !== 0) {
  10698. frameI++;
  10699. break;
  10700. }
  10701. if (frameSyncPoint + 3 !== frameI - 2) {
  10702. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  10703. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  10704. foundKeyFrame = true;
  10705. }
  10706. } // drop trailing zeroes
  10707. do {
  10708. frameI++;
  10709. } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
  10710. frameSyncPoint = frameI - 2;
  10711. frameI += 3;
  10712. break;
  10713. case 1:
  10714. // skip past non-sync sequences
  10715. if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
  10716. frameI += 3;
  10717. break;
  10718. }
  10719. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  10720. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  10721. foundKeyFrame = true;
  10722. }
  10723. frameSyncPoint = frameI - 2;
  10724. frameI += 3;
  10725. break;
  10726. default:
  10727. // the current byte isn't a one or zero, so it cannot be part
  10728. // of a sync sequence
  10729. frameI += 3;
  10730. break;
  10731. }
  10732. }
  10733. frameBuffer = frameBuffer.subarray(frameSyncPoint);
  10734. frameI -= frameSyncPoint;
  10735. frameSyncPoint = 0; // parse the final nal
  10736. if (frameBuffer && frameBuffer.byteLength > 3) {
  10737. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  10738. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  10739. foundKeyFrame = true;
  10740. }
  10741. }
  10742. return foundKeyFrame;
  10743. };
  10744. var probe$1 = {
  10745. parseType: parseType,
  10746. parsePat: parsePat,
  10747. parsePmt: parsePmt,
  10748. parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
  10749. parsePesType: parsePesType,
  10750. parsePesTime: parsePesTime,
  10751. videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
  10752. };
  10753. /**
  10754. * mux.js
  10755. *
  10756. * Copyright (c) Brightcove
  10757. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  10758. *
  10759. * Parse mpeg2 transport stream packets to extract basic timing information
  10760. */
  10761. var StreamTypes = streamTypes;
  10762. var handleRollover = timestampRolloverStream.handleRollover;
  10763. var probe = {};
  10764. probe.ts = probe$1;
  10765. probe.aac = utils;
  10766. var ONE_SECOND_IN_TS = clock$2.ONE_SECOND_IN_TS;
  10767. var MP2T_PACKET_LENGTH = 188,
  10768. // bytes
  10769. SYNC_BYTE = 0x47;
  10770. /**
  10771. * walks through segment data looking for pat and pmt packets to parse out
  10772. * program map table information
  10773. */
  10774. var parsePsi_ = function (bytes, pmt) {
  10775. var startIndex = 0,
  10776. endIndex = MP2T_PACKET_LENGTH,
  10777. packet,
  10778. type;
  10779. while (endIndex < bytes.byteLength) {
  10780. // Look for a pair of start and end sync bytes in the data..
  10781. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  10782. // We found a packet
  10783. packet = bytes.subarray(startIndex, endIndex);
  10784. type = probe.ts.parseType(packet, pmt.pid);
  10785. switch (type) {
  10786. case 'pat':
  10787. pmt.pid = probe.ts.parsePat(packet);
  10788. break;
  10789. case 'pmt':
  10790. var table = probe.ts.parsePmt(packet);
  10791. pmt.table = pmt.table || {};
  10792. Object.keys(table).forEach(function (key) {
  10793. pmt.table[key] = table[key];
  10794. });
  10795. break;
  10796. }
  10797. startIndex += MP2T_PACKET_LENGTH;
  10798. endIndex += MP2T_PACKET_LENGTH;
  10799. continue;
  10800. } // If we get here, we have somehow become de-synchronized and we need to step
  10801. // forward one byte at a time until we find a pair of sync bytes that denote
  10802. // a packet
  10803. startIndex++;
  10804. endIndex++;
  10805. }
  10806. };
  10807. /**
  10808. * walks through the segment data from the start and end to get timing information
  10809. * for the first and last audio pes packets
  10810. */
  10811. var parseAudioPes_ = function (bytes, pmt, result) {
  10812. var startIndex = 0,
  10813. endIndex = MP2T_PACKET_LENGTH,
  10814. packet,
  10815. type,
  10816. pesType,
  10817. pusi,
  10818. parsed;
  10819. var endLoop = false; // Start walking from start of segment to get first audio packet
  10820. while (endIndex <= bytes.byteLength) {
  10821. // Look for a pair of start and end sync bytes in the data..
  10822. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  10823. // We found a packet
  10824. packet = bytes.subarray(startIndex, endIndex);
  10825. type = probe.ts.parseType(packet, pmt.pid);
  10826. switch (type) {
  10827. case 'pes':
  10828. pesType = probe.ts.parsePesType(packet, pmt.table);
  10829. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  10830. if (pesType === 'audio' && pusi) {
  10831. parsed = probe.ts.parsePesTime(packet);
  10832. if (parsed) {
  10833. parsed.type = 'audio';
  10834. result.audio.push(parsed);
  10835. endLoop = true;
  10836. }
  10837. }
  10838. break;
  10839. }
  10840. if (endLoop) {
  10841. break;
  10842. }
  10843. startIndex += MP2T_PACKET_LENGTH;
  10844. endIndex += MP2T_PACKET_LENGTH;
  10845. continue;
  10846. } // If we get here, we have somehow become de-synchronized and we need to step
  10847. // forward one byte at a time until we find a pair of sync bytes that denote
  10848. // a packet
  10849. startIndex++;
  10850. endIndex++;
  10851. } // Start walking from end of segment to get last audio packet
  10852. endIndex = bytes.byteLength;
  10853. startIndex = endIndex - MP2T_PACKET_LENGTH;
  10854. endLoop = false;
  10855. while (startIndex >= 0) {
  10856. // Look for a pair of start and end sync bytes in the data..
  10857. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  10858. // We found a packet
  10859. packet = bytes.subarray(startIndex, endIndex);
  10860. type = probe.ts.parseType(packet, pmt.pid);
  10861. switch (type) {
  10862. case 'pes':
  10863. pesType = probe.ts.parsePesType(packet, pmt.table);
  10864. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  10865. if (pesType === 'audio' && pusi) {
  10866. parsed = probe.ts.parsePesTime(packet);
  10867. if (parsed) {
  10868. parsed.type = 'audio';
  10869. result.audio.push(parsed);
  10870. endLoop = true;
  10871. }
  10872. }
  10873. break;
  10874. }
  10875. if (endLoop) {
  10876. break;
  10877. }
  10878. startIndex -= MP2T_PACKET_LENGTH;
  10879. endIndex -= MP2T_PACKET_LENGTH;
  10880. continue;
  10881. } // If we get here, we have somehow become de-synchronized and we need to step
  10882. // forward one byte at a time until we find a pair of sync bytes that denote
  10883. // a packet
  10884. startIndex--;
  10885. endIndex--;
  10886. }
  10887. };
  10888. /**
  10889. * walks through the segment data from the start and end to get timing information
  10890. * for the first and last video pes packets as well as timing information for the first
  10891. * key frame.
  10892. */
  10893. var parseVideoPes_ = function (bytes, pmt, result) {
  10894. var startIndex = 0,
  10895. endIndex = MP2T_PACKET_LENGTH,
  10896. packet,
  10897. type,
  10898. pesType,
  10899. pusi,
  10900. parsed,
  10901. frame,
  10902. i,
  10903. pes;
  10904. var endLoop = false;
  10905. var currentFrame = {
  10906. data: [],
  10907. size: 0
  10908. }; // Start walking from start of segment to get first video packet
  10909. while (endIndex < bytes.byteLength) {
  10910. // Look for a pair of start and end sync bytes in the data..
  10911. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  10912. // We found a packet
  10913. packet = bytes.subarray(startIndex, endIndex);
  10914. type = probe.ts.parseType(packet, pmt.pid);
  10915. switch (type) {
  10916. case 'pes':
  10917. pesType = probe.ts.parsePesType(packet, pmt.table);
  10918. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  10919. if (pesType === 'video') {
  10920. if (pusi && !endLoop) {
  10921. parsed = probe.ts.parsePesTime(packet);
  10922. if (parsed) {
  10923. parsed.type = 'video';
  10924. result.video.push(parsed);
  10925. endLoop = true;
  10926. }
  10927. }
  10928. if (!result.firstKeyFrame) {
  10929. if (pusi) {
  10930. if (currentFrame.size !== 0) {
  10931. frame = new Uint8Array(currentFrame.size);
  10932. i = 0;
  10933. while (currentFrame.data.length) {
  10934. pes = currentFrame.data.shift();
  10935. frame.set(pes, i);
  10936. i += pes.byteLength;
  10937. }
  10938. if (probe.ts.videoPacketContainsKeyFrame(frame)) {
  10939. var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting
  10940. // the keyframe seems to work fine with HLS playback
  10941. // and definitely preferable to a crash with TypeError...
  10942. if (firstKeyFrame) {
  10943. result.firstKeyFrame = firstKeyFrame;
  10944. result.firstKeyFrame.type = 'video';
  10945. } else {
  10946. // eslint-disable-next-line
  10947. 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.');
  10948. }
  10949. }
  10950. currentFrame.size = 0;
  10951. }
  10952. }
  10953. currentFrame.data.push(packet);
  10954. currentFrame.size += packet.byteLength;
  10955. }
  10956. }
  10957. break;
  10958. }
  10959. if (endLoop && result.firstKeyFrame) {
  10960. break;
  10961. }
  10962. startIndex += MP2T_PACKET_LENGTH;
  10963. endIndex += MP2T_PACKET_LENGTH;
  10964. continue;
  10965. } // If we get here, we have somehow become de-synchronized and we need to step
  10966. // forward one byte at a time until we find a pair of sync bytes that denote
  10967. // a packet
  10968. startIndex++;
  10969. endIndex++;
  10970. } // Start walking from end of segment to get last video packet
  10971. endIndex = bytes.byteLength;
  10972. startIndex = endIndex - MP2T_PACKET_LENGTH;
  10973. endLoop = false;
  10974. while (startIndex >= 0) {
  10975. // Look for a pair of start and end sync bytes in the data..
  10976. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  10977. // We found a packet
  10978. packet = bytes.subarray(startIndex, endIndex);
  10979. type = probe.ts.parseType(packet, pmt.pid);
  10980. switch (type) {
  10981. case 'pes':
  10982. pesType = probe.ts.parsePesType(packet, pmt.table);
  10983. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  10984. if (pesType === 'video' && pusi) {
  10985. parsed = probe.ts.parsePesTime(packet);
  10986. if (parsed) {
  10987. parsed.type = 'video';
  10988. result.video.push(parsed);
  10989. endLoop = true;
  10990. }
  10991. }
  10992. break;
  10993. }
  10994. if (endLoop) {
  10995. break;
  10996. }
  10997. startIndex -= MP2T_PACKET_LENGTH;
  10998. endIndex -= MP2T_PACKET_LENGTH;
  10999. continue;
  11000. } // If we get here, we have somehow become de-synchronized and we need to step
  11001. // forward one byte at a time until we find a pair of sync bytes that denote
  11002. // a packet
  11003. startIndex--;
  11004. endIndex--;
  11005. }
  11006. };
  11007. /**
  11008. * Adjusts the timestamp information for the segment to account for
  11009. * rollover and convert to seconds based on pes packet timescale (90khz clock)
  11010. */
  11011. var adjustTimestamp_ = function (segmentInfo, baseTimestamp) {
  11012. if (segmentInfo.audio && segmentInfo.audio.length) {
  11013. var audioBaseTimestamp = baseTimestamp;
  11014. if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {
  11015. audioBaseTimestamp = segmentInfo.audio[0].dts;
  11016. }
  11017. segmentInfo.audio.forEach(function (info) {
  11018. info.dts = handleRollover(info.dts, audioBaseTimestamp);
  11019. info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds
  11020. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  11021. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  11022. });
  11023. }
  11024. if (segmentInfo.video && segmentInfo.video.length) {
  11025. var videoBaseTimestamp = baseTimestamp;
  11026. if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {
  11027. videoBaseTimestamp = segmentInfo.video[0].dts;
  11028. }
  11029. segmentInfo.video.forEach(function (info) {
  11030. info.dts = handleRollover(info.dts, videoBaseTimestamp);
  11031. info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds
  11032. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  11033. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  11034. });
  11035. if (segmentInfo.firstKeyFrame) {
  11036. var frame = segmentInfo.firstKeyFrame;
  11037. frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
  11038. frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds
  11039. frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
  11040. frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;
  11041. }
  11042. }
  11043. };
  11044. /**
  11045. * inspects the aac data stream for start and end time information
  11046. */
  11047. var inspectAac_ = function (bytes) {
  11048. var endLoop = false,
  11049. audioCount = 0,
  11050. sampleRate = null,
  11051. timestamp = null,
  11052. frameSize = 0,
  11053. byteIndex = 0,
  11054. packet;
  11055. while (bytes.length - byteIndex >= 3) {
  11056. var type = probe.aac.parseType(bytes, byteIndex);
  11057. switch (type) {
  11058. case 'timed-metadata':
  11059. // Exit early because we don't have enough to parse
  11060. // the ID3 tag header
  11061. if (bytes.length - byteIndex < 10) {
  11062. endLoop = true;
  11063. break;
  11064. }
  11065. frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  11066. // to emit a full packet
  11067. if (frameSize > bytes.length) {
  11068. endLoop = true;
  11069. break;
  11070. }
  11071. if (timestamp === null) {
  11072. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  11073. timestamp = probe.aac.parseAacTimestamp(packet);
  11074. }
  11075. byteIndex += frameSize;
  11076. break;
  11077. case 'audio':
  11078. // Exit early because we don't have enough to parse
  11079. // the ADTS frame header
  11080. if (bytes.length - byteIndex < 7) {
  11081. endLoop = true;
  11082. break;
  11083. }
  11084. frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  11085. // to emit a full packet
  11086. if (frameSize > bytes.length) {
  11087. endLoop = true;
  11088. break;
  11089. }
  11090. if (sampleRate === null) {
  11091. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  11092. sampleRate = probe.aac.parseSampleRate(packet);
  11093. }
  11094. audioCount++;
  11095. byteIndex += frameSize;
  11096. break;
  11097. default:
  11098. byteIndex++;
  11099. break;
  11100. }
  11101. if (endLoop) {
  11102. return null;
  11103. }
  11104. }
  11105. if (sampleRate === null || timestamp === null) {
  11106. return null;
  11107. }
  11108. var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
  11109. var result = {
  11110. audio: [{
  11111. type: 'audio',
  11112. dts: timestamp,
  11113. pts: timestamp
  11114. }, {
  11115. type: 'audio',
  11116. dts: timestamp + audioCount * 1024 * audioTimescale,
  11117. pts: timestamp + audioCount * 1024 * audioTimescale
  11118. }]
  11119. };
  11120. return result;
  11121. };
  11122. /**
  11123. * inspects the transport stream segment data for start and end time information
  11124. * of the audio and video tracks (when present) as well as the first key frame's
  11125. * start time.
  11126. */
  11127. var inspectTs_ = function (bytes) {
  11128. var pmt = {
  11129. pid: null,
  11130. table: null
  11131. };
  11132. var result = {};
  11133. parsePsi_(bytes, pmt);
  11134. for (var pid in pmt.table) {
  11135. if (pmt.table.hasOwnProperty(pid)) {
  11136. var type = pmt.table[pid];
  11137. switch (type) {
  11138. case StreamTypes.H264_STREAM_TYPE:
  11139. result.video = [];
  11140. parseVideoPes_(bytes, pmt, result);
  11141. if (result.video.length === 0) {
  11142. delete result.video;
  11143. }
  11144. break;
  11145. case StreamTypes.ADTS_STREAM_TYPE:
  11146. result.audio = [];
  11147. parseAudioPes_(bytes, pmt, result);
  11148. if (result.audio.length === 0) {
  11149. delete result.audio;
  11150. }
  11151. break;
  11152. }
  11153. }
  11154. }
  11155. return result;
  11156. };
  11157. /**
  11158. * Inspects segment byte data and returns an object with start and end timing information
  11159. *
  11160. * @param {Uint8Array} bytes The segment byte data
  11161. * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
  11162. * timestamps for rollover. This value must be in 90khz clock.
  11163. * @return {Object} Object containing start and end frame timing info of segment.
  11164. */
  11165. var inspect = function (bytes, baseTimestamp) {
  11166. var isAacData = probe.aac.isLikelyAacData(bytes);
  11167. var result;
  11168. if (isAacData) {
  11169. result = inspectAac_(bytes);
  11170. } else {
  11171. result = inspectTs_(bytes);
  11172. }
  11173. if (!result || !result.audio && !result.video) {
  11174. return null;
  11175. }
  11176. adjustTimestamp_(result, baseTimestamp);
  11177. return result;
  11178. };
  11179. var tsInspector = {
  11180. inspect: inspect,
  11181. parseAudioPes_: parseAudioPes_
  11182. };
  11183. /* global self */
  11184. /**
  11185. * Re-emits transmuxer events by converting them into messages to the
  11186. * world outside the worker.
  11187. *
  11188. * @param {Object} transmuxer the transmuxer to wire events on
  11189. * @private
  11190. */
  11191. const wireTransmuxerEvents = function (self, transmuxer) {
  11192. transmuxer.on('data', function (segment) {
  11193. // transfer ownership of the underlying ArrayBuffer
  11194. // instead of doing a copy to save memory
  11195. // ArrayBuffers are transferable but generic TypedArrays are not
  11196. // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
  11197. const initArray = segment.initSegment;
  11198. segment.initSegment = {
  11199. data: initArray.buffer,
  11200. byteOffset: initArray.byteOffset,
  11201. byteLength: initArray.byteLength
  11202. };
  11203. const typedArray = segment.data;
  11204. segment.data = typedArray.buffer;
  11205. self.postMessage({
  11206. action: 'data',
  11207. segment,
  11208. byteOffset: typedArray.byteOffset,
  11209. byteLength: typedArray.byteLength
  11210. }, [segment.data]);
  11211. });
  11212. transmuxer.on('done', function (data) {
  11213. self.postMessage({
  11214. action: 'done'
  11215. });
  11216. });
  11217. transmuxer.on('gopInfo', function (gopInfo) {
  11218. self.postMessage({
  11219. action: 'gopInfo',
  11220. gopInfo
  11221. });
  11222. });
  11223. transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
  11224. const videoSegmentTimingInfo = {
  11225. start: {
  11226. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  11227. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  11228. },
  11229. end: {
  11230. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  11231. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  11232. },
  11233. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  11234. };
  11235. if (timingInfo.prependedContentDuration) {
  11236. videoSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  11237. }
  11238. self.postMessage({
  11239. action: 'videoSegmentTimingInfo',
  11240. videoSegmentTimingInfo
  11241. });
  11242. });
  11243. transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
  11244. // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
  11245. const audioSegmentTimingInfo = {
  11246. start: {
  11247. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  11248. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  11249. },
  11250. end: {
  11251. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  11252. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  11253. },
  11254. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  11255. };
  11256. if (timingInfo.prependedContentDuration) {
  11257. audioSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  11258. }
  11259. self.postMessage({
  11260. action: 'audioSegmentTimingInfo',
  11261. audioSegmentTimingInfo
  11262. });
  11263. });
  11264. transmuxer.on('id3Frame', function (id3Frame) {
  11265. self.postMessage({
  11266. action: 'id3Frame',
  11267. id3Frame
  11268. });
  11269. });
  11270. transmuxer.on('caption', function (caption) {
  11271. self.postMessage({
  11272. action: 'caption',
  11273. caption
  11274. });
  11275. });
  11276. transmuxer.on('trackinfo', function (trackInfo) {
  11277. self.postMessage({
  11278. action: 'trackinfo',
  11279. trackInfo
  11280. });
  11281. });
  11282. transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
  11283. // convert to video TS since we prioritize video time over audio
  11284. self.postMessage({
  11285. action: 'audioTimingInfo',
  11286. audioTimingInfo: {
  11287. start: clock$2.videoTsToSeconds(audioTimingInfo.start),
  11288. end: clock$2.videoTsToSeconds(audioTimingInfo.end)
  11289. }
  11290. });
  11291. });
  11292. transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
  11293. self.postMessage({
  11294. action: 'videoTimingInfo',
  11295. videoTimingInfo: {
  11296. start: clock$2.videoTsToSeconds(videoTimingInfo.start),
  11297. end: clock$2.videoTsToSeconds(videoTimingInfo.end)
  11298. }
  11299. });
  11300. });
  11301. transmuxer.on('log', function (log) {
  11302. self.postMessage({
  11303. action: 'log',
  11304. log
  11305. });
  11306. });
  11307. };
  11308. /**
  11309. * All incoming messages route through this hash. If no function exists
  11310. * to handle an incoming message, then we ignore the message.
  11311. *
  11312. * @class MessageHandlers
  11313. * @param {Object} options the options to initialize with
  11314. */
  11315. class MessageHandlers {
  11316. constructor(self, options) {
  11317. this.options = options || {};
  11318. this.self = self;
  11319. this.init();
  11320. }
  11321. /**
  11322. * initialize our web worker and wire all the events.
  11323. */
  11324. init() {
  11325. if (this.transmuxer) {
  11326. this.transmuxer.dispose();
  11327. }
  11328. this.transmuxer = new transmuxer.Transmuxer(this.options);
  11329. wireTransmuxerEvents(this.self, this.transmuxer);
  11330. }
  11331. pushMp4Captions(data) {
  11332. if (!this.captionParser) {
  11333. this.captionParser = new captionParser();
  11334. this.captionParser.init();
  11335. }
  11336. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  11337. const parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
  11338. this.self.postMessage({
  11339. action: 'mp4Captions',
  11340. captions: parsed && parsed.captions || [],
  11341. logs: parsed && parsed.logs || [],
  11342. data: segment.buffer
  11343. }, [segment.buffer]);
  11344. }
  11345. probeMp4StartTime({
  11346. timescales,
  11347. data
  11348. }) {
  11349. const startTime = probe$2.startTime(timescales, data);
  11350. this.self.postMessage({
  11351. action: 'probeMp4StartTime',
  11352. startTime,
  11353. data
  11354. }, [data.buffer]);
  11355. }
  11356. probeMp4Tracks({
  11357. data
  11358. }) {
  11359. const tracks = probe$2.tracks(data);
  11360. this.self.postMessage({
  11361. action: 'probeMp4Tracks',
  11362. tracks,
  11363. data
  11364. }, [data.buffer]);
  11365. }
  11366. /**
  11367. * Probes an mp4 segment for EMSG boxes containing ID3 data.
  11368. * https://aomediacodec.github.io/id3-emsg/
  11369. *
  11370. * @param {Uint8Array} data segment data
  11371. * @param {number} offset segment start time
  11372. * @return {Object[]} an array of ID3 frames
  11373. */
  11374. probeEmsgID3({
  11375. data,
  11376. offset
  11377. }) {
  11378. const id3Frames = probe$2.getEmsgID3(data, offset);
  11379. this.self.postMessage({
  11380. action: 'probeEmsgID3',
  11381. id3Frames,
  11382. emsgData: data
  11383. }, [data.buffer]);
  11384. }
  11385. /**
  11386. * Probe an mpeg2-ts segment to determine the start time of the segment in it's
  11387. * internal "media time," as well as whether it contains video and/or audio.
  11388. *
  11389. * @private
  11390. * @param {Uint8Array} bytes - segment bytes
  11391. * @param {number} baseStartTime
  11392. * Relative reference timestamp used when adjusting frame timestamps for rollover.
  11393. * This value should be in seconds, as it's converted to a 90khz clock within the
  11394. * function body.
  11395. * @return {Object} The start time of the current segment in "media time" as well as
  11396. * whether it contains video and/or audio
  11397. */
  11398. probeTs({
  11399. data,
  11400. baseStartTime
  11401. }) {
  11402. const tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock$2.ONE_SECOND_IN_TS : void 0;
  11403. const timeInfo = tsInspector.inspect(data, tsStartTime);
  11404. let result = null;
  11405. if (timeInfo) {
  11406. result = {
  11407. // each type's time info comes back as an array of 2 times, start and end
  11408. hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
  11409. hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
  11410. };
  11411. if (result.hasVideo) {
  11412. result.videoStart = timeInfo.video[0].ptsTime;
  11413. }
  11414. if (result.hasAudio) {
  11415. result.audioStart = timeInfo.audio[0].ptsTime;
  11416. }
  11417. }
  11418. this.self.postMessage({
  11419. action: 'probeTs',
  11420. result,
  11421. data
  11422. }, [data.buffer]);
  11423. }
  11424. clearAllMp4Captions() {
  11425. if (this.captionParser) {
  11426. this.captionParser.clearAllCaptions();
  11427. }
  11428. }
  11429. clearParsedMp4Captions() {
  11430. if (this.captionParser) {
  11431. this.captionParser.clearParsedCaptions();
  11432. }
  11433. }
  11434. /**
  11435. * Adds data (a ts segment) to the start of the transmuxer pipeline for
  11436. * processing.
  11437. *
  11438. * @param {ArrayBuffer} data data to push into the muxer
  11439. */
  11440. push(data) {
  11441. // Cast array buffer to correct type for transmuxer
  11442. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  11443. this.transmuxer.push(segment);
  11444. }
  11445. /**
  11446. * Recreate the transmuxer so that the next segment added via `push`
  11447. * start with a fresh transmuxer.
  11448. */
  11449. reset() {
  11450. this.transmuxer.reset();
  11451. }
  11452. /**
  11453. * Set the value that will be used as the `baseMediaDecodeTime` time for the
  11454. * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
  11455. * set relative to the first based on the PTS values.
  11456. *
  11457. * @param {Object} data used to set the timestamp offset in the muxer
  11458. */
  11459. setTimestampOffset(data) {
  11460. const timestampOffset = data.timestampOffset || 0;
  11461. this.transmuxer.setBaseMediaDecodeTime(Math.round(clock$2.secondsToVideoTs(timestampOffset)));
  11462. }
  11463. setAudioAppendStart(data) {
  11464. this.transmuxer.setAudioAppendStart(Math.ceil(clock$2.secondsToVideoTs(data.appendStart)));
  11465. }
  11466. setRemux(data) {
  11467. this.transmuxer.setRemux(data.remux);
  11468. }
  11469. /**
  11470. * Forces the pipeline to finish processing the last segment and emit it's
  11471. * results.
  11472. *
  11473. * @param {Object} data event data, not really used
  11474. */
  11475. flush(data) {
  11476. this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
  11477. self.postMessage({
  11478. action: 'done',
  11479. type: 'transmuxed'
  11480. });
  11481. }
  11482. endTimeline() {
  11483. this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
  11484. // timelines
  11485. self.postMessage({
  11486. action: 'endedtimeline',
  11487. type: 'transmuxed'
  11488. });
  11489. }
  11490. alignGopsWith(data) {
  11491. this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
  11492. }
  11493. }
  11494. /**
  11495. * Our web worker interface so that things can talk to mux.js
  11496. * that will be running in a web worker. the scope is passed to this by
  11497. * webworkify.
  11498. *
  11499. * @param {Object} self the scope for the web worker
  11500. */
  11501. self.onmessage = function (event) {
  11502. if (event.data.action === 'init' && event.data.options) {
  11503. this.messageHandlers = new MessageHandlers(self, event.data.options);
  11504. return;
  11505. }
  11506. if (!this.messageHandlers) {
  11507. this.messageHandlers = new MessageHandlers(self);
  11508. }
  11509. if (event.data && event.data.action && event.data.action !== 'init') {
  11510. if (this.messageHandlers[event.data.action]) {
  11511. this.messageHandlers[event.data.action](event.data);
  11512. }
  11513. }
  11514. };
  11515. }));
  11516. var TransmuxWorker = factory(workerCode$1);
  11517. /* rollup-plugin-worker-factory end for worker!/home/runner/work/http-streaming/http-streaming/src/transmuxer-worker.js */
  11518. const handleData_ = (event, transmuxedData, callback) => {
  11519. const {
  11520. type,
  11521. initSegment,
  11522. captions,
  11523. captionStreams,
  11524. metadata,
  11525. videoFrameDtsTime,
  11526. videoFramePtsTime
  11527. } = event.data.segment;
  11528. transmuxedData.buffer.push({
  11529. captions,
  11530. captionStreams,
  11531. metadata
  11532. });
  11533. const boxes = event.data.segment.boxes || {
  11534. data: event.data.segment.data
  11535. };
  11536. const result = {
  11537. type,
  11538. // cast ArrayBuffer to TypedArray
  11539. data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
  11540. initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
  11541. };
  11542. if (typeof videoFrameDtsTime !== 'undefined') {
  11543. result.videoFrameDtsTime = videoFrameDtsTime;
  11544. }
  11545. if (typeof videoFramePtsTime !== 'undefined') {
  11546. result.videoFramePtsTime = videoFramePtsTime;
  11547. }
  11548. callback(result);
  11549. };
  11550. const handleDone_ = ({
  11551. transmuxedData,
  11552. callback
  11553. }) => {
  11554. // Previously we only returned data on data events,
  11555. // not on done events. Clear out the buffer to keep that consistent.
  11556. transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
  11557. // have received
  11558. callback(transmuxedData);
  11559. };
  11560. const handleGopInfo_ = (event, transmuxedData) => {
  11561. transmuxedData.gopInfo = event.data.gopInfo;
  11562. };
  11563. const processTransmux = options => {
  11564. const {
  11565. transmuxer,
  11566. bytes,
  11567. audioAppendStart,
  11568. gopsToAlignWith,
  11569. remux,
  11570. onData,
  11571. onTrackInfo,
  11572. onAudioTimingInfo,
  11573. onVideoTimingInfo,
  11574. onVideoSegmentTimingInfo,
  11575. onAudioSegmentTimingInfo,
  11576. onId3,
  11577. onCaptions,
  11578. onDone,
  11579. onEndedTimeline,
  11580. onTransmuxerLog,
  11581. isEndOfTimeline
  11582. } = options;
  11583. const transmuxedData = {
  11584. buffer: []
  11585. };
  11586. let waitForEndedTimelineEvent = isEndOfTimeline;
  11587. const handleMessage = event => {
  11588. if (transmuxer.currentTransmux !== options) {
  11589. // disposed
  11590. return;
  11591. }
  11592. if (event.data.action === 'data') {
  11593. handleData_(event, transmuxedData, onData);
  11594. }
  11595. if (event.data.action === 'trackinfo') {
  11596. onTrackInfo(event.data.trackInfo);
  11597. }
  11598. if (event.data.action === 'gopInfo') {
  11599. handleGopInfo_(event, transmuxedData);
  11600. }
  11601. if (event.data.action === 'audioTimingInfo') {
  11602. onAudioTimingInfo(event.data.audioTimingInfo);
  11603. }
  11604. if (event.data.action === 'videoTimingInfo') {
  11605. onVideoTimingInfo(event.data.videoTimingInfo);
  11606. }
  11607. if (event.data.action === 'videoSegmentTimingInfo') {
  11608. onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
  11609. }
  11610. if (event.data.action === 'audioSegmentTimingInfo') {
  11611. onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
  11612. }
  11613. if (event.data.action === 'id3Frame') {
  11614. onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
  11615. }
  11616. if (event.data.action === 'caption') {
  11617. onCaptions(event.data.caption);
  11618. }
  11619. if (event.data.action === 'endedtimeline') {
  11620. waitForEndedTimelineEvent = false;
  11621. onEndedTimeline();
  11622. }
  11623. if (event.data.action === 'log') {
  11624. onTransmuxerLog(event.data.log);
  11625. } // wait for the transmuxed event since we may have audio and video
  11626. if (event.data.type !== 'transmuxed') {
  11627. return;
  11628. } // If the "endedtimeline" event has not yet fired, and this segment represents the end
  11629. // of a timeline, that means there may still be data events before the segment
  11630. // processing can be considerred complete. In that case, the final event should be
  11631. // an "endedtimeline" event with the type "transmuxed."
  11632. if (waitForEndedTimelineEvent) {
  11633. return;
  11634. }
  11635. transmuxer.onmessage = null;
  11636. handleDone_({
  11637. transmuxedData,
  11638. callback: onDone
  11639. });
  11640. /* eslint-disable no-use-before-define */
  11641. dequeue(transmuxer);
  11642. /* eslint-enable */
  11643. };
  11644. transmuxer.onmessage = handleMessage;
  11645. if (audioAppendStart) {
  11646. transmuxer.postMessage({
  11647. action: 'setAudioAppendStart',
  11648. appendStart: audioAppendStart
  11649. });
  11650. } // allow empty arrays to be passed to clear out GOPs
  11651. if (Array.isArray(gopsToAlignWith)) {
  11652. transmuxer.postMessage({
  11653. action: 'alignGopsWith',
  11654. gopsToAlignWith
  11655. });
  11656. }
  11657. if (typeof remux !== 'undefined') {
  11658. transmuxer.postMessage({
  11659. action: 'setRemux',
  11660. remux
  11661. });
  11662. }
  11663. if (bytes.byteLength) {
  11664. const buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
  11665. const byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
  11666. transmuxer.postMessage({
  11667. action: 'push',
  11668. // Send the typed-array of data as an ArrayBuffer so that
  11669. // it can be sent as a "Transferable" and avoid the costly
  11670. // memory copy
  11671. data: buffer,
  11672. // To recreate the original typed-array, we need information
  11673. // about what portion of the ArrayBuffer it was a view into
  11674. byteOffset,
  11675. byteLength: bytes.byteLength
  11676. }, [buffer]);
  11677. }
  11678. if (isEndOfTimeline) {
  11679. transmuxer.postMessage({
  11680. action: 'endTimeline'
  11681. });
  11682. } // even if we didn't push any bytes, we have to make sure we flush in case we reached
  11683. // the end of the segment
  11684. transmuxer.postMessage({
  11685. action: 'flush'
  11686. });
  11687. };
  11688. const dequeue = transmuxer => {
  11689. transmuxer.currentTransmux = null;
  11690. if (transmuxer.transmuxQueue.length) {
  11691. transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
  11692. if (typeof transmuxer.currentTransmux === 'function') {
  11693. transmuxer.currentTransmux();
  11694. } else {
  11695. processTransmux(transmuxer.currentTransmux);
  11696. }
  11697. }
  11698. };
  11699. const processAction = (transmuxer, action) => {
  11700. transmuxer.postMessage({
  11701. action
  11702. });
  11703. dequeue(transmuxer);
  11704. };
  11705. const enqueueAction = (action, transmuxer) => {
  11706. if (!transmuxer.currentTransmux) {
  11707. transmuxer.currentTransmux = action;
  11708. processAction(transmuxer, action);
  11709. return;
  11710. }
  11711. transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
  11712. };
  11713. const reset = transmuxer => {
  11714. enqueueAction('reset', transmuxer);
  11715. };
  11716. const endTimeline = transmuxer => {
  11717. enqueueAction('endTimeline', transmuxer);
  11718. };
  11719. const transmux = options => {
  11720. if (!options.transmuxer.currentTransmux) {
  11721. options.transmuxer.currentTransmux = options;
  11722. processTransmux(options);
  11723. return;
  11724. }
  11725. options.transmuxer.transmuxQueue.push(options);
  11726. };
  11727. const createTransmuxer = options => {
  11728. const transmuxer = new TransmuxWorker();
  11729. transmuxer.currentTransmux = null;
  11730. transmuxer.transmuxQueue = [];
  11731. const term = transmuxer.terminate;
  11732. transmuxer.terminate = () => {
  11733. transmuxer.currentTransmux = null;
  11734. transmuxer.transmuxQueue.length = 0;
  11735. return term.call(transmuxer);
  11736. };
  11737. transmuxer.postMessage({
  11738. action: 'init',
  11739. options
  11740. });
  11741. return transmuxer;
  11742. };
  11743. var segmentTransmuxer = {
  11744. reset,
  11745. endTimeline,
  11746. transmux,
  11747. createTransmuxer
  11748. };
  11749. const workerCallback = function (options) {
  11750. const transmuxer = options.transmuxer;
  11751. const endAction = options.endAction || options.action;
  11752. const callback = options.callback;
  11753. const message = _extends({}, options, {
  11754. endAction: null,
  11755. transmuxer: null,
  11756. callback: null
  11757. });
  11758. const listenForEndEvent = event => {
  11759. if (event.data.action !== endAction) {
  11760. return;
  11761. }
  11762. transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.
  11763. if (event.data.data) {
  11764. event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
  11765. if (options.data) {
  11766. options.data = event.data.data;
  11767. }
  11768. }
  11769. callback(event.data);
  11770. };
  11771. transmuxer.addEventListener('message', listenForEndEvent);
  11772. if (options.data) {
  11773. const isArrayBuffer = options.data instanceof ArrayBuffer;
  11774. message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
  11775. message.byteLength = options.data.byteLength;
  11776. const transfers = [isArrayBuffer ? options.data : options.data.buffer];
  11777. transmuxer.postMessage(message, transfers);
  11778. } else {
  11779. transmuxer.postMessage(message);
  11780. }
  11781. };
  11782. const REQUEST_ERRORS = {
  11783. FAILURE: 2,
  11784. TIMEOUT: -101,
  11785. ABORTED: -102
  11786. };
  11787. /**
  11788. * Abort all requests
  11789. *
  11790. * @param {Object} activeXhrs - an object that tracks all XHR requests
  11791. */
  11792. const abortAll = activeXhrs => {
  11793. activeXhrs.forEach(xhr => {
  11794. xhr.abort();
  11795. });
  11796. };
  11797. /**
  11798. * Gather important bandwidth stats once a request has completed
  11799. *
  11800. * @param {Object} request - the XHR request from which to gather stats
  11801. */
  11802. const getRequestStats = request => {
  11803. return {
  11804. bandwidth: request.bandwidth,
  11805. bytesReceived: request.bytesReceived || 0,
  11806. roundTripTime: request.roundTripTime || 0
  11807. };
  11808. };
  11809. /**
  11810. * If possible gather bandwidth stats as a request is in
  11811. * progress
  11812. *
  11813. * @param {Event} progressEvent - an event object from an XHR's progress event
  11814. */
  11815. const getProgressStats = progressEvent => {
  11816. const request = progressEvent.target;
  11817. const roundTripTime = Date.now() - request.requestTime;
  11818. const stats = {
  11819. bandwidth: Infinity,
  11820. bytesReceived: 0,
  11821. roundTripTime: roundTripTime || 0
  11822. };
  11823. stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok
  11824. // because we should only use bandwidth stats on progress to determine when
  11825. // abort a request early due to insufficient bandwidth
  11826. stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);
  11827. return stats;
  11828. };
  11829. /**
  11830. * Handle all error conditions in one place and return an object
  11831. * with all the information
  11832. *
  11833. * @param {Error|null} error - if non-null signals an error occured with the XHR
  11834. * @param {Object} request - the XHR request that possibly generated the error
  11835. */
  11836. const handleErrors = (error, request) => {
  11837. if (request.timedout) {
  11838. return {
  11839. status: request.status,
  11840. message: 'HLS request timed-out at URL: ' + request.uri,
  11841. code: REQUEST_ERRORS.TIMEOUT,
  11842. xhr: request
  11843. };
  11844. }
  11845. if (request.aborted) {
  11846. return {
  11847. status: request.status,
  11848. message: 'HLS request aborted at URL: ' + request.uri,
  11849. code: REQUEST_ERRORS.ABORTED,
  11850. xhr: request
  11851. };
  11852. }
  11853. if (error) {
  11854. return {
  11855. status: request.status,
  11856. message: 'HLS request errored at URL: ' + request.uri,
  11857. code: REQUEST_ERRORS.FAILURE,
  11858. xhr: request
  11859. };
  11860. }
  11861. if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
  11862. return {
  11863. status: request.status,
  11864. message: 'Empty HLS response at URL: ' + request.uri,
  11865. code: REQUEST_ERRORS.FAILURE,
  11866. xhr: request
  11867. };
  11868. }
  11869. return null;
  11870. };
  11871. /**
  11872. * Handle responses for key data and convert the key data to the correct format
  11873. * for the decryption step later
  11874. *
  11875. * @param {Object} segment - a simplified copy of the segmentInfo object
  11876. * from SegmentLoader
  11877. * @param {Array} objects - objects to add the key bytes to.
  11878. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  11879. * this request
  11880. */
  11881. const handleKeyResponse = (segment, objects, finishProcessingFn) => (error, request) => {
  11882. const response = request.response;
  11883. const errorObj = handleErrors(error, request);
  11884. if (errorObj) {
  11885. return finishProcessingFn(errorObj, segment);
  11886. }
  11887. if (response.byteLength !== 16) {
  11888. return finishProcessingFn({
  11889. status: request.status,
  11890. message: 'Invalid HLS key at URL: ' + request.uri,
  11891. code: REQUEST_ERRORS.FAILURE,
  11892. xhr: request
  11893. }, segment);
  11894. }
  11895. const view = new DataView(response);
  11896. const bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  11897. for (let i = 0; i < objects.length; i++) {
  11898. objects[i].bytes = bytes;
  11899. }
  11900. return finishProcessingFn(null, segment);
  11901. };
  11902. const parseInitSegment = (segment, callback) => {
  11903. const type = detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we
  11904. // only know how to parse mp4 init segments at the moment
  11905. if (type !== 'mp4') {
  11906. const uri = segment.map.resolvedUri || segment.map.uri;
  11907. return callback({
  11908. internal: true,
  11909. message: `Found unsupported ${type || 'unknown'} container for initialization segment at URL: ${uri}`,
  11910. code: REQUEST_ERRORS.FAILURE
  11911. });
  11912. }
  11913. workerCallback({
  11914. action: 'probeMp4Tracks',
  11915. data: segment.map.bytes,
  11916. transmuxer: segment.transmuxer,
  11917. callback: ({
  11918. tracks,
  11919. data
  11920. }) => {
  11921. // transfer bytes back to us
  11922. segment.map.bytes = data;
  11923. tracks.forEach(function (track) {
  11924. segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
  11925. if (segment.map.tracks[track.type]) {
  11926. return;
  11927. }
  11928. segment.map.tracks[track.type] = track;
  11929. if (typeof track.id === 'number' && track.timescale) {
  11930. segment.map.timescales = segment.map.timescales || {};
  11931. segment.map.timescales[track.id] = track.timescale;
  11932. }
  11933. });
  11934. return callback(null);
  11935. }
  11936. });
  11937. };
  11938. /**
  11939. * Handle init-segment responses
  11940. *
  11941. * @param {Object} segment - a simplified copy of the segmentInfo object
  11942. * from SegmentLoader
  11943. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  11944. * this request
  11945. */
  11946. const handleInitSegmentResponse = ({
  11947. segment,
  11948. finishProcessingFn
  11949. }) => (error, request) => {
  11950. const errorObj = handleErrors(error, request);
  11951. if (errorObj) {
  11952. return finishProcessingFn(errorObj, segment);
  11953. }
  11954. const bytes = new Uint8Array(request.response); // init segment is encypted, we will have to wait
  11955. // until the key request is done to decrypt.
  11956. if (segment.map.key) {
  11957. segment.map.encryptedBytes = bytes;
  11958. return finishProcessingFn(null, segment);
  11959. }
  11960. segment.map.bytes = bytes;
  11961. parseInitSegment(segment, function (parseError) {
  11962. if (parseError) {
  11963. parseError.xhr = request;
  11964. parseError.status = request.status;
  11965. return finishProcessingFn(parseError, segment);
  11966. }
  11967. finishProcessingFn(null, segment);
  11968. });
  11969. };
  11970. /**
  11971. * Response handler for segment-requests being sure to set the correct
  11972. * property depending on whether the segment is encryped or not
  11973. * Also records and keeps track of stats that are used for ABR purposes
  11974. *
  11975. * @param {Object} segment - a simplified copy of the segmentInfo object
  11976. * from SegmentLoader
  11977. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  11978. * this request
  11979. */
  11980. const handleSegmentResponse = ({
  11981. segment,
  11982. finishProcessingFn,
  11983. responseType
  11984. }) => (error, request) => {
  11985. const errorObj = handleErrors(error, request);
  11986. if (errorObj) {
  11987. return finishProcessingFn(errorObj, segment);
  11988. }
  11989. const newBytes = // although responseText "should" exist, this guard serves to prevent an error being
  11990. // thrown for two primary cases:
  11991. // 1. the mime type override stops working, or is not implemented for a specific
  11992. // browser
  11993. // 2. when using mock XHR libraries like sinon that do not allow the override behavior
  11994. responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
  11995. segment.stats = getRequestStats(request);
  11996. if (segment.key) {
  11997. segment.encryptedBytes = new Uint8Array(newBytes);
  11998. } else {
  11999. segment.bytes = new Uint8Array(newBytes);
  12000. }
  12001. return finishProcessingFn(null, segment);
  12002. };
  12003. const transmuxAndNotify = ({
  12004. segment,
  12005. bytes,
  12006. trackInfoFn,
  12007. timingInfoFn,
  12008. videoSegmentTimingInfoFn,
  12009. audioSegmentTimingInfoFn,
  12010. id3Fn,
  12011. captionsFn,
  12012. isEndOfTimeline,
  12013. endedTimelineFn,
  12014. dataFn,
  12015. doneFn,
  12016. onTransmuxerLog
  12017. }) => {
  12018. const fmp4Tracks = segment.map && segment.map.tracks || {};
  12019. const isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.
  12020. // One reason for this is that in the case of full segments, we want to trust start
  12021. // times from the probe, rather than the transmuxer.
  12022. let audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
  12023. const audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
  12024. let videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
  12025. const videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
  12026. const finish = () => transmux({
  12027. bytes,
  12028. transmuxer: segment.transmuxer,
  12029. audioAppendStart: segment.audioAppendStart,
  12030. gopsToAlignWith: segment.gopsToAlignWith,
  12031. remux: isMuxed,
  12032. onData: result => {
  12033. result.type = result.type === 'combined' ? 'video' : result.type;
  12034. dataFn(segment, result);
  12035. },
  12036. onTrackInfo: trackInfo => {
  12037. if (trackInfoFn) {
  12038. if (isMuxed) {
  12039. trackInfo.isMuxed = true;
  12040. }
  12041. trackInfoFn(segment, trackInfo);
  12042. }
  12043. },
  12044. onAudioTimingInfo: audioTimingInfo => {
  12045. // we only want the first start value we encounter
  12046. if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
  12047. audioStartFn(audioTimingInfo.start);
  12048. audioStartFn = null;
  12049. } // we want to continually update the end time
  12050. if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
  12051. audioEndFn(audioTimingInfo.end);
  12052. }
  12053. },
  12054. onVideoTimingInfo: videoTimingInfo => {
  12055. // we only want the first start value we encounter
  12056. if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
  12057. videoStartFn(videoTimingInfo.start);
  12058. videoStartFn = null;
  12059. } // we want to continually update the end time
  12060. if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
  12061. videoEndFn(videoTimingInfo.end);
  12062. }
  12063. },
  12064. onVideoSegmentTimingInfo: videoSegmentTimingInfo => {
  12065. videoSegmentTimingInfoFn(videoSegmentTimingInfo);
  12066. },
  12067. onAudioSegmentTimingInfo: audioSegmentTimingInfo => {
  12068. audioSegmentTimingInfoFn(audioSegmentTimingInfo);
  12069. },
  12070. onId3: (id3Frames, dispatchType) => {
  12071. id3Fn(segment, id3Frames, dispatchType);
  12072. },
  12073. onCaptions: captions => {
  12074. captionsFn(segment, [captions]);
  12075. },
  12076. isEndOfTimeline,
  12077. onEndedTimeline: () => {
  12078. endedTimelineFn();
  12079. },
  12080. onTransmuxerLog,
  12081. onDone: result => {
  12082. if (!doneFn) {
  12083. return;
  12084. }
  12085. result.type = result.type === 'combined' ? 'video' : result.type;
  12086. doneFn(null, segment, result);
  12087. }
  12088. }); // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
  12089. // Meaning cached frame data may corrupt our notion of where this segment
  12090. // really starts. To get around this, probe for the info needed.
  12091. workerCallback({
  12092. action: 'probeTs',
  12093. transmuxer: segment.transmuxer,
  12094. data: bytes,
  12095. baseStartTime: segment.baseStartTime,
  12096. callback: data => {
  12097. segment.bytes = bytes = data.data;
  12098. const probeResult = data.result;
  12099. if (probeResult) {
  12100. trackInfoFn(segment, {
  12101. hasAudio: probeResult.hasAudio,
  12102. hasVideo: probeResult.hasVideo,
  12103. isMuxed
  12104. });
  12105. trackInfoFn = null;
  12106. }
  12107. finish();
  12108. }
  12109. });
  12110. };
  12111. const handleSegmentBytes = ({
  12112. segment,
  12113. bytes,
  12114. trackInfoFn,
  12115. timingInfoFn,
  12116. videoSegmentTimingInfoFn,
  12117. audioSegmentTimingInfoFn,
  12118. id3Fn,
  12119. captionsFn,
  12120. isEndOfTimeline,
  12121. endedTimelineFn,
  12122. dataFn,
  12123. doneFn,
  12124. onTransmuxerLog
  12125. }) => {
  12126. let bytesAsUint8Array = new Uint8Array(bytes); // TODO:
  12127. // We should have a handler that fetches the number of bytes required
  12128. // to check if something is fmp4. This will allow us to save bandwidth
  12129. // because we can only exclude a playlist and abort requests
  12130. // by codec after trackinfo triggers.
  12131. if (isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
  12132. segment.isFmp4 = true;
  12133. const {
  12134. tracks
  12135. } = segment.map;
  12136. const trackInfo = {
  12137. isFmp4: true,
  12138. hasVideo: !!tracks.video,
  12139. hasAudio: !!tracks.audio
  12140. }; // if we have a audio track, with a codec that is not set to
  12141. // encrypted audio
  12142. if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
  12143. trackInfo.audioCodec = tracks.audio.codec;
  12144. } // if we have a video track, with a codec that is not set to
  12145. // encrypted video
  12146. if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
  12147. trackInfo.videoCodec = tracks.video.codec;
  12148. }
  12149. if (tracks.video && tracks.audio) {
  12150. trackInfo.isMuxed = true;
  12151. } // since we don't support appending fmp4 data on progress, we know we have the full
  12152. // segment here
  12153. trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start
  12154. // time. The end time can be roughly calculated by the receiver using the duration.
  12155. //
  12156. // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
  12157. // that is the true start of the segment (where the playback engine should begin
  12158. // decoding).
  12159. const finishLoading = (captions, id3Frames) => {
  12160. // if the track still has audio at this point it is only possible
  12161. // for it to be audio only. See `tracks.video && tracks.audio` if statement
  12162. // above.
  12163. // we make sure to use segment.bytes here as that
  12164. dataFn(segment, {
  12165. data: bytesAsUint8Array,
  12166. type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
  12167. });
  12168. if (id3Frames && id3Frames.length) {
  12169. id3Fn(segment, id3Frames);
  12170. }
  12171. if (captions && captions.length) {
  12172. captionsFn(segment, captions);
  12173. }
  12174. doneFn(null, segment, {});
  12175. };
  12176. workerCallback({
  12177. action: 'probeMp4StartTime',
  12178. timescales: segment.map.timescales,
  12179. data: bytesAsUint8Array,
  12180. transmuxer: segment.transmuxer,
  12181. callback: ({
  12182. data,
  12183. startTime
  12184. }) => {
  12185. // transfer bytes back to us
  12186. bytes = data.buffer;
  12187. segment.bytes = bytesAsUint8Array = data;
  12188. if (trackInfo.hasAudio && !trackInfo.isMuxed) {
  12189. timingInfoFn(segment, 'audio', 'start', startTime);
  12190. }
  12191. if (trackInfo.hasVideo) {
  12192. timingInfoFn(segment, 'video', 'start', startTime);
  12193. }
  12194. workerCallback({
  12195. action: 'probeEmsgID3',
  12196. data: bytesAsUint8Array,
  12197. transmuxer: segment.transmuxer,
  12198. offset: startTime,
  12199. callback: ({
  12200. emsgData,
  12201. id3Frames
  12202. }) => {
  12203. // transfer bytes back to us
  12204. bytes = emsgData.buffer;
  12205. segment.bytes = bytesAsUint8Array = emsgData; // Run through the CaptionParser in case there are captions.
  12206. // Initialize CaptionParser if it hasn't been yet
  12207. if (!tracks.video || !emsgData.byteLength || !segment.transmuxer) {
  12208. finishLoading(undefined, id3Frames);
  12209. return;
  12210. }
  12211. workerCallback({
  12212. action: 'pushMp4Captions',
  12213. endAction: 'mp4Captions',
  12214. transmuxer: segment.transmuxer,
  12215. data: bytesAsUint8Array,
  12216. timescales: segment.map.timescales,
  12217. trackIds: [tracks.video.id],
  12218. callback: message => {
  12219. // transfer bytes back to us
  12220. bytes = message.data.buffer;
  12221. segment.bytes = bytesAsUint8Array = message.data;
  12222. message.logs.forEach(function (log) {
  12223. onTransmuxerLog(merge(log, {
  12224. stream: 'mp4CaptionParser'
  12225. }));
  12226. });
  12227. finishLoading(message.captions, id3Frames);
  12228. }
  12229. });
  12230. }
  12231. });
  12232. }
  12233. });
  12234. return;
  12235. } // VTT or other segments that don't need processing
  12236. if (!segment.transmuxer) {
  12237. doneFn(null, segment, {});
  12238. return;
  12239. }
  12240. if (typeof segment.container === 'undefined') {
  12241. segment.container = detectContainerForBytes(bytesAsUint8Array);
  12242. }
  12243. if (segment.container !== 'ts' && segment.container !== 'aac') {
  12244. trackInfoFn(segment, {
  12245. hasAudio: false,
  12246. hasVideo: false
  12247. });
  12248. doneFn(null, segment, {});
  12249. return;
  12250. } // ts or aac
  12251. transmuxAndNotify({
  12252. segment,
  12253. bytes,
  12254. trackInfoFn,
  12255. timingInfoFn,
  12256. videoSegmentTimingInfoFn,
  12257. audioSegmentTimingInfoFn,
  12258. id3Fn,
  12259. captionsFn,
  12260. isEndOfTimeline,
  12261. endedTimelineFn,
  12262. dataFn,
  12263. doneFn,
  12264. onTransmuxerLog
  12265. });
  12266. };
  12267. const decrypt = function ({
  12268. id,
  12269. key,
  12270. encryptedBytes,
  12271. decryptionWorker
  12272. }, callback) {
  12273. const decryptionHandler = event => {
  12274. if (event.data.source === id) {
  12275. decryptionWorker.removeEventListener('message', decryptionHandler);
  12276. const decrypted = event.data.decrypted;
  12277. callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
  12278. }
  12279. };
  12280. decryptionWorker.addEventListener('message', decryptionHandler);
  12281. let keyBytes;
  12282. if (key.bytes.slice) {
  12283. keyBytes = key.bytes.slice();
  12284. } else {
  12285. keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
  12286. } // incrementally decrypt the bytes
  12287. decryptionWorker.postMessage(createTransferableMessage({
  12288. source: id,
  12289. encrypted: encryptedBytes,
  12290. key: keyBytes,
  12291. iv: key.iv
  12292. }), [encryptedBytes.buffer, keyBytes.buffer]);
  12293. };
  12294. /**
  12295. * Decrypt the segment via the decryption web worker
  12296. *
  12297. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  12298. * routines
  12299. * @param {Object} segment - a simplified copy of the segmentInfo object
  12300. * from SegmentLoader
  12301. * @param {Function} trackInfoFn - a callback that receives track info
  12302. * @param {Function} timingInfoFn - a callback that receives timing info
  12303. * @param {Function} videoSegmentTimingInfoFn
  12304. * a callback that receives video timing info based on media times and
  12305. * any adjustments made by the transmuxer
  12306. * @param {Function} audioSegmentTimingInfoFn
  12307. * a callback that receives audio timing info based on media times and
  12308. * any adjustments made by the transmuxer
  12309. * @param {boolean} isEndOfTimeline
  12310. * true if this segment represents the last segment in a timeline
  12311. * @param {Function} endedTimelineFn
  12312. * a callback made when a timeline is ended, will only be called if
  12313. * isEndOfTimeline is true
  12314. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  12315. * and ready to use
  12316. * @param {Function} doneFn - a callback that is executed after decryption has completed
  12317. */
  12318. const decryptSegment = ({
  12319. decryptionWorker,
  12320. segment,
  12321. trackInfoFn,
  12322. timingInfoFn,
  12323. videoSegmentTimingInfoFn,
  12324. audioSegmentTimingInfoFn,
  12325. id3Fn,
  12326. captionsFn,
  12327. isEndOfTimeline,
  12328. endedTimelineFn,
  12329. dataFn,
  12330. doneFn,
  12331. onTransmuxerLog
  12332. }) => {
  12333. decrypt({
  12334. id: segment.requestId,
  12335. key: segment.key,
  12336. encryptedBytes: segment.encryptedBytes,
  12337. decryptionWorker
  12338. }, decryptedBytes => {
  12339. segment.bytes = decryptedBytes;
  12340. handleSegmentBytes({
  12341. segment,
  12342. bytes: segment.bytes,
  12343. trackInfoFn,
  12344. timingInfoFn,
  12345. videoSegmentTimingInfoFn,
  12346. audioSegmentTimingInfoFn,
  12347. id3Fn,
  12348. captionsFn,
  12349. isEndOfTimeline,
  12350. endedTimelineFn,
  12351. dataFn,
  12352. doneFn,
  12353. onTransmuxerLog
  12354. });
  12355. });
  12356. };
  12357. /**
  12358. * This function waits for all XHRs to finish (with either success or failure)
  12359. * before continueing processing via it's callback. The function gathers errors
  12360. * from each request into a single errors array so that the error status for
  12361. * each request can be examined later.
  12362. *
  12363. * @param {Object} activeXhrs - an object that tracks all XHR requests
  12364. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  12365. * routines
  12366. * @param {Function} trackInfoFn - a callback that receives track info
  12367. * @param {Function} timingInfoFn - a callback that receives timing info
  12368. * @param {Function} videoSegmentTimingInfoFn
  12369. * a callback that receives video timing info based on media times and
  12370. * any adjustments made by the transmuxer
  12371. * @param {Function} audioSegmentTimingInfoFn
  12372. * a callback that receives audio timing info based on media times and
  12373. * any adjustments made by the transmuxer
  12374. * @param {Function} id3Fn - a callback that receives ID3 metadata
  12375. * @param {Function} captionsFn - a callback that receives captions
  12376. * @param {boolean} isEndOfTimeline
  12377. * true if this segment represents the last segment in a timeline
  12378. * @param {Function} endedTimelineFn
  12379. * a callback made when a timeline is ended, will only be called if
  12380. * isEndOfTimeline is true
  12381. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  12382. * and ready to use
  12383. * @param {Function} doneFn - a callback that is executed after all resources have been
  12384. * downloaded and any decryption completed
  12385. */
  12386. const waitForCompletion = ({
  12387. activeXhrs,
  12388. decryptionWorker,
  12389. trackInfoFn,
  12390. timingInfoFn,
  12391. videoSegmentTimingInfoFn,
  12392. audioSegmentTimingInfoFn,
  12393. id3Fn,
  12394. captionsFn,
  12395. isEndOfTimeline,
  12396. endedTimelineFn,
  12397. dataFn,
  12398. doneFn,
  12399. onTransmuxerLog
  12400. }) => {
  12401. let count = 0;
  12402. let didError = false;
  12403. return (error, segment) => {
  12404. if (didError) {
  12405. return;
  12406. }
  12407. if (error) {
  12408. didError = true; // If there are errors, we have to abort any outstanding requests
  12409. abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we
  12410. // handle the aborted events from those requests, there are some cases where we may
  12411. // never get an aborted event. For instance, if the network connection is lost and
  12412. // there were two requests, the first may have triggered an error immediately, while
  12413. // the second request remains unsent. In that case, the aborted algorithm will not
  12414. // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
  12415. //
  12416. // We also can't rely on the ready state of the XHR, since the request that
  12417. // triggered the connection error may also show as a ready state of 0 (unsent).
  12418. // Therefore, we have to finish this group of requests immediately after the first
  12419. // seen error.
  12420. return doneFn(error, segment);
  12421. }
  12422. count += 1;
  12423. if (count === activeXhrs.length) {
  12424. const segmentFinish = function () {
  12425. if (segment.encryptedBytes) {
  12426. return decryptSegment({
  12427. decryptionWorker,
  12428. segment,
  12429. trackInfoFn,
  12430. timingInfoFn,
  12431. videoSegmentTimingInfoFn,
  12432. audioSegmentTimingInfoFn,
  12433. id3Fn,
  12434. captionsFn,
  12435. isEndOfTimeline,
  12436. endedTimelineFn,
  12437. dataFn,
  12438. doneFn,
  12439. onTransmuxerLog
  12440. });
  12441. } // Otherwise, everything is ready just continue
  12442. handleSegmentBytes({
  12443. segment,
  12444. bytes: segment.bytes,
  12445. trackInfoFn,
  12446. timingInfoFn,
  12447. videoSegmentTimingInfoFn,
  12448. audioSegmentTimingInfoFn,
  12449. id3Fn,
  12450. captionsFn,
  12451. isEndOfTimeline,
  12452. endedTimelineFn,
  12453. dataFn,
  12454. doneFn,
  12455. onTransmuxerLog
  12456. });
  12457. }; // Keep track of when *all* of the requests have completed
  12458. segment.endOfAllRequests = Date.now();
  12459. if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
  12460. return decrypt({
  12461. decryptionWorker,
  12462. // add -init to the "id" to differentiate between segment
  12463. // and init segment decryption, just in case they happen
  12464. // at the same time at some point in the future.
  12465. id: segment.requestId + '-init',
  12466. encryptedBytes: segment.map.encryptedBytes,
  12467. key: segment.map.key
  12468. }, decryptedBytes => {
  12469. segment.map.bytes = decryptedBytes;
  12470. parseInitSegment(segment, parseError => {
  12471. if (parseError) {
  12472. abortAll(activeXhrs);
  12473. return doneFn(parseError, segment);
  12474. }
  12475. segmentFinish();
  12476. });
  12477. });
  12478. }
  12479. segmentFinish();
  12480. }
  12481. };
  12482. };
  12483. /**
  12484. * Calls the abort callback if any request within the batch was aborted. Will only call
  12485. * the callback once per batch of requests, even if multiple were aborted.
  12486. *
  12487. * @param {Object} loadendState - state to check to see if the abort function was called
  12488. * @param {Function} abortFn - callback to call for abort
  12489. */
  12490. const handleLoadEnd = ({
  12491. loadendState,
  12492. abortFn
  12493. }) => event => {
  12494. const request = event.target;
  12495. if (request.aborted && abortFn && !loadendState.calledAbortFn) {
  12496. abortFn();
  12497. loadendState.calledAbortFn = true;
  12498. }
  12499. };
  12500. /**
  12501. * Simple progress event callback handler that gathers some stats before
  12502. * executing a provided callback with the `segment` object
  12503. *
  12504. * @param {Object} segment - a simplified copy of the segmentInfo object
  12505. * from SegmentLoader
  12506. * @param {Function} progressFn - a callback that is executed each time a progress event
  12507. * is received
  12508. * @param {Function} trackInfoFn - a callback that receives track info
  12509. * @param {Function} timingInfoFn - a callback that receives timing info
  12510. * @param {Function} videoSegmentTimingInfoFn
  12511. * a callback that receives video timing info based on media times and
  12512. * any adjustments made by the transmuxer
  12513. * @param {Function} audioSegmentTimingInfoFn
  12514. * a callback that receives audio timing info based on media times and
  12515. * any adjustments made by the transmuxer
  12516. * @param {boolean} isEndOfTimeline
  12517. * true if this segment represents the last segment in a timeline
  12518. * @param {Function} endedTimelineFn
  12519. * a callback made when a timeline is ended, will only be called if
  12520. * isEndOfTimeline is true
  12521. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  12522. * and ready to use
  12523. * @param {Event} event - the progress event object from XMLHttpRequest
  12524. */
  12525. const handleProgress = ({
  12526. segment,
  12527. progressFn,
  12528. trackInfoFn,
  12529. timingInfoFn,
  12530. videoSegmentTimingInfoFn,
  12531. audioSegmentTimingInfoFn,
  12532. id3Fn,
  12533. captionsFn,
  12534. isEndOfTimeline,
  12535. endedTimelineFn,
  12536. dataFn
  12537. }) => event => {
  12538. const request = event.target;
  12539. if (request.aborted) {
  12540. return;
  12541. }
  12542. segment.stats = merge(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data
  12543. if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
  12544. segment.stats.firstBytesReceivedAt = Date.now();
  12545. }
  12546. return progressFn(event, segment);
  12547. };
  12548. /**
  12549. * Load all resources and does any processing necessary for a media-segment
  12550. *
  12551. * Features:
  12552. * decrypts the media-segment if it has a key uri and an iv
  12553. * aborts *all* requests if *any* one request fails
  12554. *
  12555. * The segment object, at minimum, has the following format:
  12556. * {
  12557. * resolvedUri: String,
  12558. * [transmuxer]: Object,
  12559. * [byterange]: {
  12560. * offset: Number,
  12561. * length: Number
  12562. * },
  12563. * [key]: {
  12564. * resolvedUri: String
  12565. * [byterange]: {
  12566. * offset: Number,
  12567. * length: Number
  12568. * },
  12569. * iv: {
  12570. * bytes: Uint32Array
  12571. * }
  12572. * },
  12573. * [map]: {
  12574. * resolvedUri: String,
  12575. * [byterange]: {
  12576. * offset: Number,
  12577. * length: Number
  12578. * },
  12579. * [bytes]: Uint8Array
  12580. * }
  12581. * }
  12582. * ...where [name] denotes optional properties
  12583. *
  12584. * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
  12585. * @param {Object} xhrOptions - the base options to provide to all xhr requests
  12586. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
  12587. * decryption routines
  12588. * @param {Object} segment - a simplified copy of the segmentInfo object
  12589. * from SegmentLoader
  12590. * @param {Function} abortFn - a callback called (only once) if any piece of a request was
  12591. * aborted
  12592. * @param {Function} progressFn - a callback that receives progress events from the main
  12593. * segment's xhr request
  12594. * @param {Function} trackInfoFn - a callback that receives track info
  12595. * @param {Function} timingInfoFn - a callback that receives timing info
  12596. * @param {Function} videoSegmentTimingInfoFn
  12597. * a callback that receives video timing info based on media times and
  12598. * any adjustments made by the transmuxer
  12599. * @param {Function} audioSegmentTimingInfoFn
  12600. * a callback that receives audio timing info based on media times and
  12601. * any adjustments made by the transmuxer
  12602. * @param {Function} id3Fn - a callback that receives ID3 metadata
  12603. * @param {Function} captionsFn - a callback that receives captions
  12604. * @param {boolean} isEndOfTimeline
  12605. * true if this segment represents the last segment in a timeline
  12606. * @param {Function} endedTimelineFn
  12607. * a callback made when a timeline is ended, will only be called if
  12608. * isEndOfTimeline is true
  12609. * @param {Function} dataFn - a callback that receives data from the main segment's xhr
  12610. * request, transmuxed if needed
  12611. * @param {Function} doneFn - a callback that is executed only once all requests have
  12612. * succeeded or failed
  12613. * @return {Function} a function that, when invoked, immediately aborts all
  12614. * outstanding requests
  12615. */
  12616. const mediaSegmentRequest = ({
  12617. xhr,
  12618. xhrOptions,
  12619. decryptionWorker,
  12620. segment,
  12621. abortFn,
  12622. progressFn,
  12623. trackInfoFn,
  12624. timingInfoFn,
  12625. videoSegmentTimingInfoFn,
  12626. audioSegmentTimingInfoFn,
  12627. id3Fn,
  12628. captionsFn,
  12629. isEndOfTimeline,
  12630. endedTimelineFn,
  12631. dataFn,
  12632. doneFn,
  12633. onTransmuxerLog
  12634. }) => {
  12635. const activeXhrs = [];
  12636. const finishProcessingFn = waitForCompletion({
  12637. activeXhrs,
  12638. decryptionWorker,
  12639. trackInfoFn,
  12640. timingInfoFn,
  12641. videoSegmentTimingInfoFn,
  12642. audioSegmentTimingInfoFn,
  12643. id3Fn,
  12644. captionsFn,
  12645. isEndOfTimeline,
  12646. endedTimelineFn,
  12647. dataFn,
  12648. doneFn,
  12649. onTransmuxerLog
  12650. }); // optionally, request the decryption key
  12651. if (segment.key && !segment.key.bytes) {
  12652. const objects = [segment.key];
  12653. if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
  12654. objects.push(segment.map.key);
  12655. }
  12656. const keyRequestOptions = merge(xhrOptions, {
  12657. uri: segment.key.resolvedUri,
  12658. responseType: 'arraybuffer'
  12659. });
  12660. const keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
  12661. const keyXhr = xhr(keyRequestOptions, keyRequestCallback);
  12662. activeXhrs.push(keyXhr);
  12663. } // optionally, request the associated media init segment
  12664. if (segment.map && !segment.map.bytes) {
  12665. const differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
  12666. if (differentMapKey) {
  12667. const mapKeyRequestOptions = merge(xhrOptions, {
  12668. uri: segment.map.key.resolvedUri,
  12669. responseType: 'arraybuffer'
  12670. });
  12671. const mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
  12672. const mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
  12673. activeXhrs.push(mapKeyXhr);
  12674. }
  12675. const initSegmentOptions = merge(xhrOptions, {
  12676. uri: segment.map.resolvedUri,
  12677. responseType: 'arraybuffer',
  12678. headers: segmentXhrHeaders(segment.map)
  12679. });
  12680. const initSegmentRequestCallback = handleInitSegmentResponse({
  12681. segment,
  12682. finishProcessingFn
  12683. });
  12684. const initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
  12685. activeXhrs.push(initSegmentXhr);
  12686. }
  12687. const segmentRequestOptions = merge(xhrOptions, {
  12688. uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
  12689. responseType: 'arraybuffer',
  12690. headers: segmentXhrHeaders(segment)
  12691. });
  12692. const segmentRequestCallback = handleSegmentResponse({
  12693. segment,
  12694. finishProcessingFn,
  12695. responseType: segmentRequestOptions.responseType
  12696. });
  12697. const segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
  12698. segmentXhr.addEventListener('progress', handleProgress({
  12699. segment,
  12700. progressFn,
  12701. trackInfoFn,
  12702. timingInfoFn,
  12703. videoSegmentTimingInfoFn,
  12704. audioSegmentTimingInfoFn,
  12705. id3Fn,
  12706. captionsFn,
  12707. isEndOfTimeline,
  12708. endedTimelineFn,
  12709. dataFn
  12710. }));
  12711. activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks
  12712. // multiple times, provide a shared state object
  12713. const loadendState = {};
  12714. activeXhrs.forEach(activeXhr => {
  12715. activeXhr.addEventListener('loadend', handleLoadEnd({
  12716. loadendState,
  12717. abortFn
  12718. }));
  12719. });
  12720. return () => abortAll(activeXhrs);
  12721. };
  12722. /**
  12723. * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
  12724. * codec strings, or translating codec strings into objects that can be examined.
  12725. */
  12726. const logFn$1 = logger('CodecUtils');
  12727. /**
  12728. * Returns a set of codec strings parsed from the playlist or the default
  12729. * codec strings if no codecs were specified in the playlist
  12730. *
  12731. * @param {Playlist} media the current media playlist
  12732. * @return {Object} an object with the video and audio codecs
  12733. */
  12734. const getCodecs = function (media) {
  12735. // if the codecs were explicitly specified, use them instead of the
  12736. // defaults
  12737. const mediaAttributes = media.attributes || {};
  12738. if (mediaAttributes.CODECS) {
  12739. return parseCodecs(mediaAttributes.CODECS);
  12740. }
  12741. };
  12742. const isMaat = (main, media) => {
  12743. const mediaAttributes = media.attributes || {};
  12744. return main && main.mediaGroups && main.mediaGroups.AUDIO && mediaAttributes.AUDIO && main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  12745. };
  12746. const isMuxed = (main, media) => {
  12747. if (!isMaat(main, media)) {
  12748. return true;
  12749. }
  12750. const mediaAttributes = media.attributes || {};
  12751. const audioGroup = main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  12752. for (const groupId in audioGroup) {
  12753. // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
  12754. // or there are listed playlists (the case for DASH, as the manifest will have already
  12755. // provided all of the details necessary to generate the audio playlist, as opposed to
  12756. // HLS' externally requested playlists), then the content is demuxed.
  12757. if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
  12758. return true;
  12759. }
  12760. }
  12761. return false;
  12762. };
  12763. const unwrapCodecList = function (codecList) {
  12764. const codecs = {};
  12765. codecList.forEach(({
  12766. mediaType,
  12767. type,
  12768. details
  12769. }) => {
  12770. codecs[mediaType] = codecs[mediaType] || [];
  12771. codecs[mediaType].push(translateLegacyCodec(`${type}${details}`));
  12772. });
  12773. Object.keys(codecs).forEach(function (mediaType) {
  12774. if (codecs[mediaType].length > 1) {
  12775. 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.`);
  12776. codecs[mediaType] = null;
  12777. return;
  12778. }
  12779. codecs[mediaType] = codecs[mediaType][0];
  12780. });
  12781. return codecs;
  12782. };
  12783. const codecCount = function (codecObj) {
  12784. let count = 0;
  12785. if (codecObj.audio) {
  12786. count++;
  12787. }
  12788. if (codecObj.video) {
  12789. count++;
  12790. }
  12791. return count;
  12792. };
  12793. /**
  12794. * Calculates the codec strings for a working configuration of
  12795. * SourceBuffers to play variant streams in a main playlist. If
  12796. * there is no possible working configuration, an empty object will be
  12797. * returned.
  12798. *
  12799. * @param main {Object} the m3u8 object for the main playlist
  12800. * @param media {Object} the m3u8 object for the variant playlist
  12801. * @return {Object} the codec strings.
  12802. *
  12803. * @private
  12804. */
  12805. const codecsForPlaylist = function (main, media) {
  12806. const mediaAttributes = media.attributes || {};
  12807. const codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.
  12808. // Put another way, there is no way to have a video-only multiple-audio HLS!
  12809. if (isMaat(main, media) && !codecInfo.audio) {
  12810. if (!isMuxed(main, media)) {
  12811. // It is possible for codecs to be specified on the audio media group playlist but
  12812. // not on the rendition playlist. This is mostly the case for DASH, where audio and
  12813. // video are always separate (and separately specified).
  12814. const defaultCodecs = unwrapCodecList(codecsFromDefault(main, mediaAttributes.AUDIO) || []);
  12815. if (defaultCodecs.audio) {
  12816. codecInfo.audio = defaultCodecs.audio;
  12817. }
  12818. }
  12819. }
  12820. return codecInfo;
  12821. };
  12822. const logFn = logger('PlaylistSelector');
  12823. const representationToString = function (representation) {
  12824. if (!representation || !representation.playlist) {
  12825. return;
  12826. }
  12827. const playlist = representation.playlist;
  12828. return JSON.stringify({
  12829. id: playlist.id,
  12830. bandwidth: representation.bandwidth,
  12831. width: representation.width,
  12832. height: representation.height,
  12833. codecs: playlist.attributes && playlist.attributes.CODECS || ''
  12834. });
  12835. }; // Utilities
  12836. /**
  12837. * Returns the CSS value for the specified property on an element
  12838. * using `getComputedStyle`. Firefox has a long-standing issue where
  12839. * getComputedStyle() may return null when running in an iframe with
  12840. * `display: none`.
  12841. *
  12842. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  12843. * @param {HTMLElement} el the htmlelement to work on
  12844. * @param {string} the proprety to get the style for
  12845. */
  12846. const safeGetComputedStyle = function (el, property) {
  12847. if (!el) {
  12848. return '';
  12849. }
  12850. const result = window$1.getComputedStyle(el);
  12851. if (!result) {
  12852. return '';
  12853. }
  12854. return result[property];
  12855. };
  12856. /**
  12857. * Resuable stable sort function
  12858. *
  12859. * @param {Playlists} array
  12860. * @param {Function} sortFn Different comparators
  12861. * @function stableSort
  12862. */
  12863. const stableSort = function (array, sortFn) {
  12864. const newArray = array.slice();
  12865. array.sort(function (left, right) {
  12866. const cmp = sortFn(left, right);
  12867. if (cmp === 0) {
  12868. return newArray.indexOf(left) - newArray.indexOf(right);
  12869. }
  12870. return cmp;
  12871. });
  12872. };
  12873. /**
  12874. * A comparator function to sort two playlist object by bandwidth.
  12875. *
  12876. * @param {Object} left a media playlist object
  12877. * @param {Object} right a media playlist object
  12878. * @return {number} Greater than zero if the bandwidth attribute of
  12879. * left is greater than the corresponding attribute of right. Less
  12880. * than zero if the bandwidth of right is greater than left and
  12881. * exactly zero if the two are equal.
  12882. */
  12883. const comparePlaylistBandwidth = function (left, right) {
  12884. let leftBandwidth;
  12885. let rightBandwidth;
  12886. if (left.attributes.BANDWIDTH) {
  12887. leftBandwidth = left.attributes.BANDWIDTH;
  12888. }
  12889. leftBandwidth = leftBandwidth || window$1.Number.MAX_VALUE;
  12890. if (right.attributes.BANDWIDTH) {
  12891. rightBandwidth = right.attributes.BANDWIDTH;
  12892. }
  12893. rightBandwidth = rightBandwidth || window$1.Number.MAX_VALUE;
  12894. return leftBandwidth - rightBandwidth;
  12895. };
  12896. /**
  12897. * A comparator function to sort two playlist object by resolution (width).
  12898. *
  12899. * @param {Object} left a media playlist object
  12900. * @param {Object} right a media playlist object
  12901. * @return {number} Greater than zero if the resolution.width attribute of
  12902. * left is greater than the corresponding attribute of right. Less
  12903. * than zero if the resolution.width of right is greater than left and
  12904. * exactly zero if the two are equal.
  12905. */
  12906. const comparePlaylistResolution = function (left, right) {
  12907. let leftWidth;
  12908. let rightWidth;
  12909. if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
  12910. leftWidth = left.attributes.RESOLUTION.width;
  12911. }
  12912. leftWidth = leftWidth || window$1.Number.MAX_VALUE;
  12913. if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
  12914. rightWidth = right.attributes.RESOLUTION.width;
  12915. }
  12916. rightWidth = rightWidth || window$1.Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
  12917. // have the same media dimensions/ resolution
  12918. if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
  12919. return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
  12920. }
  12921. return leftWidth - rightWidth;
  12922. };
  12923. /**
  12924. * Chooses the appropriate media playlist based on bandwidth and player size
  12925. *
  12926. * @param {Object} main
  12927. * Object representation of the main manifest
  12928. * @param {number} playerBandwidth
  12929. * Current calculated bandwidth of the player
  12930. * @param {number} playerWidth
  12931. * Current width of the player element (should account for the device pixel ratio)
  12932. * @param {number} playerHeight
  12933. * Current height of the player element (should account for the device pixel ratio)
  12934. * @param {boolean} limitRenditionByPlayerDimensions
  12935. * True if the player width and height should be used during the selection, false otherwise
  12936. * @param {Object} playlistController
  12937. * the current playlistController object
  12938. * @return {Playlist} the highest bitrate playlist less than the
  12939. * currently detected bandwidth, accounting for some amount of
  12940. * bandwidth variance
  12941. */
  12942. let simpleSelector = function (main, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, playlistController) {
  12943. // If we end up getting called before `main` is available, exit early
  12944. if (!main) {
  12945. return;
  12946. }
  12947. const options = {
  12948. bandwidth: playerBandwidth,
  12949. width: playerWidth,
  12950. height: playerHeight,
  12951. limitRenditionByPlayerDimensions
  12952. };
  12953. let playlists = main.playlists; // if playlist is audio only, select between currently active audio group playlists.
  12954. if (Playlist.isAudioOnly(main)) {
  12955. playlists = playlistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true
  12956. // at the buttom of this function for debugging.
  12957. options.audioOnly = true;
  12958. } // convert the playlists to an intermediary representation to make comparisons easier
  12959. let sortedPlaylistReps = playlists.map(playlist => {
  12960. let bandwidth;
  12961. const width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
  12962. const height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
  12963. bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
  12964. bandwidth = bandwidth || window$1.Number.MAX_VALUE;
  12965. return {
  12966. bandwidth,
  12967. width,
  12968. height,
  12969. playlist
  12970. };
  12971. });
  12972. stableSort(sortedPlaylistReps, (left, right) => left.bandwidth - right.bandwidth); // filter out any playlists that have been excluded due to
  12973. // incompatible configurations
  12974. sortedPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isIncompatible(rep.playlist)); // filter out any playlists that have been disabled manually through the representations
  12975. // api or excluded temporarily due to playback errors.
  12976. let enabledPlaylistReps = sortedPlaylistReps.filter(rep => Playlist.isEnabled(rep.playlist));
  12977. if (!enabledPlaylistReps.length) {
  12978. // if there are no enabled playlists, then they have all been excluded or disabled
  12979. // by the user through the representations api. In this case, ignore exclusion and
  12980. // fallback to what the user wants by using playlists the user has not disabled.
  12981. enabledPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isDisabled(rep.playlist));
  12982. } // filter out any variant that has greater effective bitrate
  12983. // than the current estimated bandwidth
  12984. const bandwidthPlaylistReps = enabledPlaylistReps.filter(rep => rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth);
  12985. let highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth
  12986. // and then taking the very first element
  12987. 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.
  12988. if (limitRenditionByPlayerDimensions === false) {
  12989. const chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  12990. if (chosenRep && chosenRep.playlist) {
  12991. let type = 'sortedPlaylistReps';
  12992. if (bandwidthBestRep) {
  12993. type = 'bandwidthBestRep';
  12994. }
  12995. if (enabledPlaylistReps[0]) {
  12996. type = 'enabledPlaylistReps';
  12997. }
  12998. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  12999. return chosenRep.playlist;
  13000. }
  13001. logFn('could not choose a playlist with options', options);
  13002. return null;
  13003. } // filter out playlists without resolution information
  13004. const haveResolution = bandwidthPlaylistReps.filter(rep => rep.width && rep.height); // sort variants by resolution
  13005. stableSort(haveResolution, (left, right) => left.width - right.width); // if we have the exact resolution as the player use it
  13006. const resolutionBestRepList = haveResolution.filter(rep => rep.width === playerWidth && rep.height === playerHeight);
  13007. highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
  13008. const resolutionBestRep = resolutionBestRepList.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  13009. let resolutionPlusOneList;
  13010. let resolutionPlusOneSmallest;
  13011. let resolutionPlusOneRep; // find the smallest variant that is larger than the player
  13012. // if there is no match of exact resolution
  13013. if (!resolutionBestRep) {
  13014. resolutionPlusOneList = haveResolution.filter(rep => rep.width > playerWidth || rep.height > playerHeight); // find all the variants have the same smallest resolution
  13015. resolutionPlusOneSmallest = resolutionPlusOneList.filter(rep => rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height); // ensure that we also pick the highest bandwidth variant that
  13016. // is just-larger-than the video player
  13017. highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
  13018. resolutionPlusOneRep = resolutionPlusOneSmallest.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  13019. }
  13020. let leastPixelDiffRep; // If this selector proves to be better than others,
  13021. // resolutionPlusOneRep and resolutionBestRep and all
  13022. // the code involving them should be removed.
  13023. if (playlistController.leastPixelDiffSelector) {
  13024. // find the variant that is closest to the player's pixel size
  13025. const leastPixelDiffList = haveResolution.map(rep => {
  13026. rep.pixelDiff = Math.abs(rep.width - playerWidth) + Math.abs(rep.height - playerHeight);
  13027. return rep;
  13028. }); // get the highest bandwidth, closest resolution playlist
  13029. stableSort(leastPixelDiffList, (left, right) => {
  13030. // sort by highest bandwidth if pixelDiff is the same
  13031. if (left.pixelDiff === right.pixelDiff) {
  13032. return right.bandwidth - left.bandwidth;
  13033. }
  13034. return left.pixelDiff - right.pixelDiff;
  13035. });
  13036. leastPixelDiffRep = leastPixelDiffList[0];
  13037. } // fallback chain of variants
  13038. const chosenRep = leastPixelDiffRep || resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  13039. if (chosenRep && chosenRep.playlist) {
  13040. let type = 'sortedPlaylistReps';
  13041. if (leastPixelDiffRep) {
  13042. type = 'leastPixelDiffRep';
  13043. } else if (resolutionPlusOneRep) {
  13044. type = 'resolutionPlusOneRep';
  13045. } else if (resolutionBestRep) {
  13046. type = 'resolutionBestRep';
  13047. } else if (bandwidthBestRep) {
  13048. type = 'bandwidthBestRep';
  13049. } else if (enabledPlaylistReps[0]) {
  13050. type = 'enabledPlaylistReps';
  13051. }
  13052. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  13053. return chosenRep.playlist;
  13054. }
  13055. logFn('could not choose a playlist with options', options);
  13056. return null;
  13057. };
  13058. /**
  13059. * Chooses the appropriate media playlist based on the most recent
  13060. * bandwidth estimate and the player size.
  13061. *
  13062. * Expects to be called within the context of an instance of VhsHandler
  13063. *
  13064. * @return {Playlist} the highest bitrate playlist less than the
  13065. * currently detected bandwidth, accounting for some amount of
  13066. * bandwidth variance
  13067. */
  13068. const lastBandwidthSelector = function () {
  13069. const pixelRatio = this.useDevicePixelRatio ? window$1.devicePixelRatio || 1 : 1;
  13070. 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_);
  13071. };
  13072. /**
  13073. * Chooses the appropriate media playlist based on an
  13074. * exponential-weighted moving average of the bandwidth after
  13075. * filtering for player size.
  13076. *
  13077. * Expects to be called within the context of an instance of VhsHandler
  13078. *
  13079. * @param {number} decay - a number between 0 and 1. Higher values of
  13080. * this parameter will cause previous bandwidth estimates to lose
  13081. * significance more quickly.
  13082. * @return {Function} a function which can be invoked to create a new
  13083. * playlist selector function.
  13084. * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  13085. */
  13086. const movingAverageBandwidthSelector = function (decay) {
  13087. let average = -1;
  13088. let lastSystemBandwidth = -1;
  13089. if (decay < 0 || decay > 1) {
  13090. throw new Error('Moving average bandwidth decay must be between 0 and 1.');
  13091. }
  13092. return function () {
  13093. const pixelRatio = this.useDevicePixelRatio ? window$1.devicePixelRatio || 1 : 1;
  13094. if (average < 0) {
  13095. average = this.systemBandwidth;
  13096. lastSystemBandwidth = this.systemBandwidth;
  13097. } // stop the average value from decaying for every 250ms
  13098. // when the systemBandwidth is constant
  13099. // and
  13100. // stop average from setting to a very low value when the
  13101. // systemBandwidth becomes 0 in case of chunk cancellation
  13102. if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
  13103. average = decay * this.systemBandwidth + (1 - decay) * average;
  13104. lastSystemBandwidth = this.systemBandwidth;
  13105. }
  13106. 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_);
  13107. };
  13108. };
  13109. /**
  13110. * Chooses the appropriate media playlist based on the potential to rebuffer
  13111. *
  13112. * @param {Object} settings
  13113. * Object of information required to use this selector
  13114. * @param {Object} settings.main
  13115. * Object representation of the main manifest
  13116. * @param {number} settings.currentTime
  13117. * The current time of the player
  13118. * @param {number} settings.bandwidth
  13119. * Current measured bandwidth
  13120. * @param {number} settings.duration
  13121. * Duration of the media
  13122. * @param {number} settings.segmentDuration
  13123. * Segment duration to be used in round trip time calculations
  13124. * @param {number} settings.timeUntilRebuffer
  13125. * Time left in seconds until the player has to rebuffer
  13126. * @param {number} settings.currentTimeline
  13127. * The current timeline segments are being loaded from
  13128. * @param {SyncController} settings.syncController
  13129. * SyncController for determining if we have a sync point for a given playlist
  13130. * @return {Object|null}
  13131. * {Object} return.playlist
  13132. * The highest bandwidth playlist with the least amount of rebuffering
  13133. * {Number} return.rebufferingImpact
  13134. * The amount of time in seconds switching to this playlist will rebuffer. A
  13135. * negative value means that switching will cause zero rebuffering.
  13136. */
  13137. const minRebufferMaxBandwidthSelector = function (settings) {
  13138. const {
  13139. main,
  13140. currentTime,
  13141. bandwidth,
  13142. duration,
  13143. segmentDuration,
  13144. timeUntilRebuffer,
  13145. currentTimeline,
  13146. syncController
  13147. } = settings; // filter out any playlists that have been excluded due to
  13148. // incompatible configurations
  13149. const compatiblePlaylists = main.playlists.filter(playlist => !Playlist.isIncompatible(playlist)); // filter out any playlists that have been disabled manually through the representations
  13150. // api or excluded temporarily due to playback errors.
  13151. let enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
  13152. if (!enabledPlaylists.length) {
  13153. // if there are no enabled playlists, then they have all been excluded or disabled
  13154. // by the user through the representations api. In this case, ignore exclusion and
  13155. // fallback to what the user wants by using playlists the user has not disabled.
  13156. enabledPlaylists = compatiblePlaylists.filter(playlist => !Playlist.isDisabled(playlist));
  13157. }
  13158. const bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
  13159. const rebufferingEstimates = bandwidthPlaylists.map(playlist => {
  13160. const syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a
  13161. // sync request first. This will double the request time
  13162. const numRequests = syncPoint ? 1 : 2;
  13163. const requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);
  13164. const rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;
  13165. return {
  13166. playlist,
  13167. rebufferingImpact
  13168. };
  13169. });
  13170. const noRebufferingPlaylists = rebufferingEstimates.filter(estimate => estimate.rebufferingImpact <= 0); // Sort by bandwidth DESC
  13171. stableSort(noRebufferingPlaylists, (a, b) => comparePlaylistBandwidth(b.playlist, a.playlist));
  13172. if (noRebufferingPlaylists.length) {
  13173. return noRebufferingPlaylists[0];
  13174. }
  13175. stableSort(rebufferingEstimates, (a, b) => a.rebufferingImpact - b.rebufferingImpact);
  13176. return rebufferingEstimates[0] || null;
  13177. };
  13178. /**
  13179. * Chooses the appropriate media playlist, which in this case is the lowest bitrate
  13180. * one with video. If no renditions with video exist, return the lowest audio rendition.
  13181. *
  13182. * Expects to be called within the context of an instance of VhsHandler
  13183. *
  13184. * @return {Object|null}
  13185. * {Object} return.playlist
  13186. * The lowest bitrate playlist that contains a video codec. If no such rendition
  13187. * exists pick the lowest audio rendition.
  13188. */
  13189. const lowestBitrateCompatibleVariantSelector = function () {
  13190. // filter out any playlists that have been excluded due to
  13191. // incompatible configurations or playback errors
  13192. const playlists = this.playlists.main.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate
  13193. stableSort(playlists, (a, b) => comparePlaylistBandwidth(a, b)); // Parse and assume that playlists with no video codec have no video
  13194. // (this is not necessarily true, although it is generally true).
  13195. //
  13196. // If an entire manifest has no valid videos everything will get filtered
  13197. // out.
  13198. const playlistsWithVideo = playlists.filter(playlist => !!codecsForPlaylist(this.playlists.main, playlist).video);
  13199. return playlistsWithVideo[0] || null;
  13200. };
  13201. /**
  13202. * Combine all segments into a single Uint8Array
  13203. *
  13204. * @param {Object} segmentObj
  13205. * @return {Uint8Array} concatenated bytes
  13206. * @private
  13207. */
  13208. const concatSegments = segmentObj => {
  13209. let offset = 0;
  13210. let tempBuffer;
  13211. if (segmentObj.bytes) {
  13212. tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array
  13213. segmentObj.segments.forEach(segment => {
  13214. tempBuffer.set(segment, offset);
  13215. offset += segment.byteLength;
  13216. });
  13217. }
  13218. return tempBuffer;
  13219. };
  13220. /**
  13221. * @file text-tracks.js
  13222. */
  13223. /**
  13224. * Create captions text tracks on video.js if they do not exist
  13225. *
  13226. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  13227. * @param {Object} tech the video.js tech
  13228. * @param {Object} captionStream the caption stream to create
  13229. * @private
  13230. */
  13231. const createCaptionsTrackIfNotExists = function (inbandTextTracks, tech, captionStream) {
  13232. if (!inbandTextTracks[captionStream]) {
  13233. tech.trigger({
  13234. type: 'usage',
  13235. name: 'vhs-608'
  13236. });
  13237. let instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them
  13238. if (/^cc708_/.test(captionStream)) {
  13239. instreamId = 'SERVICE' + captionStream.split('_')[1];
  13240. }
  13241. const track = tech.textTracks().getTrackById(instreamId);
  13242. if (track) {
  13243. // Resuse an existing track with a CC# id because this was
  13244. // very likely created by videojs-contrib-hls from information
  13245. // in the m3u8 for us to use
  13246. inbandTextTracks[captionStream] = track;
  13247. } else {
  13248. // This section gets called when we have caption services that aren't specified in the manifest.
  13249. // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
  13250. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  13251. let label = captionStream;
  13252. let language = captionStream;
  13253. let def = false;
  13254. const captionService = captionServices[instreamId];
  13255. if (captionService) {
  13256. label = captionService.label;
  13257. language = captionService.language;
  13258. def = captionService.default;
  13259. } // Otherwise, create a track with the default `CC#` label and
  13260. // without a language
  13261. inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
  13262. kind: 'captions',
  13263. id: instreamId,
  13264. // TODO: investigate why this doesn't seem to turn the caption on by default
  13265. default: def,
  13266. label,
  13267. language
  13268. }, false).track;
  13269. }
  13270. }
  13271. };
  13272. /**
  13273. * Add caption text track data to a source handler given an array of captions
  13274. *
  13275. * @param {Object}
  13276. * @param {Object} inbandTextTracks the inband text tracks
  13277. * @param {number} timestampOffset the timestamp offset of the source buffer
  13278. * @param {Array} captionArray an array of caption data
  13279. * @private
  13280. */
  13281. const addCaptionData = function ({
  13282. inbandTextTracks,
  13283. captionArray,
  13284. timestampOffset
  13285. }) {
  13286. if (!captionArray) {
  13287. return;
  13288. }
  13289. const Cue = window$1.WebKitDataCue || window$1.VTTCue;
  13290. captionArray.forEach(caption => {
  13291. const track = caption.stream; // in CEA 608 captions, video.js/mux.js sends a content array
  13292. // with positioning data
  13293. if (caption.content) {
  13294. caption.content.forEach(value => {
  13295. const cue = new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, value.text);
  13296. cue.line = value.line;
  13297. cue.align = 'left';
  13298. cue.position = value.position;
  13299. cue.positionAlign = 'line-left';
  13300. inbandTextTracks[track].addCue(cue);
  13301. });
  13302. } else {
  13303. // otherwise, a text value with combined captions is sent
  13304. inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));
  13305. }
  13306. });
  13307. };
  13308. /**
  13309. * Define properties on a cue for backwards compatability,
  13310. * but warn the user that the way that they are using it
  13311. * is depricated and will be removed at a later date.
  13312. *
  13313. * @param {Cue} cue the cue to add the properties on
  13314. * @private
  13315. */
  13316. const deprecateOldCue = function (cue) {
  13317. Object.defineProperties(cue.frame, {
  13318. id: {
  13319. get() {
  13320. videojs.log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
  13321. return cue.value.key;
  13322. }
  13323. },
  13324. value: {
  13325. get() {
  13326. videojs.log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
  13327. return cue.value.data;
  13328. }
  13329. },
  13330. privateData: {
  13331. get() {
  13332. videojs.log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
  13333. return cue.value.data;
  13334. }
  13335. }
  13336. });
  13337. };
  13338. /**
  13339. * Add metadata text track data to a source handler given an array of metadata
  13340. *
  13341. * @param {Object}
  13342. * @param {Object} inbandTextTracks the inband text tracks
  13343. * @param {Array} metadataArray an array of meta data
  13344. * @param {number} timestampOffset the timestamp offset of the source buffer
  13345. * @param {number} videoDuration the duration of the video
  13346. * @private
  13347. */
  13348. const addMetadata = ({
  13349. inbandTextTracks,
  13350. metadataArray,
  13351. timestampOffset,
  13352. videoDuration
  13353. }) => {
  13354. if (!metadataArray) {
  13355. return;
  13356. }
  13357. const Cue = window$1.WebKitDataCue || window$1.VTTCue;
  13358. const metadataTrack = inbandTextTracks.metadataTrack_;
  13359. if (!metadataTrack) {
  13360. return;
  13361. }
  13362. metadataArray.forEach(metadata => {
  13363. const time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,
  13364. // ignore this bit of metadata.
  13365. // This likely occurs when you have an non-timed ID3 tag like TIT2,
  13366. // which is the "Title/Songname/Content description" frame
  13367. if (typeof time !== 'number' || window$1.isNaN(time) || time < 0 || !(time < Infinity)) {
  13368. return;
  13369. } // If we have no frames, we can't create a cue.
  13370. if (!metadata.frames || !metadata.frames.length) {
  13371. return;
  13372. }
  13373. metadata.frames.forEach(frame => {
  13374. const cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
  13375. cue.frame = frame;
  13376. cue.value = frame;
  13377. deprecateOldCue(cue);
  13378. metadataTrack.addCue(cue);
  13379. });
  13380. });
  13381. if (!metadataTrack.cues || !metadataTrack.cues.length) {
  13382. return;
  13383. } // Updating the metadeta cues so that
  13384. // the endTime of each cue is the startTime of the next cue
  13385. // the endTime of last cue is the duration of the video
  13386. const cues = metadataTrack.cues;
  13387. const cuesArray = []; // Create a copy of the TextTrackCueList...
  13388. // ...disregarding cues with a falsey value
  13389. for (let i = 0; i < cues.length; i++) {
  13390. if (cues[i]) {
  13391. cuesArray.push(cues[i]);
  13392. }
  13393. } // Group cues by their startTime value
  13394. const cuesGroupedByStartTime = cuesArray.reduce((obj, cue) => {
  13395. const timeSlot = obj[cue.startTime] || [];
  13396. timeSlot.push(cue);
  13397. obj[cue.startTime] = timeSlot;
  13398. return obj;
  13399. }, {}); // Sort startTimes by ascending order
  13400. const sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort((a, b) => Number(a) - Number(b)); // Map each cue group's endTime to the next group's startTime
  13401. sortedStartTimes.forEach((startTime, idx) => {
  13402. const cueGroup = cuesGroupedByStartTime[startTime];
  13403. const finiteDuration = isFinite(videoDuration) ? videoDuration : startTime;
  13404. const nextTime = Number(sortedStartTimes[idx + 1]) || finiteDuration; // Map each cue's endTime the next group's startTime
  13405. cueGroup.forEach(cue => {
  13406. cue.endTime = nextTime;
  13407. });
  13408. });
  13409. }; // object for mapping daterange attributes
  13410. const dateRangeAttr = {
  13411. id: 'ID',
  13412. class: 'CLASS',
  13413. startDate: 'START-DATE',
  13414. duration: 'DURATION',
  13415. endDate: 'END-DATE',
  13416. endOnNext: 'END-ON-NEXT',
  13417. plannedDuration: 'PLANNED-DURATION',
  13418. scte35Out: 'SCTE35-OUT',
  13419. scte35In: 'SCTE35-IN'
  13420. };
  13421. const dateRangeKeysToOmit = new Set(['id', 'class', 'startDate', 'duration', 'endDate', 'endOnNext', 'startTime', 'endTime', 'processDateRange']);
  13422. /**
  13423. * Add DateRange metadata text track to a source handler given an array of metadata
  13424. *
  13425. * @param {Object}
  13426. * @param {Object} inbandTextTracks the inband text tracks
  13427. * @param {Array} dateRanges parsed media playlist
  13428. * @private
  13429. */
  13430. const addDateRangeMetadata = ({
  13431. inbandTextTracks,
  13432. dateRanges
  13433. }) => {
  13434. const metadataTrack = inbandTextTracks.metadataTrack_;
  13435. if (!metadataTrack) {
  13436. return;
  13437. }
  13438. const Cue = window$1.WebKitDataCue || window$1.VTTCue;
  13439. dateRanges.forEach(dateRange => {
  13440. // we generate multiple cues for each date range with different attributes
  13441. for (const key of Object.keys(dateRange)) {
  13442. if (dateRangeKeysToOmit.has(key)) {
  13443. continue;
  13444. }
  13445. const cue = new Cue(dateRange.startTime, dateRange.endTime, '');
  13446. cue.id = dateRange.id;
  13447. cue.type = 'com.apple.quicktime.HLS';
  13448. cue.value = {
  13449. key: dateRangeAttr[key],
  13450. data: dateRange[key]
  13451. };
  13452. if (key === 'scte35Out' || key === 'scte35In') {
  13453. cue.value.data = new Uint8Array(cue.value.data.match(/[\da-f]{2}/gi)).buffer;
  13454. }
  13455. metadataTrack.addCue(cue);
  13456. }
  13457. dateRange.processDateRange();
  13458. });
  13459. };
  13460. /**
  13461. * Create metadata text track on video.js if it does not exist
  13462. *
  13463. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  13464. * @param {string} dispatchType the inband metadata track dispatch type
  13465. * @param {Object} tech the video.js tech
  13466. * @private
  13467. */
  13468. const createMetadataTrackIfNotExists = (inbandTextTracks, dispatchType, tech) => {
  13469. if (inbandTextTracks.metadataTrack_) {
  13470. return;
  13471. }
  13472. inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
  13473. kind: 'metadata',
  13474. label: 'Timed Metadata'
  13475. }, false).track;
  13476. if (!videojs.browser.IS_ANY_SAFARI) {
  13477. inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
  13478. }
  13479. };
  13480. /**
  13481. * Remove cues from a track on video.js.
  13482. *
  13483. * @param {Double} start start of where we should remove the cue
  13484. * @param {Double} end end of where the we should remove the cue
  13485. * @param {Object} track the text track to remove the cues from
  13486. * @private
  13487. */
  13488. const removeCuesFromTrack = function (start, end, track) {
  13489. let i;
  13490. let cue;
  13491. if (!track) {
  13492. return;
  13493. }
  13494. if (!track.cues) {
  13495. return;
  13496. }
  13497. i = track.cues.length;
  13498. while (i--) {
  13499. cue = track.cues[i]; // Remove any cue within the provided start and end time
  13500. if (cue.startTime >= start && cue.endTime <= end) {
  13501. track.removeCue(cue);
  13502. }
  13503. }
  13504. };
  13505. /**
  13506. * Remove duplicate cues from a track on video.js (a cue is considered a
  13507. * duplicate if it has the same time interval and text as another)
  13508. *
  13509. * @param {Object} track the text track to remove the duplicate cues from
  13510. * @private
  13511. */
  13512. const removeDuplicateCuesFromTrack = function (track) {
  13513. const cues = track.cues;
  13514. if (!cues) {
  13515. return;
  13516. }
  13517. const uniqueCues = {};
  13518. for (let i = cues.length - 1; i >= 0; i--) {
  13519. const cue = cues[i];
  13520. const cueKey = `${cue.startTime}-${cue.endTime}-${cue.text}`;
  13521. if (uniqueCues[cueKey]) {
  13522. track.removeCue(cue);
  13523. } else {
  13524. uniqueCues[cueKey] = cue;
  13525. }
  13526. }
  13527. };
  13528. /**
  13529. * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
  13530. * front of current time.
  13531. *
  13532. * @param {Array} buffer
  13533. * The current buffer of gop information
  13534. * @param {number} currentTime
  13535. * The current time
  13536. * @param {Double} mapping
  13537. * Offset to map display time to stream presentation time
  13538. * @return {Array}
  13539. * List of gops considered safe to append over
  13540. */
  13541. const gopsSafeToAlignWith = (buffer, currentTime, mapping) => {
  13542. if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
  13543. return [];
  13544. } // pts value for current time + 3 seconds to give a bit more wiggle room
  13545. const currentTimePts = Math.ceil((currentTime - mapping + 3) * ONE_SECOND_IN_TS);
  13546. let i;
  13547. for (i = 0; i < buffer.length; i++) {
  13548. if (buffer[i].pts > currentTimePts) {
  13549. break;
  13550. }
  13551. }
  13552. return buffer.slice(i);
  13553. };
  13554. /**
  13555. * Appends gop information (timing and byteLength) received by the transmuxer for the
  13556. * gops appended in the last call to appendBuffer
  13557. *
  13558. * @param {Array} buffer
  13559. * The current buffer of gop information
  13560. * @param {Array} gops
  13561. * List of new gop information
  13562. * @param {boolean} replace
  13563. * If true, replace the buffer with the new gop information. If false, append the
  13564. * new gop information to the buffer in the right location of time.
  13565. * @return {Array}
  13566. * Updated list of gop information
  13567. */
  13568. const updateGopBuffer = (buffer, gops, replace) => {
  13569. if (!gops.length) {
  13570. return buffer;
  13571. }
  13572. if (replace) {
  13573. // If we are in safe append mode, then completely overwrite the gop buffer
  13574. // with the most recent appeneded data. This will make sure that when appending
  13575. // future segments, we only try to align with gops that are both ahead of current
  13576. // time and in the last segment appended.
  13577. return gops.slice();
  13578. }
  13579. const start = gops[0].pts;
  13580. let i = 0;
  13581. for (i; i < buffer.length; i++) {
  13582. if (buffer[i].pts >= start) {
  13583. break;
  13584. }
  13585. }
  13586. return buffer.slice(0, i).concat(gops);
  13587. };
  13588. /**
  13589. * Removes gop information in buffer that overlaps with provided start and end
  13590. *
  13591. * @param {Array} buffer
  13592. * The current buffer of gop information
  13593. * @param {Double} start
  13594. * position to start the remove at
  13595. * @param {Double} end
  13596. * position to end the remove at
  13597. * @param {Double} mapping
  13598. * Offset to map display time to stream presentation time
  13599. */
  13600. const removeGopBuffer = (buffer, start, end, mapping) => {
  13601. const startPts = Math.ceil((start - mapping) * ONE_SECOND_IN_TS);
  13602. const endPts = Math.ceil((end - mapping) * ONE_SECOND_IN_TS);
  13603. const updatedBuffer = buffer.slice();
  13604. let i = buffer.length;
  13605. while (i--) {
  13606. if (buffer[i].pts <= endPts) {
  13607. break;
  13608. }
  13609. }
  13610. if (i === -1) {
  13611. // no removal because end of remove range is before start of buffer
  13612. return updatedBuffer;
  13613. }
  13614. let j = i + 1;
  13615. while (j--) {
  13616. if (buffer[j].pts <= startPts) {
  13617. break;
  13618. }
  13619. } // clamp remove range start to 0 index
  13620. j = Math.max(j, 0);
  13621. updatedBuffer.splice(j, i - j + 1);
  13622. return updatedBuffer;
  13623. };
  13624. const shallowEqual = function (a, b) {
  13625. // if both are undefined
  13626. // or one or the other is undefined
  13627. // they are not equal
  13628. if (!a && !b || !a && b || a && !b) {
  13629. return false;
  13630. } // they are the same object and thus, equal
  13631. if (a === b) {
  13632. return true;
  13633. } // sort keys so we can make sure they have
  13634. // all the same keys later.
  13635. const akeys = Object.keys(a).sort();
  13636. const bkeys = Object.keys(b).sort(); // different number of keys, not equal
  13637. if (akeys.length !== bkeys.length) {
  13638. return false;
  13639. }
  13640. for (let i = 0; i < akeys.length; i++) {
  13641. const key = akeys[i]; // different sorted keys, not equal
  13642. if (key !== bkeys[i]) {
  13643. return false;
  13644. } // different values, not equal
  13645. if (a[key] !== b[key]) {
  13646. return false;
  13647. }
  13648. }
  13649. return true;
  13650. };
  13651. // https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
  13652. const QUOTA_EXCEEDED_ERR = 22;
  13653. /**
  13654. * The segment loader has no recourse except to fetch a segment in the
  13655. * current playlist and use the internal timestamps in that segment to
  13656. * generate a syncPoint. This function returns a good candidate index
  13657. * for that process.
  13658. *
  13659. * @param {Array} segments - the segments array from a playlist.
  13660. * @return {number} An index of a segment from the playlist to load
  13661. */
  13662. const getSyncSegmentCandidate = function (currentTimeline, segments, targetTime) {
  13663. segments = segments || [];
  13664. const timelineSegments = [];
  13665. let time = 0;
  13666. for (let i = 0; i < segments.length; i++) {
  13667. const segment = segments[i];
  13668. if (currentTimeline === segment.timeline) {
  13669. timelineSegments.push(i);
  13670. time += segment.duration;
  13671. if (time > targetTime) {
  13672. return i;
  13673. }
  13674. }
  13675. }
  13676. if (timelineSegments.length === 0) {
  13677. return 0;
  13678. } // default to the last timeline segment
  13679. return timelineSegments[timelineSegments.length - 1];
  13680. }; // In the event of a quota exceeded error, keep at least one second of back buffer. This
  13681. // number was arbitrarily chosen and may be updated in the future, but seemed reasonable
  13682. // as a start to prevent any potential issues with removing content too close to the
  13683. // playhead.
  13684. const MIN_BACK_BUFFER = 1; // in ms
  13685. const CHECK_BUFFER_DELAY = 500;
  13686. const finite = num => typeof num === 'number' && isFinite(num); // With most content hovering around 30fps, if a segment has a duration less than a half
  13687. // frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
  13688. // not accurately reflect the rest of the content.
  13689. const MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
  13690. const illegalMediaSwitch = (loaderType, startingMedia, trackInfo) => {
  13691. // Although these checks should most likely cover non 'main' types, for now it narrows
  13692. // the scope of our checks.
  13693. if (loaderType !== 'main' || !startingMedia || !trackInfo) {
  13694. return null;
  13695. }
  13696. if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
  13697. return 'Neither audio nor video found in segment.';
  13698. }
  13699. if (startingMedia.hasVideo && !trackInfo.hasVideo) {
  13700. 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.';
  13701. }
  13702. if (!startingMedia.hasVideo && trackInfo.hasVideo) {
  13703. 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.';
  13704. }
  13705. return null;
  13706. };
  13707. /**
  13708. * Calculates a time value that is safe to remove from the back buffer without interrupting
  13709. * playback.
  13710. *
  13711. * @param {TimeRange} seekable
  13712. * The current seekable range
  13713. * @param {number} currentTime
  13714. * The current time of the player
  13715. * @param {number} targetDuration
  13716. * The target duration of the current playlist
  13717. * @return {number}
  13718. * Time that is safe to remove from the back buffer without interrupting playback
  13719. */
  13720. const safeBackBufferTrimTime = (seekable, currentTime, targetDuration) => {
  13721. // 30 seconds before the playhead provides a safe default for trimming.
  13722. //
  13723. // Choosing a reasonable default is particularly important for high bitrate content and
  13724. // VOD videos/live streams with large windows, as the buffer may end up overfilled and
  13725. // throw an APPEND_BUFFER_ERR.
  13726. let trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
  13727. if (seekable.length) {
  13728. // Some live playlists may have a shorter window of content than the full allowed back
  13729. // buffer. For these playlists, don't save content that's no longer within the window.
  13730. trimTime = Math.max(trimTime, seekable.start(0));
  13731. } // Don't remove within target duration of the current time to avoid the possibility of
  13732. // removing the GOP currently being played, as removing it can cause playback stalls.
  13733. const maxTrimTime = currentTime - targetDuration;
  13734. return Math.min(maxTrimTime, trimTime);
  13735. };
  13736. const segmentInfoString = segmentInfo => {
  13737. const {
  13738. startOfSegment,
  13739. duration,
  13740. segment,
  13741. part,
  13742. playlist: {
  13743. mediaSequence: seq,
  13744. id,
  13745. segments = []
  13746. },
  13747. mediaIndex: index,
  13748. partIndex,
  13749. timeline
  13750. } = segmentInfo;
  13751. const segmentLen = segments.length - 1;
  13752. let selection = 'mediaIndex/partIndex increment';
  13753. if (segmentInfo.getMediaInfoForTime) {
  13754. selection = `getMediaInfoForTime (${segmentInfo.getMediaInfoForTime})`;
  13755. } else if (segmentInfo.isSyncRequest) {
  13756. selection = 'getSyncSegmentCandidate (isSyncRequest)';
  13757. }
  13758. if (segmentInfo.independent) {
  13759. selection += ` with independent ${segmentInfo.independent}`;
  13760. }
  13761. const hasPartIndex = typeof partIndex === 'number';
  13762. const name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
  13763. const zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
  13764. preloadSegment: segment
  13765. }) - 1 : 0;
  13766. 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}]`;
  13767. };
  13768. const timingInfoPropertyForMedia = mediaType => `${mediaType}TimingInfo`;
  13769. /**
  13770. * Returns the timestamp offset to use for the segment.
  13771. *
  13772. * @param {number} segmentTimeline
  13773. * The timeline of the segment
  13774. * @param {number} currentTimeline
  13775. * The timeline currently being followed by the loader
  13776. * @param {number} startOfSegment
  13777. * The estimated segment start
  13778. * @param {TimeRange[]} buffered
  13779. * The loader's buffer
  13780. * @param {boolean} overrideCheck
  13781. * If true, no checks are made to see if the timestamp offset value should be set,
  13782. * but sets it directly to a value.
  13783. *
  13784. * @return {number|null}
  13785. * Either a number representing a new timestamp offset, or null if the segment is
  13786. * part of the same timeline
  13787. */
  13788. const timestampOffsetForSegment = ({
  13789. segmentTimeline,
  13790. currentTimeline,
  13791. startOfSegment,
  13792. buffered,
  13793. overrideCheck
  13794. }) => {
  13795. // Check to see if we are crossing a discontinuity to see if we need to set the
  13796. // timestamp offset on the transmuxer and source buffer.
  13797. //
  13798. // Previously, we changed the timestampOffset if the start of this segment was less than
  13799. // the currently set timestampOffset, but this isn't desirable as it can produce bad
  13800. // behavior, especially around long running live streams.
  13801. if (!overrideCheck && segmentTimeline === currentTimeline) {
  13802. return null;
  13803. } // When changing renditions, it's possible to request a segment on an older timeline. For
  13804. // instance, given two renditions with the following:
  13805. //
  13806. // #EXTINF:10
  13807. // segment1
  13808. // #EXT-X-DISCONTINUITY
  13809. // #EXTINF:10
  13810. // segment2
  13811. // #EXTINF:10
  13812. // segment3
  13813. //
  13814. // And the current player state:
  13815. //
  13816. // current time: 8
  13817. // buffer: 0 => 20
  13818. //
  13819. // The next segment on the current rendition would be segment3, filling the buffer from
  13820. // 20s onwards. However, if a rendition switch happens after segment2 was requested,
  13821. // then the next segment to be requested will be segment1 from the new rendition in
  13822. // order to fill time 8 and onwards. Using the buffered end would result in repeated
  13823. // content (since it would position segment1 of the new rendition starting at 20s). This
  13824. // case can be identified when the new segment's timeline is a prior value. Instead of
  13825. // using the buffered end, the startOfSegment can be used, which, hopefully, will be
  13826. // more accurate to the actual start time of the segment.
  13827. if (segmentTimeline < currentTimeline) {
  13828. return startOfSegment;
  13829. } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
  13830. // value uses the end of the last segment if it is available. While this value
  13831. // should often be correct, it's better to rely on the buffered end, as the new
  13832. // content post discontinuity should line up with the buffered end as if it were
  13833. // time 0 for the new content.
  13834. return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
  13835. };
  13836. /**
  13837. * Returns whether or not the loader should wait for a timeline change from the timeline
  13838. * change controller before processing the segment.
  13839. *
  13840. * Primary timing in VHS goes by video. This is different from most media players, as
  13841. * audio is more often used as the primary timing source. For the foreseeable future, VHS
  13842. * will continue to use video as the primary timing source, due to the current logic and
  13843. * expectations built around it.
  13844. * Since the timing follows video, in order to maintain sync, the video loader is
  13845. * responsible for setting both audio and video source buffer timestamp offsets.
  13846. *
  13847. * Setting different values for audio and video source buffers could lead to
  13848. * desyncing. The following examples demonstrate some of the situations where this
  13849. * distinction is important. Note that all of these cases involve demuxed content. When
  13850. * content is muxed, the audio and video are packaged together, therefore syncing
  13851. * separate media playlists is not an issue.
  13852. *
  13853. * CASE 1: Audio prepares to load a new timeline before video:
  13854. *
  13855. * Timeline: 0 1
  13856. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13857. * Audio Loader: ^
  13858. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13859. * Video Loader ^
  13860. *
  13861. * In the above example, the audio loader is preparing to load the 6th segment, the first
  13862. * after a discontinuity, while the video loader is still loading the 5th segment, before
  13863. * the discontinuity.
  13864. *
  13865. * If the audio loader goes ahead and loads and appends the 6th segment before the video
  13866. * loader crosses the discontinuity, then when appended, the 6th audio segment will use
  13867. * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
  13868. * the audio loader must provide the audioAppendStart value to trim the content in the
  13869. * transmuxer, and that value relies on the audio timestamp offset. Since the audio
  13870. * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
  13871. * segment until that value is provided.
  13872. *
  13873. * CASE 2: Video prepares to load a new timeline before audio:
  13874. *
  13875. * Timeline: 0 1
  13876. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13877. * Audio Loader: ^
  13878. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13879. * Video Loader ^
  13880. *
  13881. * In the above example, the video loader is preparing to load the 6th segment, the first
  13882. * after a discontinuity, while the audio loader is still loading the 5th segment, before
  13883. * the discontinuity.
  13884. *
  13885. * If the video loader goes ahead and loads and appends the 6th segment, then once the
  13886. * segment is loaded and processed, both the video and audio timestamp offsets will be
  13887. * set, since video is used as the primary timing source. This is to ensure content lines
  13888. * up appropriately, as any modifications to the video timing are reflected by audio when
  13889. * the video loader sets the audio and video timestamp offsets to the same value. However,
  13890. * setting the timestamp offset for audio before audio has had a chance to change
  13891. * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
  13892. * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
  13893. *
  13894. * CASE 3: When seeking, audio prepares to load a new timeline before video
  13895. *
  13896. * Timeline: 0 1
  13897. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13898. * Audio Loader: ^
  13899. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13900. * Video Loader ^
  13901. *
  13902. * In the above example, both audio and video loaders are loading segments from timeline
  13903. * 0, but imagine that the seek originated from timeline 1.
  13904. *
  13905. * When seeking to a new timeline, the timestamp offset will be set based on the expected
  13906. * segment start of the loaded video segment. In order to maintain sync, the audio loader
  13907. * must wait for the video loader to load its segment and update both the audio and video
  13908. * timestamp offsets before it may load and append its own segment. This is the case
  13909. * whether the seek results in a mismatched segment request (e.g., the audio loader
  13910. * chooses to load segment 3 and the video loader chooses to load segment 4) or the
  13911. * loaders choose to load the same segment index from each playlist, as the segments may
  13912. * not be aligned perfectly, even for matching segment indexes.
  13913. *
  13914. * @param {Object} timelinechangeController
  13915. * @param {number} currentTimeline
  13916. * The timeline currently being followed by the loader
  13917. * @param {number} segmentTimeline
  13918. * The timeline of the segment being loaded
  13919. * @param {('main'|'audio')} loaderType
  13920. * The loader type
  13921. * @param {boolean} audioDisabled
  13922. * Whether the audio is disabled for the loader. This should only be true when the
  13923. * loader may have muxed audio in its segment, but should not append it, e.g., for
  13924. * the main loader when an alternate audio playlist is active.
  13925. *
  13926. * @return {boolean}
  13927. * Whether the loader should wait for a timeline change from the timeline change
  13928. * controller before processing the segment
  13929. */
  13930. const shouldWaitForTimelineChange = ({
  13931. timelineChangeController,
  13932. currentTimeline,
  13933. segmentTimeline,
  13934. loaderType,
  13935. audioDisabled
  13936. }) => {
  13937. if (currentTimeline === segmentTimeline) {
  13938. return false;
  13939. }
  13940. if (loaderType === 'audio') {
  13941. const lastMainTimelineChange = timelineChangeController.lastTimelineChange({
  13942. type: 'main'
  13943. }); // Audio loader should wait if:
  13944. //
  13945. // * main hasn't had a timeline change yet (thus has not loaded its first segment)
  13946. // * main hasn't yet changed to the timeline audio is looking to load
  13947. return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
  13948. } // The main loader only needs to wait for timeline changes if there's demuxed audio.
  13949. // Otherwise, there's nothing to wait for, since audio would be muxed into the main
  13950. // loader's segments (or the content is audio/video only and handled by the main
  13951. // loader).
  13952. if (loaderType === 'main' && audioDisabled) {
  13953. const pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
  13954. type: 'audio'
  13955. }); // Main loader should wait for the audio loader if audio is not pending a timeline
  13956. // change to the current timeline.
  13957. //
  13958. // Since the main loader is responsible for setting the timestamp offset for both
  13959. // audio and video, the main loader must wait for audio to be about to change to its
  13960. // timeline before setting the offset, otherwise, if audio is behind in loading,
  13961. // segments from the previous timeline would be adjusted by the new timestamp offset.
  13962. //
  13963. // This requirement means that video will not cross a timeline until the audio is
  13964. // about to cross to it, so that way audio and video will always cross the timeline
  13965. // together.
  13966. //
  13967. // In addition to normal timeline changes, these rules also apply to the start of a
  13968. // stream (going from a non-existent timeline, -1, to timeline 0). It's important
  13969. // that these rules apply to the first timeline change because if they did not, it's
  13970. // possible that the main loader will cross two timelines before the audio loader has
  13971. // crossed one. Logic may be implemented to handle the startup as a special case, but
  13972. // it's easier to simply treat all timeline changes the same.
  13973. if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
  13974. return false;
  13975. }
  13976. return true;
  13977. }
  13978. return false;
  13979. };
  13980. const mediaDuration = timingInfos => {
  13981. let maxDuration = 0;
  13982. ['video', 'audio'].forEach(function (type) {
  13983. const typeTimingInfo = timingInfos[`${type}TimingInfo`];
  13984. if (!typeTimingInfo) {
  13985. return;
  13986. }
  13987. const {
  13988. start,
  13989. end
  13990. } = typeTimingInfo;
  13991. let duration;
  13992. if (typeof start === 'bigint' || typeof end === 'bigint') {
  13993. duration = window$1.BigInt(end) - window$1.BigInt(start);
  13994. } else if (typeof start === 'number' && typeof end === 'number') {
  13995. duration = end - start;
  13996. }
  13997. if (typeof duration !== 'undefined' && duration > maxDuration) {
  13998. maxDuration = duration;
  13999. }
  14000. }); // convert back to a number if it is lower than MAX_SAFE_INTEGER
  14001. // as we only need BigInt when we are above that.
  14002. if (typeof maxDuration === 'bigint' && maxDuration < Number.MAX_SAFE_INTEGER) {
  14003. maxDuration = Number(maxDuration);
  14004. }
  14005. return maxDuration;
  14006. };
  14007. const segmentTooLong = ({
  14008. segmentDuration,
  14009. maxDuration
  14010. }) => {
  14011. // 0 duration segments are most likely due to metadata only segments or a lack of
  14012. // information.
  14013. if (!segmentDuration) {
  14014. return false;
  14015. } // For HLS:
  14016. //
  14017. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
  14018. // The EXTINF duration of each Media Segment in the Playlist
  14019. // file, when rounded to the nearest integer, MUST be less than or equal
  14020. // to the target duration; longer segments can trigger playback stalls
  14021. // or other errors.
  14022. //
  14023. // For DASH, the mpd-parser uses the largest reported segment duration as the target
  14024. // duration. Although that reported duration is occasionally approximate (i.e., not
  14025. // exact), a strict check may report that a segment is too long more often in DASH.
  14026. return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
  14027. };
  14028. const getTroublesomeSegmentDurationMessage = (segmentInfo, sourceType) => {
  14029. // Right now we aren't following DASH's timing model exactly, so only perform
  14030. // this check for HLS content.
  14031. if (sourceType !== 'hls') {
  14032. return null;
  14033. }
  14034. const segmentDuration = mediaDuration({
  14035. audioTimingInfo: segmentInfo.audioTimingInfo,
  14036. videoTimingInfo: segmentInfo.videoTimingInfo
  14037. }); // Don't report if we lack information.
  14038. //
  14039. // If the segment has a duration of 0 it is either a lack of information or a
  14040. // metadata only segment and shouldn't be reported here.
  14041. if (!segmentDuration) {
  14042. return null;
  14043. }
  14044. const targetDuration = segmentInfo.playlist.targetDuration;
  14045. const isSegmentWayTooLong = segmentTooLong({
  14046. segmentDuration,
  14047. maxDuration: targetDuration * 2
  14048. });
  14049. const isSegmentSlightlyTooLong = segmentTooLong({
  14050. segmentDuration,
  14051. maxDuration: targetDuration
  14052. });
  14053. 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';
  14054. if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
  14055. return {
  14056. severity: isSegmentWayTooLong ? 'warn' : 'info',
  14057. message: segmentTooLongMessage
  14058. };
  14059. }
  14060. return null;
  14061. };
  14062. /**
  14063. * An object that manages segment loading and appending.
  14064. *
  14065. * @class SegmentLoader
  14066. * @param {Object} options required and optional options
  14067. * @extends videojs.EventTarget
  14068. */
  14069. class SegmentLoader extends videojs.EventTarget {
  14070. constructor(settings, options = {}) {
  14071. super(); // check pre-conditions
  14072. if (!settings) {
  14073. throw new TypeError('Initialization settings are required');
  14074. }
  14075. if (typeof settings.currentTime !== 'function') {
  14076. throw new TypeError('No currentTime getter specified');
  14077. }
  14078. if (!settings.mediaSource) {
  14079. throw new TypeError('No MediaSource specified');
  14080. } // public properties
  14081. this.bandwidth = settings.bandwidth;
  14082. this.throughput = {
  14083. rate: 0,
  14084. count: 0
  14085. };
  14086. this.roundTrip = NaN;
  14087. this.resetStats_();
  14088. this.mediaIndex = null;
  14089. this.partIndex = null; // private settings
  14090. this.hasPlayed_ = settings.hasPlayed;
  14091. this.currentTime_ = settings.currentTime;
  14092. this.seekable_ = settings.seekable;
  14093. this.seeking_ = settings.seeking;
  14094. this.duration_ = settings.duration;
  14095. this.mediaSource_ = settings.mediaSource;
  14096. this.vhs_ = settings.vhs;
  14097. this.loaderType_ = settings.loaderType;
  14098. this.currentMediaInfo_ = void 0;
  14099. this.startingMediaInfo_ = void 0;
  14100. this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
  14101. this.goalBufferLength_ = settings.goalBufferLength;
  14102. this.sourceType_ = settings.sourceType;
  14103. this.sourceUpdater_ = settings.sourceUpdater;
  14104. this.inbandTextTracks_ = settings.inbandTextTracks;
  14105. this.state_ = 'INIT';
  14106. this.timelineChangeController_ = settings.timelineChangeController;
  14107. this.shouldSaveSegmentTimingInfo_ = true;
  14108. this.parse708captions_ = settings.parse708captions;
  14109. this.useDtsForTimestampOffset_ = settings.useDtsForTimestampOffset;
  14110. this.captionServices_ = settings.captionServices;
  14111. this.exactManifestTimings = settings.exactManifestTimings;
  14112. this.addMetadataToTextTrack = settings.addMetadataToTextTrack; // private instance variables
  14113. this.checkBufferTimeout_ = null;
  14114. this.error_ = void 0;
  14115. this.currentTimeline_ = -1;
  14116. this.shouldForceTimestampOffsetAfterResync_ = false;
  14117. this.pendingSegment_ = null;
  14118. this.xhrOptions_ = null;
  14119. this.pendingSegments_ = [];
  14120. this.audioDisabled_ = false;
  14121. this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller
  14122. this.gopBuffer_ = [];
  14123. this.timeMapping_ = 0;
  14124. this.safeAppend_ = false;
  14125. this.appendInitSegment_ = {
  14126. audio: true,
  14127. video: true
  14128. };
  14129. this.playlistOfLastInitSegment_ = {
  14130. audio: null,
  14131. video: null
  14132. };
  14133. this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough
  14134. // information yet to start the loading process (e.g., if the audio loader wants to
  14135. // load a segment from the next timeline but the main loader hasn't yet crossed that
  14136. // timeline), then the load call will be added to the queue until it is ready to be
  14137. // processed.
  14138. this.loadQueue_ = [];
  14139. this.metadataQueue_ = {
  14140. id3: [],
  14141. caption: []
  14142. };
  14143. this.waitingOnRemove_ = false;
  14144. this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback
  14145. this.activeInitSegmentId_ = null;
  14146. this.initSegments_ = {}; // HLSe playback
  14147. this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
  14148. this.keyCache_ = {};
  14149. this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings
  14150. // between a time in the display time and a segment index within
  14151. // a playlist
  14152. this.syncController_ = settings.syncController;
  14153. this.syncPoint_ = {
  14154. segmentIndex: 0,
  14155. time: 0
  14156. };
  14157. this.transmuxer_ = this.createTransmuxer_();
  14158. this.triggerSyncInfoUpdate_ = () => this.trigger('syncinfoupdate');
  14159. this.syncController_.on('syncinfoupdate', this.triggerSyncInfoUpdate_);
  14160. this.mediaSource_.addEventListener('sourceopen', () => {
  14161. if (!this.isEndOfStream_()) {
  14162. this.ended_ = false;
  14163. }
  14164. }); // ...for determining the fetch location
  14165. this.fetchAtBuffer_ = false;
  14166. this.logger_ = logger(`SegmentLoader[${this.loaderType_}]`);
  14167. Object.defineProperty(this, 'state', {
  14168. get() {
  14169. return this.state_;
  14170. },
  14171. set(newState) {
  14172. if (newState !== this.state_) {
  14173. this.logger_(`${this.state_} -> ${newState}`);
  14174. this.state_ = newState;
  14175. this.trigger('statechange');
  14176. }
  14177. }
  14178. });
  14179. this.sourceUpdater_.on('ready', () => {
  14180. if (this.hasEnoughInfoToAppend_()) {
  14181. this.processCallQueue_();
  14182. }
  14183. }); // Only the main loader needs to listen for pending timeline changes, as the main
  14184. // loader should wait for audio to be ready to change its timeline so that both main
  14185. // and audio timelines change together. For more details, see the
  14186. // shouldWaitForTimelineChange function.
  14187. if (this.loaderType_ === 'main') {
  14188. this.timelineChangeController_.on('pendingtimelinechange', () => {
  14189. if (this.hasEnoughInfoToAppend_()) {
  14190. this.processCallQueue_();
  14191. }
  14192. });
  14193. } // The main loader only listens on pending timeline changes, but the audio loader,
  14194. // since its loads follow main, needs to listen on timeline changes. For more details,
  14195. // see the shouldWaitForTimelineChange function.
  14196. if (this.loaderType_ === 'audio') {
  14197. this.timelineChangeController_.on('timelinechange', () => {
  14198. if (this.hasEnoughInfoToLoad_()) {
  14199. this.processLoadQueue_();
  14200. }
  14201. if (this.hasEnoughInfoToAppend_()) {
  14202. this.processCallQueue_();
  14203. }
  14204. });
  14205. }
  14206. }
  14207. createTransmuxer_() {
  14208. return segmentTransmuxer.createTransmuxer({
  14209. remux: false,
  14210. alignGopsAtEnd: this.safeAppend_,
  14211. keepOriginalTimestamps: true,
  14212. parse708captions: this.parse708captions_,
  14213. captionServices: this.captionServices_
  14214. });
  14215. }
  14216. /**
  14217. * reset all of our media stats
  14218. *
  14219. * @private
  14220. */
  14221. resetStats_() {
  14222. this.mediaBytesTransferred = 0;
  14223. this.mediaRequests = 0;
  14224. this.mediaRequestsAborted = 0;
  14225. this.mediaRequestsTimedout = 0;
  14226. this.mediaRequestsErrored = 0;
  14227. this.mediaTransferDuration = 0;
  14228. this.mediaSecondsLoaded = 0;
  14229. this.mediaAppends = 0;
  14230. }
  14231. /**
  14232. * dispose of the SegmentLoader and reset to the default state
  14233. */
  14234. dispose() {
  14235. this.trigger('dispose');
  14236. this.state = 'DISPOSED';
  14237. this.pause();
  14238. this.abort_();
  14239. if (this.transmuxer_) {
  14240. this.transmuxer_.terminate();
  14241. }
  14242. this.resetStats_();
  14243. if (this.checkBufferTimeout_) {
  14244. window$1.clearTimeout(this.checkBufferTimeout_);
  14245. }
  14246. if (this.syncController_ && this.triggerSyncInfoUpdate_) {
  14247. this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
  14248. }
  14249. this.off();
  14250. }
  14251. setAudio(enable) {
  14252. this.audioDisabled_ = !enable;
  14253. if (enable) {
  14254. this.appendInitSegment_.audio = true;
  14255. } else {
  14256. // remove current track audio if it gets disabled
  14257. this.sourceUpdater_.removeAudio(0, this.duration_());
  14258. }
  14259. }
  14260. /**
  14261. * abort anything that is currently doing on with the SegmentLoader
  14262. * and reset to a default state
  14263. */
  14264. abort() {
  14265. if (this.state !== 'WAITING') {
  14266. if (this.pendingSegment_) {
  14267. this.pendingSegment_ = null;
  14268. }
  14269. return;
  14270. }
  14271. this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY
  14272. // since we are no longer "waiting" on any requests. XHR callback is not always run
  14273. // when the request is aborted. This will prevent the loader from being stuck in the
  14274. // WAITING state indefinitely.
  14275. this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the
  14276. // next segment
  14277. if (!this.paused()) {
  14278. this.monitorBuffer_();
  14279. }
  14280. }
  14281. /**
  14282. * abort all pending xhr requests and null any pending segements
  14283. *
  14284. * @private
  14285. */
  14286. abort_() {
  14287. if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
  14288. this.pendingSegment_.abortRequests();
  14289. } // clear out the segment being processed
  14290. this.pendingSegment_ = null;
  14291. this.callQueue_ = [];
  14292. this.loadQueue_ = [];
  14293. this.metadataQueue_.id3 = [];
  14294. this.metadataQueue_.caption = [];
  14295. this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
  14296. this.waitingOnRemove_ = false;
  14297. window$1.clearTimeout(this.quotaExceededErrorRetryTimeout_);
  14298. this.quotaExceededErrorRetryTimeout_ = null;
  14299. }
  14300. checkForAbort_(requestId) {
  14301. // If the state is APPENDING, then aborts will not modify the state, meaning the first
  14302. // callback that happens should reset the state to READY so that loading can continue.
  14303. if (this.state === 'APPENDING' && !this.pendingSegment_) {
  14304. this.state = 'READY';
  14305. return true;
  14306. }
  14307. if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
  14308. return true;
  14309. }
  14310. return false;
  14311. }
  14312. /**
  14313. * set an error on the segment loader and null out any pending segements
  14314. *
  14315. * @param {Error} error the error to set on the SegmentLoader
  14316. * @return {Error} the error that was set or that is currently set
  14317. */
  14318. error(error) {
  14319. if (typeof error !== 'undefined') {
  14320. this.logger_('error occurred:', error);
  14321. this.error_ = error;
  14322. }
  14323. this.pendingSegment_ = null;
  14324. return this.error_;
  14325. }
  14326. endOfStream() {
  14327. this.ended_ = true;
  14328. if (this.transmuxer_) {
  14329. // need to clear out any cached data to prepare for the new segment
  14330. segmentTransmuxer.reset(this.transmuxer_);
  14331. }
  14332. this.gopBuffer_.length = 0;
  14333. this.pause();
  14334. this.trigger('ended');
  14335. }
  14336. /**
  14337. * Indicates which time ranges are buffered
  14338. *
  14339. * @return {TimeRange}
  14340. * TimeRange object representing the current buffered ranges
  14341. */
  14342. buffered_() {
  14343. const trackInfo = this.getMediaInfo_();
  14344. if (!this.sourceUpdater_ || !trackInfo) {
  14345. return createTimeRanges();
  14346. }
  14347. if (this.loaderType_ === 'main') {
  14348. const {
  14349. hasAudio,
  14350. hasVideo,
  14351. isMuxed
  14352. } = trackInfo;
  14353. if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
  14354. return this.sourceUpdater_.buffered();
  14355. }
  14356. if (hasVideo) {
  14357. return this.sourceUpdater_.videoBuffered();
  14358. }
  14359. } // One case that can be ignored for now is audio only with alt audio,
  14360. // as we don't yet have proper support for that.
  14361. return this.sourceUpdater_.audioBuffered();
  14362. }
  14363. /**
  14364. * Gets and sets init segment for the provided map
  14365. *
  14366. * @param {Object} map
  14367. * The map object representing the init segment to get or set
  14368. * @param {boolean=} set
  14369. * If true, the init segment for the provided map should be saved
  14370. * @return {Object}
  14371. * map object for desired init segment
  14372. */
  14373. initSegmentForMap(map, set = false) {
  14374. if (!map) {
  14375. return null;
  14376. }
  14377. const id = initSegmentId(map);
  14378. let storedMap = this.initSegments_[id];
  14379. if (set && !storedMap && map.bytes) {
  14380. this.initSegments_[id] = storedMap = {
  14381. resolvedUri: map.resolvedUri,
  14382. byterange: map.byterange,
  14383. bytes: map.bytes,
  14384. tracks: map.tracks,
  14385. timescales: map.timescales
  14386. };
  14387. }
  14388. return storedMap || map;
  14389. }
  14390. /**
  14391. * Gets and sets key for the provided key
  14392. *
  14393. * @param {Object} key
  14394. * The key object representing the key to get or set
  14395. * @param {boolean=} set
  14396. * If true, the key for the provided key should be saved
  14397. * @return {Object}
  14398. * Key object for desired key
  14399. */
  14400. segmentKey(key, set = false) {
  14401. if (!key) {
  14402. return null;
  14403. }
  14404. const id = segmentKeyId(key);
  14405. let storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per
  14406. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
  14407. if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
  14408. this.keyCache_[id] = storedKey = {
  14409. resolvedUri: key.resolvedUri,
  14410. bytes: key.bytes
  14411. };
  14412. }
  14413. const result = {
  14414. resolvedUri: (storedKey || key).resolvedUri
  14415. };
  14416. if (storedKey) {
  14417. result.bytes = storedKey.bytes;
  14418. }
  14419. return result;
  14420. }
  14421. /**
  14422. * Returns true if all configuration required for loading is present, otherwise false.
  14423. *
  14424. * @return {boolean} True if the all configuration is ready for loading
  14425. * @private
  14426. */
  14427. couldBeginLoading_() {
  14428. return this.playlist_ && !this.paused();
  14429. }
  14430. /**
  14431. * load a playlist and start to fill the buffer
  14432. */
  14433. load() {
  14434. // un-pause
  14435. this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be
  14436. // specified
  14437. if (!this.playlist_) {
  14438. return;
  14439. } // if all the configuration is ready, initialize and begin loading
  14440. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  14441. return this.init_();
  14442. } // if we're in the middle of processing a segment already, don't
  14443. // kick off an additional segment request
  14444. if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {
  14445. return;
  14446. }
  14447. this.state = 'READY';
  14448. }
  14449. /**
  14450. * Once all the starting parameters have been specified, begin
  14451. * operation. This method should only be invoked from the INIT
  14452. * state.
  14453. *
  14454. * @private
  14455. */
  14456. init_() {
  14457. this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old
  14458. // audio data from the muxed content should be removed
  14459. this.resetEverything();
  14460. return this.monitorBuffer_();
  14461. }
  14462. /**
  14463. * set a playlist on the segment loader
  14464. *
  14465. * @param {PlaylistLoader} media the playlist to set on the segment loader
  14466. */
  14467. playlist(newPlaylist, options = {}) {
  14468. if (!newPlaylist) {
  14469. return;
  14470. }
  14471. const oldPlaylist = this.playlist_;
  14472. const segmentInfo = this.pendingSegment_;
  14473. this.playlist_ = newPlaylist;
  14474. this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist
  14475. // is always our zero-time so force a sync update each time the playlist
  14476. // is refreshed from the server
  14477. //
  14478. // Use the INIT state to determine if playback has started, as the playlist sync info
  14479. // should be fixed once requests begin (as sync points are generated based on sync
  14480. // info), but not before then.
  14481. if (this.state === 'INIT') {
  14482. newPlaylist.syncInfo = {
  14483. mediaSequence: newPlaylist.mediaSequence,
  14484. time: 0
  14485. }; // Setting the date time mapping means mapping the program date time (if available)
  14486. // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
  14487. // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
  14488. // be updated as the playlist is refreshed before the loader starts loading, the
  14489. // program date time mapping needs to be updated as well.
  14490. //
  14491. // This mapping is only done for the main loader because a program date time should
  14492. // map equivalently between playlists.
  14493. if (this.loaderType_ === 'main') {
  14494. this.syncController_.setDateTimeMappingForStart(newPlaylist);
  14495. }
  14496. }
  14497. let oldId = null;
  14498. if (oldPlaylist) {
  14499. if (oldPlaylist.id) {
  14500. oldId = oldPlaylist.id;
  14501. } else if (oldPlaylist.uri) {
  14502. oldId = oldPlaylist.uri;
  14503. }
  14504. }
  14505. this.logger_(`playlist update [${oldId} => ${newPlaylist.id || newPlaylist.uri}]`);
  14506. this.syncController_.updateMediaSequenceMap(newPlaylist, this.currentTime_(), this.loaderType_); // in VOD, this is always a rendition switch (or we updated our syncInfo above)
  14507. // in LIVE, we always want to update with new playlists (including refreshes)
  14508. this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
  14509. // buffering now
  14510. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  14511. return this.init_();
  14512. }
  14513. if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
  14514. if (this.mediaIndex !== null) {
  14515. // we must reset/resync the segment loader when we switch renditions and
  14516. // the segment loader is already synced to the previous rendition
  14517. // We only want to reset the loader here for LLHLS playback, as resetLoader sets fetchAtBuffer_
  14518. // to false, resulting in fetching segments at currentTime and causing repeated
  14519. // same-segment requests on playlist change. This erroneously drives up the playback watcher
  14520. // stalled segment count, as re-requesting segments at the currentTime or browser cached segments
  14521. // will not change the buffer.
  14522. // Reference for LLHLS fixes: https://github.com/videojs/http-streaming/pull/1201
  14523. const isLLHLS = !newPlaylist.endList && typeof newPlaylist.partTargetDuration === 'number';
  14524. if (isLLHLS) {
  14525. this.resetLoader();
  14526. } else {
  14527. this.resyncLoader();
  14528. }
  14529. }
  14530. this.currentMediaInfo_ = void 0;
  14531. this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined
  14532. return;
  14533. } // we reloaded the same playlist so we are in a live scenario
  14534. // and we will likely need to adjust the mediaIndex
  14535. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
  14536. this.logger_(`live window shift [${mediaSequenceDiff}]`); // update the mediaIndex on the SegmentLoader
  14537. // this is important because we can abort a request and this value must be
  14538. // equal to the last appended mediaIndex
  14539. if (this.mediaIndex !== null) {
  14540. this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist
  14541. // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
  14542. // new playlist was incremented by 1.
  14543. if (this.mediaIndex < 0) {
  14544. this.mediaIndex = null;
  14545. this.partIndex = null;
  14546. } else {
  14547. const segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment
  14548. // unless parts fell off of the playlist for this segment.
  14549. // In that case we need to reset partIndex and resync
  14550. if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
  14551. const mediaIndex = this.mediaIndex;
  14552. this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`);
  14553. this.resetLoader(); // We want to throw away the partIndex and the data associated with it,
  14554. // as the part was dropped from our current playlists segment.
  14555. // The mediaIndex will still be valid so keep that around.
  14556. this.mediaIndex = mediaIndex;
  14557. }
  14558. }
  14559. } // update the mediaIndex on the SegmentInfo object
  14560. // this is important because we will update this.mediaIndex with this value
  14561. // in `handleAppendsDone_` after the segment has been successfully appended
  14562. if (segmentInfo) {
  14563. segmentInfo.mediaIndex -= mediaSequenceDiff;
  14564. if (segmentInfo.mediaIndex < 0) {
  14565. segmentInfo.mediaIndex = null;
  14566. segmentInfo.partIndex = null;
  14567. } else {
  14568. // we need to update the referenced segment so that timing information is
  14569. // saved for the new playlist's segment, however, if the segment fell off the
  14570. // playlist, we can leave the old reference and just lose the timing info
  14571. if (segmentInfo.mediaIndex >= 0) {
  14572. segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
  14573. }
  14574. if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
  14575. segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
  14576. }
  14577. }
  14578. }
  14579. this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
  14580. }
  14581. /**
  14582. * Prevent the loader from fetching additional segments. If there
  14583. * is a segment request outstanding, it will finish processing
  14584. * before the loader halts. A segment loader can be unpaused by
  14585. * calling load().
  14586. */
  14587. pause() {
  14588. if (this.checkBufferTimeout_) {
  14589. window$1.clearTimeout(this.checkBufferTimeout_);
  14590. this.checkBufferTimeout_ = null;
  14591. }
  14592. }
  14593. /**
  14594. * Returns whether the segment loader is fetching additional
  14595. * segments when given the opportunity. This property can be
  14596. * modified through calls to pause() and load().
  14597. */
  14598. paused() {
  14599. return this.checkBufferTimeout_ === null;
  14600. }
  14601. /**
  14602. * Delete all the buffered data and reset the SegmentLoader
  14603. *
  14604. * @param {Function} [done] an optional callback to be executed when the remove
  14605. * operation is complete
  14606. */
  14607. resetEverything(done) {
  14608. this.ended_ = false;
  14609. this.activeInitSegmentId_ = null;
  14610. this.appendInitSegment_ = {
  14611. audio: true,
  14612. video: true
  14613. };
  14614. this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.
  14615. // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
  14616. // we then clamp the value to duration if necessary.
  14617. this.remove(0, Infinity, done); // clears fmp4 captions
  14618. if (this.transmuxer_) {
  14619. this.transmuxer_.postMessage({
  14620. action: 'clearAllMp4Captions'
  14621. }); // reset the cache in the transmuxer
  14622. this.transmuxer_.postMessage({
  14623. action: 'reset'
  14624. });
  14625. }
  14626. }
  14627. /**
  14628. * Force the SegmentLoader to resync and start loading around the currentTime instead
  14629. * of starting at the end of the buffer
  14630. *
  14631. * Useful for fast quality changes
  14632. */
  14633. resetLoader() {
  14634. this.fetchAtBuffer_ = false;
  14635. this.resyncLoader();
  14636. }
  14637. /**
  14638. * Force the SegmentLoader to restart synchronization and make a conservative guess
  14639. * before returning to the simple walk-forward method
  14640. */
  14641. resyncLoader() {
  14642. if (this.transmuxer_) {
  14643. // need to clear out any cached data to prepare for the new segment
  14644. segmentTransmuxer.reset(this.transmuxer_);
  14645. }
  14646. this.mediaIndex = null;
  14647. this.partIndex = null;
  14648. this.syncPoint_ = null;
  14649. this.isPendingTimestampOffset_ = false;
  14650. this.shouldForceTimestampOffsetAfterResync_ = true;
  14651. this.callQueue_ = [];
  14652. this.loadQueue_ = [];
  14653. this.metadataQueue_.id3 = [];
  14654. this.metadataQueue_.caption = [];
  14655. this.abort();
  14656. if (this.transmuxer_) {
  14657. this.transmuxer_.postMessage({
  14658. action: 'clearParsedMp4Captions'
  14659. });
  14660. }
  14661. }
  14662. /**
  14663. * Remove any data in the source buffer between start and end times
  14664. *
  14665. * @param {number} start - the start time of the region to remove from the buffer
  14666. * @param {number} end - the end time of the region to remove from the buffer
  14667. * @param {Function} [done] - an optional callback to be executed when the remove
  14668. * @param {boolean} force - force all remove operations to happen
  14669. * operation is complete
  14670. */
  14671. remove(start, end, done = () => {}, force = false) {
  14672. // clamp end to duration if we need to remove everything.
  14673. // This is due to a browser bug that causes issues if we remove to Infinity.
  14674. // videojs/videojs-contrib-hls#1225
  14675. if (end === Infinity) {
  14676. end = this.duration_();
  14677. } // skip removes that would throw an error
  14678. // commonly happens during a rendition switch at the start of a video
  14679. // from start 0 to end 0
  14680. if (end <= start) {
  14681. this.logger_('skipping remove because end ${end} is <= start ${start}');
  14682. return;
  14683. }
  14684. if (!this.sourceUpdater_ || !this.getMediaInfo_()) {
  14685. this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
  14686. return;
  14687. } // set it to one to complete this function's removes
  14688. let removesRemaining = 1;
  14689. const removeFinished = () => {
  14690. removesRemaining--;
  14691. if (removesRemaining === 0) {
  14692. done();
  14693. }
  14694. };
  14695. if (force || !this.audioDisabled_) {
  14696. removesRemaining++;
  14697. this.sourceUpdater_.removeAudio(start, end, removeFinished);
  14698. } // While it would be better to only remove video if the main loader has video, this
  14699. // should be safe with audio only as removeVideo will call back even if there's no
  14700. // video buffer.
  14701. //
  14702. // In theory we can check to see if there's video before calling the remove, but in
  14703. // the event that we're switching between renditions and from video to audio only
  14704. // (when we add support for that), we may need to clear the video contents despite
  14705. // what the new media will contain.
  14706. if (force || this.loaderType_ === 'main') {
  14707. this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
  14708. removesRemaining++;
  14709. this.sourceUpdater_.removeVideo(start, end, removeFinished);
  14710. } // remove any captions and ID3 tags
  14711. for (const track in this.inbandTextTracks_) {
  14712. removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
  14713. }
  14714. removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes
  14715. removeFinished();
  14716. }
  14717. /**
  14718. * (re-)schedule monitorBufferTick_ to run as soon as possible
  14719. *
  14720. * @private
  14721. */
  14722. monitorBuffer_() {
  14723. if (this.checkBufferTimeout_) {
  14724. window$1.clearTimeout(this.checkBufferTimeout_);
  14725. }
  14726. this.checkBufferTimeout_ = window$1.setTimeout(this.monitorBufferTick_.bind(this), 1);
  14727. }
  14728. /**
  14729. * As long as the SegmentLoader is in the READY state, periodically
  14730. * invoke fillBuffer_().
  14731. *
  14732. * @private
  14733. */
  14734. monitorBufferTick_() {
  14735. if (this.state === 'READY') {
  14736. this.fillBuffer_();
  14737. }
  14738. if (this.checkBufferTimeout_) {
  14739. window$1.clearTimeout(this.checkBufferTimeout_);
  14740. }
  14741. this.checkBufferTimeout_ = window$1.setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
  14742. }
  14743. /**
  14744. * fill the buffer with segements unless the sourceBuffers are
  14745. * currently updating
  14746. *
  14747. * Note: this function should only ever be called by monitorBuffer_
  14748. * and never directly
  14749. *
  14750. * @private
  14751. */
  14752. fillBuffer_() {
  14753. // TODO since the source buffer maintains a queue, and we shouldn't call this function
  14754. // except when we're ready for the next segment, this check can most likely be removed
  14755. if (this.sourceUpdater_.updating()) {
  14756. return;
  14757. } // see if we need to begin loading immediately
  14758. const segmentInfo = this.chooseNextRequest_();
  14759. if (!segmentInfo) {
  14760. return;
  14761. }
  14762. if (typeof segmentInfo.timestampOffset === 'number') {
  14763. this.isPendingTimestampOffset_ = false;
  14764. this.timelineChangeController_.pendingTimelineChange({
  14765. type: this.loaderType_,
  14766. from: this.currentTimeline_,
  14767. to: segmentInfo.timeline
  14768. });
  14769. }
  14770. this.loadSegment_(segmentInfo);
  14771. }
  14772. /**
  14773. * Determines if we should call endOfStream on the media source based
  14774. * on the state of the buffer or if appened segment was the final
  14775. * segment in the playlist.
  14776. *
  14777. * @param {number} [mediaIndex] the media index of segment we last appended
  14778. * @param {Object} [playlist] a media playlist object
  14779. * @return {boolean} do we need to call endOfStream on the MediaSource
  14780. */
  14781. isEndOfStream_(mediaIndex = this.mediaIndex, playlist = this.playlist_, partIndex = this.partIndex) {
  14782. if (!playlist || !this.mediaSource_) {
  14783. return false;
  14784. }
  14785. const segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based
  14786. const appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
  14787. 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
  14788. // so that MediaSources can trigger the `ended` event when it runs out of
  14789. // buffered data instead of waiting for me
  14790. return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;
  14791. }
  14792. /**
  14793. * Determines what request should be made given current segment loader state.
  14794. *
  14795. * @return {Object} a request object that describes the segment/part to load
  14796. */
  14797. chooseNextRequest_() {
  14798. const buffered = this.buffered_();
  14799. const bufferedEnd = lastBufferedEnd(buffered) || 0;
  14800. const bufferedTime = timeAheadOf(buffered, this.currentTime_());
  14801. const preloaded = !this.hasPlayed_() && bufferedTime >= 1;
  14802. const haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
  14803. const segments = this.playlist_.segments; // return no segment if:
  14804. // 1. we don't have segments
  14805. // 2. The video has not yet played and we already downloaded a segment
  14806. // 3. we already have enough buffered time
  14807. if (!segments.length || preloaded || haveEnoughBuffer) {
  14808. return null;
  14809. }
  14810. this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_(), this.loaderType_);
  14811. const next = {
  14812. partIndex: null,
  14813. mediaIndex: null,
  14814. startOfSegment: null,
  14815. playlist: this.playlist_,
  14816. isSyncRequest: Boolean(!this.syncPoint_)
  14817. };
  14818. if (next.isSyncRequest) {
  14819. next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
  14820. this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${next.mediaIndex}`);
  14821. } else if (this.mediaIndex !== null) {
  14822. const segment = segments[this.mediaIndex];
  14823. const partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
  14824. next.startOfSegment = segment.end ? segment.end : bufferedEnd;
  14825. if (segment.parts && segment.parts[partIndex + 1]) {
  14826. next.mediaIndex = this.mediaIndex;
  14827. next.partIndex = partIndex + 1;
  14828. } else {
  14829. next.mediaIndex = this.mediaIndex + 1;
  14830. }
  14831. } else {
  14832. // Find the segment containing the end of the buffer or current time.
  14833. const {
  14834. segmentIndex,
  14835. startTime,
  14836. partIndex
  14837. } = Playlist.getMediaInfoForTime({
  14838. exactManifestTimings: this.exactManifestTimings,
  14839. playlist: this.playlist_,
  14840. currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
  14841. startingPartIndex: this.syncPoint_.partIndex,
  14842. startingSegmentIndex: this.syncPoint_.segmentIndex,
  14843. startTime: this.syncPoint_.time
  14844. });
  14845. next.getMediaInfoForTime = this.fetchAtBuffer_ ? `bufferedEnd ${bufferedEnd}` : `currentTime ${this.currentTime_()}`;
  14846. next.mediaIndex = segmentIndex;
  14847. next.startOfSegment = startTime;
  14848. next.partIndex = partIndex;
  14849. this.logger_(`choose next request. Playlist switched and we have a sync point. Media Index: ${next.mediaIndex} `);
  14850. }
  14851. const nextSegment = segments[next.mediaIndex];
  14852. let nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or
  14853. // the next partIndex is invalid do not choose a next segment.
  14854. if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {
  14855. return null;
  14856. } // if the next segment has parts, and we don't have a partIndex.
  14857. // Set partIndex to 0
  14858. if (typeof next.partIndex !== 'number' && nextSegment.parts) {
  14859. next.partIndex = 0;
  14860. nextPart = nextSegment.parts[0];
  14861. } // independentSegments applies to every segment in a playlist. If independentSegments appears in a main playlist,
  14862. // it applies to each segment in each media playlist.
  14863. // https://datatracker.ietf.org/doc/html/draft-pantos-http-live-streaming-23#section-4.3.5.1
  14864. const hasIndependentSegments = this.vhs_.playlists && this.vhs_.playlists.main && this.vhs_.playlists.main.independentSegments || this.playlist_.independentSegments; // if we have no buffered data then we need to make sure
  14865. // that the next part we append is "independent" if possible.
  14866. // So we check if the previous part is independent, and request
  14867. // it if it is.
  14868. if (!bufferedTime && nextPart && !hasIndependentSegments && !nextPart.independent) {
  14869. if (next.partIndex === 0) {
  14870. const lastSegment = segments[next.mediaIndex - 1];
  14871. const lastSegmentLastPart = lastSegment.parts && lastSegment.parts.length && lastSegment.parts[lastSegment.parts.length - 1];
  14872. if (lastSegmentLastPart && lastSegmentLastPart.independent) {
  14873. next.mediaIndex -= 1;
  14874. next.partIndex = lastSegment.parts.length - 1;
  14875. next.independent = 'previous segment';
  14876. }
  14877. } else if (nextSegment.parts[next.partIndex - 1].independent) {
  14878. next.partIndex -= 1;
  14879. next.independent = 'previous part';
  14880. }
  14881. }
  14882. const ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:
  14883. // 1. this is the last segment in the playlist
  14884. // 2. end of stream has been called on the media source already
  14885. // 3. the player is not seeking
  14886. if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
  14887. return null;
  14888. }
  14889. if (this.shouldForceTimestampOffsetAfterResync_) {
  14890. this.shouldForceTimestampOffsetAfterResync_ = false;
  14891. next.forceTimestampOffset = true;
  14892. this.logger_('choose next request. Force timestamp offset after loader resync');
  14893. }
  14894. return this.generateSegmentInfo_(next);
  14895. }
  14896. generateSegmentInfo_(options) {
  14897. const {
  14898. independent,
  14899. playlist,
  14900. mediaIndex,
  14901. startOfSegment,
  14902. isSyncRequest,
  14903. partIndex,
  14904. forceTimestampOffset,
  14905. getMediaInfoForTime
  14906. } = options;
  14907. const segment = playlist.segments[mediaIndex];
  14908. const part = typeof partIndex === 'number' && segment.parts[partIndex];
  14909. const segmentInfo = {
  14910. requestId: 'segment-loader-' + Math.random(),
  14911. // resolve the segment URL relative to the playlist
  14912. uri: part && part.resolvedUri || segment.resolvedUri,
  14913. // the segment's mediaIndex at the time it was requested
  14914. mediaIndex,
  14915. partIndex: part ? partIndex : null,
  14916. // whether or not to update the SegmentLoader's state with this
  14917. // segment's mediaIndex
  14918. isSyncRequest,
  14919. startOfSegment,
  14920. // the segment's playlist
  14921. playlist,
  14922. // unencrypted bytes of the segment
  14923. bytes: null,
  14924. // when a key is defined for this segment, the encrypted bytes
  14925. encryptedBytes: null,
  14926. // The target timestampOffset for this segment when we append it
  14927. // to the source buffer
  14928. timestampOffset: null,
  14929. // The timeline that the segment is in
  14930. timeline: segment.timeline,
  14931. // The expected duration of the segment in seconds
  14932. duration: part && part.duration || segment.duration,
  14933. // retain the segment in case the playlist updates while doing an async process
  14934. segment,
  14935. part,
  14936. byteLength: 0,
  14937. transmuxer: this.transmuxer_,
  14938. // type of getMediaInfoForTime that was used to get this segment
  14939. getMediaInfoForTime,
  14940. independent
  14941. };
  14942. const overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
  14943. segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
  14944. segmentTimeline: segment.timeline,
  14945. currentTimeline: this.currentTimeline_,
  14946. startOfSegment,
  14947. buffered: this.buffered_(),
  14948. overrideCheck
  14949. });
  14950. const audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
  14951. if (typeof audioBufferedEnd === 'number') {
  14952. // since the transmuxer is using the actual timing values, but the buffer is
  14953. // adjusted by the timestamp offset, we must adjust the value here
  14954. segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
  14955. }
  14956. if (this.sourceUpdater_.videoBuffered().length) {
  14957. segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_, // since the transmuxer is using the actual timing values, but the time is
  14958. // adjusted by the timestmap offset, we must adjust the value here
  14959. this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);
  14960. }
  14961. return segmentInfo;
  14962. } // get the timestampoffset for a segment,
  14963. // added so that vtt segment loader can override and prevent
  14964. // adding timestamp offsets.
  14965. timestampOffsetForSegment_(options) {
  14966. return timestampOffsetForSegment(options);
  14967. }
  14968. /**
  14969. * Determines if the network has enough bandwidth to complete the current segment
  14970. * request in a timely manner. If not, the request will be aborted early and bandwidth
  14971. * updated to trigger a playlist switch.
  14972. *
  14973. * @param {Object} stats
  14974. * Object containing stats about the request timing and size
  14975. * @private
  14976. */
  14977. earlyAbortWhenNeeded_(stats) {
  14978. if (this.vhs_.tech_.paused() || // Don't abort if the current playlist is on the lowestEnabledRendition
  14979. // TODO: Replace using timeout with a boolean indicating whether this playlist is
  14980. // the lowestEnabledRendition.
  14981. !this.xhrOptions_.timeout || // Don't abort if we have no bandwidth information to estimate segment sizes
  14982. !this.playlist_.attributes.BANDWIDTH) {
  14983. return;
  14984. } // Wait at least 1 second since the first byte of data has been received before
  14985. // using the calculated bandwidth from the progress event to allow the bitrate
  14986. // to stabilize
  14987. if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
  14988. return;
  14989. }
  14990. const currentTime = this.currentTime_();
  14991. const measuredBandwidth = stats.bandwidth;
  14992. const segmentDuration = this.pendingSegment_.duration;
  14993. const requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
  14994. // if we are only left with less than 1 second when the request completes.
  14995. // A negative timeUntilRebuffering indicates we are already rebuffering
  14996. const timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download
  14997. // is larger than the estimated time until the player runs out of forward buffer
  14998. if (requestTimeRemaining <= timeUntilRebuffer$1) {
  14999. return;
  15000. }
  15001. const switchCandidate = minRebufferMaxBandwidthSelector({
  15002. main: this.vhs_.playlists.main,
  15003. currentTime,
  15004. bandwidth: measuredBandwidth,
  15005. duration: this.duration_(),
  15006. segmentDuration,
  15007. timeUntilRebuffer: timeUntilRebuffer$1,
  15008. currentTimeline: this.currentTimeline_,
  15009. syncController: this.syncController_
  15010. });
  15011. if (!switchCandidate) {
  15012. return;
  15013. }
  15014. const rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
  15015. const timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
  15016. let minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the
  15017. // potential round trip time of the new request so that we are not too aggressive
  15018. // with switching to a playlist that might save us a fraction of a second.
  15019. if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
  15020. minimumTimeSaving = 1;
  15021. }
  15022. if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
  15023. return;
  15024. } // set the bandwidth to that of the desired playlist being sure to scale by
  15025. // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
  15026. // don't trigger a bandwidthupdate as the bandwidth is artifial
  15027. this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
  15028. this.trigger('earlyabort');
  15029. }
  15030. handleAbort_(segmentInfo) {
  15031. this.logger_(`Aborting ${segmentInfoString(segmentInfo)}`);
  15032. this.mediaRequestsAborted += 1;
  15033. }
  15034. /**
  15035. * XHR `progress` event handler
  15036. *
  15037. * @param {Event}
  15038. * The XHR `progress` event
  15039. * @param {Object} simpleSegment
  15040. * A simplified segment object copy
  15041. * @private
  15042. */
  15043. handleProgress_(event, simpleSegment) {
  15044. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  15045. if (this.checkForAbort_(simpleSegment.requestId)) {
  15046. return;
  15047. }
  15048. this.trigger('progress');
  15049. }
  15050. handleTrackInfo_(simpleSegment, trackInfo) {
  15051. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  15052. if (this.checkForAbort_(simpleSegment.requestId)) {
  15053. return;
  15054. }
  15055. if (this.checkForIllegalMediaSwitch(trackInfo)) {
  15056. return;
  15057. }
  15058. trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.
  15059. // Guard against cases where we're not getting track info at all until we are
  15060. // certain that all streams will provide it.
  15061. if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
  15062. this.appendInitSegment_ = {
  15063. audio: true,
  15064. video: true
  15065. };
  15066. this.startingMediaInfo_ = trackInfo;
  15067. this.currentMediaInfo_ = trackInfo;
  15068. this.logger_('trackinfo update', trackInfo);
  15069. this.trigger('trackinfo');
  15070. } // trackinfo may cause an abort if the trackinfo
  15071. // causes a codec change to an unsupported codec.
  15072. if (this.checkForAbort_(simpleSegment.requestId)) {
  15073. return;
  15074. } // set trackinfo on the pending segment so that
  15075. // it can append.
  15076. this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info
  15077. if (this.hasEnoughInfoToAppend_()) {
  15078. this.processCallQueue_();
  15079. }
  15080. }
  15081. handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
  15082. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  15083. if (this.checkForAbort_(simpleSegment.requestId)) {
  15084. return;
  15085. }
  15086. const segmentInfo = this.pendingSegment_;
  15087. const timingInfoProperty = timingInfoPropertyForMedia(mediaType);
  15088. segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
  15089. segmentInfo[timingInfoProperty][timeType] = time;
  15090. this.logger_(`timinginfo: ${mediaType} - ${timeType} - ${time}`); // check if any calls were waiting on the timing info
  15091. if (this.hasEnoughInfoToAppend_()) {
  15092. this.processCallQueue_();
  15093. }
  15094. }
  15095. handleCaptions_(simpleSegment, captionData) {
  15096. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  15097. if (this.checkForAbort_(simpleSegment.requestId)) {
  15098. return;
  15099. } // This could only happen with fmp4 segments, but
  15100. // should still not happen in general
  15101. if (captionData.length === 0) {
  15102. this.logger_('SegmentLoader received no captions from a caption event');
  15103. return;
  15104. }
  15105. const segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing
  15106. // can be adjusted by the timestamp offset
  15107. if (!segmentInfo.hasAppendedData_) {
  15108. this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
  15109. return;
  15110. }
  15111. const timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
  15112. const captionTracks = {}; // get total start/end and captions for each track/stream
  15113. captionData.forEach(caption => {
  15114. // caption.stream is actually a track name...
  15115. // set to the existing values in tracks or default values
  15116. captionTracks[caption.stream] = captionTracks[caption.stream] || {
  15117. // Infinity, as any other value will be less than this
  15118. startTime: Infinity,
  15119. captions: [],
  15120. // 0 as an other value will be more than this
  15121. endTime: 0
  15122. };
  15123. const captionTrack = captionTracks[caption.stream];
  15124. captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);
  15125. captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);
  15126. captionTrack.captions.push(caption);
  15127. });
  15128. Object.keys(captionTracks).forEach(trackName => {
  15129. const {
  15130. startTime,
  15131. endTime,
  15132. captions
  15133. } = captionTracks[trackName];
  15134. const inbandTextTracks = this.inbandTextTracks_;
  15135. this.logger_(`adding cues from ${startTime} -> ${endTime} for ${trackName}`);
  15136. createCaptionsTrackIfNotExists(inbandTextTracks, this.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.
  15137. // We do this because a rendition change that also changes the timescale for captions
  15138. // will result in captions being re-parsed for certain segments. If we add them again
  15139. // without clearing we will have two of the same captions visible.
  15140. removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
  15141. addCaptionData({
  15142. captionArray: captions,
  15143. inbandTextTracks,
  15144. timestampOffset
  15145. });
  15146. }); // Reset stored captions since we added parsed
  15147. // captions to a text track at this point
  15148. if (this.transmuxer_) {
  15149. this.transmuxer_.postMessage({
  15150. action: 'clearParsedMp4Captions'
  15151. });
  15152. }
  15153. }
  15154. handleId3_(simpleSegment, id3Frames, dispatchType) {
  15155. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  15156. if (this.checkForAbort_(simpleSegment.requestId)) {
  15157. return;
  15158. }
  15159. const segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set
  15160. if (!segmentInfo.hasAppendedData_) {
  15161. this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
  15162. return;
  15163. }
  15164. this.addMetadataToTextTrack(dispatchType, id3Frames, this.duration_());
  15165. }
  15166. processMetadataQueue_() {
  15167. this.metadataQueue_.id3.forEach(fn => fn());
  15168. this.metadataQueue_.caption.forEach(fn => fn());
  15169. this.metadataQueue_.id3 = [];
  15170. this.metadataQueue_.caption = [];
  15171. }
  15172. processCallQueue_() {
  15173. const callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the
  15174. // functions may check the length of the load queue and default to pushing themselves
  15175. // back onto the queue.
  15176. this.callQueue_ = [];
  15177. callQueue.forEach(fun => fun());
  15178. }
  15179. processLoadQueue_() {
  15180. const loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the
  15181. // functions may check the length of the load queue and default to pushing themselves
  15182. // back onto the queue.
  15183. this.loadQueue_ = [];
  15184. loadQueue.forEach(fun => fun());
  15185. }
  15186. /**
  15187. * Determines whether the loader has enough info to load the next segment.
  15188. *
  15189. * @return {boolean}
  15190. * Whether or not the loader has enough info to load the next segment
  15191. */
  15192. hasEnoughInfoToLoad_() {
  15193. // Since primary timing goes by video, only the audio loader potentially needs to wait
  15194. // to load.
  15195. if (this.loaderType_ !== 'audio') {
  15196. return true;
  15197. }
  15198. const segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's
  15199. // enough info to load.
  15200. if (!segmentInfo) {
  15201. return false;
  15202. } // The first segment can and should be loaded immediately so that source buffers are
  15203. // created together (before appending). Source buffer creation uses the presence of
  15204. // audio and video data to determine whether to create audio/video source buffers, and
  15205. // uses processed (transmuxed or parsed) media to determine the types required.
  15206. if (!this.getCurrentMediaInfo_()) {
  15207. return true;
  15208. }
  15209. if ( // Technically, instead of waiting to load a segment on timeline changes, a segment
  15210. // can be requested and downloaded and only wait before it is transmuxed or parsed.
  15211. // But in practice, there are a few reasons why it is better to wait until a loader
  15212. // is ready to append that segment before requesting and downloading:
  15213. //
  15214. // 1. Because audio and main loaders cross discontinuities together, if this loader
  15215. // is waiting for the other to catch up, then instead of requesting another
  15216. // segment and using up more bandwidth, by not yet loading, more bandwidth is
  15217. // allotted to the loader currently behind.
  15218. // 2. media-segment-request doesn't have to have logic to consider whether a segment
  15219. // is ready to be processed or not, isolating the queueing behavior to the loader.
  15220. // 3. The audio loader bases some of its segment properties on timing information
  15221. // provided by the main loader, meaning that, if the logic for waiting on
  15222. // processing was in media-segment-request, then it would also need to know how
  15223. // to re-generate the segment information after the main loader caught up.
  15224. shouldWaitForTimelineChange({
  15225. timelineChangeController: this.timelineChangeController_,
  15226. currentTimeline: this.currentTimeline_,
  15227. segmentTimeline: segmentInfo.timeline,
  15228. loaderType: this.loaderType_,
  15229. audioDisabled: this.audioDisabled_
  15230. })) {
  15231. return false;
  15232. }
  15233. return true;
  15234. }
  15235. getCurrentMediaInfo_(segmentInfo = this.pendingSegment_) {
  15236. return segmentInfo && segmentInfo.trackInfo || this.currentMediaInfo_;
  15237. }
  15238. getMediaInfo_(segmentInfo = this.pendingSegment_) {
  15239. return this.getCurrentMediaInfo_(segmentInfo) || this.startingMediaInfo_;
  15240. }
  15241. getPendingSegmentPlaylist() {
  15242. return this.pendingSegment_ ? this.pendingSegment_.playlist : null;
  15243. }
  15244. hasEnoughInfoToAppend_() {
  15245. if (!this.sourceUpdater_.ready()) {
  15246. return false;
  15247. } // If content needs to be removed or the loader is waiting on an append reattempt,
  15248. // then no additional content should be appended until the prior append is resolved.
  15249. if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
  15250. return false;
  15251. }
  15252. const segmentInfo = this.pendingSegment_;
  15253. const trackInfo = this.getCurrentMediaInfo_(); // no segment to append any data for or
  15254. // we do not have information on this specific
  15255. // segment yet
  15256. if (!segmentInfo || !trackInfo) {
  15257. return false;
  15258. }
  15259. const {
  15260. hasAudio,
  15261. hasVideo,
  15262. isMuxed
  15263. } = trackInfo;
  15264. if (hasVideo && !segmentInfo.videoTimingInfo) {
  15265. return false;
  15266. } // muxed content only relies on video timing information for now.
  15267. if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
  15268. return false;
  15269. }
  15270. if (shouldWaitForTimelineChange({
  15271. timelineChangeController: this.timelineChangeController_,
  15272. currentTimeline: this.currentTimeline_,
  15273. segmentTimeline: segmentInfo.timeline,
  15274. loaderType: this.loaderType_,
  15275. audioDisabled: this.audioDisabled_
  15276. })) {
  15277. return false;
  15278. }
  15279. return true;
  15280. }
  15281. handleData_(simpleSegment, result) {
  15282. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  15283. if (this.checkForAbort_(simpleSegment.requestId)) {
  15284. return;
  15285. } // If there's anything in the call queue, then this data came later and should be
  15286. // executed after the calls currently queued.
  15287. if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
  15288. this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
  15289. return;
  15290. }
  15291. const segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time
  15292. this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats
  15293. this.updateMediaSecondsLoaded_(segmentInfo.part || segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort
  15294. // logic may change behavior depending on the state, and changing state too early may
  15295. // inflate our estimates of bandwidth. In the future this should be re-examined to
  15296. // note more granular states.
  15297. // don't process and append data if the mediaSource is closed
  15298. if (this.mediaSource_.readyState === 'closed') {
  15299. return;
  15300. } // if this request included an initialization segment, save that data
  15301. // to the initSegment cache
  15302. if (simpleSegment.map) {
  15303. simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request
  15304. segmentInfo.segment.map = simpleSegment.map;
  15305. } // if this request included a segment key, save that data in the cache
  15306. if (simpleSegment.key) {
  15307. this.segmentKey(simpleSegment.key, true);
  15308. }
  15309. segmentInfo.isFmp4 = simpleSegment.isFmp4;
  15310. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  15311. if (segmentInfo.isFmp4) {
  15312. this.trigger('fmp4');
  15313. segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
  15314. } else {
  15315. const trackInfo = this.getCurrentMediaInfo_();
  15316. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  15317. let firstVideoFrameTimeForData;
  15318. if (useVideoTimingInfo) {
  15319. firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
  15320. } // Segment loader knows more about segment timing than the transmuxer (in certain
  15321. // aspects), so make any changes required for a more accurate start time.
  15322. // Don't set the end time yet, as the segment may not be finished processing.
  15323. segmentInfo.timingInfo.start = this.trueSegmentStart_({
  15324. currentStart: segmentInfo.timingInfo.start,
  15325. playlist: segmentInfo.playlist,
  15326. mediaIndex: segmentInfo.mediaIndex,
  15327. currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
  15328. useVideoTimingInfo,
  15329. firstVideoFrameTimeForData,
  15330. videoTimingInfo: segmentInfo.videoTimingInfo,
  15331. audioTimingInfo: segmentInfo.audioTimingInfo
  15332. });
  15333. } // Init segments for audio and video only need to be appended in certain cases. Now
  15334. // that data is about to be appended, we can check the final cases to determine
  15335. // whether we should append an init segment.
  15336. this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,
  15337. // as we use the start of the segment to offset the best guess (playlist provided)
  15338. // timestamp offset.
  15339. this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should
  15340. // be appended or not.
  15341. if (segmentInfo.isSyncRequest) {
  15342. // first save/update our timing info for this segment.
  15343. // this is what allows us to choose an accurate segment
  15344. // and the main reason we make a sync request.
  15345. this.updateTimingInfoEnd_(segmentInfo);
  15346. this.syncController_.saveSegmentTimingInfo({
  15347. segmentInfo,
  15348. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  15349. });
  15350. const next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next
  15351. // after taking into account its timing info, do not append it.
  15352. if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
  15353. this.logger_('sync segment was incorrect, not appending');
  15354. return;
  15355. } // otherwise append it like any other segment as our guess was correct.
  15356. this.logger_('sync segment was correct, appending');
  15357. } // Save some state so that in the future anything waiting on first append (and/or
  15358. // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
  15359. // we need some notion of whether the timestamp offset or other relevant information
  15360. // has had a chance to be set.
  15361. segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
  15362. this.processMetadataQueue_();
  15363. this.appendData_(segmentInfo, result);
  15364. }
  15365. updateAppendInitSegmentStatus(segmentInfo, type) {
  15366. // alt audio doesn't manage timestamp offset
  15367. 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
  15368. // segment for each chunk
  15369. !segmentInfo.changedTimestampOffset) {
  15370. // if the timestamp offset changed, the timeline may have changed, so we have to re-
  15371. // append init segments
  15372. this.appendInitSegment_ = {
  15373. audio: true,
  15374. video: true
  15375. };
  15376. }
  15377. if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
  15378. // make sure we append init segment on playlist changes, in case the media config
  15379. // changed
  15380. this.appendInitSegment_[type] = true;
  15381. }
  15382. }
  15383. getInitSegmentAndUpdateState_({
  15384. type,
  15385. initSegment,
  15386. map,
  15387. playlist
  15388. }) {
  15389. // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
  15390. // (Section 3) required to parse the applicable Media Segments. It applies to every
  15391. // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
  15392. // or until the end of the playlist."
  15393. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
  15394. if (map) {
  15395. const id = initSegmentId(map);
  15396. if (this.activeInitSegmentId_ === id) {
  15397. // don't need to re-append the init segment if the ID matches
  15398. return null;
  15399. } // a map-specified init segment takes priority over any transmuxed (or otherwise
  15400. // obtained) init segment
  15401. //
  15402. // this also caches the init segment for later use
  15403. initSegment = this.initSegmentForMap(map, true).bytes;
  15404. this.activeInitSegmentId_ = id;
  15405. } // We used to always prepend init segments for video, however, that shouldn't be
  15406. // necessary. Instead, we should only append on changes, similar to what we've always
  15407. // done for audio. This is more important (though may not be that important) for
  15408. // frame-by-frame appending for LHLS, simply because of the increased quantity of
  15409. // appends.
  15410. if (initSegment && this.appendInitSegment_[type]) {
  15411. // Make sure we track the playlist that we last used for the init segment, so that
  15412. // we can re-append the init segment in the event that we get data from a new
  15413. // playlist. Discontinuities and track changes are handled in other sections.
  15414. this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.
  15415. this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
  15416. // we are appending the muxer init segment
  15417. this.activeInitSegmentId_ = null;
  15418. return initSegment;
  15419. }
  15420. return null;
  15421. }
  15422. handleQuotaExceededError_({
  15423. segmentInfo,
  15424. type,
  15425. bytes
  15426. }, error) {
  15427. const audioBuffered = this.sourceUpdater_.audioBuffered();
  15428. const videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
  15429. // should be cleared out during the buffer removals. However, log in case it helps
  15430. // debug.
  15431. if (audioBuffered.length > 1) {
  15432. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));
  15433. }
  15434. if (videoBuffered.length > 1) {
  15435. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));
  15436. }
  15437. const audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
  15438. const audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
  15439. const videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
  15440. const videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
  15441. if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
  15442. // Can't remove enough buffer to make room for new segment (or the browser doesn't
  15443. // allow for appends of segments this size). In the future, it may be possible to
  15444. // split up the segment and append in pieces, but for now, error out this playlist
  15445. // in an attempt to switch to a more manageable rendition.
  15446. 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(', ')}, `);
  15447. this.error({
  15448. message: 'Quota exceeded error with append of a single segment of content',
  15449. excludeUntil: Infinity
  15450. });
  15451. this.trigger('error');
  15452. return;
  15453. } // To try to resolve the quota exceeded error, clear back buffer and retry. This means
  15454. // that the segment-loader should block on future events until this one is handled, so
  15455. // that it doesn't keep moving onto further segments. Adding the call to the call
  15456. // queue will prevent further appends until waitingOnRemove_ and
  15457. // quotaExceededErrorRetryTimeout_ are cleared.
  15458. //
  15459. // Note that this will only block the current loader. In the case of demuxed content,
  15460. // the other load may keep filling as fast as possible. In practice, this should be
  15461. // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
  15462. // source buffer, or video fills without enough room for audio to append (and without
  15463. // the availability of clearing out seconds of back buffer to make room for audio).
  15464. // But it might still be good to handle this case in the future as a TODO.
  15465. this.waitingOnRemove_ = true;
  15466. this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
  15467. segmentInfo,
  15468. type,
  15469. bytes
  15470. }));
  15471. const currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content
  15472. // before retrying.
  15473. const timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
  15474. this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${timeToRemoveUntil}`);
  15475. this.remove(0, timeToRemoveUntil, () => {
  15476. this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${MIN_BACK_BUFFER}s`);
  15477. this.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
  15478. // attempts (since we can't clear less than the minimum)
  15479. this.quotaExceededErrorRetryTimeout_ = window$1.setTimeout(() => {
  15480. this.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
  15481. this.quotaExceededErrorRetryTimeout_ = null;
  15482. this.processCallQueue_();
  15483. }, MIN_BACK_BUFFER * 1000);
  15484. }, true);
  15485. }
  15486. handleAppendError_({
  15487. segmentInfo,
  15488. type,
  15489. bytes
  15490. }, error) {
  15491. // if there's no error, nothing to do
  15492. if (!error) {
  15493. return;
  15494. }
  15495. if (error.code === QUOTA_EXCEEDED_ERR) {
  15496. this.handleQuotaExceededError_({
  15497. segmentInfo,
  15498. type,
  15499. bytes
  15500. }); // A quota exceeded error should be recoverable with a future re-append, so no need
  15501. // to trigger an append error.
  15502. return;
  15503. }
  15504. this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
  15505. 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.
  15506. // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
  15507. //
  15508. // Trigger a special error so that it can be handled separately from normal,
  15509. // recoverable errors.
  15510. this.trigger('appenderror');
  15511. }
  15512. appendToSourceBuffer_({
  15513. segmentInfo,
  15514. type,
  15515. initSegment,
  15516. data,
  15517. bytes
  15518. }) {
  15519. // If this is a re-append, bytes were already created and don't need to be recreated
  15520. if (!bytes) {
  15521. const segments = [data];
  15522. let byteLength = data.byteLength;
  15523. if (initSegment) {
  15524. // if the media initialization segment is changing, append it before the content
  15525. // segment
  15526. segments.unshift(initSegment);
  15527. byteLength += initSegment.byteLength;
  15528. } // Technically we should be OK appending the init segment separately, however, we
  15529. // haven't yet tested that, and prepending is how we have always done things.
  15530. bytes = concatSegments({
  15531. bytes: byteLength,
  15532. segments
  15533. });
  15534. }
  15535. this.sourceUpdater_.appendBuffer({
  15536. segmentInfo,
  15537. type,
  15538. bytes
  15539. }, this.handleAppendError_.bind(this, {
  15540. segmentInfo,
  15541. type,
  15542. bytes
  15543. }));
  15544. }
  15545. handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
  15546. if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
  15547. return;
  15548. }
  15549. const segment = this.pendingSegment_.segment;
  15550. const timingInfoProperty = `${type}TimingInfo`;
  15551. if (!segment[timingInfoProperty]) {
  15552. segment[timingInfoProperty] = {};
  15553. }
  15554. segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
  15555. segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
  15556. segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
  15557. segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
  15558. segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging
  15559. segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
  15560. }
  15561. appendData_(segmentInfo, result) {
  15562. const {
  15563. type,
  15564. data
  15565. } = result;
  15566. if (!data || !data.byteLength) {
  15567. return;
  15568. }
  15569. if (type === 'audio' && this.audioDisabled_) {
  15570. return;
  15571. }
  15572. const initSegment = this.getInitSegmentAndUpdateState_({
  15573. type,
  15574. initSegment: result.initSegment,
  15575. playlist: segmentInfo.playlist,
  15576. map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
  15577. });
  15578. this.appendToSourceBuffer_({
  15579. segmentInfo,
  15580. type,
  15581. initSegment,
  15582. data
  15583. });
  15584. }
  15585. /**
  15586. * load a specific segment from a request into the buffer
  15587. *
  15588. * @private
  15589. */
  15590. loadSegment_(segmentInfo) {
  15591. this.state = 'WAITING';
  15592. this.pendingSegment_ = segmentInfo;
  15593. this.trimBackBuffer_(segmentInfo);
  15594. if (typeof segmentInfo.timestampOffset === 'number') {
  15595. if (this.transmuxer_) {
  15596. this.transmuxer_.postMessage({
  15597. action: 'clearAllMp4Captions'
  15598. });
  15599. }
  15600. }
  15601. if (!this.hasEnoughInfoToLoad_()) {
  15602. this.loadQueue_.push(() => {
  15603. // regenerate the audioAppendStart, timestampOffset, etc as they
  15604. // may have changed since this function was added to the queue.
  15605. const options = _extends({}, segmentInfo, {
  15606. forceTimestampOffset: true
  15607. });
  15608. _extends(segmentInfo, this.generateSegmentInfo_(options));
  15609. this.isPendingTimestampOffset_ = false;
  15610. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  15611. });
  15612. return;
  15613. }
  15614. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  15615. }
  15616. updateTransmuxerAndRequestSegment_(segmentInfo) {
  15617. // We'll update the source buffer's timestamp offset once we have transmuxed data, but
  15618. // the transmuxer still needs to be updated before then.
  15619. //
  15620. // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
  15621. // offset must be passed to the transmuxer for stream correcting adjustments.
  15622. if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
  15623. this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared
  15624. segmentInfo.gopsToAlignWith = [];
  15625. this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
  15626. this.transmuxer_.postMessage({
  15627. action: 'reset'
  15628. });
  15629. this.transmuxer_.postMessage({
  15630. action: 'setTimestampOffset',
  15631. timestampOffset: segmentInfo.timestampOffset
  15632. });
  15633. }
  15634. const simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
  15635. const isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
  15636. const isWalkingForward = this.mediaIndex !== null;
  15637. const isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ && // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
  15638. // the first timeline
  15639. segmentInfo.timeline > 0;
  15640. const isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
  15641. 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),
  15642. // then this init segment has never been seen before and should be appended.
  15643. //
  15644. // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
  15645. // both to true and leave the decision of whether to append the init segment to append time.
  15646. if (simpleSegment.map && !simpleSegment.map.bytes) {
  15647. this.logger_('going to request init segment.');
  15648. this.appendInitSegment_ = {
  15649. video: true,
  15650. audio: true
  15651. };
  15652. }
  15653. segmentInfo.abortRequests = mediaSegmentRequest({
  15654. xhr: this.vhs_.xhr,
  15655. xhrOptions: this.xhrOptions_,
  15656. decryptionWorker: this.decrypter_,
  15657. segment: simpleSegment,
  15658. abortFn: this.handleAbort_.bind(this, segmentInfo),
  15659. progressFn: this.handleProgress_.bind(this),
  15660. trackInfoFn: this.handleTrackInfo_.bind(this),
  15661. timingInfoFn: this.handleTimingInfo_.bind(this),
  15662. videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
  15663. audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
  15664. captionsFn: this.handleCaptions_.bind(this),
  15665. isEndOfTimeline,
  15666. endedTimelineFn: () => {
  15667. this.logger_('received endedtimeline callback');
  15668. },
  15669. id3Fn: this.handleId3_.bind(this),
  15670. dataFn: this.handleData_.bind(this),
  15671. doneFn: this.segmentRequestFinished_.bind(this),
  15672. onTransmuxerLog: ({
  15673. message,
  15674. level,
  15675. stream
  15676. }) => {
  15677. this.logger_(`${segmentInfoString(segmentInfo)} logged from transmuxer stream ${stream} as a ${level}: ${message}`);
  15678. }
  15679. });
  15680. }
  15681. /**
  15682. * trim the back buffer so that we don't have too much data
  15683. * in the source buffer
  15684. *
  15685. * @private
  15686. *
  15687. * @param {Object} segmentInfo - the current segment
  15688. */
  15689. trimBackBuffer_(segmentInfo) {
  15690. const removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of
  15691. // buffer and a very conservative "garbage collector"
  15692. // We manually clear out the old buffer to ensure
  15693. // we don't trigger the QuotaExceeded error
  15694. // on the source buffer during subsequent appends
  15695. if (removeToTime > 0) {
  15696. this.remove(0, removeToTime);
  15697. }
  15698. }
  15699. /**
  15700. * created a simplified copy of the segment object with just the
  15701. * information necessary to perform the XHR and decryption
  15702. *
  15703. * @private
  15704. *
  15705. * @param {Object} segmentInfo - the current segment
  15706. * @return {Object} a simplified segment object copy
  15707. */
  15708. createSimplifiedSegmentObj_(segmentInfo) {
  15709. const segment = segmentInfo.segment;
  15710. const part = segmentInfo.part;
  15711. const simpleSegment = {
  15712. resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
  15713. byterange: part ? part.byterange : segment.byterange,
  15714. requestId: segmentInfo.requestId,
  15715. transmuxer: segmentInfo.transmuxer,
  15716. audioAppendStart: segmentInfo.audioAppendStart,
  15717. gopsToAlignWith: segmentInfo.gopsToAlignWith,
  15718. part: segmentInfo.part
  15719. };
  15720. const previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
  15721. if (previousSegment && previousSegment.timeline === segment.timeline) {
  15722. // The baseStartTime of a segment is used to handle rollover when probing the TS
  15723. // segment to retrieve timing information. Since the probe only looks at the media's
  15724. // times (e.g., PTS and DTS values of the segment), and doesn't consider the
  15725. // player's time (e.g., player.currentTime()), baseStartTime should reflect the
  15726. // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
  15727. // seconds of media time, so should be used here. The previous segment is used since
  15728. // the end of the previous segment should represent the beginning of the current
  15729. // segment, so long as they are on the same timeline.
  15730. if (previousSegment.videoTimingInfo) {
  15731. simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
  15732. } else if (previousSegment.audioTimingInfo) {
  15733. simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
  15734. }
  15735. }
  15736. if (segment.key) {
  15737. // if the media sequence is greater than 2^32, the IV will be incorrect
  15738. // assuming 10s segments, that would be about 1300 years
  15739. const iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
  15740. simpleSegment.key = this.segmentKey(segment.key);
  15741. simpleSegment.key.iv = iv;
  15742. }
  15743. if (segment.map) {
  15744. simpleSegment.map = this.initSegmentForMap(segment.map);
  15745. }
  15746. return simpleSegment;
  15747. }
  15748. saveTransferStats_(stats) {
  15749. // every request counts as a media request even if it has been aborted
  15750. // or canceled due to a timeout
  15751. this.mediaRequests += 1;
  15752. if (stats) {
  15753. this.mediaBytesTransferred += stats.bytesReceived;
  15754. this.mediaTransferDuration += stats.roundTripTime;
  15755. }
  15756. }
  15757. saveBandwidthRelatedStats_(duration, stats) {
  15758. // byteLength will be used for throughput, and should be based on bytes receieved,
  15759. // which we only know at the end of the request and should reflect total bytes
  15760. // downloaded rather than just bytes processed from components of the segment
  15761. this.pendingSegment_.byteLength = stats.bytesReceived;
  15762. if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  15763. this.logger_(`Ignoring segment's bandwidth because its duration of ${duration}` + ` is less than the min to record ${MIN_SEGMENT_DURATION_TO_SAVE_STATS}`);
  15764. return;
  15765. }
  15766. this.bandwidth = stats.bandwidth;
  15767. this.roundTrip = stats.roundTripTime;
  15768. }
  15769. handleTimeout_() {
  15770. // although the VTT segment loader bandwidth isn't really used, it's good to
  15771. // maintain functinality between segment loaders
  15772. this.mediaRequestsTimedout += 1;
  15773. this.bandwidth = 1;
  15774. this.roundTrip = NaN;
  15775. this.trigger('bandwidthupdate');
  15776. this.trigger('timeout');
  15777. }
  15778. /**
  15779. * Handle the callback from the segmentRequest function and set the
  15780. * associated SegmentLoader state and errors if necessary
  15781. *
  15782. * @private
  15783. */
  15784. segmentRequestFinished_(error, simpleSegment, result) {
  15785. // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
  15786. // check the call queue directly since this function doesn't need to deal with any
  15787. // data, and can continue even if the source buffers are not set up and we didn't get
  15788. // any data from the segment
  15789. if (this.callQueue_.length) {
  15790. this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
  15791. return;
  15792. }
  15793. this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset
  15794. if (!this.pendingSegment_) {
  15795. return;
  15796. } // the request was aborted and the SegmentLoader has already started
  15797. // another request. this can happen when the timeout for an aborted
  15798. // request triggers due to a limitation in the XHR library
  15799. // do not count this as any sort of request or we risk double-counting
  15800. if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
  15801. return;
  15802. } // an error occurred from the active pendingSegment_ so reset everything
  15803. if (error) {
  15804. this.pendingSegment_ = null;
  15805. this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done
  15806. if (error.code === REQUEST_ERRORS.ABORTED) {
  15807. return;
  15808. }
  15809. this.pause(); // the error is really just that at least one of the requests timed-out
  15810. // set the bandwidth to a very low value and trigger an ABR switch to
  15811. // take emergency action
  15812. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  15813. this.handleTimeout_();
  15814. return;
  15815. } // if control-flow has arrived here, then the error is real
  15816. // emit an error event to exclude the current playlist
  15817. this.mediaRequestsErrored += 1;
  15818. this.error(error);
  15819. this.trigger('error');
  15820. return;
  15821. }
  15822. const segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request
  15823. // generated for ABR purposes
  15824. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
  15825. segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
  15826. if (result.gopInfo) {
  15827. this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
  15828. } // Although we may have already started appending on progress, we shouldn't switch the
  15829. // state away from loading until we are officially done loading the segment data.
  15830. this.state = 'APPENDING'; // used for testing
  15831. this.trigger('appending');
  15832. this.waitForAppendsToComplete_(segmentInfo);
  15833. }
  15834. setTimeMapping_(timeline) {
  15835. const timelineMapping = this.syncController_.mappingForTimeline(timeline);
  15836. if (timelineMapping !== null) {
  15837. this.timeMapping_ = timelineMapping;
  15838. }
  15839. }
  15840. updateMediaSecondsLoaded_(segment) {
  15841. if (typeof segment.start === 'number' && typeof segment.end === 'number') {
  15842. this.mediaSecondsLoaded += segment.end - segment.start;
  15843. } else {
  15844. this.mediaSecondsLoaded += segment.duration;
  15845. }
  15846. }
  15847. shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
  15848. if (timestampOffset === null) {
  15849. return false;
  15850. } // note that we're potentially using the same timestamp offset for both video and
  15851. // audio
  15852. if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  15853. return true;
  15854. }
  15855. if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  15856. return true;
  15857. }
  15858. return false;
  15859. }
  15860. trueSegmentStart_({
  15861. currentStart,
  15862. playlist,
  15863. mediaIndex,
  15864. firstVideoFrameTimeForData,
  15865. currentVideoTimestampOffset,
  15866. useVideoTimingInfo,
  15867. videoTimingInfo,
  15868. audioTimingInfo
  15869. }) {
  15870. if (typeof currentStart !== 'undefined') {
  15871. // if start was set once, keep using it
  15872. return currentStart;
  15873. }
  15874. if (!useVideoTimingInfo) {
  15875. return audioTimingInfo.start;
  15876. }
  15877. const previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained
  15878. // within that segment. Since the transmuxer maintains a cache of incomplete data
  15879. // from and/or the last frame seen, the start time may reflect a frame that starts
  15880. // in the previous segment. Check for that case and ensure the start time is
  15881. // accurate for the segment.
  15882. if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
  15883. return firstVideoFrameTimeForData;
  15884. }
  15885. return videoTimingInfo.start;
  15886. }
  15887. waitForAppendsToComplete_(segmentInfo) {
  15888. const trackInfo = this.getCurrentMediaInfo_(segmentInfo);
  15889. if (!trackInfo) {
  15890. this.error({
  15891. message: 'No starting media returned, likely due to an unsupported media format.',
  15892. playlistExclusionDuration: Infinity
  15893. });
  15894. this.trigger('error');
  15895. return;
  15896. } // Although transmuxing is done, appends may not yet be finished. Throw a marker
  15897. // on each queue this loader is responsible for to ensure that the appends are
  15898. // complete.
  15899. const {
  15900. hasAudio,
  15901. hasVideo,
  15902. isMuxed
  15903. } = trackInfo;
  15904. const waitForVideo = this.loaderType_ === 'main' && hasVideo;
  15905. const waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
  15906. segmentInfo.waitingOnAppends = 0; // segments with no data
  15907. if (!segmentInfo.hasAppendedData_) {
  15908. if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
  15909. // When there's no audio or video data in the segment, there's no audio or video
  15910. // timing information.
  15911. //
  15912. // If there's no audio or video timing information, then the timestamp offset
  15913. // can't be adjusted to the appropriate value for the transmuxer and source
  15914. // buffers.
  15915. //
  15916. // Therefore, the next segment should be used to set the timestamp offset.
  15917. this.isPendingTimestampOffset_ = true;
  15918. } // override settings for metadata only segments
  15919. segmentInfo.timingInfo = {
  15920. start: 0
  15921. };
  15922. segmentInfo.waitingOnAppends++;
  15923. if (!this.isPendingTimestampOffset_) {
  15924. // update the timestampoffset
  15925. this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have
  15926. // no video/audio data.
  15927. this.processMetadataQueue_();
  15928. } // append is "done" instantly with no data.
  15929. this.checkAppendsDone_(segmentInfo);
  15930. return;
  15931. } // Since source updater could call back synchronously, do the increments first.
  15932. if (waitForVideo) {
  15933. segmentInfo.waitingOnAppends++;
  15934. }
  15935. if (waitForAudio) {
  15936. segmentInfo.waitingOnAppends++;
  15937. }
  15938. if (waitForVideo) {
  15939. this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  15940. }
  15941. if (waitForAudio) {
  15942. this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  15943. }
  15944. }
  15945. checkAppendsDone_(segmentInfo) {
  15946. if (this.checkForAbort_(segmentInfo.requestId)) {
  15947. return;
  15948. }
  15949. segmentInfo.waitingOnAppends--;
  15950. if (segmentInfo.waitingOnAppends === 0) {
  15951. this.handleAppendsDone_();
  15952. }
  15953. }
  15954. checkForIllegalMediaSwitch(trackInfo) {
  15955. const illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.getCurrentMediaInfo_(), trackInfo);
  15956. if (illegalMediaSwitchError) {
  15957. this.error({
  15958. message: illegalMediaSwitchError,
  15959. playlistExclusionDuration: Infinity
  15960. });
  15961. this.trigger('error');
  15962. return true;
  15963. }
  15964. return false;
  15965. }
  15966. updateSourceBufferTimestampOffset_(segmentInfo) {
  15967. if (segmentInfo.timestampOffset === null || // we don't yet have the start for whatever media type (video or audio) has
  15968. // priority, timing-wise, so we must wait
  15969. typeof segmentInfo.timingInfo.start !== 'number' || // already updated the timestamp offset for this segment
  15970. segmentInfo.changedTimestampOffset || // the alt audio loader should not be responsible for setting the timestamp offset
  15971. this.loaderType_ !== 'main') {
  15972. return;
  15973. }
  15974. let didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
  15975. // the timing info here comes from video. In the event that the audio is longer than
  15976. // the video, this will trim the start of the audio.
  15977. // This also trims any offset from 0 at the beginning of the media
  15978. segmentInfo.timestampOffset -= this.getSegmentStartTimeForTimestampOffsetCalculation_({
  15979. videoTimingInfo: segmentInfo.segment.videoTimingInfo,
  15980. audioTimingInfo: segmentInfo.segment.audioTimingInfo,
  15981. timingInfo: segmentInfo.timingInfo
  15982. }); // In the event that there are part segment downloads, each will try to update the
  15983. // timestamp offset. Retaining this bit of state prevents us from updating in the
  15984. // future (within the same segment), however, there may be a better way to handle it.
  15985. segmentInfo.changedTimestampOffset = true;
  15986. if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  15987. this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
  15988. didChange = true;
  15989. }
  15990. if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  15991. this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
  15992. didChange = true;
  15993. }
  15994. if (didChange) {
  15995. this.trigger('timestampoffset');
  15996. }
  15997. }
  15998. getSegmentStartTimeForTimestampOffsetCalculation_({
  15999. videoTimingInfo,
  16000. audioTimingInfo,
  16001. timingInfo
  16002. }) {
  16003. if (!this.useDtsForTimestampOffset_) {
  16004. return timingInfo.start;
  16005. }
  16006. if (videoTimingInfo && typeof videoTimingInfo.transmuxedDecodeStart === 'number') {
  16007. return videoTimingInfo.transmuxedDecodeStart;
  16008. } // handle audio only
  16009. if (audioTimingInfo && typeof audioTimingInfo.transmuxedDecodeStart === 'number') {
  16010. return audioTimingInfo.transmuxedDecodeStart;
  16011. } // handle content not transmuxed (e.g., MP4)
  16012. return timingInfo.start;
  16013. }
  16014. updateTimingInfoEnd_(segmentInfo) {
  16015. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  16016. const trackInfo = this.getMediaInfo_();
  16017. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  16018. const prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
  16019. if (!prioritizedTimingInfo) {
  16020. return;
  16021. }
  16022. segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ? // End time may not exist in a case where we aren't parsing the full segment (one
  16023. // current example is the case of fmp4), so use the rough duration to calculate an
  16024. // end time.
  16025. prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
  16026. }
  16027. /**
  16028. * callback to run when appendBuffer is finished. detects if we are
  16029. * in a good state to do things with the data we got, or if we need
  16030. * to wait for more
  16031. *
  16032. * @private
  16033. */
  16034. handleAppendsDone_() {
  16035. // appendsdone can cause an abort
  16036. if (this.pendingSegment_) {
  16037. this.trigger('appendsdone');
  16038. }
  16039. if (!this.pendingSegment_) {
  16040. this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in
  16041. // all appending cases?
  16042. if (!this.paused()) {
  16043. this.monitorBuffer_();
  16044. }
  16045. return;
  16046. }
  16047. const segmentInfo = this.pendingSegment_; // Now that the end of the segment has been reached, we can set the end time. It's
  16048. // best to wait until all appends are done so we're sure that the primary media is
  16049. // finished (and we have its end time).
  16050. this.updateTimingInfoEnd_(segmentInfo);
  16051. if (this.shouldSaveSegmentTimingInfo_) {
  16052. // Timeline mappings should only be saved for the main loader. This is for multiple
  16053. // reasons:
  16054. //
  16055. // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
  16056. // and the main loader try to save the timeline mapping, whichever comes later
  16057. // will overwrite the first. In theory this is OK, as the mappings should be the
  16058. // same, however, it breaks for (2)
  16059. // 2) In the event of a live stream, the initial live point will make for a somewhat
  16060. // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
  16061. // the mapping will be off for one of the streams, dependent on which one was
  16062. // first saved (see (1)).
  16063. // 3) Primary timing goes by video in VHS, so the mapping should be video.
  16064. //
  16065. // Since the audio loader will wait for the main loader to load the first segment,
  16066. // the main loader will save the first timeline mapping, and ensure that there won't
  16067. // be a case where audio loads two segments without saving a mapping (thus leading
  16068. // to missing segment timing info).
  16069. this.syncController_.saveSegmentTimingInfo({
  16070. segmentInfo,
  16071. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  16072. });
  16073. }
  16074. const segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
  16075. if (segmentDurationMessage) {
  16076. if (segmentDurationMessage.severity === 'warn') {
  16077. videojs.log.warn(segmentDurationMessage.message);
  16078. } else {
  16079. this.logger_(segmentDurationMessage.message);
  16080. }
  16081. }
  16082. this.recordThroughput_(segmentInfo);
  16083. this.pendingSegment_ = null;
  16084. this.state = 'READY';
  16085. if (segmentInfo.isSyncRequest) {
  16086. this.trigger('syncinfoupdate'); // if the sync request was not appended
  16087. // then it was not the correct segment.
  16088. // throw it away and use the data it gave us
  16089. // to get the correct one.
  16090. if (!segmentInfo.hasAppendedData_) {
  16091. this.logger_(`Throwing away un-appended sync request ${segmentInfoString(segmentInfo)}`);
  16092. return;
  16093. }
  16094. }
  16095. this.logger_(`Appended ${segmentInfoString(segmentInfo)}`);
  16096. this.addSegmentMetadataCue_(segmentInfo);
  16097. this.fetchAtBuffer_ = true;
  16098. if (this.currentTimeline_ !== segmentInfo.timeline) {
  16099. this.timelineChangeController_.lastTimelineChange({
  16100. type: this.loaderType_,
  16101. from: this.currentTimeline_,
  16102. to: segmentInfo.timeline
  16103. }); // If audio is not disabled, the main segment loader is responsible for updating
  16104. // the audio timeline as well. If the content is video only, this won't have any
  16105. // impact.
  16106. if (this.loaderType_ === 'main' && !this.audioDisabled_) {
  16107. this.timelineChangeController_.lastTimelineChange({
  16108. type: 'audio',
  16109. from: this.currentTimeline_,
  16110. to: segmentInfo.timeline
  16111. });
  16112. }
  16113. }
  16114. this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before
  16115. // the following conditional otherwise it may consider this a bad "guess"
  16116. // and attempt to resync when the post-update seekable window and live
  16117. // point would mean that this was the perfect segment to fetch
  16118. this.trigger('syncinfoupdate');
  16119. const segment = segmentInfo.segment;
  16120. const part = segmentInfo.part;
  16121. const badSegmentGuess = segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3;
  16122. 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
  16123. // the currentTime_ that means that our conservative guess was too conservative.
  16124. // In that case, reset the loader state so that we try to use any information gained
  16125. // from the previous request to create a new, more accurate, sync-point.
  16126. if (badSegmentGuess || badPartGuess) {
  16127. this.logger_(`bad ${badSegmentGuess ? 'segment' : 'part'} ${segmentInfoString(segmentInfo)}`);
  16128. this.resetEverything();
  16129. return;
  16130. }
  16131. const isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment
  16132. // and conservatively guess
  16133. if (isWalkingForward) {
  16134. this.trigger('bandwidthupdate');
  16135. }
  16136. this.trigger('progress');
  16137. this.mediaIndex = segmentInfo.mediaIndex;
  16138. this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the
  16139. // buffer, end the stream. this ensures the "ended" event will
  16140. // fire if playback reaches that point.
  16141. if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
  16142. this.endOfStream();
  16143. } // used for testing
  16144. this.trigger('appended');
  16145. if (segmentInfo.hasAppendedData_) {
  16146. this.mediaAppends++;
  16147. }
  16148. if (!this.paused()) {
  16149. this.monitorBuffer_();
  16150. }
  16151. }
  16152. /**
  16153. * Records the current throughput of the decrypt, transmux, and append
  16154. * portion of the semgment pipeline. `throughput.rate` is a the cumulative
  16155. * moving average of the throughput. `throughput.count` is the number of
  16156. * data points in the average.
  16157. *
  16158. * @private
  16159. * @param {Object} segmentInfo the object returned by loadSegment
  16160. */
  16161. recordThroughput_(segmentInfo) {
  16162. if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  16163. 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}`);
  16164. return;
  16165. }
  16166. const rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide
  16167. // by zero in the case where the throughput is ridiculously high
  16168. const segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second
  16169. const segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:
  16170. // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
  16171. this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
  16172. }
  16173. /**
  16174. * Adds a cue to the segment-metadata track with some metadata information about the
  16175. * segment
  16176. *
  16177. * @private
  16178. * @param {Object} segmentInfo
  16179. * the object returned by loadSegment
  16180. * @method addSegmentMetadataCue_
  16181. */
  16182. addSegmentMetadataCue_(segmentInfo) {
  16183. if (!this.segmentMetadataTrack_) {
  16184. return;
  16185. }
  16186. const segment = segmentInfo.segment;
  16187. const start = segment.start;
  16188. const end = segment.end; // Do not try adding the cue if the start and end times are invalid.
  16189. if (!finite(start) || !finite(end)) {
  16190. return;
  16191. }
  16192. removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
  16193. const Cue = window$1.WebKitDataCue || window$1.VTTCue;
  16194. const value = {
  16195. custom: segment.custom,
  16196. dateTimeObject: segment.dateTimeObject,
  16197. dateTimeString: segment.dateTimeString,
  16198. programDateTime: segment.programDateTime,
  16199. bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
  16200. resolution: segmentInfo.playlist.attributes.RESOLUTION,
  16201. codecs: segmentInfo.playlist.attributes.CODECS,
  16202. byteLength: segmentInfo.byteLength,
  16203. uri: segmentInfo.uri,
  16204. timeline: segmentInfo.timeline,
  16205. playlist: segmentInfo.playlist.id,
  16206. start,
  16207. end
  16208. };
  16209. const data = JSON.stringify(value);
  16210. const cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between
  16211. // the differences of WebKitDataCue in safari and VTTCue in other browsers
  16212. cue.value = value;
  16213. this.segmentMetadataTrack_.addCue(cue);
  16214. }
  16215. }
  16216. function noop() {}
  16217. const toTitleCase = function (string) {
  16218. if (typeof string !== 'string') {
  16219. return string;
  16220. }
  16221. return string.replace(/./, w => w.toUpperCase());
  16222. };
  16223. /**
  16224. * @file source-updater.js
  16225. */
  16226. const bufferTypes = ['video', 'audio'];
  16227. const updating = (type, sourceUpdater) => {
  16228. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  16229. return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];
  16230. };
  16231. const nextQueueIndexOfType = (type, queue) => {
  16232. for (let i = 0; i < queue.length; i++) {
  16233. const queueEntry = queue[i];
  16234. if (queueEntry.type === 'mediaSource') {
  16235. // If the next entry is a media source entry (uses multiple source buffers), block
  16236. // processing to allow it to go through first.
  16237. return null;
  16238. }
  16239. if (queueEntry.type === type) {
  16240. return i;
  16241. }
  16242. }
  16243. return null;
  16244. };
  16245. const shiftQueue = (type, sourceUpdater) => {
  16246. if (sourceUpdater.queue.length === 0) {
  16247. return;
  16248. }
  16249. let queueIndex = 0;
  16250. let queueEntry = sourceUpdater.queue[queueIndex];
  16251. if (queueEntry.type === 'mediaSource') {
  16252. if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
  16253. sourceUpdater.queue.shift();
  16254. queueEntry.action(sourceUpdater);
  16255. if (queueEntry.doneFn) {
  16256. queueEntry.doneFn();
  16257. } // Only specific source buffer actions must wait for async updateend events. Media
  16258. // Source actions process synchronously. Therefore, both audio and video source
  16259. // buffers are now clear to process the next queue entries.
  16260. shiftQueue('audio', sourceUpdater);
  16261. shiftQueue('video', sourceUpdater);
  16262. } // Media Source actions require both source buffers, so if the media source action
  16263. // couldn't process yet (because one or both source buffers are busy), block other
  16264. // queue actions until both are available and the media source action can process.
  16265. return;
  16266. }
  16267. if (type === 'mediaSource') {
  16268. // If the queue was shifted by a media source action (this happens when pushing a
  16269. // media source action onto the queue), then it wasn't from an updateend event from an
  16270. // audio or video source buffer, so there's no change from previous state, and no
  16271. // processing should be done.
  16272. return;
  16273. } // Media source queue entries don't need to consider whether the source updater is
  16274. // started (i.e., source buffers are created) as they don't need the source buffers, but
  16275. // source buffer queue entries do.
  16276. if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || updating(type, sourceUpdater)) {
  16277. return;
  16278. }
  16279. if (queueEntry.type !== type) {
  16280. queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
  16281. if (queueIndex === null) {
  16282. // Either there's no queue entry that uses this source buffer type in the queue, or
  16283. // there's a media source queue entry before the next entry of this type, in which
  16284. // case wait for that action to process first.
  16285. return;
  16286. }
  16287. queueEntry = sourceUpdater.queue[queueIndex];
  16288. }
  16289. sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.
  16290. //
  16291. // The queue pending operation must be set before the action is performed in the event
  16292. // that the action results in a synchronous event that is acted upon. For instance, if
  16293. // an exception is thrown that can be handled, it's possible that new actions will be
  16294. // appended to an empty queue and immediately executed, but would not have the correct
  16295. // pending information if this property was set after the action was performed.
  16296. sourceUpdater.queuePending[type] = queueEntry;
  16297. queueEntry.action(type, sourceUpdater);
  16298. if (!queueEntry.doneFn) {
  16299. // synchronous operation, process next entry
  16300. sourceUpdater.queuePending[type] = null;
  16301. shiftQueue(type, sourceUpdater);
  16302. return;
  16303. }
  16304. };
  16305. const cleanupBuffer = (type, sourceUpdater) => {
  16306. const buffer = sourceUpdater[`${type}Buffer`];
  16307. const titleType = toTitleCase(type);
  16308. if (!buffer) {
  16309. return;
  16310. }
  16311. buffer.removeEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  16312. buffer.removeEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  16313. sourceUpdater.codecs[type] = null;
  16314. sourceUpdater[`${type}Buffer`] = null;
  16315. };
  16316. const inSourceBuffers = (mediaSource, sourceBuffer) => mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
  16317. const actions = {
  16318. appendBuffer: (bytes, segmentInfo, onError) => (type, sourceUpdater) => {
  16319. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  16320. // or the media source does not contain this source buffer.
  16321. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  16322. return;
  16323. }
  16324. sourceUpdater.logger_(`Appending segment ${segmentInfo.mediaIndex}'s ${bytes.length} bytes to ${type}Buffer`);
  16325. try {
  16326. sourceBuffer.appendBuffer(bytes);
  16327. } catch (e) {
  16328. sourceUpdater.logger_(`Error with code ${e.code} ` + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + `when appending segment ${segmentInfo.mediaIndex} to ${type}Buffer`);
  16329. sourceUpdater.queuePending[type] = null;
  16330. onError(e);
  16331. }
  16332. },
  16333. remove: (start, end) => (type, sourceUpdater) => {
  16334. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  16335. // or the media source does not contain this source buffer.
  16336. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  16337. return;
  16338. }
  16339. sourceUpdater.logger_(`Removing ${start} to ${end} from ${type}Buffer`);
  16340. try {
  16341. sourceBuffer.remove(start, end);
  16342. } catch (e) {
  16343. sourceUpdater.logger_(`Remove ${start} to ${end} from ${type}Buffer failed`);
  16344. }
  16345. },
  16346. timestampOffset: offset => (type, sourceUpdater) => {
  16347. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  16348. // or the media source does not contain this source buffer.
  16349. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  16350. return;
  16351. }
  16352. sourceUpdater.logger_(`Setting ${type}timestampOffset to ${offset}`);
  16353. sourceBuffer.timestampOffset = offset;
  16354. },
  16355. callback: callback => (type, sourceUpdater) => {
  16356. callback();
  16357. },
  16358. endOfStream: error => sourceUpdater => {
  16359. if (sourceUpdater.mediaSource.readyState !== 'open') {
  16360. return;
  16361. }
  16362. sourceUpdater.logger_(`Calling mediaSource endOfStream(${error || ''})`);
  16363. try {
  16364. sourceUpdater.mediaSource.endOfStream(error);
  16365. } catch (e) {
  16366. videojs.log.warn('Failed to call media source endOfStream', e);
  16367. }
  16368. },
  16369. duration: duration => sourceUpdater => {
  16370. sourceUpdater.logger_(`Setting mediaSource duration to ${duration}`);
  16371. try {
  16372. sourceUpdater.mediaSource.duration = duration;
  16373. } catch (e) {
  16374. videojs.log.warn('Failed to set media source duration', e);
  16375. }
  16376. },
  16377. abort: () => (type, sourceUpdater) => {
  16378. if (sourceUpdater.mediaSource.readyState !== 'open') {
  16379. return;
  16380. }
  16381. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  16382. // or the media source does not contain this source buffer.
  16383. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  16384. return;
  16385. }
  16386. sourceUpdater.logger_(`calling abort on ${type}Buffer`);
  16387. try {
  16388. sourceBuffer.abort();
  16389. } catch (e) {
  16390. videojs.log.warn(`Failed to abort on ${type}Buffer`, e);
  16391. }
  16392. },
  16393. addSourceBuffer: (type, codec) => sourceUpdater => {
  16394. const titleType = toTitleCase(type);
  16395. const mime = getMimeForCodec(codec);
  16396. sourceUpdater.logger_(`Adding ${type}Buffer with codec ${codec} to mediaSource`);
  16397. const sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
  16398. sourceBuffer.addEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  16399. sourceBuffer.addEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  16400. sourceUpdater.codecs[type] = codec;
  16401. sourceUpdater[`${type}Buffer`] = sourceBuffer;
  16402. },
  16403. removeSourceBuffer: type => sourceUpdater => {
  16404. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  16405. cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null
  16406. // or the media source does not contain this source buffer.
  16407. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  16408. return;
  16409. }
  16410. sourceUpdater.logger_(`Removing ${type}Buffer with codec ${sourceUpdater.codecs[type]} from mediaSource`);
  16411. try {
  16412. sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
  16413. } catch (e) {
  16414. videojs.log.warn(`Failed to removeSourceBuffer ${type}Buffer`, e);
  16415. }
  16416. },
  16417. changeType: codec => (type, sourceUpdater) => {
  16418. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  16419. const mime = getMimeForCodec(codec); // can't do anything if the media source / source buffer is null
  16420. // or the media source does not contain this source buffer.
  16421. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  16422. return;
  16423. } // do not update codec if we don't need to.
  16424. if (sourceUpdater.codecs[type] === codec) {
  16425. return;
  16426. }
  16427. sourceUpdater.logger_(`changing ${type}Buffer codec from ${sourceUpdater.codecs[type]} to ${codec}`); // check if change to the provided type is supported
  16428. try {
  16429. sourceBuffer.changeType(mime);
  16430. sourceUpdater.codecs[type] = codec;
  16431. } catch (e) {
  16432. videojs.log.warn(`Failed to changeType on ${type}Buffer`, e);
  16433. }
  16434. }
  16435. };
  16436. const pushQueue = ({
  16437. type,
  16438. sourceUpdater,
  16439. action,
  16440. doneFn,
  16441. name
  16442. }) => {
  16443. sourceUpdater.queue.push({
  16444. type,
  16445. action,
  16446. doneFn,
  16447. name
  16448. });
  16449. shiftQueue(type, sourceUpdater);
  16450. };
  16451. const onUpdateend = (type, sourceUpdater) => e => {
  16452. // Although there should, in theory, be a pending action for any updateend receieved,
  16453. // there are some actions that may trigger updateend events without set definitions in
  16454. // the w3c spec. For instance, setting the duration on the media source may trigger
  16455. // updateend events on source buffers. This does not appear to be in the spec. As such,
  16456. // if we encounter an updateend without a corresponding pending action from our queue
  16457. // for that source buffer type, process the next action.
  16458. if (sourceUpdater.queuePending[type]) {
  16459. const doneFn = sourceUpdater.queuePending[type].doneFn;
  16460. sourceUpdater.queuePending[type] = null;
  16461. if (doneFn) {
  16462. // if there's an error, report it
  16463. doneFn(sourceUpdater[`${type}Error_`]);
  16464. }
  16465. }
  16466. shiftQueue(type, sourceUpdater);
  16467. };
  16468. /**
  16469. * A queue of callbacks to be serialized and applied when a
  16470. * MediaSource and its associated SourceBuffers are not in the
  16471. * updating state. It is used by the segment loader to update the
  16472. * underlying SourceBuffers when new data is loaded, for instance.
  16473. *
  16474. * @class SourceUpdater
  16475. * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
  16476. * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
  16477. */
  16478. class SourceUpdater extends videojs.EventTarget {
  16479. constructor(mediaSource) {
  16480. super();
  16481. this.mediaSource = mediaSource;
  16482. this.sourceopenListener_ = () => shiftQueue('mediaSource', this);
  16483. this.mediaSource.addEventListener('sourceopen', this.sourceopenListener_);
  16484. this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0
  16485. this.audioTimestampOffset_ = 0;
  16486. this.videoTimestampOffset_ = 0;
  16487. this.queue = [];
  16488. this.queuePending = {
  16489. audio: null,
  16490. video: null
  16491. };
  16492. this.delayedAudioAppendQueue_ = [];
  16493. this.videoAppendQueued_ = false;
  16494. this.codecs = {};
  16495. this.onVideoUpdateEnd_ = onUpdateend('video', this);
  16496. this.onAudioUpdateEnd_ = onUpdateend('audio', this);
  16497. this.onVideoError_ = e => {
  16498. // used for debugging
  16499. this.videoError_ = e;
  16500. };
  16501. this.onAudioError_ = e => {
  16502. // used for debugging
  16503. this.audioError_ = e;
  16504. };
  16505. this.createdSourceBuffers_ = false;
  16506. this.initializedEme_ = false;
  16507. this.triggeredReady_ = false;
  16508. }
  16509. initializedEme() {
  16510. this.initializedEme_ = true;
  16511. this.triggerReady();
  16512. }
  16513. hasCreatedSourceBuffers() {
  16514. // if false, likely waiting on one of the segment loaders to get enough data to create
  16515. // source buffers
  16516. return this.createdSourceBuffers_;
  16517. }
  16518. hasInitializedAnyEme() {
  16519. return this.initializedEme_;
  16520. }
  16521. ready() {
  16522. return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
  16523. }
  16524. createSourceBuffers(codecs) {
  16525. if (this.hasCreatedSourceBuffers()) {
  16526. // already created them before
  16527. return;
  16528. } // the intial addOrChangeSourceBuffers will always be
  16529. // two add buffers.
  16530. this.addOrChangeSourceBuffers(codecs);
  16531. this.createdSourceBuffers_ = true;
  16532. this.trigger('createdsourcebuffers');
  16533. this.triggerReady();
  16534. }
  16535. triggerReady() {
  16536. // only allow ready to be triggered once, this prevents the case
  16537. // where:
  16538. // 1. we trigger createdsourcebuffers
  16539. // 2. ie 11 synchronously initializates eme
  16540. // 3. the synchronous initialization causes us to trigger ready
  16541. // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
  16542. if (this.ready() && !this.triggeredReady_) {
  16543. this.triggeredReady_ = true;
  16544. this.trigger('ready');
  16545. }
  16546. }
  16547. /**
  16548. * Add a type of source buffer to the media source.
  16549. *
  16550. * @param {string} type
  16551. * The type of source buffer to add.
  16552. *
  16553. * @param {string} codec
  16554. * The codec to add the source buffer with.
  16555. */
  16556. addSourceBuffer(type, codec) {
  16557. pushQueue({
  16558. type: 'mediaSource',
  16559. sourceUpdater: this,
  16560. action: actions.addSourceBuffer(type, codec),
  16561. name: 'addSourceBuffer'
  16562. });
  16563. }
  16564. /**
  16565. * call abort on a source buffer.
  16566. *
  16567. * @param {string} type
  16568. * The type of source buffer to call abort on.
  16569. */
  16570. abort(type) {
  16571. pushQueue({
  16572. type,
  16573. sourceUpdater: this,
  16574. action: actions.abort(type),
  16575. name: 'abort'
  16576. });
  16577. }
  16578. /**
  16579. * Call removeSourceBuffer and remove a specific type
  16580. * of source buffer on the mediaSource.
  16581. *
  16582. * @param {string} type
  16583. * The type of source buffer to remove.
  16584. */
  16585. removeSourceBuffer(type) {
  16586. if (!this.canRemoveSourceBuffer()) {
  16587. videojs.log.error('removeSourceBuffer is not supported!');
  16588. return;
  16589. }
  16590. pushQueue({
  16591. type: 'mediaSource',
  16592. sourceUpdater: this,
  16593. action: actions.removeSourceBuffer(type),
  16594. name: 'removeSourceBuffer'
  16595. });
  16596. }
  16597. /**
  16598. * Whether or not the removeSourceBuffer function is supported
  16599. * on the mediaSource.
  16600. *
  16601. * @return {boolean}
  16602. * if removeSourceBuffer can be called.
  16603. */
  16604. canRemoveSourceBuffer() {
  16605. // As of Firefox 83 removeSourceBuffer
  16606. // throws errors, so we report that it does not support this.
  16607. return !videojs.browser.IS_FIREFOX && window$1.MediaSource && window$1.MediaSource.prototype && typeof window$1.MediaSource.prototype.removeSourceBuffer === 'function';
  16608. }
  16609. /**
  16610. * Whether or not the changeType function is supported
  16611. * on our SourceBuffers.
  16612. *
  16613. * @return {boolean}
  16614. * if changeType can be called.
  16615. */
  16616. static canChangeType() {
  16617. return window$1.SourceBuffer && window$1.SourceBuffer.prototype && typeof window$1.SourceBuffer.prototype.changeType === 'function';
  16618. }
  16619. /**
  16620. * Whether or not the changeType function is supported
  16621. * on our SourceBuffers.
  16622. *
  16623. * @return {boolean}
  16624. * if changeType can be called.
  16625. */
  16626. canChangeType() {
  16627. return this.constructor.canChangeType();
  16628. }
  16629. /**
  16630. * Call the changeType function on a source buffer, given the code and type.
  16631. *
  16632. * @param {string} type
  16633. * The type of source buffer to call changeType on.
  16634. *
  16635. * @param {string} codec
  16636. * The codec string to change type with on the source buffer.
  16637. */
  16638. changeType(type, codec) {
  16639. if (!this.canChangeType()) {
  16640. videojs.log.error('changeType is not supported!');
  16641. return;
  16642. }
  16643. pushQueue({
  16644. type,
  16645. sourceUpdater: this,
  16646. action: actions.changeType(codec),
  16647. name: 'changeType'
  16648. });
  16649. }
  16650. /**
  16651. * Add source buffers with a codec or, if they are already created,
  16652. * call changeType on source buffers using changeType.
  16653. *
  16654. * @param {Object} codecs
  16655. * Codecs to switch to
  16656. */
  16657. addOrChangeSourceBuffers(codecs) {
  16658. if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
  16659. throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
  16660. }
  16661. Object.keys(codecs).forEach(type => {
  16662. const codec = codecs[type];
  16663. if (!this.hasCreatedSourceBuffers()) {
  16664. return this.addSourceBuffer(type, codec);
  16665. }
  16666. if (this.canChangeType()) {
  16667. this.changeType(type, codec);
  16668. }
  16669. });
  16670. }
  16671. /**
  16672. * Queue an update to append an ArrayBuffer.
  16673. *
  16674. * @param {MediaObject} object containing audioBytes and/or videoBytes
  16675. * @param {Function} done the function to call when done
  16676. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
  16677. */
  16678. appendBuffer(options, doneFn) {
  16679. const {
  16680. segmentInfo,
  16681. type,
  16682. bytes
  16683. } = options;
  16684. this.processedAppend_ = true;
  16685. if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
  16686. this.delayedAudioAppendQueue_.push([options, doneFn]);
  16687. this.logger_(`delayed audio append of ${bytes.length} until video append`);
  16688. return;
  16689. } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
  16690. // not be fired. This means that the queue will be blocked until the next action
  16691. // taken by the segment-loader. Provide a mechanism for segment-loader to handle
  16692. // these errors by calling the doneFn with the specific error.
  16693. const onError = doneFn;
  16694. pushQueue({
  16695. type,
  16696. sourceUpdater: this,
  16697. action: actions.appendBuffer(bytes, segmentInfo || {
  16698. mediaIndex: -1
  16699. }, onError),
  16700. doneFn,
  16701. name: 'appendBuffer'
  16702. });
  16703. if (type === 'video') {
  16704. this.videoAppendQueued_ = true;
  16705. if (!this.delayedAudioAppendQueue_.length) {
  16706. return;
  16707. }
  16708. const queue = this.delayedAudioAppendQueue_.slice();
  16709. this.logger_(`queuing delayed audio ${queue.length} appendBuffers`);
  16710. this.delayedAudioAppendQueue_.length = 0;
  16711. queue.forEach(que => {
  16712. this.appendBuffer.apply(this, que);
  16713. });
  16714. }
  16715. }
  16716. /**
  16717. * Get the audio buffer's buffered timerange.
  16718. *
  16719. * @return {TimeRange}
  16720. * The audio buffer's buffered time range
  16721. */
  16722. audioBuffered() {
  16723. // no media source/source buffer or it isn't in the media sources
  16724. // source buffer list
  16725. if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
  16726. return createTimeRanges();
  16727. }
  16728. return this.audioBuffer.buffered ? this.audioBuffer.buffered : createTimeRanges();
  16729. }
  16730. /**
  16731. * Get the video buffer's buffered timerange.
  16732. *
  16733. * @return {TimeRange}
  16734. * The video buffer's buffered time range
  16735. */
  16736. videoBuffered() {
  16737. // no media source/source buffer or it isn't in the media sources
  16738. // source buffer list
  16739. if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
  16740. return createTimeRanges();
  16741. }
  16742. return this.videoBuffer.buffered ? this.videoBuffer.buffered : createTimeRanges();
  16743. }
  16744. /**
  16745. * Get a combined video/audio buffer's buffered timerange.
  16746. *
  16747. * @return {TimeRange}
  16748. * the combined time range
  16749. */
  16750. buffered() {
  16751. const video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
  16752. const audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
  16753. if (audio && !video) {
  16754. return this.audioBuffered();
  16755. }
  16756. if (video && !audio) {
  16757. return this.videoBuffered();
  16758. }
  16759. return bufferIntersection(this.audioBuffered(), this.videoBuffered());
  16760. }
  16761. /**
  16762. * Add a callback to the queue that will set duration on the mediaSource.
  16763. *
  16764. * @param {number} duration
  16765. * The duration to set
  16766. *
  16767. * @param {Function} [doneFn]
  16768. * function to run after duration has been set.
  16769. */
  16770. setDuration(duration, doneFn = noop) {
  16771. // In order to set the duration on the media source, it's necessary to wait for all
  16772. // source buffers to no longer be updating. "If the updating attribute equals true on
  16773. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  16774. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  16775. pushQueue({
  16776. type: 'mediaSource',
  16777. sourceUpdater: this,
  16778. action: actions.duration(duration),
  16779. name: 'duration',
  16780. doneFn
  16781. });
  16782. }
  16783. /**
  16784. * Add a mediaSource endOfStream call to the queue
  16785. *
  16786. * @param {Error} [error]
  16787. * Call endOfStream with an error
  16788. *
  16789. * @param {Function} [doneFn]
  16790. * A function that should be called when the
  16791. * endOfStream call has finished.
  16792. */
  16793. endOfStream(error = null, doneFn = noop) {
  16794. if (typeof error !== 'string') {
  16795. error = undefined;
  16796. } // In order to set the duration on the media source, it's necessary to wait for all
  16797. // source buffers to no longer be updating. "If the updating attribute equals true on
  16798. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  16799. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  16800. pushQueue({
  16801. type: 'mediaSource',
  16802. sourceUpdater: this,
  16803. action: actions.endOfStream(error),
  16804. name: 'endOfStream',
  16805. doneFn
  16806. });
  16807. }
  16808. /**
  16809. * Queue an update to remove a time range from the buffer.
  16810. *
  16811. * @param {number} start where to start the removal
  16812. * @param {number} end where to end the removal
  16813. * @param {Function} [done=noop] optional callback to be executed when the remove
  16814. * operation is complete
  16815. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  16816. */
  16817. removeAudio(start, end, done = noop) {
  16818. if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
  16819. done();
  16820. return;
  16821. }
  16822. pushQueue({
  16823. type: 'audio',
  16824. sourceUpdater: this,
  16825. action: actions.remove(start, end),
  16826. doneFn: done,
  16827. name: 'remove'
  16828. });
  16829. }
  16830. /**
  16831. * Queue an update to remove a time range from the buffer.
  16832. *
  16833. * @param {number} start where to start the removal
  16834. * @param {number} end where to end the removal
  16835. * @param {Function} [done=noop] optional callback to be executed when the remove
  16836. * operation is complete
  16837. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  16838. */
  16839. removeVideo(start, end, done = noop) {
  16840. if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
  16841. done();
  16842. return;
  16843. }
  16844. pushQueue({
  16845. type: 'video',
  16846. sourceUpdater: this,
  16847. action: actions.remove(start, end),
  16848. doneFn: done,
  16849. name: 'remove'
  16850. });
  16851. }
  16852. /**
  16853. * Whether the underlying sourceBuffer is updating or not
  16854. *
  16855. * @return {boolean} the updating status of the SourceBuffer
  16856. */
  16857. updating() {
  16858. // the audio/video source buffer is updating
  16859. if (updating('audio', this) || updating('video', this)) {
  16860. return true;
  16861. }
  16862. return false;
  16863. }
  16864. /**
  16865. * Set/get the timestampoffset on the audio SourceBuffer
  16866. *
  16867. * @return {number} the timestamp offset
  16868. */
  16869. audioTimestampOffset(offset) {
  16870. if (typeof offset !== 'undefined' && this.audioBuffer && // no point in updating if it's the same
  16871. this.audioTimestampOffset_ !== offset) {
  16872. pushQueue({
  16873. type: 'audio',
  16874. sourceUpdater: this,
  16875. action: actions.timestampOffset(offset),
  16876. name: 'timestampOffset'
  16877. });
  16878. this.audioTimestampOffset_ = offset;
  16879. }
  16880. return this.audioTimestampOffset_;
  16881. }
  16882. /**
  16883. * Set/get the timestampoffset on the video SourceBuffer
  16884. *
  16885. * @return {number} the timestamp offset
  16886. */
  16887. videoTimestampOffset(offset) {
  16888. if (typeof offset !== 'undefined' && this.videoBuffer && // no point in updating if it's the same
  16889. this.videoTimestampOffset !== offset) {
  16890. pushQueue({
  16891. type: 'video',
  16892. sourceUpdater: this,
  16893. action: actions.timestampOffset(offset),
  16894. name: 'timestampOffset'
  16895. });
  16896. this.videoTimestampOffset_ = offset;
  16897. }
  16898. return this.videoTimestampOffset_;
  16899. }
  16900. /**
  16901. * Add a function to the queue that will be called
  16902. * when it is its turn to run in the audio queue.
  16903. *
  16904. * @param {Function} callback
  16905. * The callback to queue.
  16906. */
  16907. audioQueueCallback(callback) {
  16908. if (!this.audioBuffer) {
  16909. return;
  16910. }
  16911. pushQueue({
  16912. type: 'audio',
  16913. sourceUpdater: this,
  16914. action: actions.callback(callback),
  16915. name: 'callback'
  16916. });
  16917. }
  16918. /**
  16919. * Add a function to the queue that will be called
  16920. * when it is its turn to run in the video queue.
  16921. *
  16922. * @param {Function} callback
  16923. * The callback to queue.
  16924. */
  16925. videoQueueCallback(callback) {
  16926. if (!this.videoBuffer) {
  16927. return;
  16928. }
  16929. pushQueue({
  16930. type: 'video',
  16931. sourceUpdater: this,
  16932. action: actions.callback(callback),
  16933. name: 'callback'
  16934. });
  16935. }
  16936. /**
  16937. * dispose of the source updater and the underlying sourceBuffer
  16938. */
  16939. dispose() {
  16940. this.trigger('dispose');
  16941. bufferTypes.forEach(type => {
  16942. this.abort(type);
  16943. if (this.canRemoveSourceBuffer()) {
  16944. this.removeSourceBuffer(type);
  16945. } else {
  16946. this[`${type}QueueCallback`](() => cleanupBuffer(type, this));
  16947. }
  16948. });
  16949. this.videoAppendQueued_ = false;
  16950. this.delayedAudioAppendQueue_.length = 0;
  16951. if (this.sourceopenListener_) {
  16952. this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
  16953. }
  16954. this.off();
  16955. }
  16956. }
  16957. const uint8ToUtf8 = uintArray => decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
  16958. const bufferToHexString = buffer => {
  16959. const uInt8Buffer = new Uint8Array(buffer);
  16960. return Array.from(uInt8Buffer).map(byte => byte.toString(16).padStart(2, '0')).join('');
  16961. };
  16962. /**
  16963. * @file vtt-segment-loader.js
  16964. */
  16965. const VTT_LINE_TERMINATORS = new Uint8Array('\n\n'.split('').map(char => char.charCodeAt(0)));
  16966. class NoVttJsError extends Error {
  16967. constructor() {
  16968. super('Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.');
  16969. }
  16970. }
  16971. /**
  16972. * An object that manages segment loading and appending.
  16973. *
  16974. * @class VTTSegmentLoader
  16975. * @param {Object} options required and optional options
  16976. * @extends videojs.EventTarget
  16977. */
  16978. class VTTSegmentLoader extends SegmentLoader {
  16979. constructor(settings, options = {}) {
  16980. super(settings, options); // SegmentLoader requires a MediaSource be specified or it will throw an error;
  16981. // however, VTTSegmentLoader has no need of a media source, so delete the reference
  16982. this.mediaSource_ = null;
  16983. this.subtitlesTrack_ = null;
  16984. this.loaderType_ = 'subtitle';
  16985. this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks;
  16986. this.loadVttJs = settings.loadVttJs; // The VTT segment will have its own time mappings. Saving VTT segment timing info in
  16987. // the sync controller leads to improper behavior.
  16988. this.shouldSaveSegmentTimingInfo_ = false;
  16989. }
  16990. createTransmuxer_() {
  16991. // don't need to transmux any subtitles
  16992. return null;
  16993. }
  16994. /**
  16995. * Indicates which time ranges are buffered
  16996. *
  16997. * @return {TimeRange}
  16998. * TimeRange object representing the current buffered ranges
  16999. */
  17000. buffered_() {
  17001. if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
  17002. return createTimeRanges();
  17003. }
  17004. const cues = this.subtitlesTrack_.cues;
  17005. const start = cues[0].startTime;
  17006. const end = cues[cues.length - 1].startTime;
  17007. return createTimeRanges([[start, end]]);
  17008. }
  17009. /**
  17010. * Gets and sets init segment for the provided map
  17011. *
  17012. * @param {Object} map
  17013. * The map object representing the init segment to get or set
  17014. * @param {boolean=} set
  17015. * If true, the init segment for the provided map should be saved
  17016. * @return {Object}
  17017. * map object for desired init segment
  17018. */
  17019. initSegmentForMap(map, set = false) {
  17020. if (!map) {
  17021. return null;
  17022. }
  17023. const id = initSegmentId(map);
  17024. let storedMap = this.initSegments_[id];
  17025. if (set && !storedMap && map.bytes) {
  17026. // append WebVTT line terminators to the media initialization segment if it exists
  17027. // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
  17028. // requires two or more WebVTT line terminators between the WebVTT header and the
  17029. // rest of the file
  17030. const combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
  17031. const combinedSegment = new Uint8Array(combinedByteLength);
  17032. combinedSegment.set(map.bytes);
  17033. combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
  17034. this.initSegments_[id] = storedMap = {
  17035. resolvedUri: map.resolvedUri,
  17036. byterange: map.byterange,
  17037. bytes: combinedSegment
  17038. };
  17039. }
  17040. return storedMap || map;
  17041. }
  17042. /**
  17043. * Returns true if all configuration required for loading is present, otherwise false.
  17044. *
  17045. * @return {boolean} True if the all configuration is ready for loading
  17046. * @private
  17047. */
  17048. couldBeginLoading_() {
  17049. return this.playlist_ && this.subtitlesTrack_ && !this.paused();
  17050. }
  17051. /**
  17052. * Once all the starting parameters have been specified, begin
  17053. * operation. This method should only be invoked from the INIT
  17054. * state.
  17055. *
  17056. * @private
  17057. */
  17058. init_() {
  17059. this.state = 'READY';
  17060. this.resetEverything();
  17061. return this.monitorBuffer_();
  17062. }
  17063. /**
  17064. * Set a subtitle track on the segment loader to add subtitles to
  17065. *
  17066. * @param {TextTrack=} track
  17067. * The text track to add loaded subtitles to
  17068. * @return {TextTrack}
  17069. * Returns the subtitles track
  17070. */
  17071. track(track) {
  17072. if (typeof track === 'undefined') {
  17073. return this.subtitlesTrack_;
  17074. }
  17075. this.subtitlesTrack_ = track; // if we were unpaused but waiting for a sourceUpdater, start
  17076. // buffering now
  17077. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  17078. this.init_();
  17079. }
  17080. return this.subtitlesTrack_;
  17081. }
  17082. /**
  17083. * Remove any data in the source buffer between start and end times
  17084. *
  17085. * @param {number} start - the start time of the region to remove from the buffer
  17086. * @param {number} end - the end time of the region to remove from the buffer
  17087. */
  17088. remove(start, end) {
  17089. removeCuesFromTrack(start, end, this.subtitlesTrack_);
  17090. }
  17091. /**
  17092. * fill the buffer with segements unless the sourceBuffers are
  17093. * currently updating
  17094. *
  17095. * Note: this function should only ever be called by monitorBuffer_
  17096. * and never directly
  17097. *
  17098. * @private
  17099. */
  17100. fillBuffer_() {
  17101. // see if we need to begin loading immediately
  17102. const segmentInfo = this.chooseNextRequest_();
  17103. if (!segmentInfo) {
  17104. return;
  17105. }
  17106. if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
  17107. // We don't have the timestamp offset that we need to sync subtitles.
  17108. // Rerun on a timestamp offset or user interaction.
  17109. const checkTimestampOffset = () => {
  17110. this.state = 'READY';
  17111. if (!this.paused()) {
  17112. // if not paused, queue a buffer check as soon as possible
  17113. this.monitorBuffer_();
  17114. }
  17115. };
  17116. this.syncController_.one('timestampoffset', checkTimestampOffset);
  17117. this.state = 'WAITING_ON_TIMELINE';
  17118. return;
  17119. }
  17120. this.loadSegment_(segmentInfo);
  17121. } // never set a timestamp offset for vtt segments.
  17122. timestampOffsetForSegment_() {
  17123. return null;
  17124. }
  17125. chooseNextRequest_() {
  17126. return this.skipEmptySegments_(super.chooseNextRequest_());
  17127. }
  17128. /**
  17129. * Prevents the segment loader from requesting segments we know contain no subtitles
  17130. * by walking forward until we find the next segment that we don't know whether it is
  17131. * empty or not.
  17132. *
  17133. * @param {Object} segmentInfo
  17134. * a segment info object that describes the current segment
  17135. * @return {Object}
  17136. * a segment info object that describes the current segment
  17137. */
  17138. skipEmptySegments_(segmentInfo) {
  17139. while (segmentInfo && segmentInfo.segment.empty) {
  17140. // stop at the last possible segmentInfo
  17141. if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
  17142. segmentInfo = null;
  17143. break;
  17144. }
  17145. segmentInfo = this.generateSegmentInfo_({
  17146. playlist: segmentInfo.playlist,
  17147. mediaIndex: segmentInfo.mediaIndex + 1,
  17148. startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
  17149. isSyncRequest: segmentInfo.isSyncRequest
  17150. });
  17151. }
  17152. return segmentInfo;
  17153. }
  17154. stopForError(error) {
  17155. this.error(error);
  17156. this.state = 'READY';
  17157. this.pause();
  17158. this.trigger('error');
  17159. }
  17160. /**
  17161. * append a decrypted segement to the SourceBuffer through a SourceUpdater
  17162. *
  17163. * @private
  17164. */
  17165. segmentRequestFinished_(error, simpleSegment, result) {
  17166. if (!this.subtitlesTrack_) {
  17167. this.state = 'READY';
  17168. return;
  17169. }
  17170. this.saveTransferStats_(simpleSegment.stats); // the request was aborted
  17171. if (!this.pendingSegment_) {
  17172. this.state = 'READY';
  17173. this.mediaRequestsAborted += 1;
  17174. return;
  17175. }
  17176. if (error) {
  17177. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  17178. this.handleTimeout_();
  17179. }
  17180. if (error.code === REQUEST_ERRORS.ABORTED) {
  17181. this.mediaRequestsAborted += 1;
  17182. } else {
  17183. this.mediaRequestsErrored += 1;
  17184. }
  17185. this.stopForError(error);
  17186. return;
  17187. }
  17188. const segmentInfo = this.pendingSegment_; // although the VTT segment loader bandwidth isn't really used, it's good to
  17189. // maintain functionality between segment loaders
  17190. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats); // if this request included a segment key, save that data in the cache
  17191. if (simpleSegment.key) {
  17192. this.segmentKey(simpleSegment.key, true);
  17193. }
  17194. this.state = 'APPENDING'; // used for tests
  17195. this.trigger('appending');
  17196. const segment = segmentInfo.segment;
  17197. if (segment.map) {
  17198. segment.map.bytes = simpleSegment.map.bytes;
  17199. }
  17200. segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, load it and wait till it finished loading
  17201. if (typeof window$1.WebVTT !== 'function' && typeof this.loadVttJs === 'function') {
  17202. this.state = 'WAITING_ON_VTTJS'; // should be fine to call multiple times
  17203. // script will be loaded once but multiple listeners will be added to the queue, which is expected.
  17204. this.loadVttJs().then(() => this.segmentRequestFinished_(error, simpleSegment, result), () => this.stopForError({
  17205. message: 'Error loading vtt.js'
  17206. }));
  17207. return;
  17208. }
  17209. segment.requested = true;
  17210. try {
  17211. this.parseVTTCues_(segmentInfo);
  17212. } catch (e) {
  17213. this.stopForError({
  17214. message: e.message
  17215. });
  17216. return;
  17217. }
  17218. this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
  17219. if (segmentInfo.cues.length) {
  17220. segmentInfo.timingInfo = {
  17221. start: segmentInfo.cues[0].startTime,
  17222. end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
  17223. };
  17224. } else {
  17225. segmentInfo.timingInfo = {
  17226. start: segmentInfo.startOfSegment,
  17227. end: segmentInfo.startOfSegment + segmentInfo.duration
  17228. };
  17229. }
  17230. if (segmentInfo.isSyncRequest) {
  17231. this.trigger('syncinfoupdate');
  17232. this.pendingSegment_ = null;
  17233. this.state = 'READY';
  17234. return;
  17235. }
  17236. segmentInfo.byteLength = segmentInfo.bytes.byteLength;
  17237. this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to
  17238. // the subtitle track
  17239. segmentInfo.cues.forEach(cue => {
  17240. this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_ ? new window$1.VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
  17241. }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
  17242. // cues to have identical time-intervals, but if the text is also identical
  17243. // we can safely assume it is a duplicate that can be removed (ex. when a cue
  17244. // "overlaps" VTT segments)
  17245. removeDuplicateCuesFromTrack(this.subtitlesTrack_);
  17246. this.handleAppendsDone_();
  17247. }
  17248. handleData_() {// noop as we shouldn't be getting video/audio data captions
  17249. // that we do not support here.
  17250. }
  17251. updateTimingInfoEnd_() {// noop
  17252. }
  17253. /**
  17254. * Uses the WebVTT parser to parse the segment response
  17255. *
  17256. * @throws NoVttJsError
  17257. *
  17258. * @param {Object} segmentInfo
  17259. * a segment info object that describes the current segment
  17260. * @private
  17261. */
  17262. parseVTTCues_(segmentInfo) {
  17263. let decoder;
  17264. let decodeBytesToString = false;
  17265. if (typeof window$1.WebVTT !== 'function') {
  17266. // caller is responsible for exception handling.
  17267. throw new NoVttJsError();
  17268. }
  17269. if (typeof window$1.TextDecoder === 'function') {
  17270. decoder = new window$1.TextDecoder('utf8');
  17271. } else {
  17272. decoder = window$1.WebVTT.StringDecoder();
  17273. decodeBytesToString = true;
  17274. }
  17275. const parser = new window$1.WebVTT.Parser(window$1, window$1.vttjs, decoder);
  17276. segmentInfo.cues = [];
  17277. segmentInfo.timestampmap = {
  17278. MPEGTS: 0,
  17279. LOCAL: 0
  17280. };
  17281. parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
  17282. parser.ontimestampmap = map => {
  17283. segmentInfo.timestampmap = map;
  17284. };
  17285. parser.onparsingerror = error => {
  17286. videojs.log.warn('Error encountered when parsing cues: ' + error.message);
  17287. };
  17288. if (segmentInfo.segment.map) {
  17289. let mapData = segmentInfo.segment.map.bytes;
  17290. if (decodeBytesToString) {
  17291. mapData = uint8ToUtf8(mapData);
  17292. }
  17293. parser.parse(mapData);
  17294. }
  17295. let segmentData = segmentInfo.bytes;
  17296. if (decodeBytesToString) {
  17297. segmentData = uint8ToUtf8(segmentData);
  17298. }
  17299. parser.parse(segmentData);
  17300. parser.flush();
  17301. }
  17302. /**
  17303. * Updates the start and end times of any cues parsed by the WebVTT parser using
  17304. * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
  17305. * from the SyncController
  17306. *
  17307. * @param {Object} segmentInfo
  17308. * a segment info object that describes the current segment
  17309. * @param {Object} mappingObj
  17310. * object containing a mapping from TS to media time
  17311. * @param {Object} playlist
  17312. * the playlist object containing the segment
  17313. * @private
  17314. */
  17315. updateTimeMapping_(segmentInfo, mappingObj, playlist) {
  17316. const segment = segmentInfo.segment;
  17317. if (!mappingObj) {
  17318. // If the sync controller does not have a mapping of TS to Media Time for the
  17319. // timeline, then we don't have enough information to update the cue
  17320. // start/end times
  17321. return;
  17322. }
  17323. if (!segmentInfo.cues.length) {
  17324. // If there are no cues, we also do not have enough information to figure out
  17325. // segment timing. Mark that the segment contains no cues so we don't re-request
  17326. // an empty segment.
  17327. segment.empty = true;
  17328. return;
  17329. }
  17330. const {
  17331. MPEGTS,
  17332. LOCAL
  17333. } = segmentInfo.timestampmap;
  17334. /**
  17335. * From the spec:
  17336. * The MPEGTS media timestamp MUST use a 90KHz timescale,
  17337. * even when non-WebVTT Media Segments use a different timescale.
  17338. */
  17339. const mpegTsInSeconds = MPEGTS / ONE_SECOND_IN_TS;
  17340. const diff = mpegTsInSeconds - LOCAL + mappingObj.mapping;
  17341. segmentInfo.cues.forEach(cue => {
  17342. const duration = cue.endTime - cue.startTime;
  17343. const startTime = MPEGTS === 0 ? cue.startTime + diff : this.handleRollover_(cue.startTime + diff, mappingObj.time);
  17344. cue.startTime = Math.max(startTime, 0);
  17345. cue.endTime = Math.max(startTime + duration, 0);
  17346. });
  17347. if (!playlist.syncInfo) {
  17348. const firstStart = segmentInfo.cues[0].startTime;
  17349. const lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
  17350. playlist.syncInfo = {
  17351. mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
  17352. time: Math.min(firstStart, lastStart - segment.duration)
  17353. };
  17354. }
  17355. }
  17356. /**
  17357. * MPEG-TS PES timestamps are limited to 2^33.
  17358. * Once they reach 2^33, they roll over to 0.
  17359. * mux.js handles PES timestamp rollover for the following scenarios:
  17360. * [forward rollover(right)] ->
  17361. * PES timestamps monotonically increase, and once they reach 2^33, they roll over to 0
  17362. * [backward rollover(left)] -->
  17363. * we seek back to position before rollover.
  17364. *
  17365. * According to the HLS SPEC:
  17366. * When synchronizing WebVTT with PES timestamps, clients SHOULD account
  17367. * for cases where the 33-bit PES timestamps have wrapped and the WebVTT
  17368. * cue times have not. When the PES timestamp wraps, the WebVTT Segment
  17369. * SHOULD have a X-TIMESTAMP-MAP header that maps the current WebVTT
  17370. * time to the new (low valued) PES timestamp.
  17371. *
  17372. * So we want to handle rollover here and align VTT Cue start/end time to the player's time.
  17373. */
  17374. handleRollover_(value, reference) {
  17375. if (reference === null) {
  17376. return value;
  17377. }
  17378. let valueIn90khz = value * ONE_SECOND_IN_TS;
  17379. const referenceIn90khz = reference * ONE_SECOND_IN_TS;
  17380. let offset;
  17381. if (referenceIn90khz < valueIn90khz) {
  17382. // - 2^33
  17383. offset = -8589934592;
  17384. } else {
  17385. // + 2^33
  17386. offset = 8589934592;
  17387. } // distance(value - reference) > 2^32
  17388. while (Math.abs(valueIn90khz - referenceIn90khz) > 4294967296) {
  17389. valueIn90khz += offset;
  17390. }
  17391. return valueIn90khz / ONE_SECOND_IN_TS;
  17392. }
  17393. }
  17394. /**
  17395. * @file ad-cue-tags.js
  17396. */
  17397. /**
  17398. * Searches for an ad cue that overlaps with the given mediaTime
  17399. *
  17400. * @param {Object} track
  17401. * the track to find the cue for
  17402. *
  17403. * @param {number} mediaTime
  17404. * the time to find the cue at
  17405. *
  17406. * @return {Object|null}
  17407. * the found cue or null
  17408. */
  17409. const findAdCue = function (track, mediaTime) {
  17410. const cues = track.cues;
  17411. for (let i = 0; i < cues.length; i++) {
  17412. const cue = cues[i];
  17413. if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
  17414. return cue;
  17415. }
  17416. }
  17417. return null;
  17418. };
  17419. const updateAdCues = function (media, track, offset = 0) {
  17420. if (!media.segments) {
  17421. return;
  17422. }
  17423. let mediaTime = offset;
  17424. let cue;
  17425. for (let i = 0; i < media.segments.length; i++) {
  17426. const segment = media.segments[i];
  17427. if (!cue) {
  17428. // Since the cues will span for at least the segment duration, adding a fudge
  17429. // factor of half segment duration will prevent duplicate cues from being
  17430. // created when timing info is not exact (e.g. cue start time initialized
  17431. // at 10.006677, but next call mediaTime is 10.003332 )
  17432. cue = findAdCue(track, mediaTime + segment.duration / 2);
  17433. }
  17434. if (cue) {
  17435. if ('cueIn' in segment) {
  17436. // Found a CUE-IN so end the cue
  17437. cue.endTime = mediaTime;
  17438. cue.adEndTime = mediaTime;
  17439. mediaTime += segment.duration;
  17440. cue = null;
  17441. continue;
  17442. }
  17443. if (mediaTime < cue.endTime) {
  17444. // Already processed this mediaTime for this cue
  17445. mediaTime += segment.duration;
  17446. continue;
  17447. } // otherwise extend cue until a CUE-IN is found
  17448. cue.endTime += segment.duration;
  17449. } else {
  17450. if ('cueOut' in segment) {
  17451. cue = new window$1.VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
  17452. cue.adStartTime = mediaTime; // Assumes tag format to be
  17453. // #EXT-X-CUE-OUT:30
  17454. cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
  17455. track.addCue(cue);
  17456. }
  17457. if ('cueOutCont' in segment) {
  17458. // Entered into the middle of an ad cue
  17459. // Assumes tag formate to be
  17460. // #EXT-X-CUE-OUT-CONT:10/30
  17461. const [adOffset, adTotal] = segment.cueOutCont.split('/').map(parseFloat);
  17462. cue = new window$1.VTTCue(mediaTime, mediaTime + segment.duration, '');
  17463. cue.adStartTime = mediaTime - adOffset;
  17464. cue.adEndTime = cue.adStartTime + adTotal;
  17465. track.addCue(cue);
  17466. }
  17467. }
  17468. mediaTime += segment.duration;
  17469. }
  17470. };
  17471. /**
  17472. * @file sync-controller.js
  17473. */
  17474. // synchronize expired playlist segments.
  17475. // the max media sequence diff is 48 hours of live stream
  17476. // content with two second segments. Anything larger than that
  17477. // will likely be invalid.
  17478. const MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC = 86400;
  17479. const syncPointStrategies = [// Stategy "VOD": Handle the VOD-case where the sync-point is *always*
  17480. // the equivalence display-time 0 === segment-index 0
  17481. {
  17482. name: 'VOD',
  17483. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  17484. if (duration !== Infinity) {
  17485. const syncPoint = {
  17486. time: 0,
  17487. segmentIndex: 0,
  17488. partIndex: null
  17489. };
  17490. return syncPoint;
  17491. }
  17492. return null;
  17493. }
  17494. }, {
  17495. name: 'MediaSequence',
  17496. /**
  17497. * run media sequence strategy
  17498. *
  17499. * @param {SyncController} syncController
  17500. * @param {Object} playlist
  17501. * @param {number} duration
  17502. * @param {number} currentTimeline
  17503. * @param {number} currentTime
  17504. * @param {string} type
  17505. */
  17506. run: (syncController, playlist, duration, currentTimeline, currentTime, type) => {
  17507. if (!type) {
  17508. return null;
  17509. }
  17510. const mediaSequenceMap = syncController.getMediaSequenceMap(type);
  17511. if (!mediaSequenceMap || mediaSequenceMap.size === 0) {
  17512. return null;
  17513. }
  17514. if (playlist.mediaSequence === undefined || !Array.isArray(playlist.segments) || !playlist.segments.length) {
  17515. return null;
  17516. }
  17517. let currentMediaSequence = playlist.mediaSequence;
  17518. let segmentIndex = 0;
  17519. for (const segment of playlist.segments) {
  17520. const range = mediaSequenceMap.get(currentMediaSequence);
  17521. if (!range) {
  17522. // unexpected case
  17523. // we expect this playlist to be the same playlist in the map
  17524. // just break from the loop and move forward to the next strategy
  17525. break;
  17526. }
  17527. if (currentTime >= range.start && currentTime < range.end) {
  17528. // we found segment
  17529. if (Array.isArray(segment.parts) && segment.parts.length) {
  17530. let currentPartStart = range.start;
  17531. let partIndex = 0;
  17532. for (const part of segment.parts) {
  17533. const start = currentPartStart;
  17534. const end = start + part.duration;
  17535. if (currentTime >= start && currentTime < end) {
  17536. return {
  17537. time: range.start,
  17538. segmentIndex,
  17539. partIndex
  17540. };
  17541. }
  17542. partIndex++;
  17543. currentPartStart = end;
  17544. }
  17545. } // no parts found, return sync point for segment
  17546. return {
  17547. time: range.start,
  17548. segmentIndex,
  17549. partIndex: null
  17550. };
  17551. }
  17552. segmentIndex++;
  17553. currentMediaSequence++;
  17554. } // we didn't find any segments for provided current time
  17555. return null;
  17556. }
  17557. }, // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
  17558. {
  17559. name: 'ProgramDateTime',
  17560. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  17561. if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
  17562. return null;
  17563. }
  17564. let syncPoint = null;
  17565. let lastDistance = null;
  17566. const partsAndSegments = getPartsAndSegments(playlist);
  17567. currentTime = currentTime || 0;
  17568. for (let i = 0; i < partsAndSegments.length; i++) {
  17569. // start from the end and loop backwards for live
  17570. // or start from the front and loop forwards for non-live
  17571. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  17572. const partAndSegment = partsAndSegments[index];
  17573. const segment = partAndSegment.segment;
  17574. const datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
  17575. if (!datetimeMapping || !segment.dateTimeObject) {
  17576. continue;
  17577. }
  17578. const segmentTime = segment.dateTimeObject.getTime() / 1000;
  17579. let start = segmentTime + datetimeMapping; // take part duration into account.
  17580. if (segment.parts && typeof partAndSegment.partIndex === 'number') {
  17581. for (let z = 0; z < partAndSegment.partIndex; z++) {
  17582. start += segment.parts[z].duration;
  17583. }
  17584. }
  17585. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed
  17586. // currentTime and can stop looking for better candidates
  17587. if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
  17588. break;
  17589. }
  17590. lastDistance = distance;
  17591. syncPoint = {
  17592. time: start,
  17593. segmentIndex: partAndSegment.segmentIndex,
  17594. partIndex: partAndSegment.partIndex
  17595. };
  17596. }
  17597. return syncPoint;
  17598. }
  17599. }, // Stategy "Segment": We have a known time mapping for a timeline and a
  17600. // segment in the current timeline with timing data
  17601. {
  17602. name: 'Segment',
  17603. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  17604. let syncPoint = null;
  17605. let lastDistance = null;
  17606. currentTime = currentTime || 0;
  17607. const partsAndSegments = getPartsAndSegments(playlist);
  17608. for (let i = 0; i < partsAndSegments.length; i++) {
  17609. // start from the end and loop backwards for live
  17610. // or start from the front and loop forwards for non-live
  17611. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  17612. const partAndSegment = partsAndSegments[index];
  17613. const segment = partAndSegment.segment;
  17614. const start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
  17615. if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
  17616. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed
  17617. // currentTime and can stop looking for better candidates
  17618. if (lastDistance !== null && lastDistance < distance) {
  17619. break;
  17620. }
  17621. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  17622. lastDistance = distance;
  17623. syncPoint = {
  17624. time: start,
  17625. segmentIndex: partAndSegment.segmentIndex,
  17626. partIndex: partAndSegment.partIndex
  17627. };
  17628. }
  17629. }
  17630. }
  17631. return syncPoint;
  17632. }
  17633. }, // Stategy "Discontinuity": We have a discontinuity with a known
  17634. // display-time
  17635. {
  17636. name: 'Discontinuity',
  17637. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  17638. let syncPoint = null;
  17639. currentTime = currentTime || 0;
  17640. if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  17641. let lastDistance = null;
  17642. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  17643. const segmentIndex = playlist.discontinuityStarts[i];
  17644. const discontinuity = playlist.discontinuitySequence + i + 1;
  17645. const discontinuitySync = syncController.discontinuities[discontinuity];
  17646. if (discontinuitySync) {
  17647. const distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed
  17648. // currentTime and can stop looking for better candidates
  17649. if (lastDistance !== null && lastDistance < distance) {
  17650. break;
  17651. }
  17652. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  17653. lastDistance = distance;
  17654. syncPoint = {
  17655. time: discontinuitySync.time,
  17656. segmentIndex,
  17657. partIndex: null
  17658. };
  17659. }
  17660. }
  17661. }
  17662. }
  17663. return syncPoint;
  17664. }
  17665. }, // Stategy "Playlist": We have a playlist with a known mapping of
  17666. // segment index to display time
  17667. {
  17668. name: 'Playlist',
  17669. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  17670. if (playlist.syncInfo) {
  17671. const syncPoint = {
  17672. time: playlist.syncInfo.time,
  17673. segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
  17674. partIndex: null
  17675. };
  17676. return syncPoint;
  17677. }
  17678. return null;
  17679. }
  17680. }];
  17681. class SyncController extends videojs.EventTarget {
  17682. constructor(options = {}) {
  17683. super(); // ...for synching across variants
  17684. this.timelines = [];
  17685. this.discontinuities = [];
  17686. this.timelineToDatetimeMappings = {};
  17687. /**
  17688. * @type {Map<string, Map<number, { start: number, end: number }>>}
  17689. * @private
  17690. */
  17691. this.mediaSequenceStorage_ = new Map();
  17692. this.logger_ = logger('SyncController');
  17693. }
  17694. /**
  17695. * Get media sequence map by type
  17696. *
  17697. * @param {string} type - segment loader type
  17698. * @return {Map<number, { start: number, end: number }> | undefined}
  17699. */
  17700. getMediaSequenceMap(type) {
  17701. return this.mediaSequenceStorage_.get(type);
  17702. }
  17703. /**
  17704. * Update Media Sequence Map -> <MediaSequence, Range>
  17705. *
  17706. * @param {Object} playlist - parsed playlist
  17707. * @param {number} currentTime - current player's time
  17708. * @param {string} type - segment loader type
  17709. * @return {void}
  17710. */
  17711. updateMediaSequenceMap(playlist, currentTime, type) {
  17712. // we should not process this playlist if it does not have mediaSequence or segments
  17713. if (playlist.mediaSequence === undefined || !Array.isArray(playlist.segments) || !playlist.segments.length) {
  17714. return;
  17715. }
  17716. const currentMap = this.getMediaSequenceMap(type);
  17717. const result = new Map();
  17718. let currentMediaSequence = playlist.mediaSequence;
  17719. let currentBaseTime;
  17720. if (!currentMap) {
  17721. // first playlist setup:
  17722. currentBaseTime = 0;
  17723. } else if (currentMap.has(playlist.mediaSequence)) {
  17724. // further playlists setup:
  17725. currentBaseTime = currentMap.get(playlist.mediaSequence).start;
  17726. } else {
  17727. // it seems like we have a gap between playlists, use current time as a fallback:
  17728. this.logger_(`MediaSequence sync for ${type} segment loader - received a gap between playlists.
  17729. Fallback base time to: ${currentTime}.
  17730. Received media sequence: ${currentMediaSequence}.
  17731. Current map: `, currentMap);
  17732. currentBaseTime = currentTime;
  17733. }
  17734. this.logger_(`MediaSequence sync for ${type} segment loader.
  17735. Received media sequence: ${currentMediaSequence}.
  17736. base time is ${currentBaseTime}
  17737. Current map: `, currentMap);
  17738. playlist.segments.forEach(segment => {
  17739. const start = currentBaseTime;
  17740. const end = start + segment.duration;
  17741. const range = {
  17742. start,
  17743. end
  17744. };
  17745. result.set(currentMediaSequence, range);
  17746. currentMediaSequence++;
  17747. currentBaseTime = end;
  17748. });
  17749. this.mediaSequenceStorage_.set(type, result);
  17750. }
  17751. /**
  17752. * Find a sync-point for the playlist specified
  17753. *
  17754. * A sync-point is defined as a known mapping from display-time to
  17755. * a segment-index in the current playlist.
  17756. *
  17757. * @param {Playlist} playlist
  17758. * The playlist that needs a sync-point
  17759. * @param {number} duration
  17760. * Duration of the MediaSource (Infinite if playing a live source)
  17761. * @param {number} currentTimeline
  17762. * The last timeline from which a segment was loaded
  17763. * @param {number} currentTime
  17764. * Current player's time
  17765. * @param {string} type
  17766. * Segment loader type
  17767. * @return {Object}
  17768. * A sync-point object
  17769. */
  17770. getSyncPoint(playlist, duration, currentTimeline, currentTime, type) {
  17771. // Always use VOD sync point for VOD
  17772. if (duration !== Infinity) {
  17773. const vodSyncPointStrategy = syncPointStrategies.find(({
  17774. name
  17775. }) => name === 'VOD');
  17776. return vodSyncPointStrategy.run(this, playlist, duration);
  17777. }
  17778. const syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime, type);
  17779. if (!syncPoints.length) {
  17780. // Signal that we need to attempt to get a sync-point manually
  17781. // by fetching a segment in the playlist and constructing
  17782. // a sync-point from that information
  17783. return null;
  17784. } // If we have exact match just return it instead of finding the nearest distance
  17785. for (const syncPointInfo of syncPoints) {
  17786. const {
  17787. syncPoint,
  17788. strategy
  17789. } = syncPointInfo;
  17790. const {
  17791. segmentIndex,
  17792. time
  17793. } = syncPoint;
  17794. if (segmentIndex < 0) {
  17795. continue;
  17796. }
  17797. const selectedSegment = playlist.segments[segmentIndex];
  17798. const start = time;
  17799. const end = start + selectedSegment.duration;
  17800. this.logger_(`Strategy: ${strategy}. Current time: ${currentTime}. selected segment: ${segmentIndex}. Time: [${start} -> ${end}]}`);
  17801. if (currentTime >= start && currentTime < end) {
  17802. this.logger_('Found sync point with exact match: ', syncPoint);
  17803. return syncPoint;
  17804. }
  17805. } // Now find the sync-point that is closest to the currentTime because
  17806. // that should result in the most accurate guess about which segment
  17807. // to fetch
  17808. return this.selectSyncPoint_(syncPoints, {
  17809. key: 'time',
  17810. value: currentTime
  17811. });
  17812. }
  17813. /**
  17814. * Calculate the amount of time that has expired off the playlist during playback
  17815. *
  17816. * @param {Playlist} playlist
  17817. * Playlist object to calculate expired from
  17818. * @param {number} duration
  17819. * Duration of the MediaSource (Infinity if playling a live source)
  17820. * @return {number|null}
  17821. * The amount of time that has expired off the playlist during playback. Null
  17822. * if no sync-points for the playlist can be found.
  17823. */
  17824. getExpiredTime(playlist, duration) {
  17825. if (!playlist || !playlist.segments) {
  17826. return null;
  17827. }
  17828. const syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0, 'main'); // Without sync-points, there is not enough information to determine the expired time
  17829. if (!syncPoints.length) {
  17830. return null;
  17831. }
  17832. const syncPoint = this.selectSyncPoint_(syncPoints, {
  17833. key: 'segmentIndex',
  17834. value: 0
  17835. }); // If the sync-point is beyond the start of the playlist, we want to subtract the
  17836. // duration from index 0 to syncPoint.segmentIndex instead of adding.
  17837. if (syncPoint.segmentIndex > 0) {
  17838. syncPoint.time *= -1;
  17839. }
  17840. return Math.abs(syncPoint.time + sumDurations({
  17841. defaultDuration: playlist.targetDuration,
  17842. durationList: playlist.segments,
  17843. startIndex: syncPoint.segmentIndex,
  17844. endIndex: 0
  17845. }));
  17846. }
  17847. /**
  17848. * Runs each sync-point strategy and returns a list of sync-points returned by the
  17849. * strategies
  17850. *
  17851. * @private
  17852. * @param {Playlist} playlist
  17853. * The playlist that needs a sync-point
  17854. * @param {number} duration
  17855. * Duration of the MediaSource (Infinity if playing a live source)
  17856. * @param {number} currentTimeline
  17857. * The last timeline from which a segment was loaded
  17858. * @param {number} currentTime
  17859. * Current player's time
  17860. * @param {string} type
  17861. * Segment loader type
  17862. * @return {Array}
  17863. * A list of sync-point objects
  17864. */
  17865. runStrategies_(playlist, duration, currentTimeline, currentTime, type) {
  17866. const syncPoints = []; // Try to find a sync-point in by utilizing various strategies...
  17867. for (let i = 0; i < syncPointStrategies.length; i++) {
  17868. const strategy = syncPointStrategies[i];
  17869. const syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime, type);
  17870. if (syncPoint) {
  17871. syncPoint.strategy = strategy.name;
  17872. syncPoints.push({
  17873. strategy: strategy.name,
  17874. syncPoint
  17875. });
  17876. }
  17877. }
  17878. return syncPoints;
  17879. }
  17880. /**
  17881. * Selects the sync-point nearest the specified target
  17882. *
  17883. * @private
  17884. * @param {Array} syncPoints
  17885. * List of sync-points to select from
  17886. * @param {Object} target
  17887. * Object specifying the property and value we are targeting
  17888. * @param {string} target.key
  17889. * Specifies the property to target. Must be either 'time' or 'segmentIndex'
  17890. * @param {number} target.value
  17891. * The value to target for the specified key.
  17892. * @return {Object}
  17893. * The sync-point nearest the target
  17894. */
  17895. selectSyncPoint_(syncPoints, target) {
  17896. let bestSyncPoint = syncPoints[0].syncPoint;
  17897. let bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
  17898. let bestStrategy = syncPoints[0].strategy;
  17899. for (let i = 1; i < syncPoints.length; i++) {
  17900. const newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
  17901. if (newDistance < bestDistance) {
  17902. bestDistance = newDistance;
  17903. bestSyncPoint = syncPoints[i].syncPoint;
  17904. bestStrategy = syncPoints[i].strategy;
  17905. }
  17906. }
  17907. 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}` : '') + ']');
  17908. return bestSyncPoint;
  17909. }
  17910. /**
  17911. * Save any meta-data present on the segments when segments leave
  17912. * the live window to the playlist to allow for synchronization at the
  17913. * playlist level later.
  17914. *
  17915. * @param {Playlist} oldPlaylist - The previous active playlist
  17916. * @param {Playlist} newPlaylist - The updated and most current playlist
  17917. */
  17918. saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
  17919. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // Ignore large media sequence gaps
  17920. if (mediaSequenceDiff > MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC) {
  17921. videojs.log.warn(`Not saving expired segment info. Media sequence gap ${mediaSequenceDiff} is too large.`);
  17922. return;
  17923. } // When a segment expires from the playlist and it has a start time
  17924. // save that information as a possible sync-point reference in future
  17925. for (let i = mediaSequenceDiff - 1; i >= 0; i--) {
  17926. const lastRemovedSegment = oldPlaylist.segments[i];
  17927. if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
  17928. newPlaylist.syncInfo = {
  17929. mediaSequence: oldPlaylist.mediaSequence + i,
  17930. time: lastRemovedSegment.start
  17931. };
  17932. this.logger_(`playlist refresh sync: [time:${newPlaylist.syncInfo.time},` + ` mediaSequence: ${newPlaylist.syncInfo.mediaSequence}]`);
  17933. this.trigger('syncinfoupdate');
  17934. break;
  17935. }
  17936. }
  17937. }
  17938. /**
  17939. * Save the mapping from playlist's ProgramDateTime to display. This should only happen
  17940. * before segments start to load.
  17941. *
  17942. * @param {Playlist} playlist - The currently active playlist
  17943. */
  17944. setDateTimeMappingForStart(playlist) {
  17945. // It's possible for the playlist to be updated before playback starts, meaning time
  17946. // zero is not yet set. If, during these playlist refreshes, a discontinuity is
  17947. // crossed, then the old time zero mapping (for the prior timeline) would be retained
  17948. // unless the mappings are cleared.
  17949. this.timelineToDatetimeMappings = {};
  17950. if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
  17951. const firstSegment = playlist.segments[0];
  17952. const playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
  17953. this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
  17954. }
  17955. }
  17956. /**
  17957. * Calculates and saves timeline mappings, playlist sync info, and segment timing values
  17958. * based on the latest timing information.
  17959. *
  17960. * @param {Object} options
  17961. * Options object
  17962. * @param {SegmentInfo} options.segmentInfo
  17963. * The current active request information
  17964. * @param {boolean} options.shouldSaveTimelineMapping
  17965. * If there's a timeline change, determines if the timeline mapping should be
  17966. * saved for timeline mapping and program date time mappings.
  17967. */
  17968. saveSegmentTimingInfo({
  17969. segmentInfo,
  17970. shouldSaveTimelineMapping
  17971. }) {
  17972. const didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
  17973. const segment = segmentInfo.segment;
  17974. if (didCalculateSegmentTimeMapping) {
  17975. this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information
  17976. // now with segment timing information
  17977. if (!segmentInfo.playlist.syncInfo) {
  17978. segmentInfo.playlist.syncInfo = {
  17979. mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
  17980. time: segment.start
  17981. };
  17982. }
  17983. }
  17984. const dateTime = segment.dateTimeObject;
  17985. if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
  17986. this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
  17987. }
  17988. }
  17989. timestampOffsetForTimeline(timeline) {
  17990. if (typeof this.timelines[timeline] === 'undefined') {
  17991. return null;
  17992. }
  17993. return this.timelines[timeline].time;
  17994. }
  17995. mappingForTimeline(timeline) {
  17996. if (typeof this.timelines[timeline] === 'undefined') {
  17997. return null;
  17998. }
  17999. return this.timelines[timeline].mapping;
  18000. }
  18001. /**
  18002. * Use the "media time" for a segment to generate a mapping to "display time" and
  18003. * save that display time to the segment.
  18004. *
  18005. * @private
  18006. * @param {SegmentInfo} segmentInfo
  18007. * The current active request information
  18008. * @param {Object} timingInfo
  18009. * The start and end time of the current segment in "media time"
  18010. * @param {boolean} shouldSaveTimelineMapping
  18011. * If there's a timeline change, determines if the timeline mapping should be
  18012. * saved in timelines.
  18013. * @return {boolean}
  18014. * Returns false if segment time mapping could not be calculated
  18015. */
  18016. calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
  18017. // TODO: remove side effects
  18018. const segment = segmentInfo.segment;
  18019. const part = segmentInfo.part;
  18020. let mappingObj = this.timelines[segmentInfo.timeline];
  18021. let start;
  18022. let end;
  18023. if (typeof segmentInfo.timestampOffset === 'number') {
  18024. mappingObj = {
  18025. time: segmentInfo.startOfSegment,
  18026. mapping: segmentInfo.startOfSegment - timingInfo.start
  18027. };
  18028. if (shouldSaveTimelineMapping) {
  18029. this.timelines[segmentInfo.timeline] = mappingObj;
  18030. this.trigger('timestampoffset');
  18031. this.logger_(`time mapping for timeline ${segmentInfo.timeline}: ` + `[time: ${mappingObj.time}] [mapping: ${mappingObj.mapping}]`);
  18032. }
  18033. start = segmentInfo.startOfSegment;
  18034. end = timingInfo.end + mappingObj.mapping;
  18035. } else if (mappingObj) {
  18036. start = timingInfo.start + mappingObj.mapping;
  18037. end = timingInfo.end + mappingObj.mapping;
  18038. } else {
  18039. return false;
  18040. }
  18041. if (part) {
  18042. part.start = start;
  18043. part.end = end;
  18044. } // If we don't have a segment start yet or the start value we got
  18045. // is less than our current segment.start value, save a new start value.
  18046. // We have to do this because parts will have segment timing info saved
  18047. // multiple times and we want segment start to be the earliest part start
  18048. // value for that segment.
  18049. if (!segment.start || start < segment.start) {
  18050. segment.start = start;
  18051. }
  18052. segment.end = end;
  18053. return true;
  18054. }
  18055. /**
  18056. * Each time we have discontinuity in the playlist, attempt to calculate the location
  18057. * in display of the start of the discontinuity and save that. We also save an accuracy
  18058. * value so that we save values with the most accuracy (closest to 0.)
  18059. *
  18060. * @private
  18061. * @param {SegmentInfo} segmentInfo - The current active request information
  18062. */
  18063. saveDiscontinuitySyncInfo_(segmentInfo) {
  18064. const playlist = segmentInfo.playlist;
  18065. const segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where
  18066. // the start of the range and it's accuracy is 0 (greater accuracy values
  18067. // mean more approximation)
  18068. if (segment.discontinuity) {
  18069. this.discontinuities[segment.timeline] = {
  18070. time: segment.start,
  18071. accuracy: 0
  18072. };
  18073. } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  18074. // Search for future discontinuities that we can provide better timing
  18075. // information for and save that information for sync purposes
  18076. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  18077. const segmentIndex = playlist.discontinuityStarts[i];
  18078. const discontinuity = playlist.discontinuitySequence + i + 1;
  18079. const mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
  18080. const accuracy = Math.abs(mediaIndexDiff);
  18081. if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
  18082. let time;
  18083. if (mediaIndexDiff < 0) {
  18084. time = segment.start - sumDurations({
  18085. defaultDuration: playlist.targetDuration,
  18086. durationList: playlist.segments,
  18087. startIndex: segmentInfo.mediaIndex,
  18088. endIndex: segmentIndex
  18089. });
  18090. } else {
  18091. time = segment.end + sumDurations({
  18092. defaultDuration: playlist.targetDuration,
  18093. durationList: playlist.segments,
  18094. startIndex: segmentInfo.mediaIndex + 1,
  18095. endIndex: segmentIndex
  18096. });
  18097. }
  18098. this.discontinuities[discontinuity] = {
  18099. time,
  18100. accuracy
  18101. };
  18102. }
  18103. }
  18104. }
  18105. }
  18106. dispose() {
  18107. this.trigger('dispose');
  18108. this.off();
  18109. }
  18110. }
  18111. /**
  18112. * The TimelineChangeController acts as a source for segment loaders to listen for and
  18113. * keep track of latest and pending timeline changes. This is useful to ensure proper
  18114. * sync, as each loader may need to make a consideration for what timeline the other
  18115. * loader is on before making changes which could impact the other loader's media.
  18116. *
  18117. * @class TimelineChangeController
  18118. * @extends videojs.EventTarget
  18119. */
  18120. class TimelineChangeController extends videojs.EventTarget {
  18121. constructor() {
  18122. super();
  18123. this.pendingTimelineChanges_ = {};
  18124. this.lastTimelineChanges_ = {};
  18125. }
  18126. clearPendingTimelineChange(type) {
  18127. this.pendingTimelineChanges_[type] = null;
  18128. this.trigger('pendingtimelinechange');
  18129. }
  18130. pendingTimelineChange({
  18131. type,
  18132. from,
  18133. to
  18134. }) {
  18135. if (typeof from === 'number' && typeof to === 'number') {
  18136. this.pendingTimelineChanges_[type] = {
  18137. type,
  18138. from,
  18139. to
  18140. };
  18141. this.trigger('pendingtimelinechange');
  18142. }
  18143. return this.pendingTimelineChanges_[type];
  18144. }
  18145. lastTimelineChange({
  18146. type,
  18147. from,
  18148. to
  18149. }) {
  18150. if (typeof from === 'number' && typeof to === 'number') {
  18151. this.lastTimelineChanges_[type] = {
  18152. type,
  18153. from,
  18154. to
  18155. };
  18156. delete this.pendingTimelineChanges_[type];
  18157. this.trigger('timelinechange');
  18158. }
  18159. return this.lastTimelineChanges_[type];
  18160. }
  18161. dispose() {
  18162. this.trigger('dispose');
  18163. this.pendingTimelineChanges_ = {};
  18164. this.lastTimelineChanges_ = {};
  18165. this.off();
  18166. }
  18167. }
  18168. /* rollup-plugin-worker-factory start for worker!/home/runner/work/http-streaming/http-streaming/src/decrypter-worker.js */
  18169. const workerCode = transform(getWorkerString(function () {
  18170. /**
  18171. * @file stream.js
  18172. */
  18173. /**
  18174. * A lightweight readable stream implemention that handles event dispatching.
  18175. *
  18176. * @class Stream
  18177. */
  18178. var Stream = /*#__PURE__*/function () {
  18179. function Stream() {
  18180. this.listeners = {};
  18181. }
  18182. /**
  18183. * Add a listener for a specified event type.
  18184. *
  18185. * @param {string} type the event name
  18186. * @param {Function} listener the callback to be invoked when an event of
  18187. * the specified type occurs
  18188. */
  18189. var _proto = Stream.prototype;
  18190. _proto.on = function on(type, listener) {
  18191. if (!this.listeners[type]) {
  18192. this.listeners[type] = [];
  18193. }
  18194. this.listeners[type].push(listener);
  18195. }
  18196. /**
  18197. * Remove a listener for a specified event type.
  18198. *
  18199. * @param {string} type the event name
  18200. * @param {Function} listener a function previously registered for this
  18201. * type of event through `on`
  18202. * @return {boolean} if we could turn it off or not
  18203. */
  18204. ;
  18205. _proto.off = function off(type, listener) {
  18206. if (!this.listeners[type]) {
  18207. return false;
  18208. }
  18209. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  18210. // In Video.js we slice listener functions
  18211. // on trigger so that it does not mess up the order
  18212. // while we loop through.
  18213. //
  18214. // Here we slice on off so that the loop in trigger
  18215. // can continue using it's old reference to loop without
  18216. // messing up the order.
  18217. this.listeners[type] = this.listeners[type].slice(0);
  18218. this.listeners[type].splice(index, 1);
  18219. return index > -1;
  18220. }
  18221. /**
  18222. * Trigger an event of the specified type on this stream. Any additional
  18223. * arguments to this function are passed as parameters to event listeners.
  18224. *
  18225. * @param {string} type the event name
  18226. */
  18227. ;
  18228. _proto.trigger = function trigger(type) {
  18229. var callbacks = this.listeners[type];
  18230. if (!callbacks) {
  18231. return;
  18232. } // Slicing the arguments on every invocation of this method
  18233. // can add a significant amount of overhead. Avoid the
  18234. // intermediate object creation for the common case of a
  18235. // single callback argument
  18236. if (arguments.length === 2) {
  18237. var length = callbacks.length;
  18238. for (var i = 0; i < length; ++i) {
  18239. callbacks[i].call(this, arguments[1]);
  18240. }
  18241. } else {
  18242. var args = Array.prototype.slice.call(arguments, 1);
  18243. var _length = callbacks.length;
  18244. for (var _i = 0; _i < _length; ++_i) {
  18245. callbacks[_i].apply(this, args);
  18246. }
  18247. }
  18248. }
  18249. /**
  18250. * Destroys the stream and cleans up.
  18251. */
  18252. ;
  18253. _proto.dispose = function dispose() {
  18254. this.listeners = {};
  18255. }
  18256. /**
  18257. * Forwards all `data` events on this stream to the destination stream. The
  18258. * destination stream should provide a method `push` to receive the data
  18259. * events as they arrive.
  18260. *
  18261. * @param {Stream} destination the stream that will receive all `data` events
  18262. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  18263. */
  18264. ;
  18265. _proto.pipe = function pipe(destination) {
  18266. this.on('data', function (data) {
  18267. destination.push(data);
  18268. });
  18269. };
  18270. return Stream;
  18271. }();
  18272. /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
  18273. /**
  18274. * Returns the subarray of a Uint8Array without PKCS#7 padding.
  18275. *
  18276. * @param padded {Uint8Array} unencrypted bytes that have been padded
  18277. * @return {Uint8Array} the unpadded bytes
  18278. * @see http://tools.ietf.org/html/rfc5652
  18279. */
  18280. function unpad(padded) {
  18281. return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
  18282. }
  18283. /*! @name aes-decrypter @version 4.0.1 @license Apache-2.0 */
  18284. /**
  18285. * @file aes.js
  18286. *
  18287. * This file contains an adaptation of the AES decryption algorithm
  18288. * from the Standford Javascript Cryptography Library. That work is
  18289. * covered by the following copyright and permissions notice:
  18290. *
  18291. * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  18292. * All rights reserved.
  18293. *
  18294. * Redistribution and use in source and binary forms, with or without
  18295. * modification, are permitted provided that the following conditions are
  18296. * met:
  18297. *
  18298. * 1. Redistributions of source code must retain the above copyright
  18299. * notice, this list of conditions and the following disclaimer.
  18300. *
  18301. * 2. Redistributions in binary form must reproduce the above
  18302. * copyright notice, this list of conditions and the following
  18303. * disclaimer in the documentation and/or other materials provided
  18304. * with the distribution.
  18305. *
  18306. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  18307. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18308. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18309. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  18310. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  18311. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  18312. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  18313. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  18314. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  18315. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  18316. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  18317. *
  18318. * The views and conclusions contained in the software and documentation
  18319. * are those of the authors and should not be interpreted as representing
  18320. * official policies, either expressed or implied, of the authors.
  18321. */
  18322. /**
  18323. * Expand the S-box tables.
  18324. *
  18325. * @private
  18326. */
  18327. const precompute = function () {
  18328. const tables = [[[], [], [], [], []], [[], [], [], [], []]];
  18329. const encTable = tables[0];
  18330. const decTable = tables[1];
  18331. const sbox = encTable[4];
  18332. const sboxInv = decTable[4];
  18333. let i;
  18334. let x;
  18335. let xInv;
  18336. const d = [];
  18337. const th = [];
  18338. let x2;
  18339. let x4;
  18340. let x8;
  18341. let s;
  18342. let tEnc;
  18343. let tDec; // Compute double and third tables
  18344. for (i = 0; i < 256; i++) {
  18345. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  18346. }
  18347. for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  18348. // Compute sbox
  18349. s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  18350. s = s >> 8 ^ s & 255 ^ 99;
  18351. sbox[x] = s;
  18352. sboxInv[s] = x; // Compute MixColumns
  18353. x8 = d[x4 = d[x2 = d[x]]];
  18354. tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  18355. tEnc = d[s] * 0x101 ^ s * 0x1010100;
  18356. for (i = 0; i < 4; i++) {
  18357. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  18358. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  18359. }
  18360. } // Compactify. Considerable speedup on Firefox.
  18361. for (i = 0; i < 5; i++) {
  18362. encTable[i] = encTable[i].slice(0);
  18363. decTable[i] = decTable[i].slice(0);
  18364. }
  18365. return tables;
  18366. };
  18367. let aesTables = null;
  18368. /**
  18369. * Schedule out an AES key for both encryption and decryption. This
  18370. * is a low-level class. Use a cipher mode to do bulk encryption.
  18371. *
  18372. * @class AES
  18373. * @param key {Array} The key as an array of 4, 6 or 8 words.
  18374. */
  18375. class AES {
  18376. constructor(key) {
  18377. /**
  18378. * The expanded S-box and inverse S-box tables. These will be computed
  18379. * on the client so that we don't have to send them down the wire.
  18380. *
  18381. * There are two tables, _tables[0] is for encryption and
  18382. * _tables[1] is for decryption.
  18383. *
  18384. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  18385. * last (_tables[01][4]) is the S-box itself.
  18386. *
  18387. * @private
  18388. */
  18389. // if we have yet to precompute the S-box tables
  18390. // do so now
  18391. if (!aesTables) {
  18392. aesTables = precompute();
  18393. } // then make a copy of that object for use
  18394. 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()]];
  18395. let i;
  18396. let j;
  18397. let tmp;
  18398. const sbox = this._tables[0][4];
  18399. const decTable = this._tables[1];
  18400. const keyLen = key.length;
  18401. let rcon = 1;
  18402. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  18403. throw new Error('Invalid aes key size');
  18404. }
  18405. const encKey = key.slice(0);
  18406. const decKey = [];
  18407. this._key = [encKey, decKey]; // schedule encryption keys
  18408. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  18409. tmp = encKey[i - 1]; // apply sbox
  18410. if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
  18411. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
  18412. if (i % keyLen === 0) {
  18413. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  18414. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  18415. }
  18416. }
  18417. encKey[i] = encKey[i - keyLen] ^ tmp;
  18418. } // schedule decryption keys
  18419. for (j = 0; i; j++, i--) {
  18420. tmp = encKey[j & 3 ? i : i - 4];
  18421. if (i <= 4 || j < 4) {
  18422. decKey[j] = tmp;
  18423. } else {
  18424. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
  18425. }
  18426. }
  18427. }
  18428. /**
  18429. * Decrypt 16 bytes, specified as four 32-bit words.
  18430. *
  18431. * @param {number} encrypted0 the first word to decrypt
  18432. * @param {number} encrypted1 the second word to decrypt
  18433. * @param {number} encrypted2 the third word to decrypt
  18434. * @param {number} encrypted3 the fourth word to decrypt
  18435. * @param {Int32Array} out the array to write the decrypted words
  18436. * into
  18437. * @param {number} offset the offset into the output array to start
  18438. * writing results
  18439. * @return {Array} The plaintext.
  18440. */
  18441. decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
  18442. const key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
  18443. let a = encrypted0 ^ key[0];
  18444. let b = encrypted3 ^ key[1];
  18445. let c = encrypted2 ^ key[2];
  18446. let d = encrypted1 ^ key[3];
  18447. let a2;
  18448. let b2;
  18449. let c2; // key.length === 2 ?
  18450. const nInnerRounds = key.length / 4 - 2;
  18451. let i;
  18452. let kIndex = 4;
  18453. const table = this._tables[1]; // load up the tables
  18454. const table0 = table[0];
  18455. const table1 = table[1];
  18456. const table2 = table[2];
  18457. const table3 = table[3];
  18458. const sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
  18459. for (i = 0; i < nInnerRounds; i++) {
  18460. a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
  18461. b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
  18462. c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
  18463. d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
  18464. kIndex += 4;
  18465. a = a2;
  18466. b = b2;
  18467. c = c2;
  18468. } // Last round.
  18469. for (i = 0; i < 4; i++) {
  18470. out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
  18471. a2 = a;
  18472. a = b;
  18473. b = c;
  18474. c = d;
  18475. d = a2;
  18476. }
  18477. }
  18478. }
  18479. /**
  18480. * @file async-stream.js
  18481. */
  18482. /**
  18483. * A wrapper around the Stream class to use setTimeout
  18484. * and run stream "jobs" Asynchronously
  18485. *
  18486. * @class AsyncStream
  18487. * @extends Stream
  18488. */
  18489. class AsyncStream extends Stream {
  18490. constructor() {
  18491. super(Stream);
  18492. this.jobs = [];
  18493. this.delay = 1;
  18494. this.timeout_ = null;
  18495. }
  18496. /**
  18497. * process an async job
  18498. *
  18499. * @private
  18500. */
  18501. processJob_() {
  18502. this.jobs.shift()();
  18503. if (this.jobs.length) {
  18504. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  18505. } else {
  18506. this.timeout_ = null;
  18507. }
  18508. }
  18509. /**
  18510. * push a job into the stream
  18511. *
  18512. * @param {Function} job the job to push into the stream
  18513. */
  18514. push(job) {
  18515. this.jobs.push(job);
  18516. if (!this.timeout_) {
  18517. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  18518. }
  18519. }
  18520. }
  18521. /**
  18522. * @file decrypter.js
  18523. *
  18524. * An asynchronous implementation of AES-128 CBC decryption with
  18525. * PKCS#7 padding.
  18526. */
  18527. /**
  18528. * Convert network-order (big-endian) bytes into their little-endian
  18529. * representation.
  18530. */
  18531. const ntoh = function (word) {
  18532. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  18533. };
  18534. /**
  18535. * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
  18536. *
  18537. * @param {Uint8Array} encrypted the encrypted bytes
  18538. * @param {Uint32Array} key the bytes of the decryption key
  18539. * @param {Uint32Array} initVector the initialization vector (IV) to
  18540. * use for the first round of CBC.
  18541. * @return {Uint8Array} the decrypted bytes
  18542. *
  18543. * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  18544. * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
  18545. * @see https://tools.ietf.org/html/rfc2315
  18546. */
  18547. const decrypt = function (encrypted, key, initVector) {
  18548. // word-level access to the encrypted bytes
  18549. const encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
  18550. const decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
  18551. const decrypted = new Uint8Array(encrypted.byteLength);
  18552. const decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
  18553. // decrypted data
  18554. let init0;
  18555. let init1;
  18556. let init2;
  18557. let init3;
  18558. let encrypted0;
  18559. let encrypted1;
  18560. let encrypted2;
  18561. let encrypted3; // iteration variable
  18562. let wordIx; // pull out the words of the IV to ensure we don't modify the
  18563. // passed-in reference and easier access
  18564. init0 = initVector[0];
  18565. init1 = initVector[1];
  18566. init2 = initVector[2];
  18567. init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
  18568. // to each decrypted block
  18569. for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
  18570. // convert big-endian (network order) words into little-endian
  18571. // (javascript order)
  18572. encrypted0 = ntoh(encrypted32[wordIx]);
  18573. encrypted1 = ntoh(encrypted32[wordIx + 1]);
  18574. encrypted2 = ntoh(encrypted32[wordIx + 2]);
  18575. encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
  18576. decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
  18577. // plaintext
  18578. decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
  18579. decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
  18580. decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
  18581. decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
  18582. init0 = encrypted0;
  18583. init1 = encrypted1;
  18584. init2 = encrypted2;
  18585. init3 = encrypted3;
  18586. }
  18587. return decrypted;
  18588. };
  18589. /**
  18590. * The `Decrypter` class that manages decryption of AES
  18591. * data through `AsyncStream` objects and the `decrypt`
  18592. * function
  18593. *
  18594. * @param {Uint8Array} encrypted the encrypted bytes
  18595. * @param {Uint32Array} key the bytes of the decryption key
  18596. * @param {Uint32Array} initVector the initialization vector (IV) to
  18597. * @param {Function} done the function to run when done
  18598. * @class Decrypter
  18599. */
  18600. class Decrypter {
  18601. constructor(encrypted, key, initVector, done) {
  18602. const step = Decrypter.STEP;
  18603. const encrypted32 = new Int32Array(encrypted.buffer);
  18604. const decrypted = new Uint8Array(encrypted.byteLength);
  18605. let i = 0;
  18606. this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
  18607. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  18608. for (i = step; i < encrypted32.length; i += step) {
  18609. initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
  18610. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  18611. } // invoke the done() callback when everything is finished
  18612. this.asyncStream_.push(function () {
  18613. // remove pkcs#7 padding from the decrypted bytes
  18614. done(null, unpad(decrypted));
  18615. });
  18616. }
  18617. /**
  18618. * a getter for step the maximum number of bytes to process at one time
  18619. *
  18620. * @return {number} the value of step 32000
  18621. */
  18622. static get STEP() {
  18623. // 4 * 8000;
  18624. return 32000;
  18625. }
  18626. /**
  18627. * @private
  18628. */
  18629. decryptChunk_(encrypted, key, initVector, decrypted) {
  18630. return function () {
  18631. const bytes = decrypt(encrypted, key, initVector);
  18632. decrypted.set(bytes, encrypted.byteOffset);
  18633. };
  18634. }
  18635. }
  18636. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  18637. var win;
  18638. if (typeof window !== "undefined") {
  18639. win = window;
  18640. } else if (typeof commonjsGlobal !== "undefined") {
  18641. win = commonjsGlobal;
  18642. } else if (typeof self !== "undefined") {
  18643. win = self;
  18644. } else {
  18645. win = {};
  18646. }
  18647. var window_1 = win;
  18648. var isArrayBufferView = function isArrayBufferView(obj) {
  18649. if (ArrayBuffer.isView === 'function') {
  18650. return ArrayBuffer.isView(obj);
  18651. }
  18652. return obj && obj.buffer instanceof ArrayBuffer;
  18653. };
  18654. var BigInt = window_1.BigInt || Number;
  18655. [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  18656. (function () {
  18657. var a = new Uint16Array([0xFFCC]);
  18658. var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
  18659. if (b[0] === 0xFF) {
  18660. return 'big';
  18661. }
  18662. if (b[0] === 0xCC) {
  18663. return 'little';
  18664. }
  18665. return 'unknown';
  18666. })();
  18667. /**
  18668. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  18669. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  18670. *
  18671. * @param {Object} message
  18672. * Object of properties and values to send to the web worker
  18673. * @return {Object}
  18674. * Modified message with TypedArray values expanded
  18675. * @function createTransferableMessage
  18676. */
  18677. const createTransferableMessage = function (message) {
  18678. const transferable = {};
  18679. Object.keys(message).forEach(key => {
  18680. const value = message[key];
  18681. if (isArrayBufferView(value)) {
  18682. transferable[key] = {
  18683. bytes: value.buffer,
  18684. byteOffset: value.byteOffset,
  18685. byteLength: value.byteLength
  18686. };
  18687. } else {
  18688. transferable[key] = value;
  18689. }
  18690. });
  18691. return transferable;
  18692. };
  18693. /* global self */
  18694. /**
  18695. * Our web worker interface so that things can talk to aes-decrypter
  18696. * that will be running in a web worker. the scope is passed to this by
  18697. * webworkify.
  18698. */
  18699. self.onmessage = function (event) {
  18700. const data = event.data;
  18701. const encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
  18702. const key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
  18703. const iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
  18704. /* eslint-disable no-new, handle-callback-err */
  18705. new Decrypter(encrypted, key, iv, function (err, bytes) {
  18706. self.postMessage(createTransferableMessage({
  18707. source: data.source,
  18708. decrypted: bytes
  18709. }), [bytes.buffer]);
  18710. });
  18711. /* eslint-enable */
  18712. };
  18713. }));
  18714. var Decrypter = factory(workerCode);
  18715. /* rollup-plugin-worker-factory end for worker!/home/runner/work/http-streaming/http-streaming/src/decrypter-worker.js */
  18716. /**
  18717. * Convert the properties of an HLS track into an audioTrackKind.
  18718. *
  18719. * @private
  18720. */
  18721. const audioTrackKind_ = properties => {
  18722. let kind = properties.default ? 'main' : 'alternative';
  18723. if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
  18724. kind = 'main-desc';
  18725. }
  18726. return kind;
  18727. };
  18728. /**
  18729. * Pause provided segment loader and playlist loader if active
  18730. *
  18731. * @param {SegmentLoader} segmentLoader
  18732. * SegmentLoader to pause
  18733. * @param {Object} mediaType
  18734. * Active media type
  18735. * @function stopLoaders
  18736. */
  18737. const stopLoaders = (segmentLoader, mediaType) => {
  18738. segmentLoader.abort();
  18739. segmentLoader.pause();
  18740. if (mediaType && mediaType.activePlaylistLoader) {
  18741. mediaType.activePlaylistLoader.pause();
  18742. mediaType.activePlaylistLoader = null;
  18743. }
  18744. };
  18745. /**
  18746. * Start loading provided segment loader and playlist loader
  18747. *
  18748. * @param {PlaylistLoader} playlistLoader
  18749. * PlaylistLoader to start loading
  18750. * @param {Object} mediaType
  18751. * Active media type
  18752. * @function startLoaders
  18753. */
  18754. const startLoaders = (playlistLoader, mediaType) => {
  18755. // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
  18756. // playlist loader
  18757. mediaType.activePlaylistLoader = playlistLoader;
  18758. playlistLoader.load();
  18759. };
  18760. /**
  18761. * Returns a function to be called when the media group changes. It performs a
  18762. * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
  18763. * change of group is merely a rendition switch of the same content at another encoding,
  18764. * rather than a change of content, such as switching audio from English to Spanish.
  18765. *
  18766. * @param {string} type
  18767. * MediaGroup type
  18768. * @param {Object} settings
  18769. * Object containing required information for media groups
  18770. * @return {Function}
  18771. * Handler for a non-destructive resync of SegmentLoader when the active media
  18772. * group changes.
  18773. * @function onGroupChanged
  18774. */
  18775. const onGroupChanged = (type, settings) => () => {
  18776. const {
  18777. segmentLoaders: {
  18778. [type]: segmentLoader,
  18779. main: mainSegmentLoader
  18780. },
  18781. mediaTypes: {
  18782. [type]: mediaType
  18783. }
  18784. } = settings;
  18785. const activeTrack = mediaType.activeTrack();
  18786. const activeGroup = mediaType.getActiveGroup();
  18787. const previousActiveLoader = mediaType.activePlaylistLoader;
  18788. const lastGroup = mediaType.lastGroup_; // the group did not change do nothing
  18789. if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
  18790. return;
  18791. }
  18792. mediaType.lastGroup_ = activeGroup;
  18793. mediaType.lastTrack_ = activeTrack;
  18794. stopLoaders(segmentLoader, mediaType);
  18795. if (!activeGroup || activeGroup.isMainPlaylist) {
  18796. // there is no group active or active group is a main playlist and won't change
  18797. return;
  18798. }
  18799. if (!activeGroup.playlistLoader) {
  18800. if (previousActiveLoader) {
  18801. // The previous group had a playlist loader but the new active group does not
  18802. // this means we are switching from demuxed to muxed audio. In this case we want to
  18803. // do a destructive reset of the main segment loader and not restart the audio
  18804. // loaders.
  18805. mainSegmentLoader.resetEverything();
  18806. }
  18807. return;
  18808. } // Non-destructive resync
  18809. segmentLoader.resyncLoader();
  18810. startLoaders(activeGroup.playlistLoader, mediaType);
  18811. };
  18812. const onGroupChanging = (type, settings) => () => {
  18813. const {
  18814. segmentLoaders: {
  18815. [type]: segmentLoader
  18816. },
  18817. mediaTypes: {
  18818. [type]: mediaType
  18819. }
  18820. } = settings;
  18821. mediaType.lastGroup_ = null;
  18822. segmentLoader.abort();
  18823. segmentLoader.pause();
  18824. };
  18825. /**
  18826. * Returns a function to be called when the media track changes. It performs a
  18827. * destructive reset of the SegmentLoader to ensure we start loading as close to
  18828. * currentTime as possible.
  18829. *
  18830. * @param {string} type
  18831. * MediaGroup type
  18832. * @param {Object} settings
  18833. * Object containing required information for media groups
  18834. * @return {Function}
  18835. * Handler for a destructive reset of SegmentLoader when the active media
  18836. * track changes.
  18837. * @function onTrackChanged
  18838. */
  18839. const onTrackChanged = (type, settings) => () => {
  18840. const {
  18841. mainPlaylistLoader,
  18842. segmentLoaders: {
  18843. [type]: segmentLoader,
  18844. main: mainSegmentLoader
  18845. },
  18846. mediaTypes: {
  18847. [type]: mediaType
  18848. }
  18849. } = settings;
  18850. const activeTrack = mediaType.activeTrack();
  18851. const activeGroup = mediaType.getActiveGroup();
  18852. const previousActiveLoader = mediaType.activePlaylistLoader;
  18853. const lastTrack = mediaType.lastTrack_; // track did not change, do nothing
  18854. if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
  18855. return;
  18856. }
  18857. mediaType.lastGroup_ = activeGroup;
  18858. mediaType.lastTrack_ = activeTrack;
  18859. stopLoaders(segmentLoader, mediaType);
  18860. if (!activeGroup) {
  18861. // there is no group active so we do not want to restart loaders
  18862. return;
  18863. }
  18864. if (activeGroup.isMainPlaylist) {
  18865. // track did not change, do nothing
  18866. if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
  18867. return;
  18868. }
  18869. const pc = settings.vhs.playlistController_;
  18870. const newPlaylist = pc.selectPlaylist(); // media will not change do nothing
  18871. if (pc.media() === newPlaylist) {
  18872. return;
  18873. }
  18874. mediaType.logger_(`track change. Switching main audio from ${lastTrack.id} to ${activeTrack.id}`);
  18875. mainPlaylistLoader.pause();
  18876. mainSegmentLoader.resetEverything();
  18877. pc.fastQualityChange_(newPlaylist);
  18878. return;
  18879. }
  18880. if (type === 'AUDIO') {
  18881. if (!activeGroup.playlistLoader) {
  18882. // when switching from demuxed audio/video to muxed audio/video (noted by no
  18883. // playlist loader for the audio group), we want to do a destructive reset of the
  18884. // main segment loader and not restart the audio loaders
  18885. mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since
  18886. // it should be stopped
  18887. mainSegmentLoader.resetEverything();
  18888. return;
  18889. } // although the segment loader is an audio segment loader, call the setAudio
  18890. // function to ensure it is prepared to re-append the init segment (or handle other
  18891. // config changes)
  18892. segmentLoader.setAudio(true);
  18893. mainSegmentLoader.setAudio(false);
  18894. }
  18895. if (previousActiveLoader === activeGroup.playlistLoader) {
  18896. // Nothing has actually changed. This can happen because track change events can fire
  18897. // multiple times for a "single" change. One for enabling the new active track, and
  18898. // one for disabling the track that was active
  18899. startLoaders(activeGroup.playlistLoader, mediaType);
  18900. return;
  18901. }
  18902. if (segmentLoader.track) {
  18903. // For WebVTT, set the new text track in the segmentloader
  18904. segmentLoader.track(activeTrack);
  18905. } // destructive reset
  18906. segmentLoader.resetEverything();
  18907. startLoaders(activeGroup.playlistLoader, mediaType);
  18908. };
  18909. const onError = {
  18910. /**
  18911. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  18912. * an error.
  18913. *
  18914. * @param {string} type
  18915. * MediaGroup type
  18916. * @param {Object} settings
  18917. * Object containing required information for media groups
  18918. * @return {Function}
  18919. * Error handler. Logs warning (or error if the playlist is excluded) to
  18920. * console and switches back to default audio track.
  18921. * @function onError.AUDIO
  18922. */
  18923. AUDIO: (type, settings) => () => {
  18924. const {
  18925. mediaTypes: {
  18926. [type]: mediaType
  18927. },
  18928. excludePlaylist
  18929. } = settings; // switch back to default audio track
  18930. const activeTrack = mediaType.activeTrack();
  18931. const activeGroup = mediaType.activeGroup();
  18932. const id = (activeGroup.filter(group => group.default)[0] || activeGroup[0]).id;
  18933. const defaultTrack = mediaType.tracks[id];
  18934. if (activeTrack === defaultTrack) {
  18935. // Default track encountered an error. All we can do now is exclude the current
  18936. // rendition and hope another will switch audio groups
  18937. excludePlaylist({
  18938. error: {
  18939. message: 'Problem encountered loading the default audio track.'
  18940. }
  18941. });
  18942. return;
  18943. }
  18944. videojs.log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');
  18945. for (const trackId in mediaType.tracks) {
  18946. mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
  18947. }
  18948. mediaType.onTrackChanged();
  18949. },
  18950. /**
  18951. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  18952. * an error.
  18953. *
  18954. * @param {string} type
  18955. * MediaGroup type
  18956. * @param {Object} settings
  18957. * Object containing required information for media groups
  18958. * @return {Function}
  18959. * Error handler. Logs warning to console and disables the active subtitle track
  18960. * @function onError.SUBTITLES
  18961. */
  18962. SUBTITLES: (type, settings) => () => {
  18963. const {
  18964. mediaTypes: {
  18965. [type]: mediaType
  18966. }
  18967. } = settings;
  18968. videojs.log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');
  18969. const track = mediaType.activeTrack();
  18970. if (track) {
  18971. track.mode = 'disabled';
  18972. }
  18973. mediaType.onTrackChanged();
  18974. }
  18975. };
  18976. const setupListeners = {
  18977. /**
  18978. * Setup event listeners for audio playlist loader
  18979. *
  18980. * @param {string} type
  18981. * MediaGroup type
  18982. * @param {PlaylistLoader|null} playlistLoader
  18983. * PlaylistLoader to register listeners on
  18984. * @param {Object} settings
  18985. * Object containing required information for media groups
  18986. * @function setupListeners.AUDIO
  18987. */
  18988. AUDIO: (type, playlistLoader, settings) => {
  18989. if (!playlistLoader) {
  18990. // no playlist loader means audio will be muxed with the video
  18991. return;
  18992. }
  18993. const {
  18994. tech,
  18995. requestOptions,
  18996. segmentLoaders: {
  18997. [type]: segmentLoader
  18998. }
  18999. } = settings;
  19000. playlistLoader.on('loadedmetadata', () => {
  19001. const media = playlistLoader.media();
  19002. segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload
  19003. // permits, start downloading segments
  19004. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  19005. segmentLoader.load();
  19006. }
  19007. });
  19008. playlistLoader.on('loadedplaylist', () => {
  19009. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  19010. if (!tech.paused()) {
  19011. segmentLoader.load();
  19012. }
  19013. });
  19014. playlistLoader.on('error', onError[type](type, settings));
  19015. },
  19016. /**
  19017. * Setup event listeners for subtitle playlist loader
  19018. *
  19019. * @param {string} type
  19020. * MediaGroup type
  19021. * @param {PlaylistLoader|null} playlistLoader
  19022. * PlaylistLoader to register listeners on
  19023. * @param {Object} settings
  19024. * Object containing required information for media groups
  19025. * @function setupListeners.SUBTITLES
  19026. */
  19027. SUBTITLES: (type, playlistLoader, settings) => {
  19028. const {
  19029. tech,
  19030. requestOptions,
  19031. segmentLoaders: {
  19032. [type]: segmentLoader
  19033. },
  19034. mediaTypes: {
  19035. [type]: mediaType
  19036. }
  19037. } = settings;
  19038. playlistLoader.on('loadedmetadata', () => {
  19039. const media = playlistLoader.media();
  19040. segmentLoader.playlist(media, requestOptions);
  19041. segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload
  19042. // permits, start downloading segments
  19043. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  19044. segmentLoader.load();
  19045. }
  19046. });
  19047. playlistLoader.on('loadedplaylist', () => {
  19048. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  19049. if (!tech.paused()) {
  19050. segmentLoader.load();
  19051. }
  19052. });
  19053. playlistLoader.on('error', onError[type](type, settings));
  19054. }
  19055. };
  19056. const initialize = {
  19057. /**
  19058. * Setup PlaylistLoaders and AudioTracks for the audio groups
  19059. *
  19060. * @param {string} type
  19061. * MediaGroup type
  19062. * @param {Object} settings
  19063. * Object containing required information for media groups
  19064. * @function initialize.AUDIO
  19065. */
  19066. 'AUDIO': (type, settings) => {
  19067. const {
  19068. vhs,
  19069. sourceType,
  19070. segmentLoaders: {
  19071. [type]: segmentLoader
  19072. },
  19073. requestOptions,
  19074. main: {
  19075. mediaGroups
  19076. },
  19077. mediaTypes: {
  19078. [type]: {
  19079. groups,
  19080. tracks,
  19081. logger_
  19082. }
  19083. },
  19084. mainPlaylistLoader
  19085. } = settings;
  19086. const audioOnlyMain = isAudioOnly(mainPlaylistLoader.main); // force a default if we have none
  19087. if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {
  19088. mediaGroups[type] = {
  19089. main: {
  19090. default: {
  19091. default: true
  19092. }
  19093. }
  19094. };
  19095. if (audioOnlyMain) {
  19096. mediaGroups[type].main.default.playlists = mainPlaylistLoader.main.playlists;
  19097. }
  19098. }
  19099. for (const groupId in mediaGroups[type]) {
  19100. if (!groups[groupId]) {
  19101. groups[groupId] = [];
  19102. }
  19103. for (const variantLabel in mediaGroups[type][groupId]) {
  19104. let properties = mediaGroups[type][groupId][variantLabel];
  19105. let playlistLoader;
  19106. if (audioOnlyMain) {
  19107. logger_(`AUDIO group '${groupId}' label '${variantLabel}' is a main playlist`);
  19108. properties.isMainPlaylist = true;
  19109. playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
  19110. // use the resolved media playlist object
  19111. } else if (sourceType === 'vhs-json' && properties.playlists) {
  19112. playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);
  19113. } else if (properties.resolvedUri) {
  19114. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists
  19115. // should we even have properties.playlists in this check.
  19116. } else if (properties.playlists && sourceType === 'dash') {
  19117. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  19118. } else {
  19119. // no resolvedUri means the audio is muxed with the video when using this
  19120. // audio track
  19121. playlistLoader = null;
  19122. }
  19123. properties = merge({
  19124. id: variantLabel,
  19125. playlistLoader
  19126. }, properties);
  19127. setupListeners[type](type, properties.playlistLoader, settings);
  19128. groups[groupId].push(properties);
  19129. if (typeof tracks[variantLabel] === 'undefined') {
  19130. const track = new videojs.AudioTrack({
  19131. id: variantLabel,
  19132. kind: audioTrackKind_(properties),
  19133. enabled: false,
  19134. language: properties.language,
  19135. default: properties.default,
  19136. label: variantLabel
  19137. });
  19138. tracks[variantLabel] = track;
  19139. }
  19140. }
  19141. } // setup single error event handler for the segment loader
  19142. segmentLoader.on('error', onError[type](type, settings));
  19143. },
  19144. /**
  19145. * Setup PlaylistLoaders and TextTracks for the subtitle groups
  19146. *
  19147. * @param {string} type
  19148. * MediaGroup type
  19149. * @param {Object} settings
  19150. * Object containing required information for media groups
  19151. * @function initialize.SUBTITLES
  19152. */
  19153. 'SUBTITLES': (type, settings) => {
  19154. const {
  19155. tech,
  19156. vhs,
  19157. sourceType,
  19158. segmentLoaders: {
  19159. [type]: segmentLoader
  19160. },
  19161. requestOptions,
  19162. main: {
  19163. mediaGroups
  19164. },
  19165. mediaTypes: {
  19166. [type]: {
  19167. groups,
  19168. tracks
  19169. }
  19170. },
  19171. mainPlaylistLoader
  19172. } = settings;
  19173. for (const groupId in mediaGroups[type]) {
  19174. if (!groups[groupId]) {
  19175. groups[groupId] = [];
  19176. }
  19177. for (const variantLabel in mediaGroups[type][groupId]) {
  19178. if (!vhs.options_.useForcedSubtitles && mediaGroups[type][groupId][variantLabel].forced) {
  19179. // Subtitle playlists with the forced attribute are not selectable in Safari.
  19180. // According to Apple's HLS Authoring Specification:
  19181. // If content has forced subtitles and regular subtitles in a given language,
  19182. // the regular subtitles track in that language MUST contain both the forced
  19183. // subtitles and the regular subtitles for that language.
  19184. // Because of this requirement and that Safari does not add forced subtitles,
  19185. // forced subtitles are skipped here to maintain consistent experience across
  19186. // all platforms
  19187. continue;
  19188. }
  19189. let properties = mediaGroups[type][groupId][variantLabel];
  19190. let playlistLoader;
  19191. if (sourceType === 'hls') {
  19192. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
  19193. } else if (sourceType === 'dash') {
  19194. const playlists = properties.playlists.filter(p => p.excludeUntil !== Infinity);
  19195. if (!playlists.length) {
  19196. return;
  19197. }
  19198. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  19199. } else if (sourceType === 'vhs-json') {
  19200. playlistLoader = new PlaylistLoader( // if the vhs-json object included the media playlist, use the media playlist
  19201. // as provided, otherwise use the resolved URI to load the playlist
  19202. properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);
  19203. }
  19204. properties = merge({
  19205. id: variantLabel,
  19206. playlistLoader
  19207. }, properties);
  19208. setupListeners[type](type, properties.playlistLoader, settings);
  19209. groups[groupId].push(properties);
  19210. if (typeof tracks[variantLabel] === 'undefined') {
  19211. const track = tech.addRemoteTextTrack({
  19212. id: variantLabel,
  19213. kind: 'subtitles',
  19214. default: properties.default && properties.autoselect,
  19215. language: properties.language,
  19216. label: variantLabel
  19217. }, false).track;
  19218. tracks[variantLabel] = track;
  19219. }
  19220. }
  19221. } // setup single error event handler for the segment loader
  19222. segmentLoader.on('error', onError[type](type, settings));
  19223. },
  19224. /**
  19225. * Setup TextTracks for the closed-caption groups
  19226. *
  19227. * @param {String} type
  19228. * MediaGroup type
  19229. * @param {Object} settings
  19230. * Object containing required information for media groups
  19231. * @function initialize['CLOSED-CAPTIONS']
  19232. */
  19233. 'CLOSED-CAPTIONS': (type, settings) => {
  19234. const {
  19235. tech,
  19236. main: {
  19237. mediaGroups
  19238. },
  19239. mediaTypes: {
  19240. [type]: {
  19241. groups,
  19242. tracks
  19243. }
  19244. }
  19245. } = settings;
  19246. for (const groupId in mediaGroups[type]) {
  19247. if (!groups[groupId]) {
  19248. groups[groupId] = [];
  19249. }
  19250. for (const variantLabel in mediaGroups[type][groupId]) {
  19251. const properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services
  19252. if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
  19253. continue;
  19254. }
  19255. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  19256. let newProps = {
  19257. label: variantLabel,
  19258. language: properties.language,
  19259. instreamId: properties.instreamId,
  19260. default: properties.default && properties.autoselect
  19261. };
  19262. if (captionServices[newProps.instreamId]) {
  19263. newProps = merge(newProps, captionServices[newProps.instreamId]);
  19264. }
  19265. if (newProps.default === undefined) {
  19266. delete newProps.default;
  19267. } // No PlaylistLoader is required for Closed-Captions because the captions are
  19268. // embedded within the video stream
  19269. groups[groupId].push(merge({
  19270. id: variantLabel
  19271. }, properties));
  19272. if (typeof tracks[variantLabel] === 'undefined') {
  19273. const track = tech.addRemoteTextTrack({
  19274. id: newProps.instreamId,
  19275. kind: 'captions',
  19276. default: newProps.default,
  19277. language: newProps.language,
  19278. label: newProps.label
  19279. }, false).track;
  19280. tracks[variantLabel] = track;
  19281. }
  19282. }
  19283. }
  19284. }
  19285. };
  19286. const groupMatch = (list, media) => {
  19287. for (let i = 0; i < list.length; i++) {
  19288. if (playlistMatch(media, list[i])) {
  19289. return true;
  19290. }
  19291. if (list[i].playlists && groupMatch(list[i].playlists, media)) {
  19292. return true;
  19293. }
  19294. }
  19295. return false;
  19296. };
  19297. /**
  19298. * Returns a function used to get the active group of the provided type
  19299. *
  19300. * @param {string} type
  19301. * MediaGroup type
  19302. * @param {Object} settings
  19303. * Object containing required information for media groups
  19304. * @return {Function}
  19305. * Function that returns the active media group for the provided type. Takes an
  19306. * optional parameter {TextTrack} track. If no track is provided, a list of all
  19307. * variants in the group, otherwise the variant corresponding to the provided
  19308. * track is returned.
  19309. * @function activeGroup
  19310. */
  19311. const activeGroup = (type, settings) => track => {
  19312. const {
  19313. mainPlaylistLoader,
  19314. mediaTypes: {
  19315. [type]: {
  19316. groups
  19317. }
  19318. }
  19319. } = settings;
  19320. const media = mainPlaylistLoader.media();
  19321. if (!media) {
  19322. return null;
  19323. }
  19324. let variants = null; // set to variants to main media active group
  19325. if (media.attributes[type]) {
  19326. variants = groups[media.attributes[type]];
  19327. }
  19328. const groupKeys = Object.keys(groups);
  19329. if (!variants) {
  19330. // find the mainPlaylistLoader media
  19331. // that is in a media group if we are dealing
  19332. // with audio only
  19333. if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.main)) {
  19334. for (let i = 0; i < groupKeys.length; i++) {
  19335. const groupPropertyList = groups[groupKeys[i]];
  19336. if (groupMatch(groupPropertyList, media)) {
  19337. variants = groupPropertyList;
  19338. break;
  19339. }
  19340. } // use the main group if it exists
  19341. } else if (groups.main) {
  19342. variants = groups.main; // only one group, use that one
  19343. } else if (groupKeys.length === 1) {
  19344. variants = groups[groupKeys[0]];
  19345. }
  19346. }
  19347. if (typeof track === 'undefined') {
  19348. return variants;
  19349. }
  19350. if (track === null || !variants) {
  19351. // An active track was specified so a corresponding group is expected. track === null
  19352. // means no track is currently active so there is no corresponding group
  19353. return null;
  19354. }
  19355. return variants.filter(props => props.id === track.id)[0] || null;
  19356. };
  19357. const activeTrack = {
  19358. /**
  19359. * Returns a function used to get the active track of type provided
  19360. *
  19361. * @param {string} type
  19362. * MediaGroup type
  19363. * @param {Object} settings
  19364. * Object containing required information for media groups
  19365. * @return {Function}
  19366. * Function that returns the active media track for the provided type. Returns
  19367. * null if no track is active
  19368. * @function activeTrack.AUDIO
  19369. */
  19370. AUDIO: (type, settings) => () => {
  19371. const {
  19372. mediaTypes: {
  19373. [type]: {
  19374. tracks
  19375. }
  19376. }
  19377. } = settings;
  19378. for (const id in tracks) {
  19379. if (tracks[id].enabled) {
  19380. return tracks[id];
  19381. }
  19382. }
  19383. return null;
  19384. },
  19385. /**
  19386. * Returns a function used to get the active track of type provided
  19387. *
  19388. * @param {string} type
  19389. * MediaGroup type
  19390. * @param {Object} settings
  19391. * Object containing required information for media groups
  19392. * @return {Function}
  19393. * Function that returns the active media track for the provided type. Returns
  19394. * null if no track is active
  19395. * @function activeTrack.SUBTITLES
  19396. */
  19397. SUBTITLES: (type, settings) => () => {
  19398. const {
  19399. mediaTypes: {
  19400. [type]: {
  19401. tracks
  19402. }
  19403. }
  19404. } = settings;
  19405. for (const id in tracks) {
  19406. if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
  19407. return tracks[id];
  19408. }
  19409. }
  19410. return null;
  19411. }
  19412. };
  19413. const getActiveGroup = (type, {
  19414. mediaTypes
  19415. }) => () => {
  19416. const activeTrack_ = mediaTypes[type].activeTrack();
  19417. if (!activeTrack_) {
  19418. return null;
  19419. }
  19420. return mediaTypes[type].activeGroup(activeTrack_);
  19421. };
  19422. /**
  19423. * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
  19424. * Closed-Captions) specified in the main manifest.
  19425. *
  19426. * @param {Object} settings
  19427. * Object containing required information for setting up the media groups
  19428. * @param {Tech} settings.tech
  19429. * The tech of the player
  19430. * @param {Object} settings.requestOptions
  19431. * XHR request options used by the segment loaders
  19432. * @param {PlaylistLoader} settings.mainPlaylistLoader
  19433. * PlaylistLoader for the main source
  19434. * @param {VhsHandler} settings.vhs
  19435. * VHS SourceHandler
  19436. * @param {Object} settings.main
  19437. * The parsed main manifest
  19438. * @param {Object} settings.mediaTypes
  19439. * Object to store the loaders, tracks, and utility methods for each media type
  19440. * @param {Function} settings.excludePlaylist
  19441. * Excludes the current rendition and forces a rendition switch.
  19442. * @function setupMediaGroups
  19443. */
  19444. const setupMediaGroups = settings => {
  19445. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  19446. initialize[type](type, settings);
  19447. });
  19448. const {
  19449. mediaTypes,
  19450. mainPlaylistLoader,
  19451. tech,
  19452. vhs,
  19453. segmentLoaders: {
  19454. ['AUDIO']: audioSegmentLoader,
  19455. main: mainSegmentLoader
  19456. }
  19457. } = settings; // setup active group and track getters and change event handlers
  19458. ['AUDIO', 'SUBTITLES'].forEach(type => {
  19459. mediaTypes[type].activeGroup = activeGroup(type, settings);
  19460. mediaTypes[type].activeTrack = activeTrack[type](type, settings);
  19461. mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
  19462. mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
  19463. mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
  19464. mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
  19465. }); // DO NOT enable the default subtitle or caption track.
  19466. // DO enable the default audio track
  19467. const audioGroup = mediaTypes.AUDIO.activeGroup();
  19468. if (audioGroup) {
  19469. const groupId = (audioGroup.filter(group => group.default)[0] || audioGroup[0]).id;
  19470. mediaTypes.AUDIO.tracks[groupId].enabled = true;
  19471. mediaTypes.AUDIO.onGroupChanged();
  19472. mediaTypes.AUDIO.onTrackChanged();
  19473. const activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the
  19474. // track is changed, but needs to be handled here since the track may not be considered
  19475. // changed on the first call to onTrackChanged
  19476. if (!activeAudioGroup.playlistLoader) {
  19477. // either audio is muxed with video or the stream is audio only
  19478. mainSegmentLoader.setAudio(true);
  19479. } else {
  19480. // audio is demuxed
  19481. mainSegmentLoader.setAudio(false);
  19482. audioSegmentLoader.setAudio(true);
  19483. }
  19484. }
  19485. mainPlaylistLoader.on('mediachange', () => {
  19486. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanged());
  19487. });
  19488. mainPlaylistLoader.on('mediachanging', () => {
  19489. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanging());
  19490. }); // custom audio track change event handler for usage event
  19491. const onAudioTrackChanged = () => {
  19492. mediaTypes.AUDIO.onTrackChanged();
  19493. tech.trigger({
  19494. type: 'usage',
  19495. name: 'vhs-audio-change'
  19496. });
  19497. };
  19498. tech.audioTracks().addEventListener('change', onAudioTrackChanged);
  19499. tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  19500. vhs.on('dispose', () => {
  19501. tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
  19502. tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  19503. }); // clear existing audio tracks and add the ones we just created
  19504. tech.clearTracks('audio');
  19505. for (const id in mediaTypes.AUDIO.tracks) {
  19506. tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
  19507. }
  19508. };
  19509. /**
  19510. * Creates skeleton object used to store the loaders, tracks, and utility methods for each
  19511. * media type
  19512. *
  19513. * @return {Object}
  19514. * Object to store the loaders, tracks, and utility methods for each media type
  19515. * @function createMediaTypes
  19516. */
  19517. const createMediaTypes = () => {
  19518. const mediaTypes = {};
  19519. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  19520. mediaTypes[type] = {
  19521. groups: {},
  19522. tracks: {},
  19523. activePlaylistLoader: null,
  19524. activeGroup: noop,
  19525. activeTrack: noop,
  19526. getActiveGroup: noop,
  19527. onGroupChanged: noop,
  19528. onTrackChanged: noop,
  19529. lastTrack_: null,
  19530. logger_: logger(`MediaGroups[${type}]`)
  19531. };
  19532. });
  19533. return mediaTypes;
  19534. };
  19535. /**
  19536. * A utility class for setting properties and maintaining the state of the content steering manifest.
  19537. *
  19538. * Content Steering manifest format:
  19539. * VERSION: number (required) currently only version 1 is supported.
  19540. * TTL: number in seconds (optional) until the next content steering manifest reload.
  19541. * RELOAD-URI: string (optional) uri to fetch the next content steering manifest.
  19542. * SERVICE-LOCATION-PRIORITY or PATHWAY-PRIORITY a non empty array of unique string values.
  19543. * PATHWAY-CLONES: array (optional) (HLS only) pathway clone objects to copy from other playlists.
  19544. */
  19545. class SteeringManifest {
  19546. constructor() {
  19547. this.priority_ = [];
  19548. this.pathwayClones_ = new Map();
  19549. }
  19550. set version(number) {
  19551. // Only version 1 is currently supported for both DASH and HLS.
  19552. if (number === 1) {
  19553. this.version_ = number;
  19554. }
  19555. }
  19556. set ttl(seconds) {
  19557. // TTL = time-to-live, default = 300 seconds.
  19558. this.ttl_ = seconds || 300;
  19559. }
  19560. set reloadUri(uri) {
  19561. if (uri) {
  19562. // reload URI can be relative to the previous reloadUri.
  19563. this.reloadUri_ = resolveUrl(this.reloadUri_, uri);
  19564. }
  19565. }
  19566. set priority(array) {
  19567. // priority must be non-empty and unique values.
  19568. if (array && array.length) {
  19569. this.priority_ = array;
  19570. }
  19571. }
  19572. set pathwayClones(array) {
  19573. // pathwayClones must be non-empty.
  19574. if (array && array.length) {
  19575. this.pathwayClones_ = new Map(array.map(clone => [clone.ID, clone]));
  19576. }
  19577. }
  19578. get version() {
  19579. return this.version_;
  19580. }
  19581. get ttl() {
  19582. return this.ttl_;
  19583. }
  19584. get reloadUri() {
  19585. return this.reloadUri_;
  19586. }
  19587. get priority() {
  19588. return this.priority_;
  19589. }
  19590. get pathwayClones() {
  19591. return this.pathwayClones_;
  19592. }
  19593. }
  19594. /**
  19595. * This class represents a content steering manifest and associated state. See both HLS and DASH specifications.
  19596. * HLS: https://developer.apple.com/streaming/HLSContentSteeringSpecification.pdf and
  19597. * https://datatracker.ietf.org/doc/draft-pantos-hls-rfc8216bis/ section 4.4.6.6.
  19598. * DASH: https://dashif.org/docs/DASH-IF-CTS-00XX-Content-Steering-Community-Review.pdf
  19599. *
  19600. * @param {function} xhr for making a network request from the browser.
  19601. * @param {function} bandwidth for fetching the current bandwidth from the main segment loader.
  19602. */
  19603. class ContentSteeringController extends videojs.EventTarget {
  19604. constructor(xhr, bandwidth) {
  19605. super();
  19606. this.currentPathway = null;
  19607. this.defaultPathway = null;
  19608. this.queryBeforeStart = false;
  19609. this.availablePathways_ = new Set();
  19610. this.steeringManifest = new SteeringManifest();
  19611. this.proxyServerUrl_ = null;
  19612. this.manifestType_ = null;
  19613. this.ttlTimeout_ = null;
  19614. this.request_ = null;
  19615. this.currentPathwayClones = new Map();
  19616. this.nextPathwayClones = new Map();
  19617. this.excludedSteeringManifestURLs = new Set();
  19618. this.logger_ = logger('Content Steering');
  19619. this.xhr_ = xhr;
  19620. this.getBandwidth_ = bandwidth;
  19621. }
  19622. /**
  19623. * Assigns the content steering tag properties to the steering controller
  19624. *
  19625. * @param {string} baseUrl the baseURL from the main manifest for resolving the steering manifest url
  19626. * @param {Object} steeringTag the content steering tag from the main manifest
  19627. */
  19628. assignTagProperties(baseUrl, steeringTag) {
  19629. this.manifestType_ = steeringTag.serverUri ? 'HLS' : 'DASH'; // serverUri is HLS serverURL is DASH
  19630. const steeringUri = steeringTag.serverUri || steeringTag.serverURL;
  19631. if (!steeringUri) {
  19632. this.logger_(`steering manifest URL is ${steeringUri}, cannot request steering manifest.`);
  19633. this.trigger('error');
  19634. return;
  19635. } // Content steering manifests can be encoded as a data URI. We can decode, parse and return early if that's the case.
  19636. if (steeringUri.startsWith('data:')) {
  19637. this.decodeDataUriManifest_(steeringUri.substring(steeringUri.indexOf(',') + 1));
  19638. return;
  19639. } // reloadUri is the resolution of the main manifest URL and steering URL.
  19640. this.steeringManifest.reloadUri = resolveUrl(baseUrl, steeringUri); // pathwayId is HLS defaultServiceLocation is DASH
  19641. this.defaultPathway = steeringTag.pathwayId || steeringTag.defaultServiceLocation; // currently only DASH supports the following properties on <ContentSteering> tags.
  19642. this.queryBeforeStart = steeringTag.queryBeforeStart;
  19643. this.proxyServerUrl_ = steeringTag.proxyServerURL; // trigger a steering event if we have a pathway from the content steering tag.
  19644. // this tells VHS which segment pathway to start with.
  19645. // If queryBeforeStart is true we need to wait for the steering manifest response.
  19646. if (this.defaultPathway && !this.queryBeforeStart) {
  19647. this.trigger('content-steering');
  19648. }
  19649. }
  19650. /**
  19651. * Requests the content steering manifest and parse the response. This should only be called after
  19652. * assignTagProperties was called with a content steering tag.
  19653. *
  19654. * @param {string} initialUri The optional uri to make the request with.
  19655. * If set, the request should be made with exactly what is passed in this variable.
  19656. * This scenario should only happen once on initalization.
  19657. */
  19658. requestSteeringManifest(initial) {
  19659. const reloadUri = this.steeringManifest.reloadUri;
  19660. if (!reloadUri) {
  19661. return;
  19662. } // We currently don't support passing MPD query parameters directly to the content steering URL as this requires
  19663. // ExtUrlQueryInfo tag support. See the DASH content steering spec section 8.1.
  19664. // This request URI accounts for manifest URIs that have been excluded.
  19665. const uri = initial ? reloadUri : this.getRequestURI(reloadUri); // If there are no valid manifest URIs, we should stop content steering.
  19666. if (!uri) {
  19667. this.logger_('No valid content steering manifest URIs. Stopping content steering.');
  19668. this.trigger('error');
  19669. this.dispose();
  19670. return;
  19671. }
  19672. this.request_ = this.xhr_({
  19673. uri
  19674. }, (error, errorInfo) => {
  19675. if (error) {
  19676. // If the client receives HTTP 410 Gone in response to a manifest request,
  19677. // it MUST NOT issue another request for that URI for the remainder of the
  19678. // playback session. It MAY continue to use the most-recently obtained set
  19679. // of Pathways.
  19680. if (errorInfo.status === 410) {
  19681. this.logger_(`manifest request 410 ${error}.`);
  19682. this.logger_(`There will be no more content steering requests to ${uri} this session.`);
  19683. this.excludedSteeringManifestURLs.add(uri);
  19684. return;
  19685. } // If the client receives HTTP 429 Too Many Requests with a Retry-After
  19686. // header in response to a manifest request, it SHOULD wait until the time
  19687. // specified by the Retry-After header to reissue the request.
  19688. if (errorInfo.status === 429) {
  19689. const retrySeconds = errorInfo.responseHeaders['retry-after'];
  19690. this.logger_(`manifest request 429 ${error}.`);
  19691. this.logger_(`content steering will retry in ${retrySeconds} seconds.`);
  19692. this.startTTLTimeout_(parseInt(retrySeconds, 10));
  19693. return;
  19694. } // If the Steering Manifest cannot be loaded and parsed correctly, the
  19695. // client SHOULD continue to use the previous values and attempt to reload
  19696. // it after waiting for the previously-specified TTL (or 5 minutes if
  19697. // none).
  19698. this.logger_(`manifest failed to load ${error}.`);
  19699. this.startTTLTimeout_();
  19700. return;
  19701. }
  19702. const steeringManifestJson = JSON.parse(this.request_.responseText);
  19703. this.assignSteeringProperties_(steeringManifestJson);
  19704. this.startTTLTimeout_();
  19705. });
  19706. }
  19707. /**
  19708. * Set the proxy server URL and add the steering manifest url as a URI encoded parameter.
  19709. *
  19710. * @param {string} steeringUrl the steering manifest url
  19711. * @return the steering manifest url to a proxy server with all parameters set
  19712. */
  19713. setProxyServerUrl_(steeringUrl) {
  19714. const steeringUrlObject = new window$1.URL(steeringUrl);
  19715. const proxyServerUrlObject = new window$1.URL(this.proxyServerUrl_);
  19716. proxyServerUrlObject.searchParams.set('url', encodeURI(steeringUrlObject.toString()));
  19717. return this.setSteeringParams_(proxyServerUrlObject.toString());
  19718. }
  19719. /**
  19720. * Decodes and parses the data uri encoded steering manifest
  19721. *
  19722. * @param {string} dataUri the data uri to be decoded and parsed.
  19723. */
  19724. decodeDataUriManifest_(dataUri) {
  19725. const steeringManifestJson = JSON.parse(window$1.atob(dataUri));
  19726. this.assignSteeringProperties_(steeringManifestJson);
  19727. }
  19728. /**
  19729. * Set the HLS or DASH content steering manifest request query parameters. For example:
  19730. * _HLS_pathway="<CURRENT-PATHWAY-ID>" and _HLS_throughput=<THROUGHPUT>
  19731. * _DASH_pathway and _DASH_throughput
  19732. *
  19733. * @param {string} uri to add content steering server parameters to.
  19734. * @return a new uri as a string with the added steering query parameters.
  19735. */
  19736. setSteeringParams_(url) {
  19737. const urlObject = new window$1.URL(url);
  19738. const path = this.getPathway();
  19739. const networkThroughput = this.getBandwidth_();
  19740. if (path) {
  19741. const pathwayKey = `_${this.manifestType_}_pathway`;
  19742. urlObject.searchParams.set(pathwayKey, path);
  19743. }
  19744. if (networkThroughput) {
  19745. const throughputKey = `_${this.manifestType_}_throughput`;
  19746. urlObject.searchParams.set(throughputKey, networkThroughput);
  19747. }
  19748. return urlObject.toString();
  19749. }
  19750. /**
  19751. * Assigns the current steering manifest properties and to the SteeringManifest object
  19752. *
  19753. * @param {Object} steeringJson the raw JSON steering manifest
  19754. */
  19755. assignSteeringProperties_(steeringJson) {
  19756. this.steeringManifest.version = steeringJson.VERSION;
  19757. if (!this.steeringManifest.version) {
  19758. this.logger_(`manifest version is ${steeringJson.VERSION}, which is not supported.`);
  19759. this.trigger('error');
  19760. return;
  19761. }
  19762. this.steeringManifest.ttl = steeringJson.TTL;
  19763. this.steeringManifest.reloadUri = steeringJson['RELOAD-URI']; // HLS = PATHWAY-PRIORITY required. DASH = SERVICE-LOCATION-PRIORITY optional
  19764. this.steeringManifest.priority = steeringJson['PATHWAY-PRIORITY'] || steeringJson['SERVICE-LOCATION-PRIORITY']; // Pathway clones to be created/updated in HLS.
  19765. // See section 7.2 https://datatracker.ietf.org/doc/draft-pantos-hls-rfc8216bis/
  19766. this.steeringManifest.pathwayClones = steeringJson['PATHWAY-CLONES'];
  19767. this.nextPathwayClones = this.steeringManifest.pathwayClones; // 1. apply first pathway from the array.
  19768. // 2. if first pathway doesn't exist in manifest, try next pathway.
  19769. // a. if all pathways are exhausted, ignore the steering manifest priority.
  19770. // 3. if segments fail from an established pathway, try all variants/renditions, then exclude the failed pathway.
  19771. // a. exclude a pathway for a minimum of the last TTL duration. Meaning, from the next steering response,
  19772. // the excluded pathway will be ignored.
  19773. // See excludePathway usage in excludePlaylist().
  19774. // If there are no available pathways, we need to stop content steering.
  19775. if (!this.availablePathways_.size) {
  19776. this.logger_('There are no available pathways for content steering. Ending content steering.');
  19777. this.trigger('error');
  19778. this.dispose();
  19779. }
  19780. const chooseNextPathway = pathwaysByPriority => {
  19781. for (const path of pathwaysByPriority) {
  19782. if (this.availablePathways_.has(path)) {
  19783. return path;
  19784. }
  19785. } // If no pathway matches, ignore the manifest and choose the first available.
  19786. return [...this.availablePathways_][0];
  19787. };
  19788. const nextPathway = chooseNextPathway(this.steeringManifest.priority);
  19789. if (this.currentPathway !== nextPathway) {
  19790. this.currentPathway = nextPathway;
  19791. this.trigger('content-steering');
  19792. }
  19793. }
  19794. /**
  19795. * Returns the pathway to use for steering decisions
  19796. *
  19797. * @return {string} returns the current pathway or the default
  19798. */
  19799. getPathway() {
  19800. return this.currentPathway || this.defaultPathway;
  19801. }
  19802. /**
  19803. * Chooses the manifest request URI based on proxy URIs and server URLs.
  19804. * Also accounts for exclusion on certain manifest URIs.
  19805. *
  19806. * @param {string} reloadUri the base uri before parameters
  19807. *
  19808. * @return {string} the final URI for the request to the manifest server.
  19809. */
  19810. getRequestURI(reloadUri) {
  19811. if (!reloadUri) {
  19812. return null;
  19813. }
  19814. const isExcluded = uri => this.excludedSteeringManifestURLs.has(uri);
  19815. if (this.proxyServerUrl_) {
  19816. const proxyURI = this.setProxyServerUrl_(reloadUri);
  19817. if (!isExcluded(proxyURI)) {
  19818. return proxyURI;
  19819. }
  19820. }
  19821. const steeringURI = this.setSteeringParams_(reloadUri);
  19822. if (!isExcluded(steeringURI)) {
  19823. return steeringURI;
  19824. } // Return nothing if all valid manifest URIs are excluded.
  19825. return null;
  19826. }
  19827. /**
  19828. * Start the timeout for re-requesting the steering manifest at the TTL interval.
  19829. *
  19830. * @param {number} ttl time in seconds of the timeout. Defaults to the
  19831. * ttl interval in the steering manifest
  19832. */
  19833. startTTLTimeout_(ttl = this.steeringManifest.ttl) {
  19834. // 300 (5 minutes) is the default value.
  19835. const ttlMS = ttl * 1000;
  19836. this.ttlTimeout_ = window$1.setTimeout(() => {
  19837. this.requestSteeringManifest();
  19838. }, ttlMS);
  19839. }
  19840. /**
  19841. * Clear the TTL timeout if necessary.
  19842. */
  19843. clearTTLTimeout_() {
  19844. window$1.clearTimeout(this.ttlTimeout_);
  19845. this.ttlTimeout_ = null;
  19846. }
  19847. /**
  19848. * aborts any current steering xhr and sets the current request object to null
  19849. */
  19850. abort() {
  19851. if (this.request_) {
  19852. this.request_.abort();
  19853. }
  19854. this.request_ = null;
  19855. }
  19856. /**
  19857. * aborts steering requests clears the ttl timeout and resets all properties.
  19858. */
  19859. dispose() {
  19860. this.off('content-steering');
  19861. this.off('error');
  19862. this.abort();
  19863. this.clearTTLTimeout_();
  19864. this.currentPathway = null;
  19865. this.defaultPathway = null;
  19866. this.queryBeforeStart = null;
  19867. this.proxyServerUrl_ = null;
  19868. this.manifestType_ = null;
  19869. this.ttlTimeout_ = null;
  19870. this.request_ = null;
  19871. this.excludedSteeringManifestURLs = new Set();
  19872. this.availablePathways_ = new Set();
  19873. this.steeringManifest = new SteeringManifest();
  19874. }
  19875. /**
  19876. * adds a pathway to the available pathways set
  19877. *
  19878. * @param {string} pathway the pathway string to add
  19879. */
  19880. addAvailablePathway(pathway) {
  19881. if (pathway) {
  19882. this.availablePathways_.add(pathway);
  19883. }
  19884. }
  19885. /**
  19886. * Clears all pathways from the available pathways set
  19887. */
  19888. clearAvailablePathways() {
  19889. this.availablePathways_.clear();
  19890. }
  19891. /**
  19892. * Removes a pathway from the available pathways set.
  19893. */
  19894. excludePathway(pathway) {
  19895. return this.availablePathways_.delete(pathway);
  19896. }
  19897. /**
  19898. * Checks the refreshed DASH manifest content steering tag for changes.
  19899. *
  19900. * @param {string} baseURL new steering tag on DASH manifest refresh
  19901. * @param {Object} newTag the new tag to check for changes
  19902. * @return a true or false whether the new tag has different values
  19903. */
  19904. didDASHTagChange(baseURL, newTag) {
  19905. return !newTag && this.steeringManifest.reloadUri || newTag && (resolveUrl(baseURL, newTag.serverURL) !== this.steeringManifest.reloadUri || newTag.defaultServiceLocation !== this.defaultPathway || newTag.queryBeforeStart !== this.queryBeforeStart || newTag.proxyServerURL !== this.proxyServerUrl_);
  19906. }
  19907. getAvailablePathways() {
  19908. return this.availablePathways_;
  19909. }
  19910. }
  19911. /**
  19912. * @file playlist-controller.js
  19913. */
  19914. const ABORT_EARLY_EXCLUSION_SECONDS = 10;
  19915. let Vhs$1; // SegmentLoader stats that need to have each loader's
  19916. // values summed to calculate the final value
  19917. const loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];
  19918. const sumLoaderStat = function (stat) {
  19919. return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
  19920. };
  19921. const shouldSwitchToMedia = function ({
  19922. currentPlaylist,
  19923. buffered,
  19924. currentTime,
  19925. nextPlaylist,
  19926. bufferLowWaterLine,
  19927. bufferHighWaterLine,
  19928. duration,
  19929. bufferBasedABR,
  19930. log
  19931. }) {
  19932. // we have no other playlist to switch to
  19933. if (!nextPlaylist) {
  19934. videojs.log.warn('We received no playlist to switch to. Please check your stream.');
  19935. return false;
  19936. }
  19937. const sharedLogLine = `allowing switch ${currentPlaylist && currentPlaylist.id || 'null'} -> ${nextPlaylist.id}`;
  19938. if (!currentPlaylist) {
  19939. log(`${sharedLogLine} as current playlist is not set`);
  19940. return true;
  19941. } // no need to switch if playlist is the same
  19942. if (nextPlaylist.id === currentPlaylist.id) {
  19943. return false;
  19944. } // determine if current time is in a buffered range.
  19945. const isBuffered = Boolean(findRange(buffered, currentTime).length); // If the playlist is live, then we want to not take low water line into account.
  19946. // This is because in LIVE, the player plays 3 segments from the end of the
  19947. // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
  19948. // in those segments, a viewer will never experience a rendition upswitch.
  19949. if (!currentPlaylist.endList) {
  19950. // For LLHLS live streams, don't switch renditions before playback has started, as it almost
  19951. // doubles the time to first playback.
  19952. if (!isBuffered && typeof currentPlaylist.partTargetDuration === 'number') {
  19953. log(`not ${sharedLogLine} as current playlist is live llhls, but currentTime isn't in buffered.`);
  19954. return false;
  19955. }
  19956. log(`${sharedLogLine} as current playlist is live`);
  19957. return true;
  19958. }
  19959. const forwardBuffer = timeAheadOf(buffered, currentTime);
  19960. 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
  19961. // duration is below the max potential low water line
  19962. if (duration < maxBufferLowWaterLine) {
  19963. log(`${sharedLogLine} as duration < max low water line (${duration} < ${maxBufferLowWaterLine})`);
  19964. return true;
  19965. }
  19966. const nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
  19967. const currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,
  19968. // we can switch down
  19969. if (nextBandwidth < currBandwidth && (!bufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
  19970. let logLine = `${sharedLogLine} as next bandwidth < current bandwidth (${nextBandwidth} < ${currBandwidth})`;
  19971. if (bufferBasedABR) {
  19972. logLine += ` and forwardBuffer < bufferHighWaterLine (${forwardBuffer} < ${bufferHighWaterLine})`;
  19973. }
  19974. log(logLine);
  19975. return true;
  19976. } // and if our buffer is higher than the low water line,
  19977. // we can switch up
  19978. if ((!bufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
  19979. let logLine = `${sharedLogLine} as forwardBuffer >= bufferLowWaterLine (${forwardBuffer} >= ${bufferLowWaterLine})`;
  19980. if (bufferBasedABR) {
  19981. logLine += ` and next bandwidth > current bandwidth (${nextBandwidth} > ${currBandwidth})`;
  19982. }
  19983. log(logLine);
  19984. return true;
  19985. }
  19986. log(`not ${sharedLogLine} as no switching criteria met`);
  19987. return false;
  19988. };
  19989. /**
  19990. * the main playlist controller controller all interactons
  19991. * between playlists and segmentloaders. At this time this mainly
  19992. * involves a main playlist and a series of audio playlists
  19993. * if they are available
  19994. *
  19995. * @class PlaylistController
  19996. * @extends videojs.EventTarget
  19997. */
  19998. class PlaylistController extends videojs.EventTarget {
  19999. constructor(options) {
  20000. super();
  20001. const {
  20002. src,
  20003. withCredentials,
  20004. tech,
  20005. bandwidth,
  20006. externVhs,
  20007. useCueTags,
  20008. playlistExclusionDuration,
  20009. enableLowInitialPlaylist,
  20010. sourceType,
  20011. cacheEncryptionKeys,
  20012. bufferBasedABR,
  20013. leastPixelDiffSelector,
  20014. captionServices
  20015. } = options;
  20016. if (!src) {
  20017. throw new Error('A non-empty playlist URL or JSON manifest string is required');
  20018. }
  20019. let {
  20020. maxPlaylistRetries
  20021. } = options;
  20022. if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
  20023. maxPlaylistRetries = Infinity;
  20024. }
  20025. Vhs$1 = externVhs;
  20026. this.bufferBasedABR = Boolean(bufferBasedABR);
  20027. this.leastPixelDiffSelector = Boolean(leastPixelDiffSelector);
  20028. this.withCredentials = withCredentials;
  20029. this.tech_ = tech;
  20030. this.vhs_ = tech.vhs;
  20031. this.sourceType_ = sourceType;
  20032. this.useCueTags_ = useCueTags;
  20033. this.playlistExclusionDuration = playlistExclusionDuration;
  20034. this.maxPlaylistRetries = maxPlaylistRetries;
  20035. this.enableLowInitialPlaylist = enableLowInitialPlaylist;
  20036. if (this.useCueTags_) {
  20037. this.cueTagsTrack_ = this.tech_.addTextTrack('metadata', 'ad-cues');
  20038. this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
  20039. }
  20040. this.requestOptions_ = {
  20041. withCredentials,
  20042. maxPlaylistRetries,
  20043. timeout: null
  20044. };
  20045. this.on('error', this.pauseLoading);
  20046. this.mediaTypes_ = createMediaTypes();
  20047. this.mediaSource = new window$1.MediaSource();
  20048. this.handleDurationChange_ = this.handleDurationChange_.bind(this);
  20049. this.handleSourceOpen_ = this.handleSourceOpen_.bind(this);
  20050. this.handleSourceEnded_ = this.handleSourceEnded_.bind(this);
  20051. this.mediaSource.addEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  20052. this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen_);
  20053. this.mediaSource.addEventListener('sourceended', this.handleSourceEnded_); // we don't have to handle sourceclose since dispose will handle termination of
  20054. // everything, and the MediaSource should not be detached without a proper disposal
  20055. this.seekable_ = createTimeRanges();
  20056. this.hasPlayed_ = false;
  20057. this.syncController_ = new SyncController(options);
  20058. this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
  20059. kind: 'metadata',
  20060. label: 'segment-metadata'
  20061. }, false).track;
  20062. this.decrypter_ = new Decrypter();
  20063. this.sourceUpdater_ = new SourceUpdater(this.mediaSource);
  20064. this.inbandTextTracks_ = {};
  20065. this.timelineChangeController_ = new TimelineChangeController();
  20066. this.keyStatusMap_ = new Map();
  20067. const segmentLoaderSettings = {
  20068. vhs: this.vhs_,
  20069. parse708captions: options.parse708captions,
  20070. useDtsForTimestampOffset: options.useDtsForTimestampOffset,
  20071. captionServices,
  20072. mediaSource: this.mediaSource,
  20073. currentTime: this.tech_.currentTime.bind(this.tech_),
  20074. seekable: () => this.seekable(),
  20075. seeking: () => this.tech_.seeking(),
  20076. duration: () => this.duration(),
  20077. hasPlayed: () => this.hasPlayed_,
  20078. goalBufferLength: () => this.goalBufferLength(),
  20079. bandwidth,
  20080. syncController: this.syncController_,
  20081. decrypter: this.decrypter_,
  20082. sourceType: this.sourceType_,
  20083. inbandTextTracks: this.inbandTextTracks_,
  20084. cacheEncryptionKeys,
  20085. sourceUpdater: this.sourceUpdater_,
  20086. timelineChangeController: this.timelineChangeController_,
  20087. exactManifestTimings: options.exactManifestTimings,
  20088. addMetadataToTextTrack: this.addMetadataToTextTrack.bind(this)
  20089. }; // The source type check not only determines whether a special DASH playlist loader
  20090. // should be used, but also covers the case where the provided src is a vhs-json
  20091. // manifest object (instead of a URL). In the case of vhs-json, the default
  20092. // PlaylistLoader should be used.
  20093. this.mainPlaylistLoader_ = this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, this.vhs_, merge(this.requestOptions_, {
  20094. addMetadataToTextTrack: this.addMetadataToTextTrack.bind(this)
  20095. })) : new PlaylistLoader(src, this.vhs_, merge(this.requestOptions_, {
  20096. addDateRangesToTextTrack: this.addDateRangesToTextTrack_.bind(this)
  20097. }));
  20098. this.setupMainPlaylistLoaderListeners_(); // setup segment loaders
  20099. // combined audio/video or just video when alternate audio track is selected
  20100. this.mainSegmentLoader_ = new SegmentLoader(merge(segmentLoaderSettings, {
  20101. segmentMetadataTrack: this.segmentMetadataTrack_,
  20102. loaderType: 'main'
  20103. }), options); // alternate audio track
  20104. this.audioSegmentLoader_ = new SegmentLoader(merge(segmentLoaderSettings, {
  20105. loaderType: 'audio'
  20106. }), options);
  20107. this.subtitleSegmentLoader_ = new VTTSegmentLoader(merge(segmentLoaderSettings, {
  20108. loaderType: 'vtt',
  20109. featuresNativeTextTracks: this.tech_.featuresNativeTextTracks,
  20110. loadVttJs: () => new Promise((resolve, reject) => {
  20111. function onLoad() {
  20112. tech.off('vttjserror', onError);
  20113. resolve();
  20114. }
  20115. function onError() {
  20116. tech.off('vttjsloaded', onLoad);
  20117. reject();
  20118. }
  20119. tech.one('vttjsloaded', onLoad);
  20120. tech.one('vttjserror', onError); // safe to call multiple times, script will be loaded only once:
  20121. tech.addWebVttScript_();
  20122. })
  20123. }), options);
  20124. const getBandwidth = () => {
  20125. return this.mainSegmentLoader_.bandwidth;
  20126. };
  20127. this.contentSteeringController_ = new ContentSteeringController(this.vhs_.xhr, getBandwidth);
  20128. this.setupSegmentLoaderListeners_();
  20129. if (this.bufferBasedABR) {
  20130. this.mainPlaylistLoader_.one('loadedplaylist', () => this.startABRTimer_());
  20131. this.tech_.on('pause', () => this.stopABRTimer_());
  20132. this.tech_.on('play', () => this.startABRTimer_());
  20133. } // Create SegmentLoader stat-getters
  20134. // mediaRequests_
  20135. // mediaRequestsAborted_
  20136. // mediaRequestsTimedout_
  20137. // mediaRequestsErrored_
  20138. // mediaTransferDuration_
  20139. // mediaBytesTransferred_
  20140. // mediaAppends_
  20141. loaderStats.forEach(stat => {
  20142. this[stat + '_'] = sumLoaderStat.bind(this, stat);
  20143. });
  20144. this.logger_ = logger('pc');
  20145. this.triggeredFmp4Usage = false;
  20146. if (this.tech_.preload() === 'none') {
  20147. this.loadOnPlay_ = () => {
  20148. this.loadOnPlay_ = null;
  20149. this.mainPlaylistLoader_.load();
  20150. };
  20151. this.tech_.one('play', this.loadOnPlay_);
  20152. } else {
  20153. this.mainPlaylistLoader_.load();
  20154. }
  20155. this.timeToLoadedData__ = -1;
  20156. this.mainAppendsToLoadedData__ = -1;
  20157. this.audioAppendsToLoadedData__ = -1;
  20158. const event = this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
  20159. this.tech_.one(event, () => {
  20160. const timeToLoadedDataStart = Date.now();
  20161. this.tech_.one('loadeddata', () => {
  20162. this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
  20163. this.mainAppendsToLoadedData__ = this.mainSegmentLoader_.mediaAppends;
  20164. this.audioAppendsToLoadedData__ = this.audioSegmentLoader_.mediaAppends;
  20165. });
  20166. });
  20167. }
  20168. mainAppendsToLoadedData_() {
  20169. return this.mainAppendsToLoadedData__;
  20170. }
  20171. audioAppendsToLoadedData_() {
  20172. return this.audioAppendsToLoadedData__;
  20173. }
  20174. appendsToLoadedData_() {
  20175. const main = this.mainAppendsToLoadedData_();
  20176. const audio = this.audioAppendsToLoadedData_();
  20177. if (main === -1 || audio === -1) {
  20178. return -1;
  20179. }
  20180. return main + audio;
  20181. }
  20182. timeToLoadedData_() {
  20183. return this.timeToLoadedData__;
  20184. }
  20185. /**
  20186. * Run selectPlaylist and switch to the new playlist if we should
  20187. *
  20188. * @param {string} [reason=abr] a reason for why the ABR check is made
  20189. * @private
  20190. */
  20191. checkABR_(reason = 'abr') {
  20192. const nextPlaylist = this.selectPlaylist();
  20193. if (nextPlaylist && this.shouldSwitchToMedia_(nextPlaylist)) {
  20194. this.switchMedia_(nextPlaylist, reason);
  20195. }
  20196. }
  20197. switchMedia_(playlist, cause, delay) {
  20198. const oldMedia = this.media();
  20199. const oldId = oldMedia && (oldMedia.id || oldMedia.uri);
  20200. const newId = playlist && (playlist.id || playlist.uri);
  20201. if (oldId && oldId !== newId) {
  20202. this.logger_(`switch media ${oldId} -> ${newId} from ${cause}`);
  20203. this.tech_.trigger({
  20204. type: 'usage',
  20205. name: `vhs-rendition-change-${cause}`
  20206. });
  20207. }
  20208. this.mainPlaylistLoader_.media(playlist, delay);
  20209. }
  20210. /**
  20211. * A function that ensures we switch our playlists inside of `mediaTypes`
  20212. * to match the current `serviceLocation` provided by the contentSteering controller.
  20213. * We want to check media types of `AUDIO`, `SUBTITLES`, and `CLOSED-CAPTIONS`.
  20214. *
  20215. * This should only be called on a DASH playback scenario while using content steering.
  20216. * This is necessary due to differences in how media in HLS manifests are generally tied to
  20217. * a video playlist, where in DASH that is not always the case.
  20218. */
  20219. switchMediaForDASHContentSteering_() {
  20220. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  20221. const mediaType = this.mediaTypes_[type];
  20222. const activeGroup = mediaType ? mediaType.activeGroup() : null;
  20223. const pathway = this.contentSteeringController_.getPathway();
  20224. if (activeGroup && pathway) {
  20225. // activeGroup can be an array or a single group
  20226. const mediaPlaylists = activeGroup.length ? activeGroup[0].playlists : activeGroup.playlists;
  20227. const dashMediaPlaylists = mediaPlaylists.filter(p => p.attributes.serviceLocation === pathway); // Switch the current active playlist to the correct CDN
  20228. if (dashMediaPlaylists.length) {
  20229. this.mediaTypes_[type].activePlaylistLoader.media(dashMediaPlaylists[0]);
  20230. }
  20231. }
  20232. });
  20233. }
  20234. /**
  20235. * Start a timer that periodically calls checkABR_
  20236. *
  20237. * @private
  20238. */
  20239. startABRTimer_() {
  20240. this.stopABRTimer_();
  20241. this.abrTimer_ = window$1.setInterval(() => this.checkABR_(), 250);
  20242. }
  20243. /**
  20244. * Stop the timer that periodically calls checkABR_
  20245. *
  20246. * @private
  20247. */
  20248. stopABRTimer_() {
  20249. // if we're scrubbing, we don't need to pause.
  20250. // This getter will be added to Video.js in version 7.11.
  20251. if (this.tech_.scrubbing && this.tech_.scrubbing()) {
  20252. return;
  20253. }
  20254. window$1.clearInterval(this.abrTimer_);
  20255. this.abrTimer_ = null;
  20256. }
  20257. /**
  20258. * Get a list of playlists for the currently selected audio playlist
  20259. *
  20260. * @return {Array} the array of audio playlists
  20261. */
  20262. getAudioTrackPlaylists_() {
  20263. const main = this.main();
  20264. const defaultPlaylists = main && main.playlists || []; // if we don't have any audio groups then we can only
  20265. // assume that the audio tracks are contained in main
  20266. // playlist array, use that or an empty array.
  20267. if (!main || !main.mediaGroups || !main.mediaGroups.AUDIO) {
  20268. return defaultPlaylists;
  20269. }
  20270. const AUDIO = main.mediaGroups.AUDIO;
  20271. const groupKeys = Object.keys(AUDIO);
  20272. let track; // get the current active track
  20273. if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
  20274. track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from main if mediaTypes_ isn't setup yet
  20275. } else {
  20276. // default group is `main` or just the first group.
  20277. const defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
  20278. for (const label in defaultGroup) {
  20279. if (defaultGroup[label].default) {
  20280. track = {
  20281. label
  20282. };
  20283. break;
  20284. }
  20285. }
  20286. } // no active track no playlists.
  20287. if (!track) {
  20288. return defaultPlaylists;
  20289. }
  20290. const playlists = []; // get all of the playlists that are possible for the
  20291. // active track.
  20292. for (const group in AUDIO) {
  20293. if (AUDIO[group][track.label]) {
  20294. const properties = AUDIO[group][track.label];
  20295. if (properties.playlists && properties.playlists.length) {
  20296. playlists.push.apply(playlists, properties.playlists);
  20297. } else if (properties.uri) {
  20298. playlists.push(properties);
  20299. } else if (main.playlists.length) {
  20300. // if an audio group does not have a uri
  20301. // see if we have main playlists that use it as a group.
  20302. // if we do then add those to the playlists list.
  20303. for (let i = 0; i < main.playlists.length; i++) {
  20304. const playlist = main.playlists[i];
  20305. if (playlist.attributes && playlist.attributes.AUDIO && playlist.attributes.AUDIO === group) {
  20306. playlists.push(playlist);
  20307. }
  20308. }
  20309. }
  20310. }
  20311. }
  20312. if (!playlists.length) {
  20313. return defaultPlaylists;
  20314. }
  20315. return playlists;
  20316. }
  20317. /**
  20318. * Register event handlers on the main playlist loader. A helper
  20319. * function for construction time.
  20320. *
  20321. * @private
  20322. */
  20323. setupMainPlaylistLoaderListeners_() {
  20324. this.mainPlaylistLoader_.on('loadedmetadata', () => {
  20325. const media = this.mainPlaylistLoader_.media();
  20326. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  20327. // timeout the request.
  20328. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  20329. this.requestOptions_.timeout = 0;
  20330. } else {
  20331. this.requestOptions_.timeout = requestTimeout;
  20332. } // if this isn't a live video and preload permits, start
  20333. // downloading segments
  20334. if (media.endList && this.tech_.preload() !== 'none') {
  20335. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  20336. this.mainSegmentLoader_.load();
  20337. }
  20338. setupMediaGroups({
  20339. sourceType: this.sourceType_,
  20340. segmentLoaders: {
  20341. AUDIO: this.audioSegmentLoader_,
  20342. SUBTITLES: this.subtitleSegmentLoader_,
  20343. main: this.mainSegmentLoader_
  20344. },
  20345. tech: this.tech_,
  20346. requestOptions: this.requestOptions_,
  20347. mainPlaylistLoader: this.mainPlaylistLoader_,
  20348. vhs: this.vhs_,
  20349. main: this.main(),
  20350. mediaTypes: this.mediaTypes_,
  20351. excludePlaylist: this.excludePlaylist.bind(this)
  20352. });
  20353. this.triggerPresenceUsage_(this.main(), media);
  20354. this.setupFirstPlay();
  20355. if (!this.mediaTypes_.AUDIO.activePlaylistLoader || this.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
  20356. this.trigger('selectedinitialmedia');
  20357. } else {
  20358. // We must wait for the active audio playlist loader to
  20359. // finish setting up before triggering this event so the
  20360. // representations API and EME setup is correct
  20361. this.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', () => {
  20362. this.trigger('selectedinitialmedia');
  20363. });
  20364. }
  20365. });
  20366. this.mainPlaylistLoader_.on('loadedplaylist', () => {
  20367. if (this.loadOnPlay_) {
  20368. this.tech_.off('play', this.loadOnPlay_);
  20369. }
  20370. let updatedPlaylist = this.mainPlaylistLoader_.media();
  20371. if (!updatedPlaylist) {
  20372. // Add content steering listeners on first load and init.
  20373. this.attachContentSteeringListeners_();
  20374. this.initContentSteeringController_(); // exclude any variants that are not supported by the browser before selecting
  20375. // an initial media as the playlist selectors do not consider browser support
  20376. this.excludeUnsupportedVariants_();
  20377. let selectedMedia;
  20378. if (this.enableLowInitialPlaylist) {
  20379. selectedMedia = this.selectInitialPlaylist();
  20380. }
  20381. if (!selectedMedia) {
  20382. selectedMedia = this.selectPlaylist();
  20383. }
  20384. if (!selectedMedia || !this.shouldSwitchToMedia_(selectedMedia)) {
  20385. return;
  20386. }
  20387. this.initialMedia_ = selectedMedia;
  20388. this.switchMedia_(this.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will
  20389. // fire again since the playlist will be requested. In the case of vhs-json
  20390. // (where the manifest object is provided as the source), when the media
  20391. // playlist's `segments` list is already available, a media playlist won't be
  20392. // requested, and loadedplaylist won't fire again, so the playlist handler must be
  20393. // called on its own here.
  20394. const haveJsonSource = this.sourceType_ === 'vhs-json' && this.initialMedia_.segments;
  20395. if (!haveJsonSource) {
  20396. return;
  20397. }
  20398. updatedPlaylist = this.initialMedia_;
  20399. }
  20400. this.handleUpdatedMediaPlaylist(updatedPlaylist);
  20401. });
  20402. this.mainPlaylistLoader_.on('error', () => {
  20403. const error = this.mainPlaylistLoader_.error;
  20404. this.excludePlaylist({
  20405. playlistToExclude: error.playlist,
  20406. error
  20407. });
  20408. });
  20409. this.mainPlaylistLoader_.on('mediachanging', () => {
  20410. this.mainSegmentLoader_.abort();
  20411. this.mainSegmentLoader_.pause();
  20412. });
  20413. this.mainPlaylistLoader_.on('mediachange', () => {
  20414. const media = this.mainPlaylistLoader_.media();
  20415. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  20416. // timeout the request.
  20417. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  20418. this.requestOptions_.timeout = 0;
  20419. } else {
  20420. this.requestOptions_.timeout = requestTimeout;
  20421. }
  20422. if (this.sourceType_ === 'dash') {
  20423. // we don't want to re-request the same hls playlist right after it was changed
  20424. this.mainPlaylistLoader_.load();
  20425. } // TODO: Create a new event on the PlaylistLoader that signals
  20426. // that the segments have changed in some way and use that to
  20427. // update the SegmentLoader instead of doing it twice here and
  20428. // on `loadedplaylist`
  20429. this.mainSegmentLoader_.pause();
  20430. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  20431. if (this.waitingForFastQualityPlaylistReceived_) {
  20432. this.runFastQualitySwitch_();
  20433. } else {
  20434. this.mainSegmentLoader_.load();
  20435. }
  20436. this.tech_.trigger({
  20437. type: 'mediachange',
  20438. bubbles: true
  20439. });
  20440. });
  20441. this.mainPlaylistLoader_.on('playlistunchanged', () => {
  20442. const updatedPlaylist = this.mainPlaylistLoader_.media(); // ignore unchanged playlists that have already been
  20443. // excluded for not-changing. We likely just have a really slowly updating
  20444. // playlist.
  20445. if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
  20446. return;
  20447. }
  20448. const playlistOutdated = this.stuckAtPlaylistEnd_(updatedPlaylist);
  20449. if (playlistOutdated) {
  20450. // Playlist has stopped updating and we're stuck at its end. Try to
  20451. // exclude it and switch to another playlist in the hope that that
  20452. // one is updating (and give the player a chance to re-adjust to the
  20453. // safe live point).
  20454. this.excludePlaylist({
  20455. error: {
  20456. message: 'Playlist no longer updating.',
  20457. reason: 'playlist-unchanged'
  20458. }
  20459. }); // useful for monitoring QoS
  20460. this.tech_.trigger('playliststuck');
  20461. }
  20462. });
  20463. this.mainPlaylistLoader_.on('renditiondisabled', () => {
  20464. this.tech_.trigger({
  20465. type: 'usage',
  20466. name: 'vhs-rendition-disabled'
  20467. });
  20468. });
  20469. this.mainPlaylistLoader_.on('renditionenabled', () => {
  20470. this.tech_.trigger({
  20471. type: 'usage',
  20472. name: 'vhs-rendition-enabled'
  20473. });
  20474. });
  20475. }
  20476. /**
  20477. * Given an updated media playlist (whether it was loaded for the first time, or
  20478. * refreshed for live playlists), update any relevant properties and state to reflect
  20479. * changes in the media that should be accounted for (e.g., cues and duration).
  20480. *
  20481. * @param {Object} updatedPlaylist the updated media playlist object
  20482. *
  20483. * @private
  20484. */
  20485. handleUpdatedMediaPlaylist(updatedPlaylist) {
  20486. if (this.useCueTags_) {
  20487. this.updateAdCues_(updatedPlaylist);
  20488. } // TODO: Create a new event on the PlaylistLoader that signals
  20489. // that the segments have changed in some way and use that to
  20490. // update the SegmentLoader instead of doing it twice here and
  20491. // on `mediachange`
  20492. this.mainSegmentLoader_.pause();
  20493. this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
  20494. if (this.waitingForFastQualityPlaylistReceived_) {
  20495. this.runFastQualitySwitch_();
  20496. }
  20497. this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,
  20498. // as it is possible that it was temporarily stopped while waiting for
  20499. // a playlist (e.g., in case the playlist errored and we re-requested it).
  20500. if (!this.tech_.paused()) {
  20501. this.mainSegmentLoader_.load();
  20502. if (this.audioSegmentLoader_) {
  20503. this.audioSegmentLoader_.load();
  20504. }
  20505. }
  20506. }
  20507. /**
  20508. * A helper function for triggerring presence usage events once per source
  20509. *
  20510. * @private
  20511. */
  20512. triggerPresenceUsage_(main, media) {
  20513. const mediaGroups = main.mediaGroups || {};
  20514. let defaultDemuxed = true;
  20515. const audioGroupKeys = Object.keys(mediaGroups.AUDIO);
  20516. for (const mediaGroup in mediaGroups.AUDIO) {
  20517. for (const label in mediaGroups.AUDIO[mediaGroup]) {
  20518. const properties = mediaGroups.AUDIO[mediaGroup][label];
  20519. if (!properties.uri) {
  20520. defaultDemuxed = false;
  20521. }
  20522. }
  20523. }
  20524. if (defaultDemuxed) {
  20525. this.tech_.trigger({
  20526. type: 'usage',
  20527. name: 'vhs-demuxed'
  20528. });
  20529. }
  20530. if (Object.keys(mediaGroups.SUBTITLES).length) {
  20531. this.tech_.trigger({
  20532. type: 'usage',
  20533. name: 'vhs-webvtt'
  20534. });
  20535. }
  20536. if (Vhs$1.Playlist.isAes(media)) {
  20537. this.tech_.trigger({
  20538. type: 'usage',
  20539. name: 'vhs-aes'
  20540. });
  20541. }
  20542. if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
  20543. this.tech_.trigger({
  20544. type: 'usage',
  20545. name: 'vhs-alternate-audio'
  20546. });
  20547. }
  20548. if (this.useCueTags_) {
  20549. this.tech_.trigger({
  20550. type: 'usage',
  20551. name: 'vhs-playlist-cue-tags'
  20552. });
  20553. }
  20554. }
  20555. shouldSwitchToMedia_(nextPlaylist) {
  20556. const currentPlaylist = this.mainPlaylistLoader_.media() || this.mainPlaylistLoader_.pendingMedia_;
  20557. const currentTime = this.tech_.currentTime();
  20558. const bufferLowWaterLine = this.bufferLowWaterLine();
  20559. const bufferHighWaterLine = this.bufferHighWaterLine();
  20560. const buffered = this.tech_.buffered();
  20561. return shouldSwitchToMedia({
  20562. buffered,
  20563. currentTime,
  20564. currentPlaylist,
  20565. nextPlaylist,
  20566. bufferLowWaterLine,
  20567. bufferHighWaterLine,
  20568. duration: this.duration(),
  20569. bufferBasedABR: this.bufferBasedABR,
  20570. log: this.logger_
  20571. });
  20572. }
  20573. /**
  20574. * Register event handlers on the segment loaders. A helper function
  20575. * for construction time.
  20576. *
  20577. * @private
  20578. */
  20579. setupSegmentLoaderListeners_() {
  20580. this.mainSegmentLoader_.on('bandwidthupdate', () => {
  20581. // Whether or not buffer based ABR or another ABR is used, on a bandwidth change it's
  20582. // useful to check to see if a rendition switch should be made.
  20583. this.checkABR_('bandwidthupdate');
  20584. this.tech_.trigger('bandwidthupdate');
  20585. });
  20586. this.mainSegmentLoader_.on('timeout', () => {
  20587. if (this.bufferBasedABR) {
  20588. // If a rendition change is needed, then it would've be done on `bandwidthupdate`.
  20589. // Here the only consideration is that for buffer based ABR there's no guarantee
  20590. // of an immediate switch (since the bandwidth is averaged with a timeout
  20591. // bandwidth value of 1), so force a load on the segment loader to keep it going.
  20592. this.mainSegmentLoader_.load();
  20593. }
  20594. }); // `progress` events are not reliable enough of a bandwidth measure to trigger buffer
  20595. // based ABR.
  20596. if (!this.bufferBasedABR) {
  20597. this.mainSegmentLoader_.on('progress', () => {
  20598. this.trigger('progress');
  20599. });
  20600. }
  20601. this.mainSegmentLoader_.on('error', () => {
  20602. const error = this.mainSegmentLoader_.error();
  20603. this.excludePlaylist({
  20604. playlistToExclude: error.playlist,
  20605. error
  20606. });
  20607. });
  20608. this.mainSegmentLoader_.on('appenderror', () => {
  20609. this.error = this.mainSegmentLoader_.error_;
  20610. this.trigger('error');
  20611. });
  20612. this.mainSegmentLoader_.on('syncinfoupdate', () => {
  20613. this.onSyncInfoUpdate_();
  20614. });
  20615. this.mainSegmentLoader_.on('timestampoffset', () => {
  20616. this.tech_.trigger({
  20617. type: 'usage',
  20618. name: 'vhs-timestamp-offset'
  20619. });
  20620. });
  20621. this.audioSegmentLoader_.on('syncinfoupdate', () => {
  20622. this.onSyncInfoUpdate_();
  20623. });
  20624. this.audioSegmentLoader_.on('appenderror', () => {
  20625. this.error = this.audioSegmentLoader_.error_;
  20626. this.trigger('error');
  20627. });
  20628. this.mainSegmentLoader_.on('ended', () => {
  20629. this.logger_('main segment loader ended');
  20630. this.onEndOfStream();
  20631. });
  20632. this.mainSegmentLoader_.on('earlyabort', event => {
  20633. // never try to early abort with the new ABR algorithm
  20634. if (this.bufferBasedABR) {
  20635. return;
  20636. }
  20637. this.delegateLoaders_('all', ['abort']);
  20638. this.excludePlaylist({
  20639. error: {
  20640. message: 'Aborted early because there isn\'t enough bandwidth to complete ' + 'the request without rebuffering.'
  20641. },
  20642. playlistExclusionDuration: ABORT_EARLY_EXCLUSION_SECONDS
  20643. });
  20644. });
  20645. const updateCodecs = () => {
  20646. if (!this.sourceUpdater_.hasCreatedSourceBuffers()) {
  20647. return this.tryToCreateSourceBuffers_();
  20648. }
  20649. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  20650. if (!codecs) {
  20651. return;
  20652. }
  20653. this.sourceUpdater_.addOrChangeSourceBuffers(codecs);
  20654. };
  20655. this.mainSegmentLoader_.on('trackinfo', updateCodecs);
  20656. this.audioSegmentLoader_.on('trackinfo', updateCodecs);
  20657. this.mainSegmentLoader_.on('fmp4', () => {
  20658. if (!this.triggeredFmp4Usage) {
  20659. this.tech_.trigger({
  20660. type: 'usage',
  20661. name: 'vhs-fmp4'
  20662. });
  20663. this.triggeredFmp4Usage = true;
  20664. }
  20665. });
  20666. this.audioSegmentLoader_.on('fmp4', () => {
  20667. if (!this.triggeredFmp4Usage) {
  20668. this.tech_.trigger({
  20669. type: 'usage',
  20670. name: 'vhs-fmp4'
  20671. });
  20672. this.triggeredFmp4Usage = true;
  20673. }
  20674. });
  20675. this.audioSegmentLoader_.on('ended', () => {
  20676. this.logger_('audioSegmentLoader ended');
  20677. this.onEndOfStream();
  20678. });
  20679. }
  20680. mediaSecondsLoaded_() {
  20681. return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
  20682. }
  20683. /**
  20684. * Call load on our SegmentLoaders
  20685. */
  20686. load() {
  20687. this.mainSegmentLoader_.load();
  20688. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  20689. this.audioSegmentLoader_.load();
  20690. }
  20691. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  20692. this.subtitleSegmentLoader_.load();
  20693. }
  20694. }
  20695. /**
  20696. * Re-tune playback quality level for the current player
  20697. * conditions. This method will perform destructive actions like removing
  20698. * already buffered content in order to readjust the currently active
  20699. * playlist quickly. This is good for manual quality changes
  20700. *
  20701. * @private
  20702. */
  20703. fastQualityChange_(media = this.selectPlaylist()) {
  20704. if (media && media === this.mainPlaylistLoader_.media()) {
  20705. this.logger_('skipping fastQualityChange because new media is same as old');
  20706. return;
  20707. }
  20708. this.switchMedia_(media, 'fast-quality'); // we would like to avoid race condition when we call fastQuality,
  20709. // reset everything and start loading segments from prev segments instead of new because new playlist is not received yet
  20710. this.waitingForFastQualityPlaylistReceived_ = true;
  20711. }
  20712. runFastQualitySwitch_() {
  20713. this.waitingForFastQualityPlaylistReceived_ = false; // Delete all buffered data to allow an immediate quality switch, then seek to give
  20714. // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
  20715. // ahead was roughly the minimum that will accomplish this across a variety of content
  20716. // in IE and Edge, but seeking in place is sufficient on all other browsers)
  20717. // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
  20718. // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
  20719. this.mainSegmentLoader_.pause();
  20720. this.mainSegmentLoader_.resetEverything(() => {
  20721. this.tech_.setCurrentTime(this.tech_.currentTime());
  20722. }); // don't need to reset audio as it is reset when media changes
  20723. }
  20724. /**
  20725. * Begin playback.
  20726. */
  20727. play() {
  20728. if (this.setupFirstPlay()) {
  20729. return;
  20730. }
  20731. if (this.tech_.ended()) {
  20732. this.tech_.setCurrentTime(0);
  20733. }
  20734. if (this.hasPlayed_) {
  20735. this.load();
  20736. }
  20737. const seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
  20738. // seek forward to the live point
  20739. if (this.tech_.duration() === Infinity) {
  20740. if (this.tech_.currentTime() < seekable.start(0)) {
  20741. return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
  20742. }
  20743. }
  20744. }
  20745. /**
  20746. * Seek to the latest media position if this is a live video and the
  20747. * player and video are loaded and initialized.
  20748. */
  20749. setupFirstPlay() {
  20750. const media = this.mainPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play
  20751. // If 1) there is no active media
  20752. // 2) the player is paused
  20753. // 3) the first play has already been setup
  20754. // then exit early
  20755. if (!media || this.tech_.paused() || this.hasPlayed_) {
  20756. return false;
  20757. } // when the video is a live stream and/or has a start time
  20758. if (!media.endList || media.start) {
  20759. const seekable = this.seekable();
  20760. if (!seekable.length) {
  20761. // without a seekable range, the player cannot seek to begin buffering at the
  20762. // live or start point
  20763. return false;
  20764. }
  20765. const seekableEnd = seekable.end(0);
  20766. let startPoint = seekableEnd;
  20767. if (media.start) {
  20768. const offset = media.start.timeOffset;
  20769. if (offset < 0) {
  20770. startPoint = Math.max(seekableEnd + offset, seekable.start(0));
  20771. } else {
  20772. startPoint = Math.min(seekableEnd, offset);
  20773. }
  20774. } // trigger firstplay to inform the source handler to ignore the next seek event
  20775. this.trigger('firstplay'); // seek to the live point
  20776. this.tech_.setCurrentTime(startPoint);
  20777. }
  20778. this.hasPlayed_ = true; // we can begin loading now that everything is ready
  20779. this.load();
  20780. return true;
  20781. }
  20782. /**
  20783. * handle the sourceopen event on the MediaSource
  20784. *
  20785. * @private
  20786. */
  20787. handleSourceOpen_() {
  20788. // Only attempt to create the source buffer if none already exist.
  20789. // handleSourceOpen is also called when we are "re-opening" a source buffer
  20790. // after `endOfStream` has been called (in response to a seek for instance)
  20791. this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of
  20792. // code in video.js but is required because play() must be invoked
  20793. // *after* the media source has opened.
  20794. if (this.tech_.autoplay()) {
  20795. const playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request
  20796. // on browsers which return a promise
  20797. if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
  20798. playPromise.then(null, e => {});
  20799. }
  20800. }
  20801. this.trigger('sourceopen');
  20802. }
  20803. /**
  20804. * handle the sourceended event on the MediaSource
  20805. *
  20806. * @private
  20807. */
  20808. handleSourceEnded_() {
  20809. if (!this.inbandTextTracks_.metadataTrack_) {
  20810. return;
  20811. }
  20812. const cues = this.inbandTextTracks_.metadataTrack_.cues;
  20813. if (!cues || !cues.length) {
  20814. return;
  20815. }
  20816. const duration = this.duration();
  20817. cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;
  20818. }
  20819. /**
  20820. * handle the durationchange event on the MediaSource
  20821. *
  20822. * @private
  20823. */
  20824. handleDurationChange_() {
  20825. this.tech_.trigger('durationchange');
  20826. }
  20827. /**
  20828. * Calls endOfStream on the media source when all active stream types have called
  20829. * endOfStream
  20830. *
  20831. * @param {string} streamType
  20832. * Stream type of the segment loader that called endOfStream
  20833. * @private
  20834. */
  20835. onEndOfStream() {
  20836. let isEndOfStream = this.mainSegmentLoader_.ended_;
  20837. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  20838. const mainMediaInfo = this.mainSegmentLoader_.getCurrentMediaInfo_(); // if the audio playlist loader exists, then alternate audio is active
  20839. if (!mainMediaInfo || mainMediaInfo.hasVideo) {
  20840. // if we do not know if the main segment loader contains video yet or if we
  20841. // definitively know the main segment loader contains video, then we need to wait
  20842. // for both main and audio segment loaders to call endOfStream
  20843. isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
  20844. } else {
  20845. // otherwise just rely on the audio loader
  20846. isEndOfStream = this.audioSegmentLoader_.ended_;
  20847. }
  20848. }
  20849. if (!isEndOfStream) {
  20850. return;
  20851. }
  20852. this.stopABRTimer_();
  20853. this.sourceUpdater_.endOfStream();
  20854. }
  20855. /**
  20856. * Check if a playlist has stopped being updated
  20857. *
  20858. * @param {Object} playlist the media playlist object
  20859. * @return {boolean} whether the playlist has stopped being updated or not
  20860. */
  20861. stuckAtPlaylistEnd_(playlist) {
  20862. const seekable = this.seekable();
  20863. if (!seekable.length) {
  20864. // playlist doesn't have enough information to determine whether we are stuck
  20865. return false;
  20866. }
  20867. const expired = this.syncController_.getExpiredTime(playlist, this.duration());
  20868. if (expired === null) {
  20869. return false;
  20870. } // does not use the safe live end to calculate playlist end, since we
  20871. // don't want to say we are stuck while there is still content
  20872. const absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
  20873. const currentTime = this.tech_.currentTime();
  20874. const buffered = this.tech_.buffered();
  20875. if (!buffered.length) {
  20876. // return true if the playhead reached the absolute end of the playlist
  20877. return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
  20878. }
  20879. const bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
  20880. // end of playlist
  20881. return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
  20882. }
  20883. /**
  20884. * Exclude a playlist for a set amount of time, making it unavailable for selection by
  20885. * the rendition selection algorithm, then force a new playlist (rendition) selection.
  20886. *
  20887. * @param {Object=} playlistToExclude
  20888. * the playlist to exclude, defaults to the currently selected playlist
  20889. * @param {Object=} error
  20890. * an optional error
  20891. * @param {number=} playlistExclusionDuration
  20892. * an optional number of seconds to exclude the playlist
  20893. */
  20894. excludePlaylist({
  20895. playlistToExclude = this.mainPlaylistLoader_.media(),
  20896. error = {},
  20897. playlistExclusionDuration
  20898. }) {
  20899. // If the `error` was generated by the playlist loader, it will contain
  20900. // the playlist we were trying to load (but failed) and that should be
  20901. // excluded instead of the currently selected playlist which is likely
  20902. // out-of-date in this scenario
  20903. playlistToExclude = playlistToExclude || this.mainPlaylistLoader_.media();
  20904. playlistExclusionDuration = playlistExclusionDuration || error.playlistExclusionDuration || this.playlistExclusionDuration; // If there is no current playlist, then an error occurred while we were
  20905. // trying to load the main OR while we were disposing of the tech
  20906. if (!playlistToExclude) {
  20907. this.error = error;
  20908. if (this.mediaSource.readyState !== 'open') {
  20909. this.trigger('error');
  20910. } else {
  20911. this.sourceUpdater_.endOfStream('network');
  20912. }
  20913. return;
  20914. }
  20915. playlistToExclude.playlistErrors_++;
  20916. const playlists = this.mainPlaylistLoader_.main.playlists;
  20917. const enabledPlaylists = playlists.filter(isEnabled);
  20918. const isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === playlistToExclude; // Don't exclude the only playlist unless it was excluded
  20919. // forever
  20920. if (playlists.length === 1 && playlistExclusionDuration !== Infinity) {
  20921. videojs.log.warn(`Problem encountered with playlist ${playlistToExclude.id}. ` + 'Trying again since it is the only playlist.');
  20922. this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
  20923. return this.mainPlaylistLoader_.load(isFinalRendition);
  20924. }
  20925. if (isFinalRendition) {
  20926. // If we're content steering, try other pathways.
  20927. if (this.main().contentSteering) {
  20928. const pathway = this.pathwayAttribute_(playlistToExclude); // Ignore at least 1 steering manifest refresh.
  20929. const reIncludeDelay = this.contentSteeringController_.steeringManifest.ttl * 1000;
  20930. this.contentSteeringController_.excludePathway(pathway);
  20931. this.excludeThenChangePathway_();
  20932. setTimeout(() => {
  20933. this.contentSteeringController_.addAvailablePathway(pathway);
  20934. }, reIncludeDelay);
  20935. return;
  20936. } // Since we're on the final non-excluded playlist, and we're about to exclude
  20937. // it, instead of erring the player or retrying this playlist, clear out the current
  20938. // exclusion list. This allows other playlists to be attempted in case any have been
  20939. // fixed.
  20940. let reincluded = false;
  20941. playlists.forEach(playlist => {
  20942. // skip current playlist which is about to be excluded
  20943. if (playlist === playlistToExclude) {
  20944. return;
  20945. }
  20946. const excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
  20947. if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
  20948. reincluded = true;
  20949. delete playlist.excludeUntil;
  20950. }
  20951. });
  20952. if (reincluded) {
  20953. 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
  20954. // playlist. This is needed for users relying on the retryplaylist event to catch a
  20955. // case where the player might be stuck and looping through "dead" playlists.
  20956. this.tech_.trigger('retryplaylist');
  20957. }
  20958. } // Exclude this playlist
  20959. let excludeUntil;
  20960. if (playlistToExclude.playlistErrors_ > this.maxPlaylistRetries) {
  20961. excludeUntil = Infinity;
  20962. } else {
  20963. excludeUntil = Date.now() + playlistExclusionDuration * 1000;
  20964. }
  20965. playlistToExclude.excludeUntil = excludeUntil;
  20966. if (error.reason) {
  20967. playlistToExclude.lastExcludeReason_ = error.reason;
  20968. }
  20969. this.tech_.trigger('excludeplaylist');
  20970. this.tech_.trigger({
  20971. type: 'usage',
  20972. name: 'vhs-rendition-excluded'
  20973. }); // TODO: only load a new playlist if we're excluding the current playlist
  20974. // If this function was called with a playlist that's not the current active playlist
  20975. // (e.g., media().id !== playlistToExclude.id),
  20976. // then a new playlist should not be selected and loaded, as there's nothing wrong with the current playlist.
  20977. const nextPlaylist = this.selectPlaylist();
  20978. if (!nextPlaylist) {
  20979. this.error = 'Playback cannot continue. No available working or supported playlists.';
  20980. this.trigger('error');
  20981. return;
  20982. }
  20983. const logFn = error.internal ? this.logger_ : videojs.log.warn;
  20984. const errorMessage = error.message ? ' ' + error.message : '';
  20985. logFn(`${error.internal ? 'Internal problem' : 'Problem'} encountered with playlist ${playlistToExclude.id}.` + `${errorMessage} Switching to playlist ${nextPlaylist.id}.`); // if audio group changed reset audio loaders
  20986. if (nextPlaylist.attributes.AUDIO !== playlistToExclude.attributes.AUDIO) {
  20987. this.delegateLoaders_('audio', ['abort', 'pause']);
  20988. } // if subtitle group changed reset subtitle loaders
  20989. if (nextPlaylist.attributes.SUBTITLES !== playlistToExclude.attributes.SUBTITLES) {
  20990. this.delegateLoaders_('subtitle', ['abort', 'pause']);
  20991. }
  20992. this.delegateLoaders_('main', ['abort', 'pause']);
  20993. const delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;
  20994. 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
  20995. return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
  20996. }
  20997. /**
  20998. * Pause all segment/playlist loaders
  20999. */
  21000. pauseLoading() {
  21001. this.delegateLoaders_('all', ['abort', 'pause']);
  21002. this.stopABRTimer_();
  21003. }
  21004. /**
  21005. * Call a set of functions in order on playlist loaders, segment loaders,
  21006. * or both types of loaders.
  21007. *
  21008. * @param {string} filter
  21009. * Filter loaders that should call fnNames using a string. Can be:
  21010. * * all - run on all loaders
  21011. * * audio - run on all audio loaders
  21012. * * subtitle - run on all subtitle loaders
  21013. * * main - run on the main loaders
  21014. *
  21015. * @param {Array|string} fnNames
  21016. * A string or array of function names to call.
  21017. */
  21018. delegateLoaders_(filter, fnNames) {
  21019. const loaders = [];
  21020. const dontFilterPlaylist = filter === 'all';
  21021. if (dontFilterPlaylist || filter === 'main') {
  21022. loaders.push(this.mainPlaylistLoader_);
  21023. }
  21024. const mediaTypes = [];
  21025. if (dontFilterPlaylist || filter === 'audio') {
  21026. mediaTypes.push('AUDIO');
  21027. }
  21028. if (dontFilterPlaylist || filter === 'subtitle') {
  21029. mediaTypes.push('CLOSED-CAPTIONS');
  21030. mediaTypes.push('SUBTITLES');
  21031. }
  21032. mediaTypes.forEach(mediaType => {
  21033. const loader = this.mediaTypes_[mediaType] && this.mediaTypes_[mediaType].activePlaylistLoader;
  21034. if (loader) {
  21035. loaders.push(loader);
  21036. }
  21037. });
  21038. ['main', 'audio', 'subtitle'].forEach(name => {
  21039. const loader = this[`${name}SegmentLoader_`];
  21040. if (loader && (filter === name || filter === 'all')) {
  21041. loaders.push(loader);
  21042. }
  21043. });
  21044. loaders.forEach(loader => fnNames.forEach(fnName => {
  21045. if (typeof loader[fnName] === 'function') {
  21046. loader[fnName]();
  21047. }
  21048. }));
  21049. }
  21050. /**
  21051. * set the current time on all segment loaders
  21052. *
  21053. * @param {TimeRange} currentTime the current time to set
  21054. * @return {TimeRange} the current time
  21055. */
  21056. setCurrentTime(currentTime) {
  21057. const buffered = findRange(this.tech_.buffered(), currentTime);
  21058. if (!(this.mainPlaylistLoader_ && this.mainPlaylistLoader_.media())) {
  21059. // return immediately if the metadata is not ready yet
  21060. return 0;
  21061. } // it's clearly an edge-case but don't thrown an error if asked to
  21062. // seek within an empty playlist
  21063. if (!this.mainPlaylistLoader_.media().segments) {
  21064. return 0;
  21065. } // if the seek location is already buffered, continue buffering as usual
  21066. if (buffered && buffered.length) {
  21067. return currentTime;
  21068. } // cancel outstanding requests so we begin buffering at the new
  21069. // location
  21070. this.mainSegmentLoader_.pause();
  21071. this.mainSegmentLoader_.resetEverything();
  21072. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  21073. this.audioSegmentLoader_.pause();
  21074. this.audioSegmentLoader_.resetEverything();
  21075. }
  21076. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  21077. this.subtitleSegmentLoader_.pause();
  21078. this.subtitleSegmentLoader_.resetEverything();
  21079. } // start segment loader loading in case they are paused
  21080. this.load();
  21081. }
  21082. /**
  21083. * get the current duration
  21084. *
  21085. * @return {TimeRange} the duration
  21086. */
  21087. duration() {
  21088. if (!this.mainPlaylistLoader_) {
  21089. return 0;
  21090. }
  21091. const media = this.mainPlaylistLoader_.media();
  21092. if (!media) {
  21093. // no playlists loaded yet, so can't determine a duration
  21094. return 0;
  21095. } // Don't rely on the media source for duration in the case of a live playlist since
  21096. // setting the native MediaSource's duration to infinity ends up with consequences to
  21097. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  21098. //
  21099. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  21100. // however, few browsers have support for setLiveSeekableRange()
  21101. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  21102. //
  21103. // Until a time when the duration of the media source can be set to infinity, and a
  21104. // seekable range specified across browsers, just return Infinity.
  21105. if (!media.endList) {
  21106. return Infinity;
  21107. } // Since this is a VOD video, it is safe to rely on the media source's duration (if
  21108. // available). If it's not available, fall back to a playlist-calculated estimate.
  21109. if (this.mediaSource) {
  21110. return this.mediaSource.duration;
  21111. }
  21112. return Vhs$1.Playlist.duration(media);
  21113. }
  21114. /**
  21115. * check the seekable range
  21116. *
  21117. * @return {TimeRange} the seekable range
  21118. */
  21119. seekable() {
  21120. return this.seekable_;
  21121. }
  21122. onSyncInfoUpdate_() {
  21123. let audioSeekable; // TODO check for creation of both source buffers before updating seekable
  21124. //
  21125. // A fix was made to this function where a check for
  21126. // this.sourceUpdater_.hasCreatedSourceBuffers
  21127. // was added to ensure that both source buffers were created before seekable was
  21128. // updated. However, it originally had a bug where it was checking for a true and
  21129. // returning early instead of checking for false. Setting it to check for false to
  21130. // return early though created other issues. A call to play() would check for seekable
  21131. // end without verifying that a seekable range was present. In addition, even checking
  21132. // for that didn't solve some issues, as handleFirstPlay is sometimes worked around
  21133. // due to a media update calling load on the segment loaders, skipping a seek to live,
  21134. // thereby starting live streams at the beginning of the stream rather than at the end.
  21135. //
  21136. // This conditional should be fixed to wait for the creation of two source buffers at
  21137. // the same time as the other sections of code are fixed to properly seek to live and
  21138. // not throw an error due to checking for a seekable end when no seekable range exists.
  21139. //
  21140. // For now, fall back to the older behavior, with the understanding that the seekable
  21141. // range may not be completely correct, leading to a suboptimal initial live point.
  21142. if (!this.mainPlaylistLoader_) {
  21143. return;
  21144. }
  21145. let media = this.mainPlaylistLoader_.media();
  21146. if (!media) {
  21147. return;
  21148. }
  21149. let expired = this.syncController_.getExpiredTime(media, this.duration());
  21150. if (expired === null) {
  21151. // not enough information to update seekable
  21152. return;
  21153. }
  21154. const main = this.mainPlaylistLoader_.main;
  21155. const mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  21156. if (mainSeekable.length === 0) {
  21157. return;
  21158. }
  21159. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  21160. media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
  21161. expired = this.syncController_.getExpiredTime(media, this.duration());
  21162. if (expired === null) {
  21163. return;
  21164. }
  21165. audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  21166. if (audioSeekable.length === 0) {
  21167. return;
  21168. }
  21169. }
  21170. let oldEnd;
  21171. let oldStart;
  21172. if (this.seekable_ && this.seekable_.length) {
  21173. oldEnd = this.seekable_.end(0);
  21174. oldStart = this.seekable_.start(0);
  21175. }
  21176. if (!audioSeekable) {
  21177. // seekable has been calculated based on buffering video data so it
  21178. // can be returned directly
  21179. this.seekable_ = mainSeekable;
  21180. } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
  21181. // seekables are pretty far off, rely on main
  21182. this.seekable_ = mainSeekable;
  21183. } else {
  21184. 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)]]);
  21185. } // seekable is the same as last time
  21186. if (this.seekable_ && this.seekable_.length) {
  21187. if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
  21188. return;
  21189. }
  21190. }
  21191. this.logger_(`seekable updated [${printableRange(this.seekable_)}]`);
  21192. this.tech_.trigger('seekablechanged');
  21193. }
  21194. /**
  21195. * Update the player duration
  21196. */
  21197. updateDuration(isLive) {
  21198. if (this.updateDuration_) {
  21199. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  21200. this.updateDuration_ = null;
  21201. }
  21202. if (this.mediaSource.readyState !== 'open') {
  21203. this.updateDuration_ = this.updateDuration.bind(this, isLive);
  21204. this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
  21205. return;
  21206. }
  21207. if (isLive) {
  21208. const seekable = this.seekable();
  21209. if (!seekable.length) {
  21210. return;
  21211. } // Even in the case of a live playlist, the native MediaSource's duration should not
  21212. // be set to Infinity (even though this would be expected for a live playlist), since
  21213. // setting the native MediaSource's duration to infinity ends up with consequences to
  21214. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  21215. //
  21216. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  21217. // however, few browsers have support for setLiveSeekableRange()
  21218. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  21219. //
  21220. // Until a time when the duration of the media source can be set to infinity, and a
  21221. // seekable range specified across browsers, the duration should be greater than or
  21222. // equal to the last possible seekable value.
  21223. // MediaSource duration starts as NaN
  21224. // It is possible (and probable) that this case will never be reached for many
  21225. // sources, since the MediaSource reports duration as the highest value without
  21226. // accounting for timestamp offset. For example, if the timestamp offset is -100 and
  21227. // we buffered times 0 to 100 with real times of 100 to 200, even though current
  21228. // time will be between 0 and 100, the native media source may report the duration
  21229. // as 200. However, since we report duration separate from the media source (as
  21230. // Infinity), and as long as the native media source duration value is greater than
  21231. // our reported seekable range, seeks will work as expected. The large number as
  21232. // duration for live is actually a strategy used by some players to work around the
  21233. // issue of live seekable ranges cited above.
  21234. if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
  21235. this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
  21236. }
  21237. return;
  21238. }
  21239. const buffered = this.tech_.buffered();
  21240. let duration = Vhs$1.Playlist.duration(this.mainPlaylistLoader_.media());
  21241. if (buffered.length > 0) {
  21242. duration = Math.max(duration, buffered.end(buffered.length - 1));
  21243. }
  21244. if (this.mediaSource.duration !== duration) {
  21245. this.sourceUpdater_.setDuration(duration);
  21246. }
  21247. }
  21248. /**
  21249. * dispose of the PlaylistController and everything
  21250. * that it controls
  21251. */
  21252. dispose() {
  21253. this.trigger('dispose');
  21254. this.decrypter_.terminate();
  21255. this.mainPlaylistLoader_.dispose();
  21256. this.mainSegmentLoader_.dispose();
  21257. this.contentSteeringController_.dispose();
  21258. this.keyStatusMap_.clear();
  21259. if (this.loadOnPlay_) {
  21260. this.tech_.off('play', this.loadOnPlay_);
  21261. }
  21262. ['AUDIO', 'SUBTITLES'].forEach(type => {
  21263. const groups = this.mediaTypes_[type].groups;
  21264. for (const id in groups) {
  21265. groups[id].forEach(group => {
  21266. if (group.playlistLoader) {
  21267. group.playlistLoader.dispose();
  21268. }
  21269. });
  21270. }
  21271. });
  21272. this.audioSegmentLoader_.dispose();
  21273. this.subtitleSegmentLoader_.dispose();
  21274. this.sourceUpdater_.dispose();
  21275. this.timelineChangeController_.dispose();
  21276. this.stopABRTimer_();
  21277. if (this.updateDuration_) {
  21278. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  21279. }
  21280. this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  21281. this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
  21282. this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
  21283. this.off();
  21284. }
  21285. /**
  21286. * return the main playlist object if we have one
  21287. *
  21288. * @return {Object} the main playlist object that we parsed
  21289. */
  21290. main() {
  21291. return this.mainPlaylistLoader_.main;
  21292. }
  21293. /**
  21294. * return the currently selected playlist
  21295. *
  21296. * @return {Object} the currently selected playlist object that we parsed
  21297. */
  21298. media() {
  21299. // playlist loader will not return media if it has not been fully loaded
  21300. return this.mainPlaylistLoader_.media() || this.initialMedia_;
  21301. }
  21302. areMediaTypesKnown_() {
  21303. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  21304. const hasMainMediaInfo = !!this.mainSegmentLoader_.getCurrentMediaInfo_(); // if we are not using an audio loader, then we have audio media info
  21305. // otherwise check on the segment loader.
  21306. const hasAudioMediaInfo = !usingAudioLoader ? true : !!this.audioSegmentLoader_.getCurrentMediaInfo_(); // one or both loaders has not loaded sufficently to get codecs
  21307. if (!hasMainMediaInfo || !hasAudioMediaInfo) {
  21308. return false;
  21309. }
  21310. return true;
  21311. }
  21312. getCodecsOrExclude_() {
  21313. const media = {
  21314. main: this.mainSegmentLoader_.getCurrentMediaInfo_() || {},
  21315. audio: this.audioSegmentLoader_.getCurrentMediaInfo_() || {}
  21316. };
  21317. const playlist = this.mainSegmentLoader_.getPendingSegmentPlaylist() || this.media(); // set "main" media equal to video
  21318. media.video = media.main;
  21319. const playlistCodecs = codecsForPlaylist(this.main(), playlist);
  21320. const codecs = {};
  21321. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  21322. if (media.main.hasVideo) {
  21323. codecs.video = playlistCodecs.video || media.main.videoCodec || DEFAULT_VIDEO_CODEC;
  21324. }
  21325. if (media.main.isMuxed) {
  21326. codecs.video += `,${playlistCodecs.audio || media.main.audioCodec || DEFAULT_AUDIO_CODEC}`;
  21327. }
  21328. if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
  21329. codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || DEFAULT_AUDIO_CODEC; // set audio isFmp4 so we use the correct "supports" function below
  21330. media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
  21331. } // no codecs, no playback.
  21332. if (!codecs.audio && !codecs.video) {
  21333. this.excludePlaylist({
  21334. playlistToExclude: playlist,
  21335. error: {
  21336. message: 'Could not determine codecs for playlist.'
  21337. },
  21338. playlistExclusionDuration: Infinity
  21339. });
  21340. return;
  21341. } // fmp4 relies on browser support, while ts relies on muxer support
  21342. const supportFunction = (isFmp4, codec) => isFmp4 ? browserSupportsCodec(codec) : muxerSupportsCodec(codec);
  21343. const unsupportedCodecs = {};
  21344. let unsupportedAudio;
  21345. ['video', 'audio'].forEach(function (type) {
  21346. if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
  21347. const supporter = media[type].isFmp4 ? 'browser' : 'muxer';
  21348. unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
  21349. unsupportedCodecs[supporter].push(codecs[type]);
  21350. if (type === 'audio') {
  21351. unsupportedAudio = supporter;
  21352. }
  21353. }
  21354. });
  21355. if (usingAudioLoader && unsupportedAudio && playlist.attributes.AUDIO) {
  21356. const audioGroup = playlist.attributes.AUDIO;
  21357. this.main().playlists.forEach(variant => {
  21358. const variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
  21359. if (variantAudioGroup === audioGroup && variant !== playlist) {
  21360. variant.excludeUntil = Infinity;
  21361. }
  21362. });
  21363. this.logger_(`excluding audio group ${audioGroup} as ${unsupportedAudio} does not support codec(s): "${codecs.audio}"`);
  21364. } // if we have any unsupported codecs exclude this playlist.
  21365. if (Object.keys(unsupportedCodecs).length) {
  21366. const message = Object.keys(unsupportedCodecs).reduce((acc, supporter) => {
  21367. if (acc) {
  21368. acc += ', ';
  21369. }
  21370. acc += `${supporter} does not support codec(s): "${unsupportedCodecs[supporter].join(',')}"`;
  21371. return acc;
  21372. }, '') + '.';
  21373. this.excludePlaylist({
  21374. playlistToExclude: playlist,
  21375. error: {
  21376. internal: true,
  21377. message
  21378. },
  21379. playlistExclusionDuration: Infinity
  21380. });
  21381. return;
  21382. } // check if codec switching is happening
  21383. if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
  21384. const switchMessages = [];
  21385. ['video', 'audio'].forEach(type => {
  21386. const newCodec = (parseCodecs(this.sourceUpdater_.codecs[type] || '')[0] || {}).type;
  21387. const oldCodec = (parseCodecs(codecs[type] || '')[0] || {}).type;
  21388. if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
  21389. switchMessages.push(`"${this.sourceUpdater_.codecs[type]}" -> "${codecs[type]}"`);
  21390. }
  21391. });
  21392. if (switchMessages.length) {
  21393. this.excludePlaylist({
  21394. playlistToExclude: playlist,
  21395. error: {
  21396. message: `Codec switching not supported: ${switchMessages.join(', ')}.`,
  21397. internal: true
  21398. },
  21399. playlistExclusionDuration: Infinity
  21400. });
  21401. return;
  21402. }
  21403. } // TODO: when using the muxer shouldn't we just return
  21404. // the codecs that the muxer outputs?
  21405. return codecs;
  21406. }
  21407. /**
  21408. * Create source buffers and exlude any incompatible renditions.
  21409. *
  21410. * @private
  21411. */
  21412. tryToCreateSourceBuffers_() {
  21413. // media source is not ready yet or sourceBuffers are already
  21414. // created.
  21415. if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {
  21416. return;
  21417. }
  21418. if (!this.areMediaTypesKnown_()) {
  21419. return;
  21420. }
  21421. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  21422. if (!codecs) {
  21423. return;
  21424. }
  21425. this.sourceUpdater_.createSourceBuffers(codecs);
  21426. const codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
  21427. this.excludeIncompatibleVariants_(codecString);
  21428. }
  21429. /**
  21430. * Excludes playlists with codecs that are unsupported by the muxer and browser.
  21431. */
  21432. excludeUnsupportedVariants_() {
  21433. const playlists = this.main().playlists;
  21434. const ids = []; // TODO: why don't we have a property to loop through all
  21435. // playlist? Why did we ever mix indexes and keys?
  21436. Object.keys(playlists).forEach(key => {
  21437. const variant = playlists[key]; // check if we already processed this playlist.
  21438. if (ids.indexOf(variant.id) !== -1) {
  21439. return;
  21440. }
  21441. ids.push(variant.id);
  21442. const codecs = codecsForPlaylist(this.main, variant);
  21443. const unsupported = [];
  21444. if (codecs.audio && !muxerSupportsCodec(codecs.audio) && !browserSupportsCodec(codecs.audio)) {
  21445. unsupported.push(`audio codec ${codecs.audio}`);
  21446. }
  21447. if (codecs.video && !muxerSupportsCodec(codecs.video) && !browserSupportsCodec(codecs.video)) {
  21448. unsupported.push(`video codec ${codecs.video}`);
  21449. }
  21450. if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
  21451. unsupported.push(`text codec ${codecs.text}`);
  21452. }
  21453. if (unsupported.length) {
  21454. variant.excludeUntil = Infinity;
  21455. this.logger_(`excluding ${variant.id} for unsupported: ${unsupported.join(', ')}`);
  21456. }
  21457. });
  21458. }
  21459. /**
  21460. * Exclude playlists that are known to be codec or
  21461. * stream-incompatible with the SourceBuffer configuration. For
  21462. * instance, Media Source Extensions would cause the video element to
  21463. * stall waiting for video data if you switched from a variant with
  21464. * video and audio to an audio-only one.
  21465. *
  21466. * @param {Object} media a media playlist compatible with the current
  21467. * set of SourceBuffers. Variants in the current main playlist that
  21468. * do not appear to have compatible codec or stream configurations
  21469. * will be excluded from the default playlist selection algorithm
  21470. * indefinitely.
  21471. * @private
  21472. */
  21473. excludeIncompatibleVariants_(codecString) {
  21474. const ids = [];
  21475. const playlists = this.main().playlists;
  21476. const codecs = unwrapCodecList(parseCodecs(codecString));
  21477. const codecCount_ = codecCount(codecs);
  21478. const videoDetails = codecs.video && parseCodecs(codecs.video)[0] || null;
  21479. const audioDetails = codecs.audio && parseCodecs(codecs.audio)[0] || null;
  21480. Object.keys(playlists).forEach(key => {
  21481. const variant = playlists[key]; // check if we already processed this playlist.
  21482. // or it if it is already excluded forever.
  21483. if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
  21484. return;
  21485. }
  21486. ids.push(variant.id);
  21487. const exclusionReasons = []; // get codecs from the playlist for this variant
  21488. const variantCodecs = codecsForPlaylist(this.mainPlaylistLoader_.main, variant);
  21489. const variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this
  21490. // variant is incompatible. Wait for mux.js to probe
  21491. if (!variantCodecs.audio && !variantCodecs.video) {
  21492. return;
  21493. } // TODO: we can support this by removing the
  21494. // old media source and creating a new one, but it will take some work.
  21495. // The number of streams cannot change
  21496. if (variantCodecCount !== codecCount_) {
  21497. exclusionReasons.push(`codec count "${variantCodecCount}" !== "${codecCount_}"`);
  21498. } // only exclude playlists by codec change, if codecs cannot switch
  21499. // during playback.
  21500. if (!this.sourceUpdater_.canChangeType()) {
  21501. const variantVideoDetails = variantCodecs.video && parseCodecs(variantCodecs.video)[0] || null;
  21502. const variantAudioDetails = variantCodecs.audio && parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change
  21503. if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
  21504. exclusionReasons.push(`video codec "${variantVideoDetails.type}" !== "${videoDetails.type}"`);
  21505. } // the audio codec cannot change
  21506. if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
  21507. exclusionReasons.push(`audio codec "${variantAudioDetails.type}" !== "${audioDetails.type}"`);
  21508. }
  21509. }
  21510. if (exclusionReasons.length) {
  21511. variant.excludeUntil = Infinity;
  21512. this.logger_(`excluding ${variant.id}: ${exclusionReasons.join(' && ')}`);
  21513. }
  21514. });
  21515. }
  21516. updateAdCues_(media) {
  21517. let offset = 0;
  21518. const seekable = this.seekable();
  21519. if (seekable.length) {
  21520. offset = seekable.start(0);
  21521. }
  21522. updateAdCues(media, this.cueTagsTrack_, offset);
  21523. }
  21524. /**
  21525. * Calculates the desired forward buffer length based on current time
  21526. *
  21527. * @return {number} Desired forward buffer length in seconds
  21528. */
  21529. goalBufferLength() {
  21530. const currentTime = this.tech_.currentTime();
  21531. const initial = Config.GOAL_BUFFER_LENGTH;
  21532. const rate = Config.GOAL_BUFFER_LENGTH_RATE;
  21533. const max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
  21534. return Math.min(initial + currentTime * rate, max);
  21535. }
  21536. /**
  21537. * Calculates the desired buffer low water line based on current time
  21538. *
  21539. * @return {number} Desired buffer low water line in seconds
  21540. */
  21541. bufferLowWaterLine() {
  21542. const currentTime = this.tech_.currentTime();
  21543. const initial = Config.BUFFER_LOW_WATER_LINE;
  21544. const rate = Config.BUFFER_LOW_WATER_LINE_RATE;
  21545. const max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
  21546. const newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
  21547. return Math.min(initial + currentTime * rate, this.bufferBasedABR ? newMax : max);
  21548. }
  21549. bufferHighWaterLine() {
  21550. return Config.BUFFER_HIGH_WATER_LINE;
  21551. }
  21552. addDateRangesToTextTrack_(dateRanges) {
  21553. createMetadataTrackIfNotExists(this.inbandTextTracks_, 'com.apple.streaming', this.tech_);
  21554. addDateRangeMetadata({
  21555. inbandTextTracks: this.inbandTextTracks_,
  21556. dateRanges
  21557. });
  21558. }
  21559. addMetadataToTextTrack(dispatchType, metadataArray, videoDuration) {
  21560. const timestampOffset = this.sourceUpdater_.videoBuffer ? this.sourceUpdater_.videoTimestampOffset() : this.sourceUpdater_.audioTimestampOffset(); // There's potentially an issue where we could double add metadata if there's a muxed
  21561. // audio/video source with a metadata track, and an alt audio with a metadata track.
  21562. // However, this probably won't happen, and if it does it can be handled then.
  21563. createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.tech_);
  21564. addMetadata({
  21565. inbandTextTracks: this.inbandTextTracks_,
  21566. metadataArray,
  21567. timestampOffset,
  21568. videoDuration
  21569. });
  21570. }
  21571. /**
  21572. * Utility for getting the pathway or service location from an HLS or DASH playlist.
  21573. *
  21574. * @param {Object} playlist for getting pathway from.
  21575. * @return the pathway attribute of a playlist
  21576. */
  21577. pathwayAttribute_(playlist) {
  21578. return playlist.attributes['PATHWAY-ID'] || playlist.attributes.serviceLocation;
  21579. }
  21580. /**
  21581. * Initialize available pathways and apply the tag properties.
  21582. */
  21583. initContentSteeringController_() {
  21584. const main = this.main();
  21585. if (!main.contentSteering) {
  21586. return;
  21587. }
  21588. for (const playlist of main.playlists) {
  21589. this.contentSteeringController_.addAvailablePathway(this.pathwayAttribute_(playlist));
  21590. }
  21591. this.contentSteeringController_.assignTagProperties(main.uri, main.contentSteering); // request the steering manifest immediately if queryBeforeStart is set.
  21592. if (this.contentSteeringController_.queryBeforeStart) {
  21593. // When queryBeforeStart is true, initial request should omit steering parameters.
  21594. this.contentSteeringController_.requestSteeringManifest(true);
  21595. return;
  21596. } // otherwise start content steering after playback starts
  21597. this.tech_.one('canplay', () => {
  21598. this.contentSteeringController_.requestSteeringManifest();
  21599. });
  21600. }
  21601. /**
  21602. * Reset the content steering controller and re-init.
  21603. */
  21604. resetContentSteeringController_() {
  21605. this.contentSteeringController_.clearAvailablePathways();
  21606. this.contentSteeringController_.dispose();
  21607. this.initContentSteeringController_();
  21608. }
  21609. /**
  21610. * Attaches the listeners for content steering.
  21611. */
  21612. attachContentSteeringListeners_() {
  21613. this.contentSteeringController_.on('content-steering', this.excludeThenChangePathway_.bind(this));
  21614. if (this.sourceType_ === 'dash') {
  21615. this.mainPlaylistLoader_.on('loadedplaylist', () => {
  21616. const main = this.main(); // check if steering tag or pathways changed.
  21617. const didDashTagChange = this.contentSteeringController_.didDASHTagChange(main.uri, main.contentSteering);
  21618. const didPathwaysChange = () => {
  21619. const availablePathways = this.contentSteeringController_.getAvailablePathways();
  21620. const newPathways = [];
  21621. for (const playlist of main.playlists) {
  21622. const serviceLocation = playlist.attributes.serviceLocation;
  21623. if (serviceLocation) {
  21624. newPathways.push(serviceLocation);
  21625. if (!availablePathways.has(serviceLocation)) {
  21626. return true;
  21627. }
  21628. }
  21629. } // If we have no new serviceLocations and previously had availablePathways
  21630. if (!newPathways.length && availablePathways.size) {
  21631. return true;
  21632. }
  21633. return false;
  21634. };
  21635. if (didDashTagChange || didPathwaysChange()) {
  21636. this.resetContentSteeringController_();
  21637. }
  21638. });
  21639. }
  21640. }
  21641. /**
  21642. * Simple exclude and change playlist logic for content steering.
  21643. */
  21644. excludeThenChangePathway_() {
  21645. const currentPathway = this.contentSteeringController_.getPathway();
  21646. if (!currentPathway) {
  21647. return;
  21648. }
  21649. this.handlePathwayClones_();
  21650. const main = this.main();
  21651. const playlists = main.playlists;
  21652. const ids = new Set();
  21653. let didEnablePlaylists = false;
  21654. Object.keys(playlists).forEach(key => {
  21655. const variant = playlists[key];
  21656. const pathwayId = this.pathwayAttribute_(variant);
  21657. const differentPathwayId = pathwayId && currentPathway !== pathwayId;
  21658. const steeringExclusion = variant.excludeUntil === Infinity && variant.lastExcludeReason_ === 'content-steering';
  21659. if (steeringExclusion && !differentPathwayId) {
  21660. delete variant.excludeUntil;
  21661. delete variant.lastExcludeReason_;
  21662. didEnablePlaylists = true;
  21663. }
  21664. const noExcludeUntil = !variant.excludeUntil && variant.excludeUntil !== Infinity;
  21665. const shouldExclude = !ids.has(variant.id) && differentPathwayId && noExcludeUntil;
  21666. if (!shouldExclude) {
  21667. return;
  21668. }
  21669. ids.add(variant.id);
  21670. variant.excludeUntil = Infinity;
  21671. variant.lastExcludeReason_ = 'content-steering'; // TODO: kind of spammy, maybe move this.
  21672. this.logger_(`excluding ${variant.id} for ${variant.lastExcludeReason_}`);
  21673. });
  21674. if (this.contentSteeringController_.manifestType_ === 'DASH') {
  21675. Object.keys(this.mediaTypes_).forEach(key => {
  21676. const type = this.mediaTypes_[key];
  21677. if (type.activePlaylistLoader) {
  21678. const currentPlaylist = type.activePlaylistLoader.media_; // Check if the current media playlist matches the current CDN
  21679. if (currentPlaylist && currentPlaylist.attributes.serviceLocation !== currentPathway) {
  21680. didEnablePlaylists = true;
  21681. }
  21682. }
  21683. });
  21684. }
  21685. if (didEnablePlaylists) {
  21686. this.changeSegmentPathway_();
  21687. }
  21688. }
  21689. /**
  21690. * Add, update, or delete playlists and media groups for
  21691. * the pathway clones for HLS Content Steering.
  21692. *
  21693. * See https://datatracker.ietf.org/doc/draft-pantos-hls-rfc8216bis/
  21694. *
  21695. * NOTE: Pathway cloning does not currently support the `PER_VARIANT_URIS` and
  21696. * `PER_RENDITION_URIS` as we do not handle `STABLE-VARIANT-ID` or
  21697. * `STABLE-RENDITION-ID` values.
  21698. */
  21699. handlePathwayClones_() {
  21700. const main = this.main();
  21701. const playlists = main.playlists;
  21702. const currentPathwayClones = this.contentSteeringController_.currentPathwayClones;
  21703. const nextPathwayClones = this.contentSteeringController_.nextPathwayClones;
  21704. const hasClones = currentPathwayClones && currentPathwayClones.size || nextPathwayClones && nextPathwayClones.size;
  21705. if (!hasClones) {
  21706. return;
  21707. }
  21708. for (const [id, clone] of currentPathwayClones.entries()) {
  21709. const newClone = nextPathwayClones.get(id); // Delete the old pathway clone.
  21710. if (!newClone) {
  21711. this.mainPlaylistLoader_.updateOrDeleteClone(clone);
  21712. this.contentSteeringController_.excludePathway(id);
  21713. }
  21714. }
  21715. for (const [id, clone] of nextPathwayClones.entries()) {
  21716. const oldClone = currentPathwayClones.get(id); // Create a new pathway if it is a new pathway clone object.
  21717. if (!oldClone) {
  21718. const playlistsToClone = playlists.filter(p => {
  21719. return p.attributes['PATHWAY-ID'] === clone['BASE-ID'];
  21720. });
  21721. playlistsToClone.forEach(p => {
  21722. this.mainPlaylistLoader_.addClonePathway(clone, p);
  21723. });
  21724. this.contentSteeringController_.addAvailablePathway(id);
  21725. continue;
  21726. } // There have not been changes to the pathway clone object, so skip.
  21727. if (this.equalPathwayClones_(oldClone, clone)) {
  21728. continue;
  21729. } // Update a preexisting cloned pathway.
  21730. // True is set for the update flag.
  21731. this.mainPlaylistLoader_.updateOrDeleteClone(clone, true);
  21732. this.contentSteeringController_.addAvailablePathway(id);
  21733. } // Deep copy contents of next to current pathways.
  21734. this.contentSteeringController_.currentPathwayClones = new Map(JSON.parse(JSON.stringify([...nextPathwayClones])));
  21735. }
  21736. /**
  21737. * Determines whether two pathway clone objects are equivalent.
  21738. *
  21739. * @param {Object} a The first pathway clone object.
  21740. * @param {Object} b The second pathway clone object.
  21741. * @return {boolean} True if the pathway clone objects are equal, false otherwise.
  21742. */
  21743. equalPathwayClones_(a, b) {
  21744. if (a['BASE-ID'] !== b['BASE-ID'] || a.ID !== b.ID || a['URI-REPLACEMENT'].HOST !== b['URI-REPLACEMENT'].HOST) {
  21745. return false;
  21746. }
  21747. const aParams = a['URI-REPLACEMENT'].PARAMS;
  21748. const bParams = b['URI-REPLACEMENT'].PARAMS; // We need to iterate through both lists of params because one could be
  21749. // missing a parameter that the other has.
  21750. for (const p in aParams) {
  21751. if (aParams[p] !== bParams[p]) {
  21752. return false;
  21753. }
  21754. }
  21755. for (const p in bParams) {
  21756. if (aParams[p] !== bParams[p]) {
  21757. return false;
  21758. }
  21759. }
  21760. return true;
  21761. }
  21762. /**
  21763. * Changes the current playlists for audio, video and subtitles after a new pathway
  21764. * is chosen from content steering.
  21765. */
  21766. changeSegmentPathway_() {
  21767. const nextPlaylist = this.selectPlaylist();
  21768. this.pauseLoading(); // Switch audio and text track playlists if necessary in DASH
  21769. if (this.contentSteeringController_.manifestType_ === 'DASH') {
  21770. this.switchMediaForDASHContentSteering_();
  21771. }
  21772. this.switchMedia_(nextPlaylist, 'content-steering');
  21773. }
  21774. /**
  21775. * Iterates through playlists and check their keyId set and compare with the
  21776. * keyStatusMap, only enable playlists that have a usable key. If the playlist
  21777. * has no keyId leave it enabled by default.
  21778. */
  21779. excludeNonUsablePlaylistsByKeyId_() {
  21780. if (!this.mainPlaylistLoader_ || !this.mainPlaylistLoader_.main) {
  21781. return;
  21782. }
  21783. let nonUsableKeyStatusCount = 0;
  21784. const NON_USABLE = 'non-usable';
  21785. this.mainPlaylistLoader_.main.playlists.forEach(playlist => {
  21786. const keyIdSet = this.mainPlaylistLoader_.getKeyIdSet(playlist); // If the playlist doesn't have keyIDs lets not exclude it.
  21787. if (!keyIdSet || !keyIdSet.size) {
  21788. return;
  21789. }
  21790. keyIdSet.forEach(key => {
  21791. const USABLE = 'usable';
  21792. const hasUsableKeyStatus = this.keyStatusMap_.has(key) && this.keyStatusMap_.get(key) === USABLE;
  21793. const nonUsableExclusion = playlist.lastExcludeReason_ === NON_USABLE && playlist.excludeUntil === Infinity;
  21794. if (!hasUsableKeyStatus) {
  21795. // Only exclude playlists that haven't already been excluded as non-usable.
  21796. if (playlist.excludeUntil !== Infinity && playlist.lastExcludeReason_ !== NON_USABLE) {
  21797. playlist.excludeUntil = Infinity;
  21798. playlist.lastExcludeReason_ = NON_USABLE;
  21799. this.logger_(`excluding playlist ${playlist.id} because the key ID ${key} doesn't exist in the keyStatusMap or is not ${USABLE}`);
  21800. } // count all nonUsableKeyStatus
  21801. nonUsableKeyStatusCount++;
  21802. } else if (hasUsableKeyStatus && nonUsableExclusion) {
  21803. delete playlist.excludeUntil;
  21804. delete playlist.lastExcludeReason_;
  21805. this.logger_(`enabling playlist ${playlist.id} because key ID ${key} is ${USABLE}`);
  21806. }
  21807. });
  21808. }); // If for whatever reason every playlist has a non usable key status. Lets try re-including the SD renditions as a failsafe.
  21809. if (nonUsableKeyStatusCount >= this.mainPlaylistLoader_.main.playlists.length) {
  21810. this.mainPlaylistLoader_.main.playlists.forEach(playlist => {
  21811. const isNonHD = playlist && playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height < 720;
  21812. const excludedForNonUsableKey = playlist.excludeUntil === Infinity && playlist.lastExcludeReason_ === NON_USABLE;
  21813. if (isNonHD && excludedForNonUsableKey) {
  21814. // Only delete the excludeUntil so we don't try and re-exclude these playlists.
  21815. delete playlist.excludeUntil;
  21816. videojs.log.warn(`enabling non-HD playlist ${playlist.id} because all playlists were excluded due to ${NON_USABLE} key IDs`);
  21817. }
  21818. });
  21819. }
  21820. }
  21821. /**
  21822. * Adds a keystatus to the keystatus map, tries to convert to string if necessary.
  21823. *
  21824. * @param {any} keyId the keyId to add a status for
  21825. * @param {string} status the status of the keyId
  21826. */
  21827. addKeyStatus_(keyId, status) {
  21828. const isString = typeof keyId === 'string';
  21829. const keyIdHexString = isString ? keyId : bufferToHexString(keyId);
  21830. const formattedKeyIdString = keyIdHexString.slice(0, 32).toLowerCase();
  21831. this.logger_(`KeyStatus '${status}' with key ID ${formattedKeyIdString} added to the keyStatusMap`);
  21832. this.keyStatusMap_.set(formattedKeyIdString, status);
  21833. }
  21834. /**
  21835. * Utility function for adding key status to the keyStatusMap and filtering usable encrypted playlists.
  21836. *
  21837. * @param {any} keyId the keyId from the keystatuschange event
  21838. * @param {string} status the key status string
  21839. */
  21840. updatePlaylistByKeyStatus(keyId, status) {
  21841. this.addKeyStatus_(keyId, status);
  21842. if (!this.waitingForFastQualityPlaylistReceived_) {
  21843. this.excludeNonUsableThenChangePlaylist_();
  21844. } // Listen to loadedplaylist with a single listener and check for new contentProtection elements when a playlist is updated.
  21845. this.mainPlaylistLoader_.off('loadedplaylist', this.excludeNonUsableThenChangePlaylist_.bind(this));
  21846. this.mainPlaylistLoader_.on('loadedplaylist', this.excludeNonUsableThenChangePlaylist_.bind(this));
  21847. }
  21848. excludeNonUsableThenChangePlaylist_() {
  21849. this.excludeNonUsablePlaylistsByKeyId_();
  21850. this.fastQualityChange_();
  21851. }
  21852. }
  21853. /**
  21854. * Returns a function that acts as the Enable/disable playlist function.
  21855. *
  21856. * @param {PlaylistLoader} loader - The main playlist loader
  21857. * @param {string} playlistID - id of the playlist
  21858. * @param {Function} changePlaylistFn - A function to be called after a
  21859. * playlist's enabled-state has been changed. Will NOT be called if a
  21860. * playlist's enabled-state is unchanged
  21861. * @param {boolean=} enable - Value to set the playlist enabled-state to
  21862. * or if undefined returns the current enabled-state for the playlist
  21863. * @return {Function} Function for setting/getting enabled
  21864. */
  21865. const enableFunction = (loader, playlistID, changePlaylistFn) => enable => {
  21866. const playlist = loader.main.playlists[playlistID];
  21867. const incompatible = isIncompatible(playlist);
  21868. const currentlyEnabled = isEnabled(playlist);
  21869. if (typeof enable === 'undefined') {
  21870. return currentlyEnabled;
  21871. }
  21872. if (enable) {
  21873. delete playlist.disabled;
  21874. } else {
  21875. playlist.disabled = true;
  21876. }
  21877. if (enable !== currentlyEnabled && !incompatible) {
  21878. // Ensure the outside world knows about our changes
  21879. changePlaylistFn();
  21880. if (enable) {
  21881. loader.trigger('renditionenabled');
  21882. } else {
  21883. loader.trigger('renditiondisabled');
  21884. }
  21885. }
  21886. return enable;
  21887. };
  21888. /**
  21889. * The representation object encapsulates the publicly visible information
  21890. * in a media playlist along with a setter/getter-type function (enabled)
  21891. * for changing the enabled-state of a particular playlist entry
  21892. *
  21893. * @class Representation
  21894. */
  21895. class Representation {
  21896. constructor(vhsHandler, playlist, id) {
  21897. const {
  21898. playlistController_: pc
  21899. } = vhsHandler;
  21900. const qualityChangeFunction = pc.fastQualityChange_.bind(pc); // some playlist attributes are optional
  21901. if (playlist.attributes) {
  21902. const resolution = playlist.attributes.RESOLUTION;
  21903. this.width = resolution && resolution.width;
  21904. this.height = resolution && resolution.height;
  21905. this.bandwidth = playlist.attributes.BANDWIDTH;
  21906. this.frameRate = playlist.attributes['FRAME-RATE'];
  21907. }
  21908. this.codecs = codecsForPlaylist(pc.main(), playlist);
  21909. this.playlist = playlist; // The id is simply the ordinality of the media playlist
  21910. // within the main playlist
  21911. this.id = id; // Partially-apply the enableFunction to create a playlist-
  21912. // specific variant
  21913. this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
  21914. }
  21915. }
  21916. /**
  21917. * A mixin function that adds the `representations` api to an instance
  21918. * of the VhsHandler class
  21919. *
  21920. * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
  21921. * representation API into
  21922. */
  21923. const renditionSelectionMixin = function (vhsHandler) {
  21924. // Add a single API-specific function to the VhsHandler instance
  21925. vhsHandler.representations = () => {
  21926. const main = vhsHandler.playlistController_.main();
  21927. const playlists = isAudioOnly(main) ? vhsHandler.playlistController_.getAudioTrackPlaylists_() : main.playlists;
  21928. if (!playlists) {
  21929. return [];
  21930. }
  21931. return playlists.filter(media => !isIncompatible(media)).map((e, i) => new Representation(vhsHandler, e, e.id));
  21932. };
  21933. };
  21934. /**
  21935. * @file playback-watcher.js
  21936. *
  21937. * Playback starts, and now my watch begins. It shall not end until my death. I shall
  21938. * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
  21939. * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
  21940. * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
  21941. * my life and honor to the Playback Watch, for this Player and all the Players to come.
  21942. */
  21943. const timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
  21944. /**
  21945. * @class PlaybackWatcher
  21946. */
  21947. class PlaybackWatcher {
  21948. /**
  21949. * Represents an PlaybackWatcher object.
  21950. *
  21951. * @class
  21952. * @param {Object} options an object that includes the tech and settings
  21953. */
  21954. constructor(options) {
  21955. this.playlistController_ = options.playlistController;
  21956. this.tech_ = options.tech;
  21957. this.seekable = options.seekable;
  21958. this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
  21959. this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
  21960. this.media = options.media;
  21961. this.consecutiveUpdates = 0;
  21962. this.lastRecordedTime = null;
  21963. this.checkCurrentTimeTimeout_ = null;
  21964. this.logger_ = logger('PlaybackWatcher');
  21965. this.logger_('initialize');
  21966. const playHandler = () => this.monitorCurrentTime_();
  21967. const canPlayHandler = () => this.monitorCurrentTime_();
  21968. const waitingHandler = () => this.techWaiting_();
  21969. const cancelTimerHandler = () => this.resetTimeUpdate_();
  21970. const pc = this.playlistController_;
  21971. const loaderTypes = ['main', 'subtitle', 'audio'];
  21972. const loaderChecks = {};
  21973. loaderTypes.forEach(type => {
  21974. loaderChecks[type] = {
  21975. reset: () => this.resetSegmentDownloads_(type),
  21976. updateend: () => this.checkSegmentDownloads_(type)
  21977. };
  21978. pc[`${type}SegmentLoader_`].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer
  21979. // isn't changing we want to reset. We cannot assume that the new rendition
  21980. // will also be stalled, until after new appends.
  21981. pc[`${type}SegmentLoader_`].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.
  21982. // This prevents one segment playlists (single vtt or single segment content)
  21983. // from being detected as stalling. As the buffer will not change in those cases, since
  21984. // the buffer is the entire video duration.
  21985. this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
  21986. });
  21987. /**
  21988. * We check if a seek was into a gap through the following steps:
  21989. * 1. We get a seeking event and we do not get a seeked event. This means that
  21990. * a seek was attempted but not completed.
  21991. * 2. We run `fixesBadSeeks_` on segment loader appends. This means that we already
  21992. * removed everything from our buffer and appended a segment, and should be ready
  21993. * to check for gaps.
  21994. */
  21995. const setSeekingHandlers = fn => {
  21996. ['main', 'audio'].forEach(type => {
  21997. pc[`${type}SegmentLoader_`][fn]('appended', this.seekingAppendCheck_);
  21998. });
  21999. };
  22000. this.seekingAppendCheck_ = () => {
  22001. if (this.fixesBadSeeks_()) {
  22002. this.consecutiveUpdates = 0;
  22003. this.lastRecordedTime = this.tech_.currentTime();
  22004. setSeekingHandlers('off');
  22005. }
  22006. };
  22007. this.clearSeekingAppendCheck_ = () => setSeekingHandlers('off');
  22008. this.watchForBadSeeking_ = () => {
  22009. this.clearSeekingAppendCheck_();
  22010. setSeekingHandlers('on');
  22011. };
  22012. this.tech_.on('seeked', this.clearSeekingAppendCheck_);
  22013. this.tech_.on('seeking', this.watchForBadSeeking_);
  22014. this.tech_.on('waiting', waitingHandler);
  22015. this.tech_.on(timerCancelEvents, cancelTimerHandler);
  22016. this.tech_.on('canplay', canPlayHandler);
  22017. /*
  22018. An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
  22019. is surfaced in one of two ways:
  22020. 1) The `waiting` event is fired before the player has buffered content, making it impossible
  22021. to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
  22022. we can check if playback is stalled due to a gap, and skip the gap if necessary.
  22023. 2) A source with a gap at the beginning of the stream is loaded programatically while the player
  22024. is in a playing state. To catch this case, it's important that our one-time play listener is setup
  22025. even if the player is in a playing state
  22026. */
  22027. this.tech_.one('play', playHandler); // Define the dispose function to clean up our events
  22028. this.dispose = () => {
  22029. this.clearSeekingAppendCheck_();
  22030. this.logger_('dispose');
  22031. this.tech_.off('waiting', waitingHandler);
  22032. this.tech_.off(timerCancelEvents, cancelTimerHandler);
  22033. this.tech_.off('canplay', canPlayHandler);
  22034. this.tech_.off('play', playHandler);
  22035. this.tech_.off('seeking', this.watchForBadSeeking_);
  22036. this.tech_.off('seeked', this.clearSeekingAppendCheck_);
  22037. loaderTypes.forEach(type => {
  22038. pc[`${type}SegmentLoader_`].off('appendsdone', loaderChecks[type].updateend);
  22039. pc[`${type}SegmentLoader_`].off('playlistupdate', loaderChecks[type].reset);
  22040. this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
  22041. });
  22042. if (this.checkCurrentTimeTimeout_) {
  22043. window$1.clearTimeout(this.checkCurrentTimeTimeout_);
  22044. }
  22045. this.resetTimeUpdate_();
  22046. };
  22047. }
  22048. /**
  22049. * Periodically check current time to see if playback stopped
  22050. *
  22051. * @private
  22052. */
  22053. monitorCurrentTime_() {
  22054. this.checkCurrentTime_();
  22055. if (this.checkCurrentTimeTimeout_) {
  22056. window$1.clearTimeout(this.checkCurrentTimeTimeout_);
  22057. } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  22058. this.checkCurrentTimeTimeout_ = window$1.setTimeout(this.monitorCurrentTime_.bind(this), 250);
  22059. }
  22060. /**
  22061. * Reset stalled download stats for a specific type of loader
  22062. *
  22063. * @param {string} type
  22064. * The segment loader type to check.
  22065. *
  22066. * @listens SegmentLoader#playlistupdate
  22067. * @listens Tech#seeking
  22068. * @listens Tech#seeked
  22069. */
  22070. resetSegmentDownloads_(type) {
  22071. const loader = this.playlistController_[`${type}SegmentLoader_`];
  22072. if (this[`${type}StalledDownloads_`] > 0) {
  22073. this.logger_(`resetting possible stalled download count for ${type} loader`);
  22074. }
  22075. this[`${type}StalledDownloads_`] = 0;
  22076. this[`${type}Buffered_`] = loader.buffered_();
  22077. }
  22078. /**
  22079. * Checks on every segment `appendsdone` to see
  22080. * if segment appends are making progress. If they are not
  22081. * and we are still downloading bytes. We exclude the playlist.
  22082. *
  22083. * @param {string} type
  22084. * The segment loader type to check.
  22085. *
  22086. * @listens SegmentLoader#appendsdone
  22087. */
  22088. checkSegmentDownloads_(type) {
  22089. const pc = this.playlistController_;
  22090. const loader = pc[`${type}SegmentLoader_`];
  22091. const buffered = loader.buffered_();
  22092. const isBufferedDifferent = isRangeDifferent(this[`${type}Buffered_`], buffered);
  22093. this[`${type}Buffered_`] = buffered; // if another watcher is going to fix the issue or
  22094. // the buffered value for this loader changed
  22095. // appends are working
  22096. if (isBufferedDifferent) {
  22097. this.resetSegmentDownloads_(type);
  22098. return;
  22099. }
  22100. this[`${type}StalledDownloads_`]++;
  22101. this.logger_(`found #${this[`${type}StalledDownloads_`]} ${type} appends that did not increase buffer (possible stalled download)`, {
  22102. playlistId: loader.playlist_ && loader.playlist_.id,
  22103. buffered: timeRangesToArray(buffered)
  22104. }); // after 10 possibly stalled appends with no reset, exclude
  22105. if (this[`${type}StalledDownloads_`] < 10) {
  22106. return;
  22107. }
  22108. this.logger_(`${type} loader stalled download exclusion`);
  22109. this.resetSegmentDownloads_(type);
  22110. this.tech_.trigger({
  22111. type: 'usage',
  22112. name: `vhs-${type}-download-exclusion`
  22113. });
  22114. if (type === 'subtitle') {
  22115. return;
  22116. } // TODO: should we exclude audio tracks rather than main tracks
  22117. // when type is audio?
  22118. pc.excludePlaylist({
  22119. error: {
  22120. message: `Excessive ${type} segment downloading detected.`
  22121. },
  22122. playlistExclusionDuration: Infinity
  22123. });
  22124. }
  22125. /**
  22126. * The purpose of this function is to emulate the "waiting" event on
  22127. * browsers that do not emit it when they are waiting for more
  22128. * data to continue playback
  22129. *
  22130. * @private
  22131. */
  22132. checkCurrentTime_() {
  22133. if (this.tech_.paused() || this.tech_.seeking()) {
  22134. return;
  22135. }
  22136. const currentTime = this.tech_.currentTime();
  22137. const buffered = this.tech_.buffered();
  22138. if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
  22139. // If current time is at the end of the final buffered region, then any playback
  22140. // stall is most likely caused by buffering in a low bandwidth environment. The tech
  22141. // should fire a `waiting` event in this scenario, but due to browser and tech
  22142. // inconsistencies. Calling `techWaiting_` here allows us to simulate
  22143. // responding to a native `waiting` event when the tech fails to emit one.
  22144. return this.techWaiting_();
  22145. }
  22146. if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
  22147. this.consecutiveUpdates++;
  22148. this.waiting_();
  22149. } else if (currentTime === this.lastRecordedTime) {
  22150. this.consecutiveUpdates++;
  22151. } else {
  22152. this.consecutiveUpdates = 0;
  22153. this.lastRecordedTime = currentTime;
  22154. }
  22155. }
  22156. /**
  22157. * Resets the 'timeupdate' mechanism designed to detect that we are stalled
  22158. *
  22159. * @private
  22160. */
  22161. resetTimeUpdate_() {
  22162. this.consecutiveUpdates = 0;
  22163. }
  22164. /**
  22165. * Fixes situations where there's a bad seek
  22166. *
  22167. * @return {boolean} whether an action was taken to fix the seek
  22168. * @private
  22169. */
  22170. fixesBadSeeks_() {
  22171. const seeking = this.tech_.seeking();
  22172. if (!seeking) {
  22173. return false;
  22174. } // TODO: It's possible that these seekable checks should be moved out of this function
  22175. // and into a function that runs on seekablechange. It's also possible that we only need
  22176. // afterSeekableWindow as the buffered check at the bottom is good enough to handle before
  22177. // seekable range.
  22178. const seekable = this.seekable();
  22179. const currentTime = this.tech_.currentTime();
  22180. const isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
  22181. let seekTo;
  22182. if (isAfterSeekableRange) {
  22183. const seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
  22184. seekTo = seekableEnd;
  22185. }
  22186. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  22187. const seekableStart = seekable.start(0); // sync to the beginning of the live window
  22188. // provide a buffer of .1 seconds to handle rounding/imprecise numbers
  22189. seekTo = seekableStart + ( // if the playlist is too short and the seekable range is an exact time (can
  22190. // happen in live with a 3 segment playlist), then don't use a time delta
  22191. seekableStart === seekable.end(0) ? 0 : SAFE_TIME_DELTA);
  22192. }
  22193. if (typeof seekTo !== 'undefined') {
  22194. this.logger_(`Trying to seek outside of seekable at time ${currentTime} with ` + `seekable range ${printableRange(seekable)}. Seeking to ` + `${seekTo}.`);
  22195. this.tech_.setCurrentTime(seekTo);
  22196. return true;
  22197. }
  22198. const sourceUpdater = this.playlistController_.sourceUpdater_;
  22199. const buffered = this.tech_.buffered();
  22200. const audioBuffered = sourceUpdater.audioBuffer ? sourceUpdater.audioBuffered() : null;
  22201. const videoBuffered = sourceUpdater.videoBuffer ? sourceUpdater.videoBuffered() : null;
  22202. const media = this.media(); // verify that at least two segment durations or one part duration have been
  22203. // appended before checking for a gap.
  22204. const minAppendedDuration = media.partTargetDuration ? media.partTargetDuration : (media.targetDuration - TIME_FUDGE_FACTOR) * 2; // verify that at least two segment durations have been
  22205. // appended before checking for a gap.
  22206. const bufferedToCheck = [audioBuffered, videoBuffered];
  22207. for (let i = 0; i < bufferedToCheck.length; i++) {
  22208. // skip null buffered
  22209. if (!bufferedToCheck[i]) {
  22210. continue;
  22211. }
  22212. const timeAhead = timeAheadOf(bufferedToCheck[i], currentTime); // if we are less than two video/audio segment durations or one part
  22213. // duration behind we haven't appended enough to call this a bad seek.
  22214. if (timeAhead < minAppendedDuration) {
  22215. return false;
  22216. }
  22217. }
  22218. const nextRange = findNextRange(buffered, currentTime); // we have appended enough content, but we don't have anything buffered
  22219. // to seek over the gap
  22220. if (nextRange.length === 0) {
  22221. return false;
  22222. }
  22223. seekTo = nextRange.start(0) + SAFE_TIME_DELTA;
  22224. this.logger_(`Buffered region starts (${nextRange.start(0)}) ` + ` just beyond seek point (${currentTime}). Seeking to ${seekTo}.`);
  22225. this.tech_.setCurrentTime(seekTo);
  22226. return true;
  22227. }
  22228. /**
  22229. * Handler for situations when we determine the player is waiting.
  22230. *
  22231. * @private
  22232. */
  22233. waiting_() {
  22234. if (this.techWaiting_()) {
  22235. return;
  22236. } // All tech waiting checks failed. Use last resort correction
  22237. const currentTime = this.tech_.currentTime();
  22238. const buffered = this.tech_.buffered();
  22239. const currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered
  22240. // region with no indication that anything is amiss (seen in Firefox). Seeking to
  22241. // currentTime is usually enough to kickstart the player. This checks that the player
  22242. // is currently within a buffered region before attempting a corrective seek.
  22243. // Chrome does not appear to continue `timeupdate` events after a `waiting` event
  22244. // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
  22245. // make sure there is ~3 seconds of forward buffer before taking any corrective action
  22246. // to avoid triggering an `unknownwaiting` event when the network is slow.
  22247. if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
  22248. this.resetTimeUpdate_();
  22249. this.tech_.setCurrentTime(currentTime);
  22250. 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
  22251. this.tech_.trigger({
  22252. type: 'usage',
  22253. name: 'vhs-unknown-waiting'
  22254. });
  22255. return;
  22256. }
  22257. }
  22258. /**
  22259. * Handler for situations when the tech fires a `waiting` event
  22260. *
  22261. * @return {boolean}
  22262. * True if an action (or none) was needed to correct the waiting. False if no
  22263. * checks passed
  22264. * @private
  22265. */
  22266. techWaiting_() {
  22267. const seekable = this.seekable();
  22268. const currentTime = this.tech_.currentTime();
  22269. if (this.tech_.seeking()) {
  22270. // Tech is seeking or already waiting on another action, no action needed
  22271. return true;
  22272. }
  22273. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  22274. const livePoint = seekable.end(seekable.length - 1);
  22275. this.logger_(`Fell out of live window at time ${currentTime}. Seeking to ` + `live point (seekable end) ${livePoint}`);
  22276. this.resetTimeUpdate_();
  22277. this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS
  22278. this.tech_.trigger({
  22279. type: 'usage',
  22280. name: 'vhs-live-resync'
  22281. });
  22282. return true;
  22283. }
  22284. const sourceUpdater = this.tech_.vhs.playlistController_.sourceUpdater_;
  22285. const buffered = this.tech_.buffered();
  22286. const videoUnderflow = this.videoUnderflow_({
  22287. audioBuffered: sourceUpdater.audioBuffered(),
  22288. videoBuffered: sourceUpdater.videoBuffered(),
  22289. currentTime
  22290. });
  22291. if (videoUnderflow) {
  22292. // Even though the video underflowed and was stuck in a gap, the audio overplayed
  22293. // the gap, leading currentTime into a buffered range. Seeking to currentTime
  22294. // allows the video to catch up to the audio position without losing any audio
  22295. // (only suffering ~3 seconds of frozen video and a pause in audio playback).
  22296. this.resetTimeUpdate_();
  22297. this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS
  22298. this.tech_.trigger({
  22299. type: 'usage',
  22300. name: 'vhs-video-underflow'
  22301. });
  22302. return true;
  22303. }
  22304. const nextRange = findNextRange(buffered, currentTime); // check for gap
  22305. if (nextRange.length > 0) {
  22306. this.logger_(`Stopped at ${currentTime} and seeking to ${nextRange.start(0)}`);
  22307. this.resetTimeUpdate_();
  22308. this.skipTheGap_(currentTime);
  22309. return true;
  22310. } // All checks failed. Returning false to indicate failure to correct waiting
  22311. return false;
  22312. }
  22313. afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow = false) {
  22314. if (!seekable.length) {
  22315. // we can't make a solid case if there's no seekable, default to false
  22316. return false;
  22317. }
  22318. let allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;
  22319. const isLive = !playlist.endList;
  22320. const isLLHLS = typeof playlist.partTargetDuration === 'number';
  22321. if (isLive && (isLLHLS || allowSeeksWithinUnsafeLiveWindow)) {
  22322. allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;
  22323. }
  22324. if (currentTime > allowedEnd) {
  22325. return true;
  22326. }
  22327. return false;
  22328. }
  22329. beforeSeekableWindow_(seekable, currentTime) {
  22330. if (seekable.length && // can't fall before 0 and 0 seekable start identifies VOD stream
  22331. seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
  22332. return true;
  22333. }
  22334. return false;
  22335. }
  22336. videoUnderflow_({
  22337. videoBuffered,
  22338. audioBuffered,
  22339. currentTime
  22340. }) {
  22341. // audio only content will not have video underflow :)
  22342. if (!videoBuffered) {
  22343. return;
  22344. }
  22345. let gap; // find a gap in demuxed content.
  22346. if (videoBuffered.length && audioBuffered.length) {
  22347. // in Chrome audio will continue to play for ~3s when we run out of video
  22348. // so we have to check that the video buffer did have some buffer in the
  22349. // past.
  22350. const lastVideoRange = findRange(videoBuffered, currentTime - 3);
  22351. const videoRange = findRange(videoBuffered, currentTime);
  22352. const audioRange = findRange(audioBuffered, currentTime);
  22353. if (audioRange.length && !videoRange.length && lastVideoRange.length) {
  22354. gap = {
  22355. start: lastVideoRange.end(0),
  22356. end: audioRange.end(0)
  22357. };
  22358. } // find a gap in muxed content.
  22359. } else {
  22360. const nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are
  22361. // stuck in a gap due to video underflow.
  22362. if (!nextRange.length) {
  22363. gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
  22364. }
  22365. }
  22366. if (gap) {
  22367. this.logger_(`Encountered a gap in video from ${gap.start} to ${gap.end}. ` + `Seeking to current time ${currentTime}`);
  22368. return true;
  22369. }
  22370. return false;
  22371. }
  22372. /**
  22373. * Timer callback. If playback still has not proceeded, then we seek
  22374. * to the start of the next buffered region.
  22375. *
  22376. * @private
  22377. */
  22378. skipTheGap_(scheduledCurrentTime) {
  22379. const buffered = this.tech_.buffered();
  22380. const currentTime = this.tech_.currentTime();
  22381. const nextRange = findNextRange(buffered, currentTime);
  22382. this.resetTimeUpdate_();
  22383. if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
  22384. return;
  22385. }
  22386. this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played
  22387. this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
  22388. this.tech_.trigger({
  22389. type: 'usage',
  22390. name: 'vhs-gap-skip'
  22391. });
  22392. }
  22393. gapFromVideoUnderflow_(buffered, currentTime) {
  22394. // At least in Chrome, if there is a gap in the video buffer, the audio will continue
  22395. // playing for ~3 seconds after the video gap starts. This is done to account for
  22396. // video buffer underflow/underrun (note that this is not done when there is audio
  22397. // buffer underflow/underrun -- in that case the video will stop as soon as it
  22398. // encounters the gap, as audio stalls are more noticeable/jarring to a user than
  22399. // video stalls). The player's time will reflect the playthrough of audio, so the
  22400. // time will appear as if we are in a buffered region, even if we are stuck in a
  22401. // "gap."
  22402. //
  22403. // Example:
  22404. // video buffer: 0 => 10.1, 10.2 => 20
  22405. // audio buffer: 0 => 20
  22406. // overall buffer: 0 => 10.1, 10.2 => 20
  22407. // current time: 13
  22408. //
  22409. // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
  22410. // however, the audio continued playing until it reached ~3 seconds past the gap
  22411. // (13 seconds), at which point it stops as well. Since current time is past the
  22412. // gap, findNextRange will return no ranges.
  22413. //
  22414. // To check for this issue, we see if there is a gap that starts somewhere within
  22415. // a 3 second range (3 seconds +/- 1 second) back from our current time.
  22416. const gaps = findGaps(buffered);
  22417. for (let i = 0; i < gaps.length; i++) {
  22418. const start = gaps.start(i);
  22419. const end = gaps.end(i); // gap is starts no more than 4 seconds back
  22420. if (currentTime - start < 4 && currentTime - start > 2) {
  22421. return {
  22422. start,
  22423. end
  22424. };
  22425. }
  22426. }
  22427. return null;
  22428. }
  22429. }
  22430. const defaultOptions = {
  22431. errorInterval: 30,
  22432. getSource(next) {
  22433. const tech = this.tech({
  22434. IWillNotUseThisInPlugins: true
  22435. });
  22436. const sourceObj = tech.currentSource_ || this.currentSource();
  22437. return next(sourceObj);
  22438. }
  22439. };
  22440. /**
  22441. * Main entry point for the plugin
  22442. *
  22443. * @param {Player} player a reference to a videojs Player instance
  22444. * @param {Object} [options] an object with plugin options
  22445. * @private
  22446. */
  22447. const initPlugin = function (player, options) {
  22448. let lastCalled = 0;
  22449. let seekTo = 0;
  22450. const localOptions = merge(defaultOptions, options);
  22451. player.ready(() => {
  22452. player.trigger({
  22453. type: 'usage',
  22454. name: 'vhs-error-reload-initialized'
  22455. });
  22456. });
  22457. /**
  22458. * Player modifications to perform that must wait until `loadedmetadata`
  22459. * has been triggered
  22460. *
  22461. * @private
  22462. */
  22463. const loadedMetadataHandler = function () {
  22464. if (seekTo) {
  22465. player.currentTime(seekTo);
  22466. }
  22467. };
  22468. /**
  22469. * Set the source on the player element, play, and seek if necessary
  22470. *
  22471. * @param {Object} sourceObj An object specifying the source url and mime-type to play
  22472. * @private
  22473. */
  22474. const setSource = function (sourceObj) {
  22475. if (sourceObj === null || sourceObj === undefined) {
  22476. return;
  22477. }
  22478. seekTo = player.duration() !== Infinity && player.currentTime() || 0;
  22479. player.one('loadedmetadata', loadedMetadataHandler);
  22480. player.src(sourceObj);
  22481. player.trigger({
  22482. type: 'usage',
  22483. name: 'vhs-error-reload'
  22484. });
  22485. player.play();
  22486. };
  22487. /**
  22488. * Attempt to get a source from either the built-in getSource function
  22489. * or a custom function provided via the options
  22490. *
  22491. * @private
  22492. */
  22493. const errorHandler = function () {
  22494. // Do not attempt to reload the source if a source-reload occurred before
  22495. // 'errorInterval' time has elapsed since the last source-reload
  22496. if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
  22497. player.trigger({
  22498. type: 'usage',
  22499. name: 'vhs-error-reload-canceled'
  22500. });
  22501. return;
  22502. }
  22503. if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
  22504. videojs.log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
  22505. return;
  22506. }
  22507. lastCalled = Date.now();
  22508. return localOptions.getSource.call(player, setSource);
  22509. };
  22510. /**
  22511. * Unbind any event handlers that were bound by the plugin
  22512. *
  22513. * @private
  22514. */
  22515. const cleanupEvents = function () {
  22516. player.off('loadedmetadata', loadedMetadataHandler);
  22517. player.off('error', errorHandler);
  22518. player.off('dispose', cleanupEvents);
  22519. };
  22520. /**
  22521. * Cleanup before re-initializing the plugin
  22522. *
  22523. * @param {Object} [newOptions] an object with plugin options
  22524. * @private
  22525. */
  22526. const reinitPlugin = function (newOptions) {
  22527. cleanupEvents();
  22528. initPlugin(player, newOptions);
  22529. };
  22530. player.on('error', errorHandler);
  22531. player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before
  22532. // initializing the plugin
  22533. player.reloadSourceOnError = reinitPlugin;
  22534. };
  22535. /**
  22536. * Reload the source when an error is detected as long as there
  22537. * wasn't an error previously within the last 30 seconds
  22538. *
  22539. * @param {Object} [options] an object with plugin options
  22540. */
  22541. const reloadSourceOnError = function (options) {
  22542. initPlugin(this, options);
  22543. };
  22544. var version$4 = "3.10.0";
  22545. var version$3 = "7.0.2";
  22546. var version$2 = "1.3.0";
  22547. var version$1 = "7.1.0";
  22548. var version = "4.0.1";
  22549. /**
  22550. * @file videojs-http-streaming.js
  22551. *
  22552. * The main file for the VHS project.
  22553. * License: https://github.com/videojs/videojs-http-streaming/blob/main/LICENSE
  22554. */
  22555. const Vhs = {
  22556. PlaylistLoader,
  22557. Playlist,
  22558. utils,
  22559. STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
  22560. INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
  22561. lastBandwidthSelector,
  22562. movingAverageBandwidthSelector,
  22563. comparePlaylistBandwidth,
  22564. comparePlaylistResolution,
  22565. xhr: xhrFactory()
  22566. }; // Define getter/setters for config properties
  22567. Object.keys(Config).forEach(prop => {
  22568. Object.defineProperty(Vhs, prop, {
  22569. get() {
  22570. videojs.log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  22571. return Config[prop];
  22572. },
  22573. set(value) {
  22574. videojs.log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  22575. if (typeof value !== 'number' || value < 0) {
  22576. videojs.log.warn(`value of Vhs.${prop} must be greater than or equal to 0`);
  22577. return;
  22578. }
  22579. Config[prop] = value;
  22580. }
  22581. });
  22582. });
  22583. const LOCAL_STORAGE_KEY = 'videojs-vhs';
  22584. /**
  22585. * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
  22586. *
  22587. * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
  22588. * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
  22589. * @function handleVhsMediaChange
  22590. */
  22591. const handleVhsMediaChange = function (qualityLevels, playlistLoader) {
  22592. const newPlaylist = playlistLoader.media();
  22593. let selectedIndex = -1;
  22594. for (let i = 0; i < qualityLevels.length; i++) {
  22595. if (qualityLevels[i].id === newPlaylist.id) {
  22596. selectedIndex = i;
  22597. break;
  22598. }
  22599. }
  22600. qualityLevels.selectedIndex_ = selectedIndex;
  22601. qualityLevels.trigger({
  22602. selectedIndex,
  22603. type: 'change'
  22604. });
  22605. };
  22606. /**
  22607. * Adds quality levels to list once playlist metadata is available
  22608. *
  22609. * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
  22610. * @param {Object} vhs Vhs object to listen to for media events.
  22611. * @function handleVhsLoadedMetadata
  22612. */
  22613. const handleVhsLoadedMetadata = function (qualityLevels, vhs) {
  22614. vhs.representations().forEach(rep => {
  22615. qualityLevels.addQualityLevel(rep);
  22616. });
  22617. handleVhsMediaChange(qualityLevels, vhs.playlists);
  22618. }; // VHS is a source handler, not a tech. Make sure attempts to use it
  22619. // as one do not cause exceptions.
  22620. Vhs.canPlaySource = function () {
  22621. return videojs.log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  22622. };
  22623. const emeKeySystems = (keySystemOptions, mainPlaylist, audioPlaylist) => {
  22624. if (!keySystemOptions) {
  22625. return keySystemOptions;
  22626. }
  22627. let codecs = {};
  22628. if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
  22629. codecs = unwrapCodecList(parseCodecs(mainPlaylist.attributes.CODECS));
  22630. }
  22631. if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
  22632. codecs.audio = audioPlaylist.attributes.CODECS;
  22633. }
  22634. const videoContentType = getMimeForCodec(codecs.video);
  22635. const audioContentType = getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist
  22636. const keySystemContentTypes = {};
  22637. for (const keySystem in keySystemOptions) {
  22638. keySystemContentTypes[keySystem] = {};
  22639. if (audioContentType) {
  22640. keySystemContentTypes[keySystem].audioContentType = audioContentType;
  22641. }
  22642. if (videoContentType) {
  22643. keySystemContentTypes[keySystem].videoContentType = videoContentType;
  22644. } // Default to using the video playlist's PSSH even though they may be different, as
  22645. // videojs-contrib-eme will only accept one in the options.
  22646. //
  22647. // This shouldn't be an issue for most cases as early intialization will handle all
  22648. // unique PSSH values, and if they aren't, then encrypted events should have the
  22649. // specific information needed for the unique license.
  22650. if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
  22651. keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
  22652. } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
  22653. // so we need to prevent overwriting the URL entirely
  22654. if (typeof keySystemOptions[keySystem] === 'string') {
  22655. keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
  22656. }
  22657. }
  22658. return merge(keySystemOptions, keySystemContentTypes);
  22659. };
  22660. /**
  22661. * @typedef {Object} KeySystems
  22662. *
  22663. * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
  22664. * Note: not all options are listed here.
  22665. *
  22666. * @property {Uint8Array} [pssh]
  22667. * Protection System Specific Header
  22668. */
  22669. /**
  22670. * Goes through all the playlists and collects an array of KeySystems options objects
  22671. * containing each playlist's keySystems and their pssh values, if available.
  22672. *
  22673. * @param {Object[]} playlists
  22674. * The playlists to look through
  22675. * @param {string[]} keySystems
  22676. * The keySystems to collect pssh values for
  22677. *
  22678. * @return {KeySystems[]}
  22679. * An array of KeySystems objects containing available key systems and their
  22680. * pssh values
  22681. */
  22682. const getAllPsshKeySystemsOptions = (playlists, keySystems) => {
  22683. return playlists.reduce((keySystemsArr, playlist) => {
  22684. if (!playlist.contentProtection) {
  22685. return keySystemsArr;
  22686. }
  22687. const keySystemsOptions = keySystems.reduce((keySystemsObj, keySystem) => {
  22688. const keySystemOptions = playlist.contentProtection[keySystem];
  22689. if (keySystemOptions && keySystemOptions.pssh) {
  22690. keySystemsObj[keySystem] = {
  22691. pssh: keySystemOptions.pssh
  22692. };
  22693. }
  22694. return keySystemsObj;
  22695. }, {});
  22696. if (Object.keys(keySystemsOptions).length) {
  22697. keySystemsArr.push(keySystemsOptions);
  22698. }
  22699. return keySystemsArr;
  22700. }, []);
  22701. };
  22702. /**
  22703. * Returns a promise that waits for the
  22704. * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
  22705. *
  22706. * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
  22707. * browsers.
  22708. *
  22709. * As per the above ticket, this is particularly important for Chrome, where, if
  22710. * unencrypted content is appended before encrypted content and the key session has not
  22711. * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
  22712. * during playback.
  22713. *
  22714. * @param {Object} player
  22715. * The player instance
  22716. * @param {Object[]} sourceKeySystems
  22717. * The key systems options from the player source
  22718. * @param {Object} [audioMedia]
  22719. * The active audio media playlist (optional)
  22720. * @param {Object[]} mainPlaylists
  22721. * The playlists found on the main playlist object
  22722. *
  22723. * @return {Object}
  22724. * Promise that resolves when the key session has been created
  22725. */
  22726. const waitForKeySessionCreation = ({
  22727. player,
  22728. sourceKeySystems,
  22729. audioMedia,
  22730. mainPlaylists
  22731. }) => {
  22732. if (!player.eme.initializeMediaKeys) {
  22733. return Promise.resolve();
  22734. } // TODO should all audio PSSH values be initialized for DRM?
  22735. //
  22736. // All unique video rendition pssh values are initialized for DRM, but here only
  22737. // the initial audio playlist license is initialized. In theory, an encrypted
  22738. // event should be fired if the user switches to an alternative audio playlist
  22739. // where a license is required, but this case hasn't yet been tested. In addition, there
  22740. // may be many alternate audio playlists unlikely to be used (e.g., multiple different
  22741. // languages).
  22742. const playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
  22743. const keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
  22744. const initializationFinishedPromises = [];
  22745. const keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
  22746. // only place where it should not be deduped is for ms-prefixed APIs, but
  22747. // the existence of modern EME APIs in addition to
  22748. // ms-prefixed APIs on Edge should prevent this from being a concern.
  22749. // initializeMediaKeys also won't use the webkit-prefixed APIs.
  22750. keySystemsOptionsArr.forEach(keySystemsOptions => {
  22751. keySessionCreatedPromises.push(new Promise((resolve, reject) => {
  22752. player.tech_.one('keysessioncreated', resolve);
  22753. }));
  22754. initializationFinishedPromises.push(new Promise((resolve, reject) => {
  22755. player.eme.initializeMediaKeys({
  22756. keySystems: keySystemsOptions
  22757. }, err => {
  22758. if (err) {
  22759. reject(err);
  22760. return;
  22761. }
  22762. resolve();
  22763. });
  22764. }));
  22765. }); // The reasons Promise.race is chosen over Promise.any:
  22766. //
  22767. // * Promise.any is only available in Safari 14+.
  22768. // * None of these promises are expected to reject. If they do reject, it might be
  22769. // better here for the race to surface the rejection, rather than mask it by using
  22770. // Promise.any.
  22771. return Promise.race([// If a session was previously created, these will all finish resolving without
  22772. // creating a new session, otherwise it will take until the end of all license
  22773. // requests, which is why the key session check is used (to make setup much faster).
  22774. Promise.all(initializationFinishedPromises), // Once a single session is created, the browser knows DRM will be used.
  22775. Promise.race(keySessionCreatedPromises)]);
  22776. };
  22777. /**
  22778. * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
  22779. * there are keySystems on the source, sets up source options to prepare the source for
  22780. * eme.
  22781. *
  22782. * @param {Object} player
  22783. * The player instance
  22784. * @param {Object[]} sourceKeySystems
  22785. * The key systems options from the player source
  22786. * @param {Object} media
  22787. * The active media playlist
  22788. * @param {Object} [audioMedia]
  22789. * The active audio media playlist (optional)
  22790. *
  22791. * @return {boolean}
  22792. * Whether or not options were configured and EME is available
  22793. */
  22794. const setupEmeOptions = ({
  22795. player,
  22796. sourceKeySystems,
  22797. media,
  22798. audioMedia
  22799. }) => {
  22800. const sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
  22801. if (!sourceOptions) {
  22802. return false;
  22803. }
  22804. player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing
  22805. // do nothing.
  22806. if (sourceOptions && !player.eme) {
  22807. videojs.log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
  22808. return false;
  22809. }
  22810. return true;
  22811. };
  22812. const getVhsLocalStorage = () => {
  22813. if (!window$1.localStorage) {
  22814. return null;
  22815. }
  22816. const storedObject = window$1.localStorage.getItem(LOCAL_STORAGE_KEY);
  22817. if (!storedObject) {
  22818. return null;
  22819. }
  22820. try {
  22821. return JSON.parse(storedObject);
  22822. } catch (e) {
  22823. // someone may have tampered with the value
  22824. return null;
  22825. }
  22826. };
  22827. const updateVhsLocalStorage = options => {
  22828. if (!window$1.localStorage) {
  22829. return false;
  22830. }
  22831. let objectToStore = getVhsLocalStorage();
  22832. objectToStore = objectToStore ? merge(objectToStore, options) : options;
  22833. try {
  22834. window$1.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
  22835. } catch (e) {
  22836. // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
  22837. // storage is set to 0).
  22838. // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
  22839. // No need to perform any operation.
  22840. return false;
  22841. }
  22842. return objectToStore;
  22843. };
  22844. /**
  22845. * Parses VHS-supported media types from data URIs. See
  22846. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  22847. * for information on data URIs.
  22848. *
  22849. * @param {string} dataUri
  22850. * The data URI
  22851. *
  22852. * @return {string|Object}
  22853. * The parsed object/string, or the original string if no supported media type
  22854. * was found
  22855. */
  22856. const expandDataUri = dataUri => {
  22857. if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
  22858. return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
  22859. } // no known case for this data URI, return the string as-is
  22860. return dataUri;
  22861. };
  22862. /**
  22863. * Adds a request hook to an xhr object
  22864. *
  22865. * @param {Object} xhr object to add the onRequest hook to
  22866. * @param {function} callback hook function for an xhr request
  22867. */
  22868. const addOnRequestHook = (xhr, callback) => {
  22869. if (!xhr._requestCallbackSet) {
  22870. xhr._requestCallbackSet = new Set();
  22871. }
  22872. xhr._requestCallbackSet.add(callback);
  22873. };
  22874. /**
  22875. * Adds a response hook to an xhr object
  22876. *
  22877. * @param {Object} xhr object to add the onResponse hook to
  22878. * @param {function} callback hook function for an xhr response
  22879. */
  22880. const addOnResponseHook = (xhr, callback) => {
  22881. if (!xhr._responseCallbackSet) {
  22882. xhr._responseCallbackSet = new Set();
  22883. }
  22884. xhr._responseCallbackSet.add(callback);
  22885. };
  22886. /**
  22887. * Removes a request hook on an xhr object, deletes the onRequest set if empty.
  22888. *
  22889. * @param {Object} xhr object to remove the onRequest hook from
  22890. * @param {function} callback hook function to remove
  22891. */
  22892. const removeOnRequestHook = (xhr, callback) => {
  22893. if (!xhr._requestCallbackSet) {
  22894. return;
  22895. }
  22896. xhr._requestCallbackSet.delete(callback);
  22897. if (!xhr._requestCallbackSet.size) {
  22898. delete xhr._requestCallbackSet;
  22899. }
  22900. };
  22901. /**
  22902. * Removes a response hook on an xhr object, deletes the onResponse set if empty.
  22903. *
  22904. * @param {Object} xhr object to remove the onResponse hook from
  22905. * @param {function} callback hook function to remove
  22906. */
  22907. const removeOnResponseHook = (xhr, callback) => {
  22908. if (!xhr._responseCallbackSet) {
  22909. return;
  22910. }
  22911. xhr._responseCallbackSet.delete(callback);
  22912. if (!xhr._responseCallbackSet.size) {
  22913. delete xhr._responseCallbackSet;
  22914. }
  22915. };
  22916. /**
  22917. * Whether the browser has built-in HLS support.
  22918. */
  22919. Vhs.supportsNativeHls = function () {
  22920. if (!document || !document.createElement) {
  22921. return false;
  22922. }
  22923. const video = document.createElement('video'); // native HLS is definitely not supported if HTML5 video isn't
  22924. if (!videojs.getTech('Html5').isSupported()) {
  22925. return false;
  22926. } // HLS manifests can go by many mime-types
  22927. const canPlay = [// Apple santioned
  22928. 'application/vnd.apple.mpegurl', // Apple sanctioned for backwards compatibility
  22929. 'audio/mpegurl', // Very common
  22930. 'audio/x-mpegurl', // Very common
  22931. 'application/x-mpegurl', // Included for completeness
  22932. 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
  22933. return canPlay.some(function (canItPlay) {
  22934. return /maybe|probably/i.test(video.canPlayType(canItPlay));
  22935. });
  22936. }();
  22937. Vhs.supportsNativeDash = function () {
  22938. if (!document || !document.createElement || !videojs.getTech('Html5').isSupported()) {
  22939. return false;
  22940. }
  22941. return /maybe|probably/i.test(document.createElement('video').canPlayType('application/dash+xml'));
  22942. }();
  22943. Vhs.supportsTypeNatively = type => {
  22944. if (type === 'hls') {
  22945. return Vhs.supportsNativeHls;
  22946. }
  22947. if (type === 'dash') {
  22948. return Vhs.supportsNativeDash;
  22949. }
  22950. return false;
  22951. };
  22952. /**
  22953. * VHS is a source handler, not a tech. Make sure attempts to use it
  22954. * as one do not cause exceptions.
  22955. */
  22956. Vhs.isSupported = function () {
  22957. return videojs.log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  22958. };
  22959. /**
  22960. * A global function for setting an onRequest hook
  22961. *
  22962. * @param {function} callback for request modifiction
  22963. */
  22964. Vhs.xhr.onRequest = function (callback) {
  22965. addOnRequestHook(Vhs.xhr, callback);
  22966. };
  22967. /**
  22968. * A global function for setting an onResponse hook
  22969. *
  22970. * @param {callback} callback for response data retrieval
  22971. */
  22972. Vhs.xhr.onResponse = function (callback) {
  22973. addOnResponseHook(Vhs.xhr, callback);
  22974. };
  22975. /**
  22976. * Deletes a global onRequest callback if it exists
  22977. *
  22978. * @param {function} callback to delete from the global set
  22979. */
  22980. Vhs.xhr.offRequest = function (callback) {
  22981. removeOnRequestHook(Vhs.xhr, callback);
  22982. };
  22983. /**
  22984. * Deletes a global onResponse callback if it exists
  22985. *
  22986. * @param {function} callback to delete from the global set
  22987. */
  22988. Vhs.xhr.offResponse = function (callback) {
  22989. removeOnResponseHook(Vhs.xhr, callback);
  22990. };
  22991. const Component = videojs.getComponent('Component');
  22992. /**
  22993. * The Vhs Handler object, where we orchestrate all of the parts
  22994. * of VHS to interact with video.js
  22995. *
  22996. * @class VhsHandler
  22997. * @extends videojs.Component
  22998. * @param {Object} source the soruce object
  22999. * @param {Tech} tech the parent tech object
  23000. * @param {Object} options optional and required options
  23001. */
  23002. class VhsHandler extends Component {
  23003. constructor(source, tech, options) {
  23004. super(tech, options.vhs); // if a tech level `initialBandwidth` option was passed
  23005. // use that over the VHS level `bandwidth` option
  23006. if (typeof options.initialBandwidth === 'number') {
  23007. this.options_.bandwidth = options.initialBandwidth;
  23008. }
  23009. this.logger_ = logger('VhsHandler'); // we need access to the player in some cases,
  23010. // so, get it from Video.js via the `playerId`
  23011. if (tech.options_ && tech.options_.playerId) {
  23012. const _player = videojs.getPlayer(tech.options_.playerId);
  23013. this.player_ = _player;
  23014. }
  23015. this.tech_ = tech;
  23016. this.source_ = source;
  23017. this.stats = {};
  23018. this.ignoreNextSeekingEvent_ = false;
  23019. this.setOptions_();
  23020. if (this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
  23021. tech.overrideNativeAudioTracks(true);
  23022. tech.overrideNativeVideoTracks(true);
  23023. } else if (this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
  23024. // overriding native VHS only works if audio tracks have been emulated
  23025. // error early if we're misconfigured
  23026. throw new Error('Overriding native VHS requires emulated tracks. ' + 'See https://git.io/vMpjB');
  23027. } // listen for fullscreenchange events for this player so that we
  23028. // can adjust our quality selection quickly
  23029. this.on(document, ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], event => {
  23030. const fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  23031. if (fullscreenElement && fullscreenElement.contains(this.tech_.el())) {
  23032. this.playlistController_.fastQualityChange_();
  23033. } else {
  23034. // When leaving fullscreen, since the in page pixel dimensions should be smaller
  23035. // than full screen, see if there should be a rendition switch down to preserve
  23036. // bandwidth.
  23037. this.playlistController_.checkABR_();
  23038. }
  23039. });
  23040. this.on(this.tech_, 'seeking', function () {
  23041. if (this.ignoreNextSeekingEvent_) {
  23042. this.ignoreNextSeekingEvent_ = false;
  23043. return;
  23044. }
  23045. this.setCurrentTime(this.tech_.currentTime());
  23046. });
  23047. this.on(this.tech_, 'error', function () {
  23048. // verify that the error was real and we are loaded
  23049. // enough to have pc loaded.
  23050. if (this.tech_.error() && this.playlistController_) {
  23051. this.playlistController_.pauseLoading();
  23052. }
  23053. });
  23054. this.on(this.tech_, 'play', this.play);
  23055. }
  23056. /**
  23057. * Set VHS options based on options from configuration, as well as partial
  23058. * options to be passed at a later time.
  23059. *
  23060. * @param {Object} options A partial chunk of config options
  23061. */
  23062. setOptions_(options = {}) {
  23063. this.options_ = merge(this.options_, options); // defaults
  23064. this.options_.withCredentials = this.options_.withCredentials || false;
  23065. this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
  23066. this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
  23067. this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
  23068. this.options_.useForcedSubtitles = this.options_.useForcedSubtitles || false;
  23069. this.options_.useNetworkInformationApi = this.options_.useNetworkInformationApi || false;
  23070. this.options_.useDtsForTimestampOffset = this.options_.useDtsForTimestampOffset || false;
  23071. this.options_.customTagParsers = this.options_.customTagParsers || [];
  23072. this.options_.customTagMappers = this.options_.customTagMappers || [];
  23073. this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
  23074. this.options_.llhls = this.options_.llhls === false ? false : true;
  23075. this.options_.bufferBasedABR = this.options_.bufferBasedABR || false;
  23076. if (typeof this.options_.playlistExclusionDuration !== 'number') {
  23077. this.options_.playlistExclusionDuration = 60;
  23078. }
  23079. if (typeof this.options_.bandwidth !== 'number') {
  23080. if (this.options_.useBandwidthFromLocalStorage) {
  23081. const storedObject = getVhsLocalStorage();
  23082. if (storedObject && storedObject.bandwidth) {
  23083. this.options_.bandwidth = storedObject.bandwidth;
  23084. this.tech_.trigger({
  23085. type: 'usage',
  23086. name: 'vhs-bandwidth-from-local-storage'
  23087. });
  23088. }
  23089. if (storedObject && storedObject.throughput) {
  23090. this.options_.throughput = storedObject.throughput;
  23091. this.tech_.trigger({
  23092. type: 'usage',
  23093. name: 'vhs-throughput-from-local-storage'
  23094. });
  23095. }
  23096. }
  23097. } // if bandwidth was not set by options or pulled from local storage, start playlist
  23098. // selection at a reasonable bandwidth
  23099. if (typeof this.options_.bandwidth !== 'number') {
  23100. this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
  23101. } // If the bandwidth number is unchanged from the initial setting
  23102. // then this takes precedence over the enableLowInitialPlaylist option
  23103. this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src
  23104. ['withCredentials', 'useDevicePixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'customTagParsers', 'customTagMappers', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'bufferBasedABR', 'liveRangeSafeTimeDelta', 'llhls', 'useForcedSubtitles', 'useNetworkInformationApi', 'useDtsForTimestampOffset', 'exactManifestTimings', 'leastPixelDiffSelector'].forEach(option => {
  23105. if (typeof this.source_[option] !== 'undefined') {
  23106. this.options_[option] = this.source_[option];
  23107. }
  23108. });
  23109. this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
  23110. this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
  23111. } // alias for public method to set options
  23112. setOptions(options = {}) {
  23113. this.setOptions_(options);
  23114. }
  23115. /**
  23116. * called when player.src gets called, handle a new source
  23117. *
  23118. * @param {Object} src the source object to handle
  23119. */
  23120. src(src, type) {
  23121. // do nothing if the src is falsey
  23122. if (!src) {
  23123. return;
  23124. }
  23125. this.setOptions_(); // add main playlist controller options
  23126. this.options_.src = expandDataUri(this.source_.src);
  23127. this.options_.tech = this.tech_;
  23128. this.options_.externVhs = Vhs;
  23129. this.options_.sourceType = simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech
  23130. this.options_.seekTo = time => {
  23131. this.tech_.setCurrentTime(time);
  23132. };
  23133. this.playlistController_ = new PlaylistController(this.options_);
  23134. const playbackWatcherOptions = merge({
  23135. liveRangeSafeTimeDelta: SAFE_TIME_DELTA
  23136. }, this.options_, {
  23137. seekable: () => this.seekable(),
  23138. media: () => this.playlistController_.media(),
  23139. playlistController: this.playlistController_
  23140. });
  23141. this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
  23142. this.playlistController_.on('error', () => {
  23143. const player = videojs.players[this.tech_.options_.playerId];
  23144. let error = this.playlistController_.error;
  23145. if (typeof error === 'object' && !error.code) {
  23146. error.code = 3;
  23147. } else if (typeof error === 'string') {
  23148. error = {
  23149. message: error,
  23150. code: 3
  23151. };
  23152. }
  23153. player.error(error);
  23154. });
  23155. const defaultSelector = this.options_.bufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards
  23156. // compatibility with < v2
  23157. this.playlistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
  23158. this.playlistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2
  23159. this.playlists = this.playlistController_.mainPlaylistLoader_;
  23160. this.mediaSource = this.playlistController_.mediaSource; // Proxy assignment of some properties to the main playlist
  23161. // controller. Using a custom property for backwards compatibility
  23162. // with < v2
  23163. Object.defineProperties(this, {
  23164. selectPlaylist: {
  23165. get() {
  23166. return this.playlistController_.selectPlaylist;
  23167. },
  23168. set(selectPlaylist) {
  23169. this.playlistController_.selectPlaylist = selectPlaylist.bind(this);
  23170. }
  23171. },
  23172. throughput: {
  23173. get() {
  23174. return this.playlistController_.mainSegmentLoader_.throughput.rate;
  23175. },
  23176. set(throughput) {
  23177. this.playlistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value
  23178. // for the cumulative average
  23179. this.playlistController_.mainSegmentLoader_.throughput.count = 1;
  23180. }
  23181. },
  23182. bandwidth: {
  23183. get() {
  23184. let playerBandwidthEst = this.playlistController_.mainSegmentLoader_.bandwidth;
  23185. const networkInformation = window$1.navigator.connection || window$1.navigator.mozConnection || window$1.navigator.webkitConnection;
  23186. const tenMbpsAsBitsPerSecond = 10e6;
  23187. if (this.options_.useNetworkInformationApi && networkInformation) {
  23188. // downlink returns Mbps
  23189. // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlink
  23190. const networkInfoBandwidthEstBitsPerSec = networkInformation.downlink * 1000 * 1000; // downlink maxes out at 10 Mbps. In the event that both networkInformationApi and the player
  23191. // estimate a bandwidth greater than 10 Mbps, use the larger of the two estimates to ensure that
  23192. // high quality streams are not filtered out.
  23193. if (networkInfoBandwidthEstBitsPerSec >= tenMbpsAsBitsPerSecond && playerBandwidthEst >= tenMbpsAsBitsPerSecond) {
  23194. playerBandwidthEst = Math.max(playerBandwidthEst, networkInfoBandwidthEstBitsPerSec);
  23195. } else {
  23196. playerBandwidthEst = networkInfoBandwidthEstBitsPerSec;
  23197. }
  23198. }
  23199. return playerBandwidthEst;
  23200. },
  23201. set(bandwidth) {
  23202. this.playlistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
  23203. // `count` is set to zero that current value of `rate` isn't included
  23204. // in the cumulative average
  23205. this.playlistController_.mainSegmentLoader_.throughput = {
  23206. rate: 0,
  23207. count: 0
  23208. };
  23209. }
  23210. },
  23211. /**
  23212. * `systemBandwidth` is a combination of two serial processes bit-rates. The first
  23213. * is the network bitrate provided by `bandwidth` and the second is the bitrate of
  23214. * the entire process after that - decryption, transmuxing, and appending - provided
  23215. * by `throughput`.
  23216. *
  23217. * Since the two process are serial, the overall system bandwidth is given by:
  23218. * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
  23219. */
  23220. systemBandwidth: {
  23221. get() {
  23222. const invBandwidth = 1 / (this.bandwidth || 1);
  23223. let invThroughput;
  23224. if (this.throughput > 0) {
  23225. invThroughput = 1 / this.throughput;
  23226. } else {
  23227. invThroughput = 0;
  23228. }
  23229. const systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
  23230. return systemBitrate;
  23231. },
  23232. set() {
  23233. videojs.log.error('The "systemBandwidth" property is read-only');
  23234. }
  23235. }
  23236. });
  23237. if (this.options_.bandwidth) {
  23238. this.bandwidth = this.options_.bandwidth;
  23239. }
  23240. if (this.options_.throughput) {
  23241. this.throughput = this.options_.throughput;
  23242. }
  23243. Object.defineProperties(this.stats, {
  23244. bandwidth: {
  23245. get: () => this.bandwidth || 0,
  23246. enumerable: true
  23247. },
  23248. mediaRequests: {
  23249. get: () => this.playlistController_.mediaRequests_() || 0,
  23250. enumerable: true
  23251. },
  23252. mediaRequestsAborted: {
  23253. get: () => this.playlistController_.mediaRequestsAborted_() || 0,
  23254. enumerable: true
  23255. },
  23256. mediaRequestsTimedout: {
  23257. get: () => this.playlistController_.mediaRequestsTimedout_() || 0,
  23258. enumerable: true
  23259. },
  23260. mediaRequestsErrored: {
  23261. get: () => this.playlistController_.mediaRequestsErrored_() || 0,
  23262. enumerable: true
  23263. },
  23264. mediaTransferDuration: {
  23265. get: () => this.playlistController_.mediaTransferDuration_() || 0,
  23266. enumerable: true
  23267. },
  23268. mediaBytesTransferred: {
  23269. get: () => this.playlistController_.mediaBytesTransferred_() || 0,
  23270. enumerable: true
  23271. },
  23272. mediaSecondsLoaded: {
  23273. get: () => this.playlistController_.mediaSecondsLoaded_() || 0,
  23274. enumerable: true
  23275. },
  23276. mediaAppends: {
  23277. get: () => this.playlistController_.mediaAppends_() || 0,
  23278. enumerable: true
  23279. },
  23280. mainAppendsToLoadedData: {
  23281. get: () => this.playlistController_.mainAppendsToLoadedData_() || 0,
  23282. enumerable: true
  23283. },
  23284. audioAppendsToLoadedData: {
  23285. get: () => this.playlistController_.audioAppendsToLoadedData_() || 0,
  23286. enumerable: true
  23287. },
  23288. appendsToLoadedData: {
  23289. get: () => this.playlistController_.appendsToLoadedData_() || 0,
  23290. enumerable: true
  23291. },
  23292. timeToLoadedData: {
  23293. get: () => this.playlistController_.timeToLoadedData_() || 0,
  23294. enumerable: true
  23295. },
  23296. buffered: {
  23297. get: () => timeRangesToArray(this.tech_.buffered()),
  23298. enumerable: true
  23299. },
  23300. currentTime: {
  23301. get: () => this.tech_.currentTime(),
  23302. enumerable: true
  23303. },
  23304. currentSource: {
  23305. get: () => this.tech_.currentSource_,
  23306. enumerable: true
  23307. },
  23308. currentTech: {
  23309. get: () => this.tech_.name_,
  23310. enumerable: true
  23311. },
  23312. duration: {
  23313. get: () => this.tech_.duration(),
  23314. enumerable: true
  23315. },
  23316. main: {
  23317. get: () => this.playlists.main,
  23318. enumerable: true
  23319. },
  23320. playerDimensions: {
  23321. get: () => this.tech_.currentDimensions(),
  23322. enumerable: true
  23323. },
  23324. seekable: {
  23325. get: () => timeRangesToArray(this.tech_.seekable()),
  23326. enumerable: true
  23327. },
  23328. timestamp: {
  23329. get: () => Date.now(),
  23330. enumerable: true
  23331. },
  23332. videoPlaybackQuality: {
  23333. get: () => this.tech_.getVideoPlaybackQuality(),
  23334. enumerable: true
  23335. }
  23336. });
  23337. this.tech_.one('canplay', this.playlistController_.setupFirstPlay.bind(this.playlistController_));
  23338. this.tech_.on('bandwidthupdate', () => {
  23339. if (this.options_.useBandwidthFromLocalStorage) {
  23340. updateVhsLocalStorage({
  23341. bandwidth: this.bandwidth,
  23342. throughput: Math.round(this.throughput)
  23343. });
  23344. }
  23345. });
  23346. this.playlistController_.on('selectedinitialmedia', () => {
  23347. // Add the manual rendition mix-in to VhsHandler
  23348. renditionSelectionMixin(this);
  23349. });
  23350. this.playlistController_.sourceUpdater_.on('createdsourcebuffers', () => {
  23351. this.setupEme_();
  23352. }); // the bandwidth of the primary segment loader is our best
  23353. // estimate of overall bandwidth
  23354. this.on(this.playlistController_, 'progress', function () {
  23355. this.tech_.trigger('progress');
  23356. }); // In the live case, we need to ignore the very first `seeking` event since
  23357. // that will be the result of the seek-to-live behavior
  23358. this.on(this.playlistController_, 'firstplay', function () {
  23359. this.ignoreNextSeekingEvent_ = true;
  23360. });
  23361. this.setupQualityLevels_(); // do nothing if the tech has been disposed already
  23362. // this can occur if someone sets the src in player.ready(), for instance
  23363. if (!this.tech_.el()) {
  23364. return;
  23365. }
  23366. this.mediaSourceUrl_ = window$1.URL.createObjectURL(this.playlistController_.mediaSource);
  23367. this.tech_.src(this.mediaSourceUrl_);
  23368. }
  23369. createKeySessions_() {
  23370. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  23371. this.logger_('waiting for EME key session creation');
  23372. waitForKeySessionCreation({
  23373. player: this.player_,
  23374. sourceKeySystems: this.source_.keySystems,
  23375. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
  23376. mainPlaylists: this.playlists.main.playlists
  23377. }).then(() => {
  23378. this.logger_('created EME key session');
  23379. this.playlistController_.sourceUpdater_.initializedEme();
  23380. }).catch(err => {
  23381. this.logger_('error while creating EME key session', err);
  23382. this.player_.error({
  23383. message: 'Failed to initialize media keys for EME',
  23384. code: 3
  23385. });
  23386. });
  23387. }
  23388. handleWaitingForKey_() {
  23389. // If waitingforkey is fired, it's possible that the data that's necessary to retrieve
  23390. // the key is in the manifest. While this should've happened on initial source load, it
  23391. // may happen again in live streams where the keys change, and the manifest info
  23392. // reflects the update.
  23393. //
  23394. // Because videojs-contrib-eme compares the PSSH data we send to that of PSSH data it's
  23395. // already requested keys for, we don't have to worry about this generating extraneous
  23396. // requests.
  23397. this.logger_('waitingforkey fired, attempting to create any new key sessions');
  23398. this.createKeySessions_();
  23399. }
  23400. /**
  23401. * If necessary and EME is available, sets up EME options and waits for key session
  23402. * creation.
  23403. *
  23404. * This function also updates the source updater so taht it can be used, as for some
  23405. * browsers, EME must be configured before content is appended (if appending unencrypted
  23406. * content before encrypted content).
  23407. */
  23408. setupEme_() {
  23409. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  23410. const didSetupEmeOptions = setupEmeOptions({
  23411. player: this.player_,
  23412. sourceKeySystems: this.source_.keySystems,
  23413. media: this.playlists.media(),
  23414. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
  23415. });
  23416. this.player_.tech_.on('keystatuschange', e => {
  23417. this.playlistController_.updatePlaylistByKeyStatus(e.keyId, e.status);
  23418. });
  23419. this.handleWaitingForKey_ = this.handleWaitingForKey_.bind(this);
  23420. this.player_.tech_.on('waitingforkey', this.handleWaitingForKey_);
  23421. if (!didSetupEmeOptions) {
  23422. // If EME options were not set up, we've done all we could to initialize EME.
  23423. this.playlistController_.sourceUpdater_.initializedEme();
  23424. return;
  23425. }
  23426. this.createKeySessions_();
  23427. }
  23428. /**
  23429. * Initializes the quality levels and sets listeners to update them.
  23430. *
  23431. * @method setupQualityLevels_
  23432. * @private
  23433. */
  23434. setupQualityLevels_() {
  23435. const player = videojs.players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin
  23436. // or qualityLevels_ listeners have already been setup, do nothing.
  23437. if (!player || !player.qualityLevels || this.qualityLevels_) {
  23438. return;
  23439. }
  23440. this.qualityLevels_ = player.qualityLevels();
  23441. this.playlistController_.on('selectedinitialmedia', () => {
  23442. handleVhsLoadedMetadata(this.qualityLevels_, this);
  23443. });
  23444. this.playlists.on('mediachange', () => {
  23445. handleVhsMediaChange(this.qualityLevels_, this.playlists);
  23446. });
  23447. }
  23448. /**
  23449. * return the version
  23450. */
  23451. static version() {
  23452. return {
  23453. '@videojs/http-streaming': version$4,
  23454. 'mux.js': version$3,
  23455. 'mpd-parser': version$2,
  23456. 'm3u8-parser': version$1,
  23457. 'aes-decrypter': version
  23458. };
  23459. }
  23460. /**
  23461. * return the version
  23462. */
  23463. version() {
  23464. return this.constructor.version();
  23465. }
  23466. canChangeType() {
  23467. return SourceUpdater.canChangeType();
  23468. }
  23469. /**
  23470. * Begin playing the video.
  23471. */
  23472. play() {
  23473. this.playlistController_.play();
  23474. }
  23475. /**
  23476. * a wrapper around the function in PlaylistController
  23477. */
  23478. setCurrentTime(currentTime) {
  23479. this.playlistController_.setCurrentTime(currentTime);
  23480. }
  23481. /**
  23482. * a wrapper around the function in PlaylistController
  23483. */
  23484. duration() {
  23485. return this.playlistController_.duration();
  23486. }
  23487. /**
  23488. * a wrapper around the function in PlaylistController
  23489. */
  23490. seekable() {
  23491. return this.playlistController_.seekable();
  23492. }
  23493. /**
  23494. * Abort all outstanding work and cleanup.
  23495. */
  23496. dispose() {
  23497. if (this.playbackWatcher_) {
  23498. this.playbackWatcher_.dispose();
  23499. }
  23500. if (this.playlistController_) {
  23501. this.playlistController_.dispose();
  23502. }
  23503. if (this.qualityLevels_) {
  23504. this.qualityLevels_.dispose();
  23505. }
  23506. if (this.tech_ && this.tech_.vhs) {
  23507. delete this.tech_.vhs;
  23508. }
  23509. if (this.mediaSourceUrl_ && window$1.URL.revokeObjectURL) {
  23510. window$1.URL.revokeObjectURL(this.mediaSourceUrl_);
  23511. this.mediaSourceUrl_ = null;
  23512. }
  23513. if (this.tech_) {
  23514. this.tech_.off('waitingforkey', this.handleWaitingForKey_);
  23515. }
  23516. super.dispose();
  23517. }
  23518. convertToProgramTime(time, callback) {
  23519. return getProgramTime({
  23520. playlist: this.playlistController_.media(),
  23521. time,
  23522. callback
  23523. });
  23524. } // the player must be playing before calling this
  23525. seekToProgramTime(programTime, callback, pauseAfterSeek = true, retryCount = 2) {
  23526. return seekToProgramTime({
  23527. programTime,
  23528. playlist: this.playlistController_.media(),
  23529. retryCount,
  23530. pauseAfterSeek,
  23531. seekTo: this.options_.seekTo,
  23532. tech: this.options_.tech,
  23533. callback
  23534. });
  23535. }
  23536. /**
  23537. * Adds the onRequest, onResponse, offRequest and offResponse functions
  23538. * to the VhsHandler xhr Object.
  23539. */
  23540. setupXhrHooks_() {
  23541. /**
  23542. * A player function for setting an onRequest hook
  23543. *
  23544. * @param {function} callback for request modifiction
  23545. */
  23546. this.xhr.onRequest = callback => {
  23547. addOnRequestHook(this.xhr, callback);
  23548. };
  23549. /**
  23550. * A player function for setting an onResponse hook
  23551. *
  23552. * @param {callback} callback for response data retrieval
  23553. */
  23554. this.xhr.onResponse = callback => {
  23555. addOnResponseHook(this.xhr, callback);
  23556. };
  23557. /**
  23558. * Deletes a player onRequest callback if it exists
  23559. *
  23560. * @param {function} callback to delete from the player set
  23561. */
  23562. this.xhr.offRequest = callback => {
  23563. removeOnRequestHook(this.xhr, callback);
  23564. };
  23565. /**
  23566. * Deletes a player onResponse callback if it exists
  23567. *
  23568. * @param {function} callback to delete from the player set
  23569. */
  23570. this.xhr.offResponse = callback => {
  23571. removeOnResponseHook(this.xhr, callback);
  23572. }; // Trigger an event on the player to notify the user that vhs is ready to set xhr hooks.
  23573. // This allows hooks to be set before the source is set to vhs when handleSource is called.
  23574. this.player_.trigger('xhr-hooks-ready');
  23575. }
  23576. }
  23577. /**
  23578. * The Source Handler object, which informs video.js what additional
  23579. * MIME types are supported and sets up playback. It is registered
  23580. * automatically to the appropriate tech based on the capabilities of
  23581. * the browser it is running in. It is not necessary to use or modify
  23582. * this object in normal usage.
  23583. */
  23584. const VhsSourceHandler = {
  23585. name: 'videojs-http-streaming',
  23586. VERSION: version$4,
  23587. canHandleSource(srcObj, options = {}) {
  23588. const localOptions = merge(videojs.options, options);
  23589. return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
  23590. },
  23591. handleSource(source, tech, options = {}) {
  23592. const localOptions = merge(videojs.options, options);
  23593. tech.vhs = new VhsHandler(source, tech, localOptions);
  23594. tech.vhs.xhr = xhrFactory();
  23595. tech.vhs.setupXhrHooks_();
  23596. tech.vhs.src(source.src, source.type);
  23597. return tech.vhs;
  23598. },
  23599. canPlayType(type, options) {
  23600. const simpleType = simpleTypeFromSourceType(type);
  23601. if (!simpleType) {
  23602. return '';
  23603. }
  23604. const overrideNative = VhsSourceHandler.getOverrideNative(options);
  23605. const supportsTypeNatively = Vhs.supportsTypeNatively(simpleType);
  23606. const canUseMsePlayback = !supportsTypeNatively || overrideNative;
  23607. return canUseMsePlayback ? 'maybe' : '';
  23608. },
  23609. getOverrideNative(options = {}) {
  23610. const {
  23611. vhs = {}
  23612. } = options;
  23613. const defaultOverrideNative = !(videojs.browser.IS_ANY_SAFARI || videojs.browser.IS_IOS);
  23614. const {
  23615. overrideNative = defaultOverrideNative
  23616. } = vhs;
  23617. return overrideNative;
  23618. }
  23619. };
  23620. /**
  23621. * Check to see if the native MediaSource object exists and supports
  23622. * an MP4 container with both H.264 video and AAC-LC audio.
  23623. *
  23624. * @return {boolean} if native media sources are supported
  23625. */
  23626. const supportsNativeMediaSources = () => {
  23627. return browserSupportsCodec('avc1.4d400d,mp4a.40.2');
  23628. }; // register source handlers with the appropriate techs
  23629. if (supportsNativeMediaSources()) {
  23630. videojs.getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
  23631. }
  23632. videojs.VhsHandler = VhsHandler;
  23633. videojs.VhsSourceHandler = VhsSourceHandler;
  23634. videojs.Vhs = Vhs;
  23635. if (!videojs.use) {
  23636. videojs.registerComponent('Vhs', Vhs);
  23637. }
  23638. videojs.options.vhs = videojs.options.vhs || {};
  23639. if (!videojs.getPlugin || !videojs.getPlugin('reloadSourceOnError')) {
  23640. videojs.registerPlugin('reloadSourceOnError', reloadSourceOnError);
  23641. }
  23642. export { LOCAL_STORAGE_KEY, Vhs, VhsHandler, VhsSourceHandler, emeKeySystems, expandDataUri, getAllPsshKeySystemsOptions, setupEmeOptions, waitForKeySessionCreation };