videojs-live.js 442 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076
  1. /**
  2. * 感谢原作者提供以下代码
  3. * 原作者github地址
  4. * https://github.com/videojs
  5. */
  6. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.videojsContribHls = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  7. /**
  8. * @file bin-utils.js
  9. */
  10. /**
  11. * convert a TimeRange to text
  12. *
  13. * @param {TimeRange} range the timerange to use for conversion
  14. * @param {Number} i the iterator on the range to convert
  15. */
  16. 'use strict';
  17. Object.defineProperty(exports, '__esModule', {
  18. value: true
  19. });
  20. var textRange = function textRange(range, i) {
  21. return range.start(i) + '-' + range.end(i);
  22. };
  23. /**
  24. * format a number as hex string
  25. *
  26. * @param {Number} e The number
  27. * @param {Number} i the iterator
  28. */
  29. var formatHexString = function formatHexString(e, i) {
  30. var value = e.toString(16);
  31. return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
  32. };
  33. var formatAsciiString = function formatAsciiString(e) {
  34. if (e >= 0x20 && e < 0x7e) {
  35. return String.fromCharCode(e);
  36. }
  37. return '.';
  38. };
  39. /**
  40. * utils to help dump binary data to the console
  41. */
  42. var utils = {
  43. hexDump: function hexDump(data) {
  44. var bytes = Array.prototype.slice.call(data);
  45. var step = 16;
  46. var result = '';
  47. var hex = undefined;
  48. var ascii = undefined;
  49. for (var j = 0; j < bytes.length / step; j++) {
  50. hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
  51. ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
  52. result += hex + ' ' + ascii + '\n';
  53. }
  54. return result;
  55. },
  56. tagDump: function tagDump(tag) {
  57. return utils.hexDump(tag.bytes);
  58. },
  59. textRanges: function textRanges(ranges) {
  60. var result = '';
  61. var i = undefined;
  62. for (i = 0; i < ranges.length; i++) {
  63. result += textRange(ranges, i) + ' ';
  64. }
  65. return result;
  66. }
  67. };
  68. exports['default'] = utils;
  69. module.exports = exports['default'];
  70. },{}],2:[function(require,module,exports){
  71. /**
  72. * @file decrypter/aes.js
  73. *
  74. * This file contains an adaptation of the AES decryption algorithm
  75. * from the Standford Javascript Cryptography Library. That work is
  76. * covered by the following copyright and permissions notice:
  77. *
  78. * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  79. * All rights reserved.
  80. *
  81. * Redistribution and use in source and binary forms, with or without
  82. * modification, are permitted provided that the following conditions are
  83. * met:
  84. *
  85. * 1. Redistributions of source code must retain the above copyright
  86. * notice, this list of conditions and the following disclaimer.
  87. *
  88. * 2. Redistributions in binary form must reproduce the above
  89. * copyright notice, this list of conditions and the following
  90. * disclaimer in the documentation and/or other materials provided
  91. * with the distribution.
  92. *
  93. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  94. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  95. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  96. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  97. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  98. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  99. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  100. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  101. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  102. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  103. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  104. *
  105. * The views and conclusions contained in the software and documentation
  106. * are those of the authors and should not be interpreted as representing
  107. * official policies, either expressed or implied, of the authors.
  108. */
  109. /**
  110. * Expand the S-box tables.
  111. *
  112. * @private
  113. */
  114. 'use strict';
  115. Object.defineProperty(exports, '__esModule', {
  116. value: true
  117. });
  118. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  119. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  120. var precompute = function precompute() {
  121. var tables = [[[], [], [], [], []], [[], [], [], [], []]];
  122. var encTable = tables[0];
  123. var decTable = tables[1];
  124. var sbox = encTable[4];
  125. var sboxInv = decTable[4];
  126. var i = undefined;
  127. var x = undefined;
  128. var xInv = undefined;
  129. var d = [];
  130. var th = [];
  131. var x2 = undefined;
  132. var x4 = undefined;
  133. var x8 = undefined;
  134. var s = undefined;
  135. var tEnc = undefined;
  136. var tDec = undefined;
  137. // Compute double and third tables
  138. for (i = 0; i < 256; i++) {
  139. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  140. }
  141. for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  142. // Compute sbox
  143. s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  144. s = s >> 8 ^ s & 255 ^ 99;
  145. sbox[x] = s;
  146. sboxInv[s] = x;
  147. // Compute MixColumns
  148. x8 = d[x4 = d[x2 = d[x]]];
  149. tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  150. tEnc = d[s] * 0x101 ^ s * 0x1010100;
  151. for (i = 0; i < 4; i++) {
  152. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  153. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  154. }
  155. }
  156. // Compactify. Considerable speedup on Firefox.
  157. for (i = 0; i < 5; i++) {
  158. encTable[i] = encTable[i].slice(0);
  159. decTable[i] = decTable[i].slice(0);
  160. }
  161. return tables;
  162. };
  163. var aesTables = null;
  164. /**
  165. * Schedule out an AES key for both encryption and decryption. This
  166. * is a low-level class. Use a cipher mode to do bulk encryption.
  167. *
  168. * @class AES
  169. * @param key {Array} The key as an array of 4, 6 or 8 words.
  170. */
  171. var AES = (function () {
  172. function AES(key) {
  173. _classCallCheck(this, AES);
  174. /**
  175. * The expanded S-box and inverse S-box tables. These will be computed
  176. * on the client so that we don't have to send them down the wire.
  177. *
  178. * There are two tables, _tables[0] is for encryption and
  179. * _tables[1] is for decryption.
  180. *
  181. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  182. * last (_tables[01][4]) is the S-box itself.
  183. *
  184. * @private
  185. */
  186. // if we have yet to precompute the S-box tables
  187. // do so now
  188. if (!aesTables) {
  189. aesTables = precompute();
  190. }
  191. // then make a copy of that object for use
  192. 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()]];
  193. var i = undefined;
  194. var j = undefined;
  195. var tmp = undefined;
  196. var encKey = undefined;
  197. var decKey = undefined;
  198. var sbox = this._tables[0][4];
  199. var decTable = this._tables[1];
  200. var keyLen = key.length;
  201. var rcon = 1;
  202. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  203. throw new Error('Invalid aes key size');
  204. }
  205. encKey = key.slice(0);
  206. decKey = [];
  207. this._key = [encKey, decKey];
  208. // schedule encryption keys
  209. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  210. tmp = encKey[i - 1];
  211. // apply sbox
  212. if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
  213. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255];
  214. // shift rows and add rcon
  215. if (i % keyLen === 0) {
  216. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  217. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  218. }
  219. }
  220. encKey[i] = encKey[i - keyLen] ^ tmp;
  221. }
  222. // schedule decryption keys
  223. for (j = 0; i; j++, i--) {
  224. tmp = encKey[j & 3 ? i : i - 4];
  225. if (i <= 4 || j < 4) {
  226. decKey[j] = tmp;
  227. } else {
  228. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
  229. }
  230. }
  231. }
  232. /**
  233. * Decrypt 16 bytes, specified as four 32-bit words.
  234. *
  235. * @param {Number} encrypted0 the first word to decrypt
  236. * @param {Number} encrypted1 the second word to decrypt
  237. * @param {Number} encrypted2 the third word to decrypt
  238. * @param {Number} encrypted3 the fourth word to decrypt
  239. * @param {Int32Array} out the array to write the decrypted words
  240. * into
  241. * @param {Number} offset the offset into the output array to start
  242. * writing results
  243. * @return {Array} The plaintext.
  244. */
  245. _createClass(AES, [{
  246. key: 'decrypt',
  247. value: function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
  248. var key = this._key[1];
  249. // state variables a,b,c,d are loaded with pre-whitened data
  250. var a = encrypted0 ^ key[0];
  251. var b = encrypted3 ^ key[1];
  252. var c = encrypted2 ^ key[2];
  253. var d = encrypted1 ^ key[3];
  254. var a2 = undefined;
  255. var b2 = undefined;
  256. var c2 = undefined;
  257. // key.length === 2 ?
  258. var nInnerRounds = key.length / 4 - 2;
  259. var i = undefined;
  260. var kIndex = 4;
  261. var table = this._tables[1];
  262. // load up the tables
  263. var table0 = table[0];
  264. var table1 = table[1];
  265. var table2 = table[2];
  266. var table3 = table[3];
  267. var sbox = table[4];
  268. // Inner rounds. Cribbed from OpenSSL.
  269. for (i = 0; i < nInnerRounds; i++) {
  270. a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
  271. b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
  272. c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
  273. d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
  274. kIndex += 4;
  275. a = a2;b = b2;c = c2;
  276. }
  277. // Last round.
  278. for (i = 0; i < 4; i++) {
  279. out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
  280. a2 = a;a = b;b = c;c = d;d = a2;
  281. }
  282. }
  283. }]);
  284. return AES;
  285. })();
  286. exports['default'] = AES;
  287. module.exports = exports['default'];
  288. },{}],3:[function(require,module,exports){
  289. /**
  290. * @file decrypter/async-stream.js
  291. */
  292. 'use strict';
  293. Object.defineProperty(exports, '__esModule', {
  294. value: true
  295. });
  296. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  297. var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  298. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  299. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  300. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  301. var _stream = require('../stream');
  302. var _stream2 = _interopRequireDefault(_stream);
  303. /**
  304. * A wrapper around the Stream class to use setTiemout
  305. * and run stream "jobs" Asynchronously
  306. *
  307. * @class AsyncStream
  308. * @extends Stream
  309. */
  310. var AsyncStream = (function (_Stream) {
  311. _inherits(AsyncStream, _Stream);
  312. function AsyncStream() {
  313. _classCallCheck(this, AsyncStream);
  314. _get(Object.getPrototypeOf(AsyncStream.prototype), 'constructor', this).call(this, _stream2['default']);
  315. this.jobs = [];
  316. this.delay = 1;
  317. this.timeout_ = null;
  318. }
  319. /**
  320. * process an async job
  321. *
  322. * @private
  323. */
  324. _createClass(AsyncStream, [{
  325. key: 'processJob_',
  326. value: function processJob_() {
  327. this.jobs.shift()();
  328. if (this.jobs.length) {
  329. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  330. } else {
  331. this.timeout_ = null;
  332. }
  333. }
  334. /**
  335. * push a job into the stream
  336. *
  337. * @param {Function} job the job to push into the stream
  338. */
  339. }, {
  340. key: 'push',
  341. value: function push(job) {
  342. this.jobs.push(job);
  343. if (!this.timeout_) {
  344. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  345. }
  346. }
  347. }]);
  348. return AsyncStream;
  349. })(_stream2['default']);
  350. exports['default'] = AsyncStream;
  351. module.exports = exports['default'];
  352. },{"../stream":18}],4:[function(require,module,exports){
  353. /**
  354. * @file decrypter/decrypter.js
  355. *
  356. * An asynchronous implementation of AES-128 CBC decryption with
  357. * PKCS#7 padding.
  358. */
  359. 'use strict';
  360. Object.defineProperty(exports, '__esModule', {
  361. value: true
  362. });
  363. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  364. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  365. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  366. var _aes = require('./aes');
  367. var _aes2 = _interopRequireDefault(_aes);
  368. var _asyncStream = require('./async-stream');
  369. var _asyncStream2 = _interopRequireDefault(_asyncStream);
  370. var _pkcs7 = require('pkcs7');
  371. /**
  372. * Convert network-order (big-endian) bytes into their little-endian
  373. * representation.
  374. */
  375. var ntoh = function ntoh(word) {
  376. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  377. };
  378. /**
  379. * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
  380. *
  381. * @param {Uint8Array} encrypted the encrypted bytes
  382. * @param {Uint32Array} key the bytes of the decryption key
  383. * @param {Uint32Array} initVector the initialization vector (IV) to
  384. * use for the first round of CBC.
  385. * @return {Uint8Array} the decrypted bytes
  386. *
  387. * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  388. * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
  389. * @see https://tools.ietf.org/html/rfc2315
  390. */
  391. var decrypt = function decrypt(encrypted, key, initVector) {
  392. // word-level access to the encrypted bytes
  393. var encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
  394. var decipher = new _aes2['default'](Array.prototype.slice.call(key));
  395. // byte and word-level access for the decrypted output
  396. var decrypted = new Uint8Array(encrypted.byteLength);
  397. var decrypted32 = new Int32Array(decrypted.buffer);
  398. // temporary variables for working with the IV, encrypted, and
  399. // decrypted data
  400. var init0 = undefined;
  401. var init1 = undefined;
  402. var init2 = undefined;
  403. var init3 = undefined;
  404. var encrypted0 = undefined;
  405. var encrypted1 = undefined;
  406. var encrypted2 = undefined;
  407. var encrypted3 = undefined;
  408. // iteration variable
  409. var wordIx = undefined;
  410. // pull out the words of the IV to ensure we don't modify the
  411. // passed-in reference and easier access
  412. init0 = initVector[0];
  413. init1 = initVector[1];
  414. init2 = initVector[2];
  415. init3 = initVector[3];
  416. // decrypt four word sequences, applying cipher-block chaining (CBC)
  417. // to each decrypted block
  418. for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
  419. // convert big-endian (network order) words into little-endian
  420. // (javascript order)
  421. encrypted0 = ntoh(encrypted32[wordIx]);
  422. encrypted1 = ntoh(encrypted32[wordIx + 1]);
  423. encrypted2 = ntoh(encrypted32[wordIx + 2]);
  424. encrypted3 = ntoh(encrypted32[wordIx + 3]);
  425. // decrypt the block
  426. decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx);
  427. // XOR with the IV, and restore network byte-order to obtain the
  428. // plaintext
  429. decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
  430. decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
  431. decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
  432. decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3);
  433. // setup the IV for the next round
  434. init0 = encrypted0;
  435. init1 = encrypted1;
  436. init2 = encrypted2;
  437. init3 = encrypted3;
  438. }
  439. return decrypted;
  440. };
  441. exports.decrypt = decrypt;
  442. /**
  443. * The `Decrypter` class that manages decryption of AES
  444. * data through `AsyncStream` objects and the `decrypt`
  445. * function
  446. *
  447. * @param {Uint8Array} encrypted the encrypted bytes
  448. * @param {Uint32Array} key the bytes of the decryption key
  449. * @param {Uint32Array} initVector the initialization vector (IV) to
  450. * @param {Function} done the function to run when done
  451. * @class Decrypter
  452. */
  453. var Decrypter = (function () {
  454. function Decrypter(encrypted, key, initVector, done) {
  455. _classCallCheck(this, Decrypter);
  456. var step = Decrypter.STEP;
  457. var encrypted32 = new Int32Array(encrypted.buffer);
  458. var decrypted = new Uint8Array(encrypted.byteLength);
  459. var i = 0;
  460. this.asyncStream_ = new _asyncStream2['default']();
  461. // split up the encryption job and do the individual chunks asynchronously
  462. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  463. for (i = step; i < encrypted32.length; i += step) {
  464. initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
  465. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  466. }
  467. // invoke the done() callback when everything is finished
  468. this.asyncStream_.push(function () {
  469. // remove pkcs#7 padding from the decrypted bytes
  470. done(null, (0, _pkcs7.unpad)(decrypted));
  471. });
  472. }
  473. /**
  474. * a getter for step the maximum number of bytes to process at one time
  475. *
  476. * @return {Number} the value of step 32000
  477. */
  478. _createClass(Decrypter, [{
  479. key: 'decryptChunk_',
  480. /**
  481. * @private
  482. */
  483. value: function decryptChunk_(encrypted, key, initVector, decrypted) {
  484. return function () {
  485. var bytes = decrypt(encrypted, key, initVector);
  486. decrypted.set(bytes, encrypted.byteOffset);
  487. };
  488. }
  489. }], [{
  490. key: 'STEP',
  491. get: function get() {
  492. // 4 * 8000;
  493. return 32000;
  494. }
  495. }]);
  496. return Decrypter;
  497. })();
  498. exports.Decrypter = Decrypter;
  499. exports['default'] = {
  500. Decrypter: Decrypter,
  501. decrypt: decrypt
  502. };
  503. },{"./aes":2,"./async-stream":3,"pkcs7":23}],5:[function(require,module,exports){
  504. /**
  505. * @file decrypter/index.js
  506. *
  507. * Index module to easily import the primary components of AES-128
  508. * decryption. Like this:
  509. *
  510. * ```js
  511. * import {Decrypter, decrypt, AsyncStream} from './src/decrypter';
  512. * ```
  513. */
  514. 'use strict';
  515. Object.defineProperty(exports, '__esModule', {
  516. value: true
  517. });
  518. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  519. var _decrypter = require('./decrypter');
  520. var _asyncStream = require('./async-stream');
  521. var _asyncStream2 = _interopRequireDefault(_asyncStream);
  522. exports['default'] = {
  523. decrypt: _decrypter.decrypt,
  524. Decrypter: _decrypter.Decrypter,
  525. AsyncStream: _asyncStream2['default']
  526. };
  527. module.exports = exports['default'];
  528. },{"./async-stream":3,"./decrypter":4}],6:[function(require,module,exports){
  529. (function (global){
  530. /**
  531. * @file hls-audio-track.js
  532. */
  533. 'use strict';
  534. Object.defineProperty(exports, '__esModule', {
  535. value: true
  536. });
  537. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  538. var _get = function get(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x2 = parent; _x3 = property; _x4 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  539. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  540. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  541. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  542. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  543. var _playlistLoader = require('./playlist-loader');
  544. var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
  545. /**
  546. * HlsAudioTrack extends video.js audio tracks but adds HLS
  547. * specific data storage such as playlist loaders, mediaGroups
  548. * and default/autoselect
  549. *
  550. * @param {Object} options options to create HlsAudioTrack with
  551. * @class HlsAudioTrack
  552. * @extends AudioTrack
  553. */
  554. var HlsAudioTrack = (function (_AudioTrack) {
  555. _inherits(HlsAudioTrack, _AudioTrack);
  556. function HlsAudioTrack(options) {
  557. _classCallCheck(this, HlsAudioTrack);
  558. _get(Object.getPrototypeOf(HlsAudioTrack.prototype), 'constructor', this).call(this, {
  559. kind: options['default'] ? 'main' : 'alternative',
  560. enabled: options['default'] || false,
  561. language: options.language,
  562. label: options.label
  563. });
  564. this.hls = options.hls;
  565. this.autoselect = options.autoselect || false;
  566. this['default'] = options['default'] || false;
  567. this.withCredentials = options.withCredentials || false;
  568. this.mediaGroups_ = [];
  569. this.addLoader(options.mediaGroup, options.resolvedUri);
  570. }
  571. /**
  572. * get a PlaylistLoader from this track given a mediaGroup name
  573. *
  574. * @param {String} mediaGroup the mediaGroup to get the loader for
  575. * @return {PlaylistLoader|Null} the PlaylistLoader or null
  576. */
  577. _createClass(HlsAudioTrack, [{
  578. key: 'getLoader',
  579. value: function getLoader(mediaGroup) {
  580. for (var i = 0; i < this.mediaGroups_.length; i++) {
  581. var mgl = this.mediaGroups_[i];
  582. if (mgl.mediaGroup === mediaGroup) {
  583. return mgl.loader;
  584. }
  585. }
  586. }
  587. /**
  588. * add a PlaylistLoader given a mediaGroup, and a uri. for a combined track
  589. * we store null for the playlistloader
  590. *
  591. * @param {String} mediaGroup the mediaGroup to get the loader for
  592. * @param {String} uri the uri to get the audio track/mediaGroup from
  593. */
  594. }, {
  595. key: 'addLoader',
  596. value: function addLoader(mediaGroup) {
  597. var uri = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  598. var loader = null;
  599. if (uri) {
  600. // TODO: this should probably happen upstream in Master Playlist
  601. // Controller when we can switch PlaylistLoader sources
  602. // then we can just store the uri here instead
  603. loader = new _playlistLoader2['default'](uri, this.hls, this.withCredentials);
  604. }
  605. this.mediaGroups_.push({ mediaGroup: mediaGroup, loader: loader });
  606. }
  607. /**
  608. * remove a playlist loader from a track given the mediaGroup
  609. *
  610. * @param {String} mediaGroup the mediaGroup to remove
  611. */
  612. }, {
  613. key: 'removeLoader',
  614. value: function removeLoader(mediaGroup) {
  615. for (var i = 0; i < this.mediaGroups_.length; i++) {
  616. var mgl = this.mediaGroups_[i];
  617. if (mgl.mediaGroup === mediaGroup) {
  618. if (mgl.loader) {
  619. mgl.loader.dispose();
  620. }
  621. this.mediaGroups_.splice(i, 1);
  622. return;
  623. }
  624. }
  625. }
  626. /**
  627. * Dispose of this audio track and
  628. * the playlist loader that it holds inside
  629. */
  630. }, {
  631. key: 'dispose',
  632. value: function dispose() {
  633. var i = this.mediaGroups_.length;
  634. while (i--) {
  635. this.removeLoader(this.mediaGroups_[i].mediaGroup);
  636. }
  637. }
  638. }]);
  639. return HlsAudioTrack;
  640. })(_videoJs.AudioTrack);
  641. exports['default'] = HlsAudioTrack;
  642. module.exports = exports['default'];
  643. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  644. },{"./playlist-loader":12}],7:[function(require,module,exports){
  645. /**
  646. * @file m3u8/index.js
  647. *
  648. * Utilities for parsing M3U8 files. If the entire manifest is available,
  649. * `Parser` will create an object representation with enough detail for managing
  650. * playback. `ParseStream` and `LineStream` are lower-level parsing primitives
  651. * that do not assume the entirety of the manifest is ready and expose a
  652. * ReadableStream-like interface.
  653. */
  654. 'use strict';
  655. Object.defineProperty(exports, '__esModule', {
  656. value: true
  657. });
  658. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  659. var _lineStream = require('./line-stream');
  660. var _lineStream2 = _interopRequireDefault(_lineStream);
  661. var _parseStream = require('./parse-stream');
  662. var _parseStream2 = _interopRequireDefault(_parseStream);
  663. var _parser = require('./parser');
  664. var _parser2 = _interopRequireDefault(_parser);
  665. exports['default'] = {
  666. LineStream: _lineStream2['default'],
  667. ParseStream: _parseStream2['default'],
  668. Parser: _parser2['default']
  669. };
  670. module.exports = exports['default'];
  671. },{"./line-stream":8,"./parse-stream":9,"./parser":10}],8:[function(require,module,exports){
  672. /**
  673. * @file m3u8/line-stream.js
  674. */
  675. 'use strict';
  676. Object.defineProperty(exports, '__esModule', {
  677. value: true
  678. });
  679. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  680. var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  681. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  682. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  683. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  684. var _stream = require('../stream');
  685. var _stream2 = _interopRequireDefault(_stream);
  686. /**
  687. * A stream that buffers string input and generates a `data` event for each
  688. * line.
  689. *
  690. * @class LineStream
  691. * @extends Stream
  692. */
  693. var LineStream = (function (_Stream) {
  694. _inherits(LineStream, _Stream);
  695. function LineStream() {
  696. _classCallCheck(this, LineStream);
  697. _get(Object.getPrototypeOf(LineStream.prototype), 'constructor', this).call(this);
  698. this.buffer = '';
  699. }
  700. /**
  701. * Add new data to be parsed.
  702. *
  703. * @param {String} data the text to process
  704. */
  705. _createClass(LineStream, [{
  706. key: 'push',
  707. value: function push(data) {
  708. var nextNewline = undefined;
  709. this.buffer += data;
  710. nextNewline = this.buffer.indexOf('\n');
  711. for (; nextNewline > -1; nextNewline = this.buffer.indexOf('\n')) {
  712. this.trigger('data', this.buffer.substring(0, nextNewline));
  713. this.buffer = this.buffer.substring(nextNewline + 1);
  714. }
  715. }
  716. }]);
  717. return LineStream;
  718. })(_stream2['default']);
  719. exports['default'] = LineStream;
  720. module.exports = exports['default'];
  721. },{"../stream":18}],9:[function(require,module,exports){
  722. /**
  723. * @file m3u8/parse-stream.js
  724. */
  725. 'use strict';
  726. Object.defineProperty(exports, '__esModule', {
  727. value: true
  728. });
  729. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  730. var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  731. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  732. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  733. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  734. var _stream = require('../stream');
  735. var _stream2 = _interopRequireDefault(_stream);
  736. /**
  737. * "forgiving" attribute list psuedo-grammar:
  738. * attributes -> keyvalue (',' keyvalue)*
  739. * keyvalue -> key '=' value
  740. * key -> [^=]*
  741. * value -> '"' [^"]* '"' | [^,]*
  742. */
  743. var attributeSeparator = function attributeSeparator() {
  744. var key = '[^=]*';
  745. var value = '"[^"]*"|[^,]*';
  746. var keyvalue = '(?:' + key + ')=(?:' + value + ')';
  747. return new RegExp('(?:^|,)(' + keyvalue + ')');
  748. };
  749. /**
  750. * Parse attributes from a line given the seperator
  751. *
  752. * @param {String} attributes the attibute line to parse
  753. */
  754. var parseAttributes = function parseAttributes(attributes) {
  755. // split the string using attributes as the separator
  756. var attrs = attributes.split(attributeSeparator());
  757. var i = attrs.length;
  758. var result = {};
  759. var attr = undefined;
  760. while (i--) {
  761. // filter out unmatched portions of the string
  762. if (attrs[i] === '') {
  763. continue;
  764. }
  765. // split the key and value
  766. attr = /([^=]*)=(.*)/.exec(attrs[i]).slice(1);
  767. // trim whitespace and remove optional quotes around the value
  768. attr[0] = attr[0].replace(/^\s+|\s+$/g, '');
  769. attr[1] = attr[1].replace(/^\s+|\s+$/g, '');
  770. attr[1] = attr[1].replace(/^['"](.*)['"]$/g, '$1');
  771. result[attr[0]] = attr[1];
  772. }
  773. return result;
  774. };
  775. /**
  776. * A line-level M3U8 parser event stream. It expects to receive input one
  777. * line at a time and performs a context-free parse of its contents. A stream
  778. * interpretation of a manifest can be useful if the manifest is expected to
  779. * be too large to fit comfortably into memory or the entirety of the input
  780. * is not immediately available. Otherwise, it's probably much easier to work
  781. * with a regular `Parser` object.
  782. *
  783. * Produces `data` events with an object that captures the parser's
  784. * interpretation of the input. That object has a property `tag` that is one
  785. * of `uri`, `comment`, or `tag`. URIs only have a single additional
  786. * property, `line`, which captures the entirety of the input without
  787. * interpretation. Comments similarly have a single additional property
  788. * `text` which is the input without the leading `#`.
  789. *
  790. * Tags always have a property `tagType` which is the lower-cased version of
  791. * the M3U8 directive without the `#EXT` or `#EXT-X-` prefix. For instance,
  792. * `#EXT-X-MEDIA-SEQUENCE` becomes `media-sequence` when parsed. Unrecognized
  793. * tags are given the tag type `unknown` and a single additional property
  794. * `data` with the remainder of the input.
  795. *
  796. * @class ParseStream
  797. * @extends Stream
  798. */
  799. var ParseStream = (function (_Stream) {
  800. _inherits(ParseStream, _Stream);
  801. function ParseStream() {
  802. _classCallCheck(this, ParseStream);
  803. _get(Object.getPrototypeOf(ParseStream.prototype), 'constructor', this).call(this);
  804. }
  805. /**
  806. * Parses an additional line of input.
  807. *
  808. * @param {String} line a single line of an M3U8 file to parse
  809. */
  810. _createClass(ParseStream, [{
  811. key: 'push',
  812. value: function push(line) {
  813. var match = undefined;
  814. var event = undefined;
  815. // strip whitespace
  816. line = line.replace(/^[\u0000\s]+|[\u0000\s]+$/g, '');
  817. if (line.length === 0) {
  818. // ignore empty lines
  819. return;
  820. }
  821. // URIs
  822. if (line[0] !== '#') {
  823. this.trigger('data', {
  824. type: 'uri',
  825. uri: line
  826. });
  827. return;
  828. }
  829. // Comments
  830. if (line.indexOf('#EXT') !== 0) {
  831. this.trigger('data', {
  832. type: 'comment',
  833. text: line.slice(1)
  834. });
  835. return;
  836. }
  837. // strip off any carriage returns here so the regex matching
  838. // doesn't have to account for them.
  839. line = line.replace('\r', '');
  840. // Tags
  841. match = /^#EXTM3U/.exec(line);
  842. if (match) {
  843. this.trigger('data', {
  844. type: 'tag',
  845. tagType: 'm3u'
  846. });
  847. return;
  848. }
  849. match = /^#EXTINF:?([0-9\.]*)?,?(.*)?$/.exec(line);
  850. if (match) {
  851. event = {
  852. type: 'tag',
  853. tagType: 'inf'
  854. };
  855. if (match[1]) {
  856. event.duration = parseFloat(match[1]);
  857. }
  858. if (match[2]) {
  859. event.title = match[2];
  860. }
  861. this.trigger('data', event);
  862. return;
  863. }
  864. match = /^#EXT-X-TARGETDURATION:?([0-9.]*)?/.exec(line);
  865. if (match) {
  866. event = {
  867. type: 'tag',
  868. tagType: 'targetduration'
  869. };
  870. if (match[1]) {
  871. event.duration = parseInt(match[1], 10);
  872. }
  873. this.trigger('data', event);
  874. return;
  875. }
  876. match = /^#ZEN-TOTAL-DURATION:?([0-9.]*)?/.exec(line);
  877. if (match) {
  878. event = {
  879. type: 'tag',
  880. tagType: 'totalduration'
  881. };
  882. if (match[1]) {
  883. event.duration = parseInt(match[1], 10);
  884. }
  885. this.trigger('data', event);
  886. return;
  887. }
  888. match = /^#EXT-X-VERSION:?([0-9.]*)?/.exec(line);
  889. if (match) {
  890. event = {
  891. type: 'tag',
  892. tagType: 'version'
  893. };
  894. if (match[1]) {
  895. event.version = parseInt(match[1], 10);
  896. }
  897. this.trigger('data', event);
  898. return;
  899. }
  900. match = /^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(line);
  901. if (match) {
  902. event = {
  903. type: 'tag',
  904. tagType: 'media-sequence'
  905. };
  906. if (match[1]) {
  907. event.number = parseInt(match[1], 10);
  908. }
  909. this.trigger('data', event);
  910. return;
  911. }
  912. match = /^#EXT-X-DISCONTINUITY-SEQUENCE:?(\-?[0-9.]*)?/.exec(line);
  913. if (match) {
  914. event = {
  915. type: 'tag',
  916. tagType: 'discontinuity-sequence'
  917. };
  918. if (match[1]) {
  919. event.number = parseInt(match[1], 10);
  920. }
  921. this.trigger('data', event);
  922. return;
  923. }
  924. match = /^#EXT-X-PLAYLIST-TYPE:?(.*)?$/.exec(line);
  925. if (match) {
  926. event = {
  927. type: 'tag',
  928. tagType: 'playlist-type'
  929. };
  930. if (match[1]) {
  931. event.playlistType = match[1];
  932. }
  933. this.trigger('data', event);
  934. return;
  935. }
  936. match = /^#EXT-X-BYTERANGE:?([0-9.]*)?@?([0-9.]*)?/.exec(line);
  937. if (match) {
  938. event = {
  939. type: 'tag',
  940. tagType: 'byterange'
  941. };
  942. if (match[1]) {
  943. event.length = parseInt(match[1], 10);
  944. }
  945. if (match[2]) {
  946. event.offset = parseInt(match[2], 10);
  947. }
  948. this.trigger('data', event);
  949. return;
  950. }
  951. match = /^#EXT-X-ALLOW-CACHE:?(YES|NO)?/.exec(line);
  952. if (match) {
  953. event = {
  954. type: 'tag',
  955. tagType: 'allow-cache'
  956. };
  957. if (match[1]) {
  958. event.allowed = !/NO/.test(match[1]);
  959. }
  960. this.trigger('data', event);
  961. return;
  962. }
  963. match = /^#EXT-X-STREAM-INF:?(.*)$/.exec(line);
  964. if (match) {
  965. event = {
  966. type: 'tag',
  967. tagType: 'stream-inf'
  968. };
  969. if (match[1]) {
  970. event.attributes = parseAttributes(match[1]);
  971. if (event.attributes.RESOLUTION) {
  972. var split = event.attributes.RESOLUTION.split('x');
  973. var resolution = {};
  974. if (split[0]) {
  975. resolution.width = parseInt(split[0], 10);
  976. }
  977. if (split[1]) {
  978. resolution.height = parseInt(split[1], 10);
  979. }
  980. event.attributes.RESOLUTION = resolution;
  981. }
  982. if (event.attributes.BANDWIDTH) {
  983. event.attributes.BANDWIDTH = parseInt(event.attributes.BANDWIDTH, 10);
  984. }
  985. if (event.attributes['PROGRAM-ID']) {
  986. event.attributes['PROGRAM-ID'] = parseInt(event.attributes['PROGRAM-ID'], 10);
  987. }
  988. }
  989. this.trigger('data', event);
  990. return;
  991. }
  992. match = /^#EXT-X-MEDIA:?(.*)$/.exec(line);
  993. if (match) {
  994. event = {
  995. type: 'tag',
  996. tagType: 'media'
  997. };
  998. if (match[1]) {
  999. event.attributes = parseAttributes(match[1]);
  1000. }
  1001. this.trigger('data', event);
  1002. return;
  1003. }
  1004. match = /^#EXT-X-ENDLIST/.exec(line);
  1005. if (match) {
  1006. this.trigger('data', {
  1007. type: 'tag',
  1008. tagType: 'endlist'
  1009. });
  1010. return;
  1011. }
  1012. match = /^#EXT-X-DISCONTINUITY/.exec(line);
  1013. if (match) {
  1014. this.trigger('data', {
  1015. type: 'tag',
  1016. tagType: 'discontinuity'
  1017. });
  1018. return;
  1019. }
  1020. match = /^#EXT-X-KEY:?(.*)$/.exec(line);
  1021. if (match) {
  1022. event = {
  1023. type: 'tag',
  1024. tagType: 'key'
  1025. };
  1026. if (match[1]) {
  1027. event.attributes = parseAttributes(match[1]);
  1028. // parse the IV string into a Uint32Array
  1029. if (event.attributes.IV) {
  1030. if (event.attributes.IV.substring(0, 2).toLowerCase() === '0x') {
  1031. event.attributes.IV = event.attributes.IV.substring(2);
  1032. }
  1033. event.attributes.IV = event.attributes.IV.match(/.{8}/g);
  1034. event.attributes.IV[0] = parseInt(event.attributes.IV[0], 16);
  1035. event.attributes.IV[1] = parseInt(event.attributes.IV[1], 16);
  1036. event.attributes.IV[2] = parseInt(event.attributes.IV[2], 16);
  1037. event.attributes.IV[3] = parseInt(event.attributes.IV[3], 16);
  1038. event.attributes.IV = new Uint32Array(event.attributes.IV);
  1039. }
  1040. }
  1041. this.trigger('data', event);
  1042. return;
  1043. }
  1044. // unknown tag type
  1045. this.trigger('data', {
  1046. type: 'tag',
  1047. data: line.slice(4, line.length)
  1048. });
  1049. }
  1050. }]);
  1051. return ParseStream;
  1052. })(_stream2['default']);
  1053. exports['default'] = ParseStream;
  1054. module.exports = exports['default'];
  1055. },{"../stream":18}],10:[function(require,module,exports){
  1056. (function (global){
  1057. /**
  1058. * @file m3u8/parser.js
  1059. */
  1060. 'use strict';
  1061. Object.defineProperty(exports, '__esModule', {
  1062. value: true
  1063. });
  1064. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  1065. var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  1066. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  1067. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  1068. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  1069. var _stream = require('../stream');
  1070. var _stream2 = _interopRequireDefault(_stream);
  1071. var _lineStream = require('./line-stream');
  1072. var _lineStream2 = _interopRequireDefault(_lineStream);
  1073. var _parseStream = require('./parse-stream');
  1074. var _parseStream2 = _interopRequireDefault(_parseStream);
  1075. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  1076. /**
  1077. * A parser for M3U8 files. The current interpretation of the input is
  1078. * exposed as a property `manifest` on parser objects. It's just two lines to
  1079. * create and parse a manifest once you have the contents available as a string:
  1080. *
  1081. * ```js
  1082. * var parser = new videojs.m3u8.Parser();
  1083. * parser.push(xhr.responseText);
  1084. * ```
  1085. *
  1086. * New input can later be applied to update the manifest object by calling
  1087. * `push` again.
  1088. *
  1089. * The parser attempts to create a usable manifest object even if the
  1090. * underlying input is somewhat nonsensical. It emits `info` and `warning`
  1091. * events during the parse if it encounters input that seems invalid or
  1092. * requires some property of the manifest object to be defaulted.
  1093. *
  1094. * @class Parser
  1095. * @extends Stream
  1096. */
  1097. var Parser = (function (_Stream) {
  1098. _inherits(Parser, _Stream);
  1099. function Parser() {
  1100. _classCallCheck(this, Parser);
  1101. _get(Object.getPrototypeOf(Parser.prototype), 'constructor', this).call(this);
  1102. this.lineStream = new _lineStream2['default']();
  1103. this.parseStream = new _parseStream2['default']();
  1104. this.lineStream.pipe(this.parseStream);
  1105. /* eslint-disable consistent-this */
  1106. var self = this;
  1107. /* eslint-enable consistent-this */
  1108. var uris = [];
  1109. var currentUri = {};
  1110. var _key = undefined;
  1111. var noop = function noop() {};
  1112. var defaultMediaGroups = {
  1113. 'AUDIO': {},
  1114. 'VIDEO': {},
  1115. 'CLOSED-CAPTIONS': {},
  1116. 'SUBTITLES': {}
  1117. };
  1118. // group segments into numbered timelines delineated by discontinuities
  1119. var currentTimeline = 0;
  1120. // the manifest is empty until the parse stream begins delivering data
  1121. this.manifest = {
  1122. allowCache: true,
  1123. discontinuityStarts: []
  1124. };
  1125. // update the manifest with the m3u8 entry from the parse stream
  1126. this.parseStream.on('data', function (entry) {
  1127. var mediaGroup = undefined;
  1128. var rendition = undefined;
  1129. ({
  1130. tag: function tag() {
  1131. // switch based on the tag type
  1132. (({
  1133. 'allow-cache': function allowCache() {
  1134. this.manifest.allowCache = entry.allowed;
  1135. if (!('allowed' in entry)) {
  1136. this.trigger('info', {
  1137. message: 'defaulting allowCache to YES'
  1138. });
  1139. this.manifest.allowCache = true;
  1140. }
  1141. },
  1142. byterange: function byterange() {
  1143. var byterange = {};
  1144. if ('length' in entry) {
  1145. currentUri.byterange = byterange;
  1146. byterange.length = entry.length;
  1147. if (!('offset' in entry)) {
  1148. this.trigger('info', {
  1149. message: 'defaulting offset to zero'
  1150. });
  1151. entry.offset = 0;
  1152. }
  1153. }
  1154. if ('offset' in entry) {
  1155. currentUri.byterange = byterange;
  1156. byterange.offset = entry.offset;
  1157. }
  1158. },
  1159. endlist: function endlist() {
  1160. this.manifest.endList = true;
  1161. },
  1162. inf: function inf() {
  1163. if (!('mediaSequence' in this.manifest)) {
  1164. this.manifest.mediaSequence = 0;
  1165. this.trigger('info', {
  1166. message: 'defaulting media sequence to zero'
  1167. });
  1168. }
  1169. if (!('discontinuitySequence' in this.manifest)) {
  1170. this.manifest.discontinuitySequence = 0;
  1171. this.trigger('info', {
  1172. message: 'defaulting discontinuity sequence to zero'
  1173. });
  1174. }
  1175. if (entry.duration >= 0) {
  1176. currentUri.duration = entry.duration;
  1177. }
  1178. this.manifest.segments = uris;
  1179. },
  1180. key: function key() {
  1181. if (!entry.attributes) {
  1182. this.trigger('warn', {
  1183. message: 'ignoring key declaration without attribute list'
  1184. });
  1185. return;
  1186. }
  1187. // clear the active encryption key
  1188. if (entry.attributes.METHOD === 'NONE') {
  1189. _key = null;
  1190. return;
  1191. }
  1192. if (!entry.attributes.URI) {
  1193. this.trigger('warn', {
  1194. message: 'ignoring key declaration without URI'
  1195. });
  1196. return;
  1197. }
  1198. if (!entry.attributes.METHOD) {
  1199. this.trigger('warn', {
  1200. message: 'defaulting key method to AES-128'
  1201. });
  1202. }
  1203. // setup an encryption key for upcoming segments
  1204. _key = {
  1205. method: entry.attributes.METHOD || 'AES-128',
  1206. uri: entry.attributes.URI
  1207. };
  1208. if (typeof entry.attributes.IV !== 'undefined') {
  1209. _key.iv = entry.attributes.IV;
  1210. }
  1211. },
  1212. 'media-sequence': function mediaSequence() {
  1213. if (!isFinite(entry.number)) {
  1214. this.trigger('warn', {
  1215. message: 'ignoring invalid media sequence: ' + entry.number
  1216. });
  1217. return;
  1218. }
  1219. this.manifest.mediaSequence = entry.number;
  1220. },
  1221. 'discontinuity-sequence': function discontinuitySequence() {
  1222. if (!isFinite(entry.number)) {
  1223. this.trigger('warn', {
  1224. message: 'ignoring invalid discontinuity sequence: ' + entry.number
  1225. });
  1226. return;
  1227. }
  1228. this.manifest.discontinuitySequence = entry.number;
  1229. currentTimeline = entry.number;
  1230. },
  1231. 'playlist-type': function playlistType() {
  1232. if (!/VOD|EVENT/.test(entry.playlistType)) {
  1233. this.trigger('warn', {
  1234. message: 'ignoring unknown playlist type: ' + entry.playlist
  1235. });
  1236. return;
  1237. }
  1238. this.manifest.playlistType = entry.playlistType;
  1239. },
  1240. 'stream-inf': function streamInf() {
  1241. this.manifest.playlists = uris;
  1242. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  1243. if (!entry.attributes) {
  1244. this.trigger('warn', {
  1245. message: 'ignoring empty stream-inf attributes'
  1246. });
  1247. return;
  1248. }
  1249. if (!currentUri.attributes) {
  1250. currentUri.attributes = {};
  1251. }
  1252. currentUri.attributes = (0, _videoJs.mergeOptions)(currentUri.attributes, entry.attributes);
  1253. },
  1254. media: function media() {
  1255. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  1256. if (!(entry.attributes && entry.attributes.TYPE && entry.attributes['GROUP-ID'] && entry.attributes.NAME)) {
  1257. this.trigger('warn', {
  1258. message: 'ignoring incomplete or missing media group'
  1259. });
  1260. return;
  1261. }
  1262. // find the media group, creating defaults as necessary
  1263. var mediaGroupType = this.manifest.mediaGroups[entry.attributes.TYPE];
  1264. mediaGroupType[entry.attributes['GROUP-ID']] = mediaGroupType[entry.attributes['GROUP-ID']] || {};
  1265. mediaGroup = mediaGroupType[entry.attributes['GROUP-ID']];
  1266. // collect the rendition metadata
  1267. rendition = {
  1268. 'default': /yes/i.test(entry.attributes.DEFAULT)
  1269. };
  1270. if (rendition['default']) {
  1271. rendition.autoselect = true;
  1272. } else {
  1273. rendition.autoselect = /yes/i.test(entry.attributes.AUTOSELECT);
  1274. }
  1275. if (entry.attributes.LANGUAGE) {
  1276. rendition.language = entry.attributes.LANGUAGE;
  1277. }
  1278. if (entry.attributes.URI) {
  1279. rendition.uri = entry.attributes.URI;
  1280. }
  1281. // insert the new rendition
  1282. mediaGroup[entry.attributes.NAME] = rendition;
  1283. },
  1284. discontinuity: function discontinuity() {
  1285. currentTimeline += 1;
  1286. currentUri.discontinuity = true;
  1287. this.manifest.discontinuityStarts.push(uris.length);
  1288. },
  1289. targetduration: function targetduration() {
  1290. if (!isFinite(entry.duration) || entry.duration < 0) {
  1291. this.trigger('warn', {
  1292. message: 'ignoring invalid target duration: ' + entry.duration
  1293. });
  1294. return;
  1295. }
  1296. this.manifest.targetDuration = entry.duration;
  1297. },
  1298. totalduration: function totalduration() {
  1299. if (!isFinite(entry.duration) || entry.duration < 0) {
  1300. this.trigger('warn', {
  1301. message: 'ignoring invalid total duration: ' + entry.duration
  1302. });
  1303. return;
  1304. }
  1305. this.manifest.totalDuration = entry.duration;
  1306. }
  1307. })[entry.tagType] || noop).call(self);
  1308. },
  1309. uri: function uri() {
  1310. currentUri.uri = entry.uri;
  1311. uris.push(currentUri);
  1312. // if no explicit duration was declared, use the target duration
  1313. if (this.manifest.targetDuration && !('duration' in currentUri)) {
  1314. this.trigger('warn', {
  1315. message: 'defaulting segment duration to the target duration'
  1316. });
  1317. currentUri.duration = this.manifest.targetDuration;
  1318. }
  1319. // annotate with encryption information, if necessary
  1320. if (_key) {
  1321. currentUri.key = _key;
  1322. }
  1323. currentUri.timeline = currentTimeline;
  1324. // prepare for the next URI
  1325. currentUri = {};
  1326. },
  1327. comment: function comment() {
  1328. // comments are not important for playback
  1329. }
  1330. })[entry.type].call(self);
  1331. });
  1332. }
  1333. /**
  1334. * Parse the input string and update the manifest object.
  1335. *
  1336. * @param {String} chunk a potentially incomplete portion of the manifest
  1337. */
  1338. _createClass(Parser, [{
  1339. key: 'push',
  1340. value: function push(chunk) {
  1341. this.lineStream.push(chunk);
  1342. }
  1343. /**
  1344. * Flush any remaining input. This can be handy if the last line of an M3U8
  1345. * manifest did not contain a trailing newline but the file has been
  1346. * completely received.
  1347. */
  1348. }, {
  1349. key: 'end',
  1350. value: function end() {
  1351. // flush any buffered input
  1352. this.lineStream.push('\n');
  1353. }
  1354. }]);
  1355. return Parser;
  1356. })(_stream2['default']);
  1357. exports['default'] = Parser;
  1358. module.exports = exports['default'];
  1359. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1360. },{"../stream":18,"./line-stream":8,"./parse-stream":9}],11:[function(require,module,exports){
  1361. (function (global){
  1362. /**
  1363. * @file master-playlist-controller.js
  1364. */
  1365. 'use strict';
  1366. Object.defineProperty(exports, '__esModule', {
  1367. value: true
  1368. });
  1369. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  1370. var _get = function get(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x2 = parent; _x3 = property; _x4 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  1371. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  1372. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  1373. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  1374. var _playlistLoader = require('./playlist-loader');
  1375. var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
  1376. var _segmentLoader = require('./segment-loader');
  1377. var _segmentLoader2 = _interopRequireDefault(_segmentLoader);
  1378. var _ranges = require('./ranges');
  1379. var _ranges2 = _interopRequireDefault(_ranges);
  1380. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  1381. var _videoJs2 = _interopRequireDefault(_videoJs);
  1382. var _hlsAudioTrack = require('./hls-audio-track');
  1383. var _hlsAudioTrack2 = _interopRequireDefault(_hlsAudioTrack);
  1384. // 5 minute blacklist
  1385. var BLACKLIST_DURATION = 5 * 60 * 1000;
  1386. var Hls = undefined;
  1387. var parseCodecs = function parseCodecs(codecs) {
  1388. var result = {
  1389. codecCount: 0,
  1390. videoCodec: null,
  1391. audioProfile: null
  1392. };
  1393. result.codecCount = codecs.split(',').length;
  1394. result.codecCount = result.codecCount || 2;
  1395. // parse the video codec but ignore the version
  1396. result.videoCodec = /(^|\s|,)+(avc1)[^ ,]*/i.exec(codecs);
  1397. result.videoCodec = result.videoCodec && result.videoCodec[2];
  1398. // parse the last field of the audio codec
  1399. result.audioProfile = /(^|\s|,)+mp4a.\d+\.(\d+)/i.exec(codecs);
  1400. result.audioProfile = result.audioProfile && result.audioProfile[2];
  1401. return result;
  1402. };
  1403. /**
  1404. * the master playlist controller controller all interactons
  1405. * between playlists and segmentloaders. At this time this mainly
  1406. * involves a master playlist and a series of audio playlists
  1407. * if they are available
  1408. *
  1409. * @class MasterPlaylistController
  1410. * @extends videojs.EventTarget
  1411. */
  1412. var MasterPlaylistController = (function (_videojs$EventTarget) {
  1413. _inherits(MasterPlaylistController, _videojs$EventTarget);
  1414. function MasterPlaylistController(_ref) {
  1415. var _this = this;
  1416. var url = _ref.url;
  1417. var withCredentials = _ref.withCredentials;
  1418. var mode = _ref.mode;
  1419. var tech = _ref.tech;
  1420. var bandwidth = _ref.bandwidth;
  1421. var externHls = _ref.externHls;
  1422. _classCallCheck(this, MasterPlaylistController);
  1423. _get(Object.getPrototypeOf(MasterPlaylistController.prototype), 'constructor', this).call(this);
  1424. Hls = externHls;
  1425. this.withCredentials = withCredentials;
  1426. this.tech_ = tech;
  1427. this.hls_ = tech.hls;
  1428. this.mode_ = mode;
  1429. this.audioTracks_ = [];
  1430. this.mediaSource = new _videoJs2['default'].MediaSource({ mode: mode });
  1431. this.mediaSource.on('audioinfo', function (e) {
  1432. return _this.trigger(e);
  1433. });
  1434. // load the media source into the player
  1435. this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen_.bind(this));
  1436. var segmentLoaderOptions = {
  1437. hls: this.hls_,
  1438. mediaSource: this.mediaSource,
  1439. currentTime: this.tech_.currentTime.bind(this.tech_),
  1440. withCredentials: this.withCredentials,
  1441. seekable: function seekable() {
  1442. return _this.seekable();
  1443. },
  1444. seeking: function seeking() {
  1445. return _this.tech_.seeking();
  1446. },
  1447. setCurrentTime: function setCurrentTime(a) {
  1448. return _this.setCurrentTime(a);
  1449. },
  1450. hasPlayed: function hasPlayed() {
  1451. return _this.tech_.played().length !== 0;
  1452. },
  1453. bandwidth: bandwidth
  1454. };
  1455. // combined audio/video or just video when alternate audio track is selected
  1456. this.mainSegmentLoader_ = new _segmentLoader2['default'](segmentLoaderOptions);
  1457. // alternate audio track
  1458. this.audioSegmentLoader_ = new _segmentLoader2['default'](segmentLoaderOptions);
  1459. if (!url) {
  1460. throw new Error('A non-empty playlist URL is required');
  1461. }
  1462. this.masterPlaylistLoader_ = new _playlistLoader2['default'](url, this.hls_, this.withCredentials);
  1463. this.masterPlaylistLoader_.on('loadedmetadata', function () {
  1464. var media = _this.masterPlaylistLoader_.media();
  1465. // if this isn't a live video and preload permits, start
  1466. // downloading segments
  1467. if (media.endList && _this.tech_.preload() !== 'none') {
  1468. _this.mainSegmentLoader_.playlist(media);
  1469. _this.mainSegmentLoader_.expired(_this.masterPlaylistLoader_.expired_);
  1470. _this.mainSegmentLoader_.load();
  1471. }
  1472. _this.setupSourceBuffer_();
  1473. _this.setupFirstPlay();
  1474. _this.useAudio();
  1475. });
  1476. this.masterPlaylistLoader_.on('loadedplaylist', function () {
  1477. var updatedPlaylist = _this.masterPlaylistLoader_.media();
  1478. var seekable = undefined;
  1479. if (!updatedPlaylist) {
  1480. // select the initial variant
  1481. _this.initialMedia_ = _this.selectPlaylist();
  1482. _this.masterPlaylistLoader_.media(_this.initialMedia_);
  1483. _this.fillAudioTracks_();
  1484. _this.trigger('selectedinitialmedia');
  1485. return;
  1486. }
  1487. _this.mainSegmentLoader_.playlist(updatedPlaylist);
  1488. _this.mainSegmentLoader_.expired(_this.masterPlaylistLoader_.expired_);
  1489. _this.updateDuration();
  1490. // update seekable
  1491. seekable = _this.seekable();
  1492. if (!updatedPlaylist.endList && seekable.length !== 0) {
  1493. _this.mediaSource.addSeekableRange_(seekable.start(0), seekable.end(0));
  1494. }
  1495. });
  1496. this.masterPlaylistLoader_.on('error', function () {
  1497. _this.blacklistCurrentPlaylist(_this.masterPlaylistLoader_.error);
  1498. });
  1499. this.masterPlaylistLoader_.on('mediachanging', function () {
  1500. _this.mainSegmentLoader_.pause();
  1501. });
  1502. this.masterPlaylistLoader_.on('mediachange', function () {
  1503. _this.mainSegmentLoader_.abort();
  1504. _this.mainSegmentLoader_.load();
  1505. _this.tech_.trigger({
  1506. type: 'mediachange',
  1507. bubbles: true
  1508. });
  1509. });
  1510. this.mainSegmentLoader_.on('progress', function () {
  1511. // figure out what stream the next segment should be downloaded from
  1512. // with the updated bandwidth information
  1513. _this.masterPlaylistLoader_.media(_this.selectPlaylist());
  1514. _this.trigger('progress');
  1515. });
  1516. this.mainSegmentLoader_.on('error', function () {
  1517. _this.blacklistCurrentPlaylist(_this.mainSegmentLoader_.error());
  1518. });
  1519. this.audioSegmentLoader_.on('error', function () {
  1520. _videoJs2['default'].log.warn('Problem encountered with the current alternate audio track' + '. Switching back to default.');
  1521. _this.audioSegmentLoader_.abort();
  1522. _this.audioPlaylistLoader_ = null;
  1523. _this.useAudio();
  1524. });
  1525. this.masterPlaylistLoader_.load();
  1526. }
  1527. /**
  1528. * fill our internal list of HlsAudioTracks with data from
  1529. * the master playlist or use a default
  1530. *
  1531. * @private
  1532. */
  1533. _createClass(MasterPlaylistController, [{
  1534. key: 'fillAudioTracks_',
  1535. value: function fillAudioTracks_() {
  1536. var master = this.master();
  1537. var mediaGroups = master.mediaGroups || {};
  1538. // force a default if we have none or we are not
  1539. // in html5 mode (the only mode to support more than one
  1540. // audio track)
  1541. if (!mediaGroups || !mediaGroups.AUDIO || Object.keys(mediaGroups.AUDIO).length === 0 || this.mode_ !== 'html5') {
  1542. // "main" audio group, track name "default"
  1543. mediaGroups.AUDIO = { main: { 'default': { 'default': true } } };
  1544. }
  1545. var tracks = {};
  1546. for (var mediaGroup in mediaGroups.AUDIO) {
  1547. for (var label in mediaGroups.AUDIO[mediaGroup]) {
  1548. var properties = mediaGroups.AUDIO[mediaGroup][label];
  1549. // if the track already exists add a new "location"
  1550. // since tracks in different mediaGroups are actually the same
  1551. // track with different locations to download them from
  1552. if (tracks[label]) {
  1553. tracks[label].addLoader(mediaGroup, properties.resolvedUri);
  1554. continue;
  1555. }
  1556. var track = new _hlsAudioTrack2['default'](_videoJs2['default'].mergeOptions(properties, {
  1557. hls: this.hls_,
  1558. withCredentials: this.withCredential,
  1559. mediaGroup: mediaGroup,
  1560. label: label
  1561. }));
  1562. tracks[label] = track;
  1563. this.audioTracks_.push(track);
  1564. }
  1565. }
  1566. }
  1567. /**
  1568. * Call load on our SegmentLoaders
  1569. */
  1570. }, {
  1571. key: 'load',
  1572. value: function load() {
  1573. this.mainSegmentLoader_.load();
  1574. if (this.audioPlaylistLoader_) {
  1575. this.audioSegmentLoader_.load();
  1576. }
  1577. }
  1578. /**
  1579. * Get the current active Media Group for Audio
  1580. * given the selected playlist and its attributes
  1581. */
  1582. }, {
  1583. key: 'activeAudioGroup',
  1584. value: function activeAudioGroup() {
  1585. var media = this.masterPlaylistLoader_.media();
  1586. var mediaGroup = 'main';
  1587. if (media && media.attributes && media.attributes.AUDIO) {
  1588. mediaGroup = media.attributes.AUDIO;
  1589. }
  1590. return mediaGroup;
  1591. }
  1592. /**
  1593. * Use any audio track that we have, and start to load it
  1594. */
  1595. }, {
  1596. key: 'useAudio',
  1597. value: function useAudio() {
  1598. var _this2 = this;
  1599. var track = undefined;
  1600. this.audioTracks_.forEach(function (t) {
  1601. if (!track && t.enabled) {
  1602. track = t;
  1603. }
  1604. });
  1605. // called too early or no track is enabled
  1606. if (!track) {
  1607. return;
  1608. }
  1609. // Pause any alternative audio
  1610. if (this.audioPlaylistLoader_) {
  1611. this.audioPlaylistLoader_.pause();
  1612. this.audioPlaylistLoader_ = null;
  1613. this.audioSegmentLoader_.pause();
  1614. }
  1615. // If the audio track for the active audio group has
  1616. // a playlist loader than it is an alterative audio track
  1617. // otherwise it is a part of the mainSegmenLoader
  1618. var loader = track.getLoader(this.activeAudioGroup());
  1619. if (!loader) {
  1620. this.mainSegmentLoader_.clearBuffer();
  1621. return;
  1622. }
  1623. // TODO: it may be better to create the playlist loader here
  1624. // when we can change an audioPlaylistLoaders src
  1625. this.audioPlaylistLoader_ = loader;
  1626. if (this.audioPlaylistLoader_.started) {
  1627. this.audioPlaylistLoader_.load();
  1628. this.audioSegmentLoader_.load();
  1629. this.audioSegmentLoader_.clearBuffer();
  1630. return;
  1631. }
  1632. this.audioPlaylistLoader_.on('loadedmetadata', function () {
  1633. /* eslint-disable no-shadow */
  1634. var media = _this2.audioPlaylistLoader_.media();
  1635. /* eslint-enable no-shadow */
  1636. _this2.audioSegmentLoader_.playlist(media);
  1637. _this2.addMimeType_(_this2.audioSegmentLoader_, 'mp4a.40.2', media);
  1638. // if the video is already playing, or if this isn't a live video and preload
  1639. // permits, start downloading segments
  1640. if (!_this2.tech_.paused() || media.endList && _this2.tech_.preload() !== 'none') {
  1641. _this2.audioSegmentLoader_.load();
  1642. }
  1643. if (!media.endList) {
  1644. // trigger the playlist loader to start "expired time"-tracking
  1645. _this2.audioPlaylistLoader_.trigger('firstplay');
  1646. }
  1647. });
  1648. this.audioPlaylistLoader_.on('loadedplaylist', function () {
  1649. var updatedPlaylist = undefined;
  1650. if (_this2.audioPlaylistLoader_) {
  1651. updatedPlaylist = _this2.audioPlaylistLoader_.media();
  1652. }
  1653. if (!updatedPlaylist) {
  1654. // only one playlist to select
  1655. _this2.audioPlaylistLoader_.media(_this2.audioPlaylistLoader_.playlists.master.playlists[0]);
  1656. return;
  1657. }
  1658. _this2.audioSegmentLoader_.playlist(updatedPlaylist);
  1659. });
  1660. this.audioPlaylistLoader_.on('error', function () {
  1661. _videoJs2['default'].log.warn('Problem encountered loading the alternate audio track' + '. Switching back to default.');
  1662. _this2.audioSegmentLoader_.abort();
  1663. _this2.audioPlaylistLoader_ = null;
  1664. _this2.useAudio();
  1665. });
  1666. this.audioSegmentLoader_.clearBuffer();
  1667. this.audioPlaylistLoader_.start();
  1668. }
  1669. /**
  1670. * Re-tune playback quality level for the current player
  1671. * conditions. This method may perform destructive actions, like
  1672. * removing already buffered content, to readjust the currently
  1673. * active playlist quickly.
  1674. *
  1675. * @private
  1676. */
  1677. }, {
  1678. key: 'fastQualityChange_',
  1679. value: function fastQualityChange_() {
  1680. var media = this.selectPlaylist();
  1681. if (media !== this.masterPlaylistLoader_.media()) {
  1682. this.masterPlaylistLoader_.media(media);
  1683. this.mainSegmentLoader_.sourceUpdater_.remove(this.tech_.currentTime() + 5, Infinity);
  1684. }
  1685. }
  1686. /**
  1687. * Begin playback.
  1688. */
  1689. }, {
  1690. key: 'play',
  1691. value: function play() {
  1692. if (this.setupFirstPlay()) {
  1693. return;
  1694. }
  1695. if (this.tech_.ended()) {
  1696. this.tech_.setCurrentTime(0);
  1697. }
  1698. this.load();
  1699. // if the viewer has paused and we fell out of the live window,
  1700. // seek forward to the earliest available position
  1701. if (this.tech_.duration() === Infinity) {
  1702. if (this.tech_.currentTime() < this.tech_.seekable().start(0)) {
  1703. return this.tech_.setCurrentTime(this.tech_.seekable().start(0));
  1704. }
  1705. }
  1706. }
  1707. /**
  1708. * Seek to the latest media position if this is a live video and the
  1709. * player and video are loaded and initialized.
  1710. */
  1711. }, {
  1712. key: 'setupFirstPlay',
  1713. value: function setupFirstPlay() {
  1714. var seekable = undefined;
  1715. var media = this.masterPlaylistLoader_.media();
  1716. // check that everything is ready to begin buffering
  1717. // 1) the active media playlist is available
  1718. if (media &&
  1719. // 2) the video is a live stream
  1720. !media.endList &&
  1721. // 3) the player is not paused
  1722. !this.tech_.paused() &&
  1723. // 4) the player has not started playing
  1724. !this.hasPlayed_) {
  1725. this.load();
  1726. // trigger the playlist loader to start "expired time"-tracking
  1727. this.masterPlaylistLoader_.trigger('firstplay');
  1728. this.hasPlayed_ = true;
  1729. // seek to the latest media position for live videos
  1730. seekable = this.seekable();
  1731. if (seekable.length) {
  1732. this.tech_.setCurrentTime(seekable.end(0));
  1733. }
  1734. return true;
  1735. }
  1736. return false;
  1737. }
  1738. /**
  1739. * handle the sourceopen event on the MediaSource
  1740. *
  1741. * @private
  1742. */
  1743. }, {
  1744. key: 'handleSourceOpen_',
  1745. value: function handleSourceOpen_() {
  1746. // Only attempt to create the source buffer if none already exist.
  1747. // handleSourceOpen is also called when we are "re-opening" a source buffer
  1748. // after `endOfStream` has been called (in response to a seek for instance)
  1749. this.setupSourceBuffer_();
  1750. // if autoplay is enabled, begin playback. This is duplicative of
  1751. // code in video.js but is required because play() must be invoked
  1752. // *after* the media source has opened.
  1753. if (this.tech_.autoplay()) {
  1754. this.tech_.play();
  1755. }
  1756. this.trigger('sourceopen');
  1757. }
  1758. /**
  1759. * Blacklists a playlist when an error occurs for a set amount of time
  1760. * making it unavailable for selection by the rendition selection algorithm
  1761. * and then forces a new playlist (rendition) selection.
  1762. *
  1763. * @param {Object=} error an optional error that may include the playlist
  1764. * to blacklist
  1765. */
  1766. }, {
  1767. key: 'blacklistCurrentPlaylist',
  1768. value: function blacklistCurrentPlaylist() {
  1769. var error = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  1770. var currentPlaylist = undefined;
  1771. var nextPlaylist = undefined;
  1772. // If the `error` was generated by the playlist loader, it will contain
  1773. // the playlist we were trying to load (but failed) and that should be
  1774. // blacklisted instead of the currently selected playlist which is likely
  1775. // out-of-date in this scenario
  1776. currentPlaylist = error.playlist || this.masterPlaylistLoader_.media();
  1777. // If there is no current playlist, then an error occurred while we were
  1778. // trying to load the master OR while we were disposing of the tech
  1779. if (!currentPlaylist) {
  1780. this.error = error;
  1781. return this.mediaSource.endOfStream('network');
  1782. }
  1783. // Blacklist this playlist
  1784. currentPlaylist.excludeUntil = Date.now() + BLACKLIST_DURATION;
  1785. // Select a new playlist
  1786. nextPlaylist = this.selectPlaylist();
  1787. if (nextPlaylist) {
  1788. _videoJs2['default'].log.warn('Problem encountered with the current ' + 'HLS playlist. Switching to another playlist.');
  1789. return this.masterPlaylistLoader_.media(nextPlaylist);
  1790. }
  1791. _videoJs2['default'].log.warn('Problem encountered with the current ' + 'HLS playlist. No suitable alternatives found.');
  1792. // We have no more playlists we can select so we must fail
  1793. this.error = error;
  1794. return this.mediaSource.endOfStream('network');
  1795. }
  1796. /**
  1797. * Pause all segment loaders
  1798. */
  1799. }, {
  1800. key: 'pauseLoading',
  1801. value: function pauseLoading() {
  1802. this.mainSegmentLoader_.pause();
  1803. if (this.audioPlaylistLoader_) {
  1804. this.audioSegmentLoader_.pause();
  1805. }
  1806. }
  1807. /**
  1808. * set the current time on all segment loaders
  1809. *
  1810. * @param {TimeRange} currentTime the current time to set
  1811. * @return {TimeRange} the current time
  1812. */
  1813. }, {
  1814. key: 'setCurrentTime',
  1815. value: function setCurrentTime(currentTime) {
  1816. var buffered = _ranges2['default'].findRange(this.tech_.buffered(), currentTime);
  1817. if (!(this.masterPlaylistLoader_ && this.masterPlaylistLoader_.media())) {
  1818. // return immediately if the metadata is not ready yet
  1819. return 0;
  1820. }
  1821. // it's clearly an edge-case but don't thrown an error if asked to
  1822. // seek within an empty playlist
  1823. if (!this.masterPlaylistLoader_.media().segments) {
  1824. return 0;
  1825. }
  1826. // if the seek location is already buffered, continue buffering as
  1827. // usual
  1828. if (buffered && buffered.length) {
  1829. return currentTime;
  1830. }
  1831. // cancel outstanding requests so we begin buffering at the new
  1832. // location
  1833. this.mainSegmentLoader_.abort();
  1834. if (this.audioPlaylistLoader_) {
  1835. this.audioSegmentLoader_.abort();
  1836. }
  1837. if (!this.tech_.paused()) {
  1838. this.mainSegmentLoader_.load();
  1839. if (this.audioPlaylistLoader_) {
  1840. this.audioSegmentLoader_.load();
  1841. }
  1842. }
  1843. }
  1844. /**
  1845. * get the current duration
  1846. *
  1847. * @return {TimeRange} the duration
  1848. */
  1849. }, {
  1850. key: 'duration',
  1851. value: function duration() {
  1852. if (!this.masterPlaylistLoader_) {
  1853. return 0;
  1854. }
  1855. if (this.mediaSource) {
  1856. return this.mediaSource.duration;
  1857. }
  1858. return Hls.Playlist.duration(this.masterPlaylistLoader_.media());
  1859. }
  1860. /**
  1861. * check the seekable range
  1862. *
  1863. * @return {TimeRange} the seekable range
  1864. */
  1865. }, {
  1866. key: 'seekable',
  1867. value: function seekable() {
  1868. var media = undefined;
  1869. var mainSeekable = undefined;
  1870. var audioSeekable = undefined;
  1871. if (!this.masterPlaylistLoader_) {
  1872. return _videoJs2['default'].createTimeRanges();
  1873. }
  1874. media = this.masterPlaylistLoader_.media();
  1875. if (!media) {
  1876. return _videoJs2['default'].createTimeRanges();
  1877. }
  1878. mainSeekable = Hls.Playlist.seekable(media, this.masterPlaylistLoader_.expired_);
  1879. if (mainSeekable.length === 0) {
  1880. return mainSeekable;
  1881. }
  1882. if (this.audioPlaylistLoader_) {
  1883. audioSeekable = Hls.Playlist.seekable(this.audioPlaylistLoader_.media(), this.audioPlaylistLoader_.expired_);
  1884. if (audioSeekable.length === 0) {
  1885. return audioSeekable;
  1886. }
  1887. }
  1888. if (!audioSeekable) {
  1889. // seekable has been calculated based on buffering video data so it
  1890. // can be returned directly
  1891. return mainSeekable;
  1892. }
  1893. return _videoJs2['default'].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)]]);
  1894. }
  1895. /**
  1896. * Update the player duration
  1897. */
  1898. }, {
  1899. key: 'updateDuration',
  1900. value: function updateDuration() {
  1901. var _this3 = this;
  1902. var oldDuration = this.mediaSource.duration;
  1903. var newDuration = Hls.Playlist.duration(this.masterPlaylistLoader_.media());
  1904. var buffered = this.tech_.buffered();
  1905. var setDuration = function setDuration() {
  1906. _this3.mediaSource.duration = newDuration;
  1907. _this3.tech_.trigger('durationchange');
  1908. _this3.mediaSource.removeEventListener('sourceopen', setDuration);
  1909. };
  1910. if (buffered.length > 0) {
  1911. newDuration = Math.max(newDuration, buffered.end(buffered.length - 1));
  1912. }
  1913. // if the duration has changed, invalidate the cached value
  1914. if (oldDuration !== newDuration) {
  1915. // update the duration
  1916. if (this.mediaSource.readyState !== 'open') {
  1917. this.mediaSource.addEventListener('sourceopen', setDuration);
  1918. } else {
  1919. setDuration();
  1920. }
  1921. }
  1922. }
  1923. /**
  1924. * dispose of the MasterPlaylistController and everything
  1925. * that it controls
  1926. */
  1927. }, {
  1928. key: 'dispose',
  1929. value: function dispose() {
  1930. this.masterPlaylistLoader_.dispose();
  1931. this.audioTracks_.forEach(function (track) {
  1932. track.dispose();
  1933. });
  1934. this.audioTracks_.length = 0;
  1935. this.mainSegmentLoader_.dispose();
  1936. this.audioSegmentLoader_.dispose();
  1937. }
  1938. /**
  1939. * return the master playlist object if we have one
  1940. *
  1941. * @return {Object} the master playlist object that we parsed
  1942. */
  1943. }, {
  1944. key: 'master',
  1945. value: function master() {
  1946. return this.masterPlaylistLoader_.master;
  1947. }
  1948. /**
  1949. * return the currently selected playlist
  1950. *
  1951. * @return {Object} the currently selected playlist object that we parsed
  1952. */
  1953. }, {
  1954. key: 'media',
  1955. value: function media() {
  1956. // playlist loader will not return media if it has not been fully loaded
  1957. return this.masterPlaylistLoader_.media() || this.initialMedia_;
  1958. }
  1959. /**
  1960. * setup our internal source buffers on our segment Loaders
  1961. *
  1962. * @private
  1963. */
  1964. }, {
  1965. key: 'setupSourceBuffer_',
  1966. value: function setupSourceBuffer_() {
  1967. var media = this.masterPlaylistLoader_.media();
  1968. // wait until a media playlist is available and the Media Source is
  1969. // attached
  1970. if (!media || this.mediaSource.readyState !== 'open') {
  1971. return;
  1972. }
  1973. this.addMimeType_(this.mainSegmentLoader_, 'avc1.4d400d, mp4a.40.2', media);
  1974. // exclude any incompatible variant streams from future playlist
  1975. // selection
  1976. this.excludeIncompatibleVariants_(media);
  1977. }
  1978. /**
  1979. * add a time type to a segmentLoader
  1980. *
  1981. * @param {SegmentLoader} segmentLoader the segmentloader to work on
  1982. * @param {String} codecs to use by default
  1983. * @param {Object} the parsed media object
  1984. * @private
  1985. */
  1986. }, {
  1987. key: 'addMimeType_',
  1988. value: function addMimeType_(segmentLoader, defaultCodecs, media) {
  1989. var mimeType = 'video/mp2t';
  1990. // if the codecs were explicitly specified, pass them along to the
  1991. // source buffer
  1992. if (media.attributes && media.attributes.CODECS) {
  1993. mimeType += '; codecs="' + media.attributes.CODECS + '"';
  1994. } else {
  1995. mimeType += '; codecs="' + defaultCodecs + '"';
  1996. }
  1997. segmentLoader.mimeType(mimeType);
  1998. }
  1999. /**
  2000. * Blacklist playlists that are known to be codec or
  2001. * stream-incompatible with the SourceBuffer configuration. For
  2002. * instance, Media Source Extensions would cause the video element to
  2003. * stall waiting for video data if you switched from a variant with
  2004. * video and audio to an audio-only one.
  2005. *
  2006. * @param {Object} media a media playlist compatible with the current
  2007. * set of SourceBuffers. Variants in the current master playlist that
  2008. * do not appear to have compatible codec or stream configurations
  2009. * will be excluded from the default playlist selection algorithm
  2010. * indefinitely.
  2011. * @private
  2012. */
  2013. }, {
  2014. key: 'excludeIncompatibleVariants_',
  2015. value: function excludeIncompatibleVariants_(media) {
  2016. var master = this.masterPlaylistLoader_.master;
  2017. var codecCount = 2;
  2018. var videoCodec = null;
  2019. var audioProfile = null;
  2020. var codecs = undefined;
  2021. if (media.attributes && media.attributes.CODECS) {
  2022. codecs = parseCodecs(media.attributes.CODECS);
  2023. videoCodec = codecs.videoCodec;
  2024. audioProfile = codecs.audioProfile;
  2025. codecCount = codecs.codecCount;
  2026. }
  2027. master.playlists.forEach(function (variant) {
  2028. var variantCodecs = {
  2029. codecCount: 2,
  2030. videoCodec: null,
  2031. audioProfile: null
  2032. };
  2033. if (variant.attributes && variant.attributes.CODECS) {
  2034. variantCodecs = parseCodecs(variant.attributes.CODECS);
  2035. }
  2036. // if the streams differ in the presence or absence of audio or
  2037. // video, they are incompatible
  2038. if (variantCodecs.codecCount !== codecCount) {
  2039. variant.excludeUntil = Infinity;
  2040. }
  2041. // if h.264 is specified on the current playlist, some flavor of
  2042. // it must be specified on all compatible variants
  2043. if (variantCodecs.videoCodec !== videoCodec) {
  2044. variant.excludeUntil = Infinity;
  2045. }
  2046. // HE-AAC ("mp4a.40.5") is incompatible with all other versions of
  2047. // AAC audio in Chrome 46. Don't mix the two.
  2048. if (variantCodecs.audioProfile === '5' && audioProfile !== '5' || audioProfile === '5' && variantCodecs.audioProfile !== '5') {
  2049. variant.excludeUntil = Infinity;
  2050. }
  2051. });
  2052. }
  2053. }]);
  2054. return MasterPlaylistController;
  2055. })(_videoJs2['default'].EventTarget);
  2056. exports['default'] = MasterPlaylistController;
  2057. module.exports = exports['default'];
  2058. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2059. },{"./hls-audio-track":6,"./playlist-loader":12,"./ranges":14,"./segment-loader":16}],12:[function(require,module,exports){
  2060. (function (global){
  2061. /**
  2062. * @file playlist-loader.js
  2063. *
  2064. * A state machine that manages the loading, caching, and updating of
  2065. * M3U8 playlists.
  2066. *
  2067. */
  2068. 'use strict';
  2069. Object.defineProperty(exports, '__esModule', {
  2070. value: true
  2071. });
  2072. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  2073. var _resolveUrl = require('./resolve-url');
  2074. var _resolveUrl2 = _interopRequireDefault(_resolveUrl);
  2075. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  2076. var _stream = require('./stream');
  2077. var _stream2 = _interopRequireDefault(_stream);
  2078. var _m3u8 = require('./m3u8');
  2079. var _m3u82 = _interopRequireDefault(_m3u8);
  2080. /**
  2081. * Returns a new array of segments that is the result of merging
  2082. * properties from an older list of segments onto an updated
  2083. * list. No properties on the updated playlist will be overridden.
  2084. *
  2085. * @param {Array} original the outdated list of segments
  2086. * @param {Array} update the updated list of segments
  2087. * @param {Number=} offset the index of the first update
  2088. * segment in the original segment list. For non-live playlists,
  2089. * this should always be zero and does not need to be
  2090. * specified. For live playlists, it should be the difference
  2091. * between the media sequence numbers in the original and updated
  2092. * playlists.
  2093. * @return a list of merged segment objects
  2094. */
  2095. var updateSegments = function updateSegments(original, update, offset) {
  2096. var result = update.slice();
  2097. var length = undefined;
  2098. var i = undefined;
  2099. offset = offset || 0;
  2100. length = Math.min(original.length, update.length + offset);
  2101. for (i = offset; i < length; i++) {
  2102. result[i - offset] = (0, _videoJs.mergeOptions)(original[i], result[i - offset]);
  2103. }
  2104. return result;
  2105. };
  2106. /**
  2107. * Returns a new master playlist that is the result of merging an
  2108. * updated media playlist into the original version. If the
  2109. * updated media playlist does not match any of the playlist
  2110. * entries in the original master playlist, null is returned.
  2111. *
  2112. * @param {Object} master a parsed master M3U8 object
  2113. * @param {Object} media a parsed media M3U8 object
  2114. * @return {Object} a new object that represents the original
  2115. * master playlist with the updated media playlist merged in, or
  2116. * null if the merge produced no change.
  2117. */
  2118. var updateMaster = function updateMaster(master, media) {
  2119. var changed = false;
  2120. var result = (0, _videoJs.mergeOptions)(master, {});
  2121. var i = master.playlists.length;
  2122. var playlist = undefined;
  2123. var segment = undefined;
  2124. var j = undefined;
  2125. while (i--) {
  2126. playlist = result.playlists[i];
  2127. if (playlist.uri === media.uri) {
  2128. // consider the playlist unchanged if the number of segments
  2129. // are equal and the media sequence number is unchanged
  2130. if (playlist.segments && media.segments && playlist.segments.length === media.segments.length && playlist.mediaSequence === media.mediaSequence) {
  2131. continue;
  2132. }
  2133. result.playlists[i] = (0, _videoJs.mergeOptions)(playlist, media);
  2134. result.playlists[media.uri] = result.playlists[i];
  2135. // if the update could overlap existing segment information,
  2136. // merge the two lists
  2137. if (playlist.segments) {
  2138. result.playlists[i].segments = updateSegments(playlist.segments, media.segments, media.mediaSequence - playlist.mediaSequence);
  2139. }
  2140. // resolve any missing segment and key URIs
  2141. j = 0;
  2142. if (result.playlists[i].segments) {
  2143. j = result.playlists[i].segments.length;
  2144. }
  2145. while (j--) {
  2146. segment = result.playlists[i].segments[j];
  2147. if (!segment.resolvedUri) {
  2148. segment.resolvedUri = (0, _resolveUrl2['default'])(playlist.resolvedUri, segment.uri);
  2149. }
  2150. if (segment.key && !segment.key.resolvedUri) {
  2151. segment.key.resolvedUri = (0, _resolveUrl2['default'])(playlist.resolvedUri, segment.key.uri);
  2152. }
  2153. }
  2154. changed = true;
  2155. }
  2156. }
  2157. return changed ? result : null;
  2158. };
  2159. /**
  2160. * Load a playlist from a remote loacation
  2161. *
  2162. * @class PlaylistLoader
  2163. * @extends Stream
  2164. * @param {String} srcUrl the url to start with
  2165. * @param {Boolean} withCredentials the withCredentials xhr option
  2166. * @constructor
  2167. */
  2168. var PlaylistLoader = function PlaylistLoader(srcUrl, hls, withCredentials) {
  2169. var _this = this;
  2170. /* eslint-disable consistent-this */
  2171. var loader = this;
  2172. /* eslint-enable consistent-this */
  2173. var dispose = undefined;
  2174. var mediaUpdateTimeout = undefined;
  2175. var request = undefined;
  2176. var playlistRequestError = undefined;
  2177. var haveMetadata = undefined;
  2178. PlaylistLoader.prototype.constructor.call(this);
  2179. this.hls_ = hls;
  2180. // a flag that disables "expired time"-tracking this setting has
  2181. // no effect when not playing a live stream
  2182. this.trackExpiredTime_ = false;
  2183. if (!srcUrl) {
  2184. throw new Error('A non-empty playlist URL is required');
  2185. }
  2186. playlistRequestError = function (xhr, url, startingState) {
  2187. loader.setBandwidth(request || xhr);
  2188. // any in-flight request is now finished
  2189. request = null;
  2190. if (startingState) {
  2191. loader.state = startingState;
  2192. }
  2193. loader.error = {
  2194. playlist: loader.master.playlists[url],
  2195. status: xhr.status,
  2196. message: 'HLS playlist request error at URL: ' + url,
  2197. responseText: xhr.responseText,
  2198. code: xhr.status >= 500 ? 4 : 2
  2199. };
  2200. loader.trigger('error');
  2201. };
  2202. // update the playlist loader's state in response to a new or
  2203. // updated playlist.
  2204. haveMetadata = function (xhr, url) {
  2205. var parser = undefined;
  2206. var refreshDelay = undefined;
  2207. var update = undefined;
  2208. loader.setBandwidth(request || xhr);
  2209. // any in-flight request is now finished
  2210. request = null;
  2211. loader.state = 'HAVE_METADATA';
  2212. parser = new _m3u82['default'].Parser();
  2213. parser.push(xhr.responseText);
  2214. parser.end();
  2215. parser.manifest.uri = url;
  2216. // merge this playlist into the master
  2217. update = updateMaster(loader.master, parser.manifest);
  2218. refreshDelay = (parser.manifest.targetDuration || 10) * 1000;
  2219. if (update) {
  2220. loader.master = update;
  2221. loader.updateMediaPlaylist_(parser.manifest);
  2222. } else {
  2223. // if the playlist is unchanged since the last reload,
  2224. // try again after half the target duration
  2225. refreshDelay /= 2;
  2226. }
  2227. // refresh live playlists after a target duration passes
  2228. if (!loader.media().endList) {
  2229. window.clearTimeout(mediaUpdateTimeout);
  2230. mediaUpdateTimeout = window.setTimeout(function () {
  2231. loader.trigger('mediaupdatetimeout');
  2232. }, refreshDelay);
  2233. }
  2234. loader.trigger('loadedplaylist');
  2235. };
  2236. // initialize the loader state
  2237. loader.state = 'HAVE_NOTHING';
  2238. // track the time that has expired from the live window
  2239. // this allows the seekable start range to be calculated even if
  2240. // all segments with timing information have expired
  2241. this.expired_ = 0;
  2242. // capture the prototype dispose function
  2243. dispose = this.dispose;
  2244. /**
  2245. * Abort any outstanding work and clean up.
  2246. */
  2247. loader.dispose = function () {
  2248. loader.stopRequest();
  2249. window.clearTimeout(mediaUpdateTimeout);
  2250. dispose.call(this);
  2251. };
  2252. loader.stopRequest = function () {
  2253. if (request) {
  2254. var oldRequest = request;
  2255. request = null;
  2256. oldRequest.onreadystatechange = null;
  2257. oldRequest.abort();
  2258. }
  2259. };
  2260. /**
  2261. * When called without any arguments, returns the currently
  2262. * active media playlist. When called with a single argument,
  2263. * triggers the playlist loader to asynchronously switch to the
  2264. * specified media playlist. Calling this method while the
  2265. * loader is in the HAVE_NOTHING causes an error to be emitted
  2266. * but otherwise has no effect.
  2267. *
  2268. * @param {Object=} playlis tthe parsed media playlist
  2269. * object to switch to
  2270. * @return {Playlist} the current loaded media
  2271. */
  2272. loader.media = function (playlist) {
  2273. var startingState = loader.state;
  2274. var mediaChange = undefined;
  2275. // getter
  2276. if (!playlist) {
  2277. return loader.media_;
  2278. }
  2279. // setter
  2280. if (loader.state === 'HAVE_NOTHING') {
  2281. throw new Error('Cannot switch media playlist from ' + loader.state);
  2282. }
  2283. // find the playlist object if the target playlist has been
  2284. // specified by URI
  2285. if (typeof playlist === 'string') {
  2286. if (!loader.master.playlists[playlist]) {
  2287. throw new Error('Unknown playlist URI: ' + playlist);
  2288. }
  2289. playlist = loader.master.playlists[playlist];
  2290. }
  2291. mediaChange = !loader.media_ || playlist.uri !== loader.media_.uri;
  2292. // switch to fully loaded playlists immediately
  2293. if (loader.master.playlists[playlist.uri].endList) {
  2294. // abort outstanding playlist requests
  2295. if (request) {
  2296. request.onreadystatechange = null;
  2297. request.abort();
  2298. request = null;
  2299. }
  2300. loader.state = 'HAVE_METADATA';
  2301. loader.media_ = playlist;
  2302. // trigger media change if the active media has been updated
  2303. if (mediaChange) {
  2304. loader.trigger('mediachanging');
  2305. loader.trigger('mediachange');
  2306. }
  2307. return;
  2308. }
  2309. // switching to the active playlist is a no-op
  2310. if (!mediaChange) {
  2311. return;
  2312. }
  2313. loader.state = 'SWITCHING_MEDIA';
  2314. // there is already an outstanding playlist request
  2315. if (request) {
  2316. if ((0, _resolveUrl2['default'])(loader.master.uri, playlist.uri) === request.url) {
  2317. // requesting to switch to the same playlist multiple times
  2318. // has no effect after the first
  2319. return;
  2320. }
  2321. request.onreadystatechange = null;
  2322. request.abort();
  2323. request = null;
  2324. }
  2325. // request the new playlist
  2326. if (this.media_) {
  2327. this.trigger('mediachanging');
  2328. }
  2329. request = this.hls_.xhr({
  2330. uri: (0, _resolveUrl2['default'])(loader.master.uri, playlist.uri),
  2331. withCredentials: withCredentials
  2332. }, function (error, req) {
  2333. // disposed
  2334. if (!request) {
  2335. return;
  2336. }
  2337. if (error) {
  2338. return playlistRequestError(request, playlist.uri, startingState);
  2339. }
  2340. haveMetadata(req, playlist.uri);
  2341. // fire loadedmetadata the first time a media playlist is loaded
  2342. if (startingState === 'HAVE_MASTER') {
  2343. loader.trigger('loadedmetadata');
  2344. } else {
  2345. loader.trigger('mediachange');
  2346. }
  2347. });
  2348. };
  2349. /**
  2350. * set the bandwidth on an xhr to the bandwidth on the playlist
  2351. */
  2352. loader.setBandwidth = function (xhr) {
  2353. loader.bandwidth = xhr.bandwidth;
  2354. };
  2355. // In a live playlist, don't keep track of the expired time
  2356. // until HLS tells us that "first play" has commenced
  2357. loader.on('firstplay', function () {
  2358. this.trackExpiredTime_ = true;
  2359. });
  2360. // live playlist staleness timeout
  2361. loader.on('mediaupdatetimeout', function () {
  2362. if (loader.state !== 'HAVE_METADATA') {
  2363. // only refresh the media playlist if no other activity is going on
  2364. return;
  2365. }
  2366. loader.state = 'HAVE_CURRENT_METADATA';
  2367. request = this.hls_.xhr({
  2368. uri: (0, _resolveUrl2['default'])(loader.master.uri, loader.media().uri),
  2369. withCredentials: withCredentials
  2370. }, function (error, req) {
  2371. // disposed
  2372. if (!request) {
  2373. return;
  2374. }
  2375. if (error) {
  2376. return playlistRequestError(request, loader.media().uri);
  2377. }
  2378. haveMetadata(request, loader.media().uri);
  2379. });
  2380. });
  2381. /**
  2382. * pause loading of the playlist
  2383. */
  2384. loader.pause = function () {
  2385. loader.stopRequest();
  2386. window.clearTimeout(mediaUpdateTimeout);
  2387. };
  2388. /**
  2389. * start loading of the playlist
  2390. */
  2391. loader.load = function () {
  2392. if (loader.started) {
  2393. if (!loader.media().endList) {
  2394. loader.trigger('mediaupdatetimeout');
  2395. } else {
  2396. loader.trigger('loadedplaylist');
  2397. }
  2398. } else {
  2399. loader.start();
  2400. }
  2401. };
  2402. /**
  2403. * start loading of the playlist
  2404. */
  2405. loader.start = function () {
  2406. loader.started = true;
  2407. // request the specified URL
  2408. request = _this.hls_.xhr({
  2409. uri: srcUrl,
  2410. withCredentials: withCredentials
  2411. }, function (error, req) {
  2412. var parser = undefined;
  2413. var playlist = undefined;
  2414. var i = undefined;
  2415. // disposed
  2416. if (!request) {
  2417. return;
  2418. }
  2419. // clear the loader's request reference
  2420. request = null;
  2421. if (error) {
  2422. loader.error = {
  2423. status: req.status,
  2424. message: 'HLS playlist request error at URL: ' + srcUrl,
  2425. responseText: req.responseText,
  2426. // MEDIA_ERR_NETWORK
  2427. code: 2
  2428. };
  2429. return loader.trigger('error');
  2430. }
  2431. parser = new _m3u82['default'].Parser();
  2432. parser.push(req.responseText);
  2433. parser.end();
  2434. loader.state = 'HAVE_MASTER';
  2435. parser.manifest.uri = srcUrl;
  2436. // loaded a master playlist
  2437. if (parser.manifest.playlists) {
  2438. loader.master = parser.manifest;
  2439. // setup by-URI lookups and resolve media playlist URIs
  2440. i = loader.master.playlists.length;
  2441. while (i--) {
  2442. playlist = loader.master.playlists[i];
  2443. loader.master.playlists[playlist.uri] = playlist;
  2444. playlist.resolvedUri = (0, _resolveUrl2['default'])(loader.master.uri, playlist.uri);
  2445. }
  2446. // resolve any media group URIs
  2447. for (var groupKey in loader.master.mediaGroups.AUDIO) {
  2448. for (var labelKey in loader.master.mediaGroups.AUDIO[groupKey]) {
  2449. var alternateAudio = loader.master.mediaGroups.AUDIO[groupKey][labelKey];
  2450. if (alternateAudio.uri) {
  2451. alternateAudio.resolvedUri = (0, _resolveUrl2['default'])(loader.master.uri, alternateAudio.uri);
  2452. }
  2453. }
  2454. }
  2455. loader.trigger('loadedplaylist');
  2456. if (!request) {
  2457. // no media playlist was specifically selected so start
  2458. // from the first listed one
  2459. loader.media(parser.manifest.playlists[0]);
  2460. }
  2461. return;
  2462. }
  2463. // loaded a media playlist
  2464. // infer a master playlist if none was previously requested
  2465. loader.master = {
  2466. uri: window.location.href,
  2467. playlists: [{
  2468. uri: srcUrl
  2469. }]
  2470. };
  2471. loader.master.playlists[srcUrl] = loader.master.playlists[0];
  2472. loader.master.playlists[0].resolvedUri = srcUrl;
  2473. haveMetadata(req, srcUrl);
  2474. return loader.trigger('loadedmetadata');
  2475. });
  2476. };
  2477. };
  2478. PlaylistLoader.prototype = new _stream2['default']();
  2479. /**
  2480. * Update the PlaylistLoader state to reflect the changes in an
  2481. * update to the current media playlist.
  2482. *
  2483. * @param {Object} update the updated media playlist object
  2484. */
  2485. PlaylistLoader.prototype.updateMediaPlaylist_ = function (update) {
  2486. var outdated = undefined;
  2487. var i = undefined;
  2488. var segment = undefined;
  2489. outdated = this.media_;
  2490. this.media_ = this.master.playlists[update.uri];
  2491. if (!outdated) {
  2492. return;
  2493. }
  2494. // don't track expired time until this flag is truthy
  2495. if (!this.trackExpiredTime_) {
  2496. return;
  2497. }
  2498. // if the update was the result of a rendition switch do not
  2499. // attempt to calculate expired_ since media-sequences need not
  2500. // correlate between renditions/variants
  2501. if (update.uri !== outdated.uri) {
  2502. return;
  2503. }
  2504. // try using precise timing from first segment of the updated
  2505. // playlist
  2506. if (update.segments.length) {
  2507. if (typeof update.segments[0].start !== 'undefined') {
  2508. this.expired_ = update.segments[0].start;
  2509. return;
  2510. } else if (typeof update.segments[0].end !== 'undefined') {
  2511. this.expired_ = update.segments[0].end - update.segments[0].duration;
  2512. return;
  2513. }
  2514. }
  2515. // calculate expired by walking the outdated playlist
  2516. i = update.mediaSequence - outdated.mediaSequence - 1;
  2517. for (; i >= 0; i--) {
  2518. segment = outdated.segments[i];
  2519. if (!segment) {
  2520. // we missed information on this segment completely between
  2521. // playlist updates so we'll have to take an educated guess
  2522. // once we begin buffering again, any error we introduce can
  2523. // be corrected
  2524. this.expired_ += outdated.targetDuration || 10;
  2525. continue;
  2526. }
  2527. if (typeof segment.end !== 'undefined') {
  2528. this.expired_ = segment.end;
  2529. return;
  2530. }
  2531. if (typeof segment.start !== 'undefined') {
  2532. this.expired_ = segment.start + segment.duration;
  2533. return;
  2534. }
  2535. this.expired_ += segment.duration;
  2536. }
  2537. };
  2538. exports['default'] = PlaylistLoader;
  2539. module.exports = exports['default'];
  2540. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2541. },{"./m3u8":7,"./resolve-url":15,"./stream":18}],13:[function(require,module,exports){
  2542. (function (global){
  2543. /**
  2544. * @file playlist.js
  2545. *
  2546. * Playlist related utilities.
  2547. */
  2548. 'use strict';
  2549. Object.defineProperty(exports, '__esModule', {
  2550. value: true
  2551. });
  2552. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  2553. var Playlist = {
  2554. /**
  2555. * The number of segments that are unsafe to start playback at in
  2556. * a live stream. Changing this value can cause playback stalls.
  2557. * See HTTP Live Streaming, "Playing the Media Playlist File"
  2558. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-18#section-6.3.3
  2559. */
  2560. UNSAFE_LIVE_SEGMENTS: 3
  2561. };
  2562. /**
  2563. * walk backward until we find a duration we can use
  2564. * or return a failure
  2565. *
  2566. * @param {Playlist} playlist the playlist to walk through
  2567. * @param {Number} endSequence the mediaSequence to stop walking on
  2568. */
  2569. var backwardDuration = function backwardDuration(playlist, endSequence) {
  2570. var result = 0;
  2571. var i = endSequence - playlist.mediaSequence;
  2572. // if a start time is available for segment immediately following
  2573. // the interval, use it
  2574. var segment = playlist.segments[i];
  2575. // Walk backward until we find the latest segment with timeline
  2576. // information that is earlier than endSequence
  2577. if (segment) {
  2578. if (typeof segment.start !== 'undefined') {
  2579. return { result: segment.start, precise: true };
  2580. }
  2581. if (typeof segment.end !== 'undefined') {
  2582. return {
  2583. result: segment.end - segment.duration,
  2584. precise: true
  2585. };
  2586. }
  2587. }
  2588. while (i--) {
  2589. segment = playlist.segments[i];
  2590. if (typeof segment.end !== 'undefined') {
  2591. return { result: result + segment.end, precise: true };
  2592. }
  2593. result += segment.duration;
  2594. if (typeof segment.start !== 'undefined') {
  2595. return { result: result + segment.start, precise: true };
  2596. }
  2597. }
  2598. return { result: result, precise: false };
  2599. };
  2600. /**
  2601. * walk forward until we find a duration we can use
  2602. * or return a failure
  2603. *
  2604. * @param {Playlist} playlist the playlist to walk through
  2605. * @param {Number} endSequence the mediaSequence to stop walking on
  2606. */
  2607. var forwardDuration = function forwardDuration(playlist, endSequence) {
  2608. var result = 0;
  2609. var segment = undefined;
  2610. var i = endSequence - playlist.mediaSequence;
  2611. // Walk forward until we find the earliest segment with timeline
  2612. // information
  2613. for (; i < playlist.segments.length; i++) {
  2614. segment = playlist.segments[i];
  2615. if (typeof segment.start !== 'undefined') {
  2616. return {
  2617. result: segment.start - result,
  2618. precise: true
  2619. };
  2620. }
  2621. result += segment.duration;
  2622. if (typeof segment.end !== 'undefined') {
  2623. return {
  2624. result: segment.end - result,
  2625. precise: true
  2626. };
  2627. }
  2628. }
  2629. // indicate we didn't find a useful duration estimate
  2630. return { result: -1, precise: false };
  2631. };
  2632. /**
  2633. * Calculate the media duration from the segments associated with a
  2634. * playlist. The duration of a subinterval of the available segments
  2635. * may be calculated by specifying an end index.
  2636. *
  2637. * @param {Object} playlist a media playlist object
  2638. * @param {Number=} endSequence an exclusive upper boundary
  2639. * for the playlist. Defaults to playlist length.
  2640. * @param {Number} expired the amount of time that has dropped
  2641. * off the front of the playlist in a live scenario
  2642. * @return {Number} the duration between the first available segment
  2643. * and end index.
  2644. */
  2645. var intervalDuration = function intervalDuration(playlist, endSequence, expired) {
  2646. var backward = undefined;
  2647. var forward = undefined;
  2648. if (typeof endSequence === 'undefined') {
  2649. endSequence = playlist.mediaSequence + playlist.segments.length;
  2650. }
  2651. if (endSequence < playlist.mediaSequence) {
  2652. return 0;
  2653. }
  2654. // do a backward walk to estimate the duration
  2655. backward = backwardDuration(playlist, endSequence);
  2656. if (backward.precise) {
  2657. // if we were able to base our duration estimate on timing
  2658. // information provided directly from the Media Source, return
  2659. // it
  2660. return backward.result;
  2661. }
  2662. // walk forward to see if a precise duration estimate can be made
  2663. // that way
  2664. forward = forwardDuration(playlist, endSequence);
  2665. if (forward.precise) {
  2666. // we found a segment that has been buffered and so it's
  2667. // position is known precisely
  2668. return forward.result;
  2669. }
  2670. // return the less-precise, playlist-based duration estimate
  2671. return backward.result + expired;
  2672. };
  2673. /**
  2674. * Calculates the duration of a playlist. If a start and end index
  2675. * are specified, the duration will be for the subset of the media
  2676. * timeline between those two indices. The total duration for live
  2677. * playlists is always Infinity.
  2678. *
  2679. * @param {Object} playlist a media playlist object
  2680. * @param {Number=} endSequence an exclusive upper
  2681. * boundary for the playlist. Defaults to the playlist media
  2682. * sequence number plus its length.
  2683. * @param {Number=} expired the amount of time that has
  2684. * dropped off the front of the playlist in a live scenario
  2685. * @return {Number} the duration between the start index and end
  2686. * index.
  2687. */
  2688. var duration = function duration(playlist, endSequence, expired) {
  2689. if (!playlist) {
  2690. return 0;
  2691. }
  2692. if (typeof expired !== 'number') {
  2693. expired = 0;
  2694. }
  2695. // if a slice of the total duration is not requested, use
  2696. // playlist-level duration indicators when they're present
  2697. if (typeof endSequence === 'undefined') {
  2698. // if present, use the duration specified in the playlist
  2699. if (playlist.totalDuration) {
  2700. return playlist.totalDuration;
  2701. }
  2702. // duration should be Infinity for live playlists
  2703. if (!playlist.endList) {
  2704. return window.Infinity;
  2705. }
  2706. }
  2707. // calculate the total duration based on the segment durations
  2708. return intervalDuration(playlist, endSequence, expired);
  2709. };
  2710. exports.duration = duration;
  2711. /**
  2712. * Calculates the interval of time that is currently seekable in a
  2713. * playlist. The returned time ranges are relative to the earliest
  2714. * moment in the specified playlist that is still available. A full
  2715. * seekable implementation for live streams would need to offset
  2716. * these values by the duration of content that has expired from the
  2717. * stream.
  2718. *
  2719. * @param {Object} playlist a media playlist object
  2720. * @param {Number=} expired the amount of time that has
  2721. * dropped off the front of the playlist in a live scenario
  2722. * @return {TimeRanges} the periods of time that are valid targets
  2723. * for seeking
  2724. */
  2725. var seekable = function seekable(playlist, expired) {
  2726. var start = undefined;
  2727. var end = undefined;
  2728. var endSequence = undefined;
  2729. if (typeof expired !== 'number') {
  2730. expired = 0;
  2731. }
  2732. // without segments, there are no seekable ranges
  2733. if (!playlist || !playlist.segments) {
  2734. return (0, _videoJs.createTimeRange)();
  2735. }
  2736. // when the playlist is complete, the entire duration is seekable
  2737. if (playlist.endList) {
  2738. return (0, _videoJs.createTimeRange)(0, duration(playlist));
  2739. }
  2740. // live playlists should not expose three segment durations worth
  2741. // of content from the end of the playlist
  2742. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-16#section-6.3.3
  2743. start = intervalDuration(playlist, playlist.mediaSequence, expired);
  2744. endSequence = Math.max(0, playlist.segments.length - Playlist.UNSAFE_LIVE_SEGMENTS);
  2745. end = intervalDuration(playlist, playlist.mediaSequence + endSequence, expired);
  2746. return (0, _videoJs.createTimeRange)(start, end);
  2747. };
  2748. exports.seekable = seekable;
  2749. /**
  2750. * Determine the index of the segment that contains a specified
  2751. * playback position in a media playlist.
  2752. *
  2753. * @param {Object} playlist the media playlist to query
  2754. * @param {Number} time The number of seconds since the earliest
  2755. * possible position to determine the containing segment for
  2756. * @param {Number=} expired the duration of content, in
  2757. * seconds, that has been removed from this playlist because it
  2758. * expired
  2759. * @return {Number} The number of the media segment that contains
  2760. * that time position.
  2761. */
  2762. var getMediaIndexForTime_ = function getMediaIndexForTime_(playlist, time, expired) {
  2763. var i = undefined;
  2764. var segment = undefined;
  2765. var originalTime = time;
  2766. var numSegments = playlist.segments.length;
  2767. var lastSegment = numSegments - 1;
  2768. var startIndex = undefined;
  2769. var endIndex = undefined;
  2770. var knownStart = undefined;
  2771. var knownEnd = undefined;
  2772. if (!playlist) {
  2773. return 0;
  2774. }
  2775. // when the requested position is earlier than the current set of
  2776. // segments, return the earliest segment index
  2777. if (time < 0) {
  2778. return 0;
  2779. }
  2780. expired = expired || 0;
  2781. // find segments with known timing information that bound the
  2782. // target time
  2783. for (i = 0; i < numSegments; i++) {
  2784. segment = playlist.segments[i];
  2785. if (segment.end) {
  2786. if (segment.end > time) {
  2787. knownEnd = segment.end;
  2788. endIndex = i;
  2789. break;
  2790. } else {
  2791. knownStart = segment.end;
  2792. startIndex = i + 1;
  2793. }
  2794. }
  2795. }
  2796. // time was equal to or past the end of the last segment in the playlist
  2797. if (startIndex === numSegments) {
  2798. return numSegments;
  2799. }
  2800. // use the bounds we just found and playlist information to
  2801. // estimate the segment that contains the time we are looking for
  2802. if (typeof startIndex !== 'undefined') {
  2803. // We have a known-start point that is before our desired time so
  2804. // walk from that point forwards
  2805. time = time - knownStart;
  2806. for (i = startIndex; i < (endIndex || numSegments); i++) {
  2807. segment = playlist.segments[i];
  2808. time -= segment.duration;
  2809. if (time < 0) {
  2810. return i;
  2811. }
  2812. }
  2813. if (i >= endIndex) {
  2814. // We haven't found a segment but we did hit a known end point
  2815. // so fallback to interpolating between the segment index
  2816. // based on the known span of the timeline we are dealing with
  2817. // and the number of segments inside that span
  2818. return startIndex + Math.floor((originalTime - knownStart) / (knownEnd - knownStart) * (endIndex - startIndex));
  2819. }
  2820. // We _still_ haven't found a segment so load the last one
  2821. return lastSegment;
  2822. } else if (typeof endIndex !== 'undefined') {
  2823. // We _only_ have a known-end point that is after our desired time so
  2824. // walk from that point backwards
  2825. time = knownEnd - time;
  2826. for (i = endIndex; i >= 0; i--) {
  2827. segment = playlist.segments[i];
  2828. time -= segment.duration;
  2829. if (time < 0) {
  2830. return i;
  2831. }
  2832. }
  2833. // We haven't found a segment so load the first one if time is zero
  2834. if (time === 0) {
  2835. return 0;
  2836. }
  2837. return -1;
  2838. }
  2839. // We known nothing so walk from the front of the playlist,
  2840. // subtracting durations until we find a segment that contains
  2841. // time and return it
  2842. time = time - expired;
  2843. if (time < 0) {
  2844. return -1;
  2845. }
  2846. for (i = 0; i < numSegments; i++) {
  2847. segment = playlist.segments[i];
  2848. time -= segment.duration;
  2849. if (time < 0) {
  2850. return i;
  2851. }
  2852. }
  2853. // We are out of possible candidates so load the last one...
  2854. // The last one is the least likely to overlap a buffer and therefore
  2855. // the one most likely to tell us something about the timeline
  2856. return lastSegment;
  2857. };
  2858. exports.getMediaIndexForTime_ = getMediaIndexForTime_;
  2859. Playlist.duration = duration;
  2860. Playlist.seekable = seekable;
  2861. Playlist.getMediaIndexForTime_ = getMediaIndexForTime_;
  2862. // exports
  2863. exports['default'] = Playlist;
  2864. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2865. },{}],14:[function(require,module,exports){
  2866. (function (global){
  2867. /**
  2868. * ranges
  2869. *
  2870. * Utilities for working with TimeRanges.
  2871. *
  2872. */
  2873. 'use strict';
  2874. Object.defineProperty(exports, '__esModule', {
  2875. value: true
  2876. });
  2877. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  2878. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  2879. var _videoJs2 = _interopRequireDefault(_videoJs);
  2880. // Fudge factor to account for TimeRanges rounding
  2881. var TIME_FUDGE_FACTOR = 1 / 30;
  2882. var filterRanges = function filterRanges(timeRanges, predicate) {
  2883. var results = [];
  2884. var i = undefined;
  2885. if (timeRanges && timeRanges.length) {
  2886. // Search for ranges that match the predicate
  2887. for (i = 0; i < timeRanges.length; i++) {
  2888. if (predicate(timeRanges.start(i), timeRanges.end(i))) {
  2889. results.push([timeRanges.start(i), timeRanges.end(i)]);
  2890. }
  2891. }
  2892. }
  2893. return _videoJs2['default'].createTimeRanges(results);
  2894. };
  2895. /**
  2896. * Attempts to find the buffered TimeRange that contains the specified
  2897. * time.
  2898. * @param {TimeRanges} buffered - the TimeRanges object to query
  2899. * @param {number} time - the time to filter on.
  2900. * @returns {TimeRanges} a new TimeRanges object
  2901. */
  2902. var findRange = function findRange(buffered, time) {
  2903. return filterRanges(buffered, function (start, end) {
  2904. return start - TIME_FUDGE_FACTOR <= time && end + TIME_FUDGE_FACTOR >= time;
  2905. });
  2906. };
  2907. /**
  2908. * Returns the TimeRanges that begin at or later than the specified
  2909. * time.
  2910. * @param {TimeRanges} timeRanges - the TimeRanges object to query
  2911. * @param {number} time - the time to filter on.
  2912. * @returns {TimeRanges} a new TimeRanges object.
  2913. */
  2914. var findNextRange = function findNextRange(timeRanges, time) {
  2915. return filterRanges(timeRanges, function (start) {
  2916. return start - TIME_FUDGE_FACTOR >= time;
  2917. });
  2918. };
  2919. /**
  2920. * Search for a likely end time for the segment that was just appened
  2921. * based on the state of the `buffered` property before and after the
  2922. * append. If we fin only one such uncommon end-point return it.
  2923. * @param {TimeRanges} original - the buffered time ranges before the update
  2924. * @param {TimeRanges} update - the buffered time ranges after the update
  2925. * @returns {Number|null} the end time added between `original` and `update`,
  2926. * or null if one cannot be unambiguously determined.
  2927. */
  2928. var findSoleUncommonTimeRangesEnd = function findSoleUncommonTimeRangesEnd(original, update) {
  2929. var i = undefined;
  2930. var start = undefined;
  2931. var end = undefined;
  2932. var result = [];
  2933. var edges = [];
  2934. // In order to qualify as a possible candidate, the end point must:
  2935. // 1) Not have already existed in the `original` ranges
  2936. // 2) Not result from the shrinking of a range that already existed
  2937. // in the `original` ranges
  2938. // 3) Not be contained inside of a range that existed in `original`
  2939. var overlapsCurrentEnd = function overlapsCurrentEnd(span) {
  2940. return span[0] <= end && span[1] >= end;
  2941. };
  2942. if (original) {
  2943. // Save all the edges in the `original` TimeRanges object
  2944. for (i = 0; i < original.length; i++) {
  2945. start = original.start(i);
  2946. end = original.end(i);
  2947. edges.push([start, end]);
  2948. }
  2949. }
  2950. if (update) {
  2951. // Save any end-points in `update` that are not in the `original`
  2952. // TimeRanges object
  2953. for (i = 0; i < update.length; i++) {
  2954. start = update.start(i);
  2955. end = update.end(i);
  2956. if (edges.some(overlapsCurrentEnd)) {
  2957. continue;
  2958. }
  2959. // at this point it must be a unique non-shrinking end edge
  2960. result.push(end);
  2961. }
  2962. }
  2963. // we err on the side of caution and return null if didn't find
  2964. // exactly *one* differing end edge in the search above
  2965. if (result.length !== 1) {
  2966. return null;
  2967. }
  2968. return result[0];
  2969. };
  2970. /**
  2971. * Calculate the intersection of two TimeRanges
  2972. * @param {TimeRanges} bufferA
  2973. * @param {TimeRanges} bufferB
  2974. * @returns {TimeRanges} The interesection of `bufferA` with `bufferB`
  2975. */
  2976. var bufferIntersection = function bufferIntersection(bufferA, bufferB) {
  2977. var start = null;
  2978. var end = null;
  2979. var arity = 0;
  2980. var extents = [];
  2981. var ranges = [];
  2982. if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
  2983. return _videoJs2['default'].createTimeRange();
  2984. }
  2985. // Handle the case where we have both buffers and create an
  2986. // intersection of the two
  2987. var count = bufferA.length;
  2988. // A) Gather up all start and end times
  2989. while (count--) {
  2990. extents.push({ time: bufferA.start(count), type: 'start' });
  2991. extents.push({ time: bufferA.end(count), type: 'end' });
  2992. }
  2993. count = bufferB.length;
  2994. while (count--) {
  2995. extents.push({ time: bufferB.start(count), type: 'start' });
  2996. extents.push({ time: bufferB.end(count), type: 'end' });
  2997. }
  2998. // B) Sort them by time
  2999. extents.sort(function (a, b) {
  3000. return a.time - b.time;
  3001. });
  3002. // C) Go along one by one incrementing arity for start and decrementing
  3003. // arity for ends
  3004. for (count = 0; count < extents.length; count++) {
  3005. if (extents[count].type === 'start') {
  3006. arity++;
  3007. // D) If arity is ever incremented to 2 we are entering an
  3008. // overlapping range
  3009. if (arity === 2) {
  3010. start = extents[count].time;
  3011. }
  3012. } else if (extents[count].type === 'end') {
  3013. arity--;
  3014. // E) If arity is ever decremented to 1 we leaving an
  3015. // overlapping range
  3016. if (arity === 1) {
  3017. end = extents[count].time;
  3018. }
  3019. }
  3020. // F) Record overlapping ranges
  3021. if (start !== null && end !== null) {
  3022. ranges.push([start, end]);
  3023. start = null;
  3024. end = null;
  3025. }
  3026. }
  3027. return _videoJs2['default'].createTimeRanges(ranges);
  3028. };
  3029. /**
  3030. * Calculates the percentage of `segmentRange` that overlaps the
  3031. * `buffered` time ranges.
  3032. * @param {TimeRanges} segmentRange - the time range that the segment covers
  3033. * @param {TimeRanges} buffered - the currently buffered time ranges
  3034. * @returns {Number} percent of the segment currently buffered
  3035. */
  3036. var calculateBufferedPercent = function calculateBufferedPercent(segmentRange, buffered) {
  3037. var segmentDuration = segmentRange.end(0) - segmentRange.start(0);
  3038. var intersection = bufferIntersection(segmentRange, buffered);
  3039. var overlapDuration = 0;
  3040. var count = intersection.length;
  3041. while (count--) {
  3042. overlapDuration += intersection.end(count) - intersection.start(count);
  3043. }
  3044. return overlapDuration / segmentDuration * 100;
  3045. };
  3046. exports['default'] = {
  3047. findRange: findRange,
  3048. findNextRange: findNextRange,
  3049. findSoleUncommonTimeRangesEnd: findSoleUncommonTimeRangesEnd,
  3050. calculateBufferedPercent: calculateBufferedPercent,
  3051. TIME_FUDGE_FACTOR: TIME_FUDGE_FACTOR
  3052. };
  3053. module.exports = exports['default'];
  3054. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3055. },{}],15:[function(require,module,exports){
  3056. /**
  3057. * @file resolve-url.js
  3058. */
  3059. 'use strict';
  3060. Object.defineProperty(exports, '__esModule', {
  3061. value: true
  3062. });
  3063. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  3064. var _globalDocument = require('global/document');
  3065. var _globalDocument2 = _interopRequireDefault(_globalDocument);
  3066. /**
  3067. * Constructs a new URI by interpreting a path relative to another
  3068. * URI.
  3069. *
  3070. * @see http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
  3071. * @param {String} basePath a relative or absolute URI
  3072. * @param {String} path a path part to combine with the base
  3073. * @return {String} a URI that is equivalent to composing `base`
  3074. * with `path`
  3075. */
  3076. var resolveUrl = function resolveUrl(basePath, path) {
  3077. // use the base element to get the browser to handle URI resolution
  3078. var oldBase = _globalDocument2['default'].querySelector('base');
  3079. var docHead = _globalDocument2['default'].querySelector('head');
  3080. var a = _globalDocument2['default'].createElement('a');
  3081. var base = oldBase;
  3082. var oldHref = undefined;
  3083. var result = undefined;
  3084. // prep the document
  3085. if (oldBase) {
  3086. oldHref = oldBase.href;
  3087. } else {
  3088. base = docHead.appendChild(_globalDocument2['default'].createElement('base'));
  3089. }
  3090. base.href = basePath;
  3091. a.href = path;
  3092. result = a.href;
  3093. // clean up
  3094. if (oldBase) {
  3095. oldBase.href = oldHref;
  3096. } else {
  3097. docHead.removeChild(base);
  3098. }
  3099. return result;
  3100. };
  3101. exports['default'] = resolveUrl;
  3102. module.exports = exports['default'];
  3103. },{"global/document":21}],16:[function(require,module,exports){
  3104. (function (global){
  3105. /**
  3106. * @file segment-loader.js
  3107. */
  3108. 'use strict';
  3109. Object.defineProperty(exports, '__esModule', {
  3110. value: true
  3111. });
  3112. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  3113. var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  3114. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  3115. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  3116. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  3117. var _ranges = require('./ranges');
  3118. var _ranges2 = _interopRequireDefault(_ranges);
  3119. var _playlist = require('./playlist');
  3120. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  3121. var _videoJs2 = _interopRequireDefault(_videoJs);
  3122. var _sourceUpdater = require('./source-updater');
  3123. var _sourceUpdater2 = _interopRequireDefault(_sourceUpdater);
  3124. var _decrypter = require('./decrypter');
  3125. // in ms
  3126. var CHECK_BUFFER_DELAY = 500;
  3127. // the desired length of video to maintain in the buffer, in seconds
  3128. var GOAL_BUFFER_LENGTH = 30;
  3129. exports.GOAL_BUFFER_LENGTH = GOAL_BUFFER_LENGTH;
  3130. /**
  3131. * Updates segment with information about its end-point in time and, optionally,
  3132. * the segment duration if we have enough information to determine a segment duration
  3133. * accurately.
  3134. *
  3135. * @param {Object} playlist a media playlist object
  3136. * @param {Number} segmentIndex the index of segment we last appended
  3137. * @param {Number} segmentEnd the known of the segment referenced by segmentIndex
  3138. */
  3139. var updateSegmentMetadata = function updateSegmentMetadata(playlist, segmentIndex, segmentEnd) {
  3140. if (!playlist) {
  3141. return false;
  3142. }
  3143. var segment = playlist.segments[segmentIndex];
  3144. var previousSegment = playlist.segments[segmentIndex - 1];
  3145. if (segmentEnd && segment) {
  3146. segment.end = segmentEnd;
  3147. // fix up segment durations based on segment end data
  3148. if (!previousSegment) {
  3149. // first segment is always has a start time of 0 making its duration
  3150. // equal to the segment end
  3151. segment.duration = segment.end;
  3152. } else if (previousSegment.end) {
  3153. segment.duration = segment.end - previousSegment.end;
  3154. }
  3155. return true;
  3156. }
  3157. return false;
  3158. };
  3159. /**
  3160. * Determines if we should call endOfStream on the media source based
  3161. * on the state of the buffer or if appened segment was the final
  3162. * segment in the playlist.
  3163. *
  3164. * @param {Object} playlist a media playlist object
  3165. * @param {Object} mediaSource the MediaSource object
  3166. * @param {Number} segmentIndex the index of segment we last appended
  3167. * @param {Object} currentBuffered buffered region that currentTime resides in
  3168. * @returns {Boolean} do we need to call endOfStream on the MediaSource
  3169. */
  3170. var detectEndOfStream = function detectEndOfStream(playlist, mediaSource, segmentIndex, currentBuffered) {
  3171. if (!playlist) {
  3172. return false;
  3173. }
  3174. var segments = playlist.segments;
  3175. // determine a few boolean values to help make the branch below easier
  3176. // to read
  3177. var appendedLastSegment = segmentIndex === segments.length - 1;
  3178. var bufferedToEnd = currentBuffered.length && segments[segments.length - 1].end <= currentBuffered.end(0);
  3179. // if we've buffered to the end of the video, we need to call endOfStream
  3180. // so that MediaSources can trigger the `ended` event when it runs out of
  3181. // buffered data instead of waiting for me
  3182. return playlist.endList && mediaSource.readyState === 'open' && (appendedLastSegment || bufferedToEnd);
  3183. };
  3184. /* Turns segment byterange into a string suitable for use in
  3185. * HTTP Range requests
  3186. */
  3187. var byterangeStr = function byterangeStr(byterange) {
  3188. var byterangeStart = undefined;
  3189. var byterangeEnd = undefined;
  3190. // `byterangeEnd` is one less than `offset + length` because the HTTP range
  3191. // header uses inclusive ranges
  3192. byterangeEnd = byterange.offset + byterange.length - 1;
  3193. byterangeStart = byterange.offset;
  3194. return 'bytes=' + byterangeStart + '-' + byterangeEnd;
  3195. };
  3196. /* Defines headers for use in the xhr request for a particular segment.
  3197. */
  3198. var segmentXhrHeaders = function segmentXhrHeaders(segment) {
  3199. var headers = {};
  3200. if ('byterange' in segment) {
  3201. headers.Range = byterangeStr(segment.byterange);
  3202. }
  3203. return headers;
  3204. };
  3205. /**
  3206. * An object that manages segment loading and appending.
  3207. *
  3208. * @class SegmentLoader
  3209. * @param {Object} options required and optional options
  3210. * @extends videojs.EventTarget
  3211. */
  3212. var SegmentLoader = (function (_videojs$EventTarget) {
  3213. _inherits(SegmentLoader, _videojs$EventTarget);
  3214. function SegmentLoader(options) {
  3215. _classCallCheck(this, SegmentLoader);
  3216. _get(Object.getPrototypeOf(SegmentLoader.prototype), 'constructor', this).call(this);
  3217. var settings = undefined;
  3218. // check pre-conditions
  3219. if (!options) {
  3220. throw new TypeError('Initialization options are required');
  3221. }
  3222. if (typeof options.currentTime !== 'function') {
  3223. throw new TypeError('No currentTime getter specified');
  3224. }
  3225. if (!options.mediaSource) {
  3226. throw new TypeError('No MediaSource specified');
  3227. }
  3228. settings = _videoJs2['default'].mergeOptions(_videoJs2['default'].options.hls, options);
  3229. // public properties
  3230. this.state = 'INIT';
  3231. this.bandwidth = settings.bandwidth;
  3232. this.roundTrip = NaN;
  3233. this.bytesReceived = 0;
  3234. // private properties
  3235. this.hasPlayed_ = settings.hasPlayed;
  3236. this.currentTime_ = settings.currentTime;
  3237. this.seekable_ = settings.seekable;
  3238. this.seeking_ = settings.seeking;
  3239. this.setCurrentTime_ = settings.setCurrentTime;
  3240. this.mediaSource_ = settings.mediaSource;
  3241. this.withCredentials_ = settings.withCredentials;
  3242. this.checkBufferTimeout_ = null;
  3243. this.error_ = void 0;
  3244. this.expired_ = 0;
  3245. this.timeCorrection_ = 0;
  3246. this.currentTimeline_ = -1;
  3247. this.xhr_ = null;
  3248. this.pendingSegment_ = null;
  3249. this.sourceUpdater_ = null;
  3250. this.hls_ = settings.hls;
  3251. }
  3252. /**
  3253. * dispose of the SegmentLoader and reset to the default state
  3254. */
  3255. _createClass(SegmentLoader, [{
  3256. key: 'dispose',
  3257. value: function dispose() {
  3258. this.state = 'DISPOSED';
  3259. this.abort_();
  3260. if (this.sourceUpdater_) {
  3261. this.sourceUpdater_.dispose();
  3262. }
  3263. }
  3264. /**
  3265. * abort anything that is currently doing on with the SegmentLoader
  3266. * and reset to a default state
  3267. */
  3268. }, {
  3269. key: 'abort',
  3270. value: function abort() {
  3271. if (this.state !== 'WAITING') {
  3272. return;
  3273. }
  3274. this.abort_();
  3275. // don't wait for buffer check timeouts to begin fetching the
  3276. // next segment
  3277. if (!this.paused()) {
  3278. this.state = 'READY';
  3279. this.fillBuffer_();
  3280. }
  3281. }
  3282. /**
  3283. * set an error on the segment loader and null out any pending segements
  3284. *
  3285. * @param {Error} error the error to set on the SegmentLoader
  3286. * @return {Error} the error that was set or that is currently set
  3287. */
  3288. }, {
  3289. key: 'error',
  3290. value: function error(_error) {
  3291. if (typeof _error !== 'undefined') {
  3292. this.error_ = _error;
  3293. }
  3294. this.pendingSegment_ = null;
  3295. return this.error_;
  3296. }
  3297. /**
  3298. * load a playlist and start to fill the buffer
  3299. */
  3300. }, {
  3301. key: 'load',
  3302. value: function load() {
  3303. this.monitorBuffer_();
  3304. // if we don't have a playlist yet, keep waiting for one to be
  3305. // specified
  3306. if (!this.playlist_) {
  3307. return;
  3308. }
  3309. // if we're in the middle of processing a segment already, don't
  3310. // kick off an additional segment request
  3311. if (!this.sourceUpdater_ || this.state !== 'READY' && this.state !== 'INIT') {
  3312. return;
  3313. }
  3314. this.state = 'READY';
  3315. this.fillBuffer_();
  3316. }
  3317. /**
  3318. * set a playlist on the segment loader
  3319. *
  3320. * @param {PlaylistLoader} media the playlist to set on the segment loader
  3321. */
  3322. }, {
  3323. key: 'playlist',
  3324. value: function playlist(media) {
  3325. this.playlist_ = media;
  3326. // if we were unpaused but waiting for a playlist, start
  3327. // buffering now
  3328. if (this.sourceUpdater_ && media && this.state === 'INIT' && !this.paused()) {
  3329. this.state = 'READY';
  3330. return this.fillBuffer_();
  3331. }
  3332. }
  3333. /**
  3334. * Prevent the loader from fetching additional segments. If there
  3335. * is a segment request outstanding, it will finish processing
  3336. * before the loader halts. A segment loader can be unpaused by
  3337. * calling load().
  3338. */
  3339. }, {
  3340. key: 'pause',
  3341. value: function pause() {
  3342. if (this.checkBufferTimeout_) {
  3343. window.clearTimeout(this.checkBufferTimeout_);
  3344. this.checkBufferTimeout_ = null;
  3345. }
  3346. }
  3347. /**
  3348. * Returns whether the segment loader is fetching additional
  3349. * segments when given the opportunity. This property can be
  3350. * modified through calls to pause() and load().
  3351. */
  3352. }, {
  3353. key: 'paused',
  3354. value: function paused() {
  3355. return this.checkBufferTimeout_ === null;
  3356. }
  3357. /**
  3358. * setter for expired time on the SegmentLoader
  3359. *
  3360. * @param {Number} expired the exired time to set
  3361. */
  3362. }, {
  3363. key: 'expired',
  3364. value: function expired(_expired) {
  3365. this.expired_ = _expired;
  3366. }
  3367. /**
  3368. * create/set the following mimetype on the SourceBuffer through a
  3369. * SourceUpdater
  3370. *
  3371. * @param {String} mimeType the mime type string to use
  3372. */
  3373. }, {
  3374. key: 'mimeType',
  3375. value: function mimeType(_mimeType) {
  3376. // TODO Allow source buffers to be re-created with different mime-types
  3377. if (!this.sourceUpdater_) {
  3378. this.sourceUpdater_ = new _sourceUpdater2['default'](this.mediaSource_, _mimeType);
  3379. this.clearBuffer();
  3380. // if we were unpaused but waiting for a sourceUpdater, start
  3381. // buffering now
  3382. if (this.playlist_ && this.state === 'INIT' && !this.paused()) {
  3383. this.state = 'READY';
  3384. return this.fillBuffer_();
  3385. }
  3386. }
  3387. }
  3388. /**
  3389. * asynchronously/recursively monitor the buffer
  3390. *
  3391. * @private
  3392. */
  3393. }, {
  3394. key: 'monitorBuffer_',
  3395. value: function monitorBuffer_() {
  3396. if (this.state === 'READY') {
  3397. this.fillBuffer_();
  3398. }
  3399. if (this.checkBufferTimeout_) {
  3400. window.clearTimeout(this.checkBufferTimeout_);
  3401. }
  3402. this.checkBufferTimeout_ = window.setTimeout(this.monitorBuffer_.bind(this), CHECK_BUFFER_DELAY);
  3403. }
  3404. /**
  3405. * Return the amount of a segment specified by the mediaIndex overlaps
  3406. * the current buffered content.
  3407. *
  3408. * @param {Object} playlist the playlist object to fetch segments from
  3409. * @param {Number} mediaIndex the index of the segment in the playlist
  3410. * @param {TimeRanges} buffered the state of the buffer
  3411. * @returns {Number} percentage of the segment's time range that is
  3412. * already in `buffered`
  3413. */
  3414. }, {
  3415. key: 'getSegmentBufferedPercent_',
  3416. value: function getSegmentBufferedPercent_(playlist, mediaIndex, currentTime, buffered) {
  3417. var segment = playlist.segments[mediaIndex];
  3418. var startOfSegment = (0, _playlist.duration)(playlist, playlist.mediaSequence + mediaIndex, this.expired_);
  3419. var segmentRange = _videoJs2['default'].createTimeRanges([[Math.max(currentTime, startOfSegment), startOfSegment + segment.duration]]);
  3420. return _ranges2['default'].calculateBufferedPercent(segmentRange, buffered);
  3421. }
  3422. /**
  3423. * Determines what segment request should be made, given current
  3424. * playback state.
  3425. *
  3426. * @param {TimeRanges} buffered - the state of the buffer
  3427. * @param {Object} playlist - the playlist object to fetch segments from
  3428. * @param {Number} currentTime - the playback position in seconds
  3429. * @returns {Object} a segment info object that describes the
  3430. * request that should be made or null if no request is necessary
  3431. */
  3432. }, {
  3433. key: 'checkBuffer_',
  3434. value: function checkBuffer_(buffered, playlist, currentTime) {
  3435. var currentBuffered = _ranges2['default'].findRange(buffered, currentTime);
  3436. // There are times when MSE reports the first segment as starting a
  3437. // little after 0-time so add a fudge factor to try and fix those cases
  3438. // or we end up fetching the same first segment over and over
  3439. if (currentBuffered.length === 0 && currentTime === 0) {
  3440. currentBuffered = _ranges2['default'].findRange(buffered, currentTime + _ranges2['default'].TIME_FUDGE_FACTOR);
  3441. }
  3442. var bufferedTime = undefined;
  3443. var currentBufferedEnd = undefined;
  3444. var timestampOffset = this.sourceUpdater_.timestampOffset();
  3445. var segment = undefined;
  3446. var mediaIndex = undefined;
  3447. if (!playlist.segments.length) {
  3448. return;
  3449. }
  3450. if (currentBuffered.length === 0) {
  3451. // find the segment containing currentTime
  3452. mediaIndex = (0, _playlist.getMediaIndexForTime_)(playlist, currentTime + this.timeCorrection_, this.expired_);
  3453. } else {
  3454. // find the segment adjacent to the end of the current
  3455. // buffered region
  3456. currentBufferedEnd = currentBuffered.end(0);
  3457. bufferedTime = Math.max(0, currentBufferedEnd - currentTime);
  3458. // if the video has not yet played only, and we already have
  3459. // one segment downloaded do nothing
  3460. if (!this.hasPlayed_() && bufferedTime >= 1) {
  3461. return null;
  3462. }
  3463. // if there is plenty of content buffered, and the video has
  3464. // been played before relax for awhile
  3465. if (this.hasPlayed_() && bufferedTime >= GOAL_BUFFER_LENGTH) {
  3466. return null;
  3467. }
  3468. mediaIndex = (0, _playlist.getMediaIndexForTime_)(playlist, currentBufferedEnd + this.timeCorrection_, this.expired_);
  3469. }
  3470. if (mediaIndex < 0 || mediaIndex === playlist.segments.length) {
  3471. return null;
  3472. }
  3473. segment = playlist.segments[mediaIndex];
  3474. var startOfSegment = (0, _playlist.duration)(playlist, playlist.mediaSequence + mediaIndex, this.expired_);
  3475. // We will need to change timestampOffset of the sourceBuffer if either of
  3476. // the following conditions are true:
  3477. // - The segment.timeline !== this.currentTimeline
  3478. // (we are crossing a discontinuity somehow)
  3479. // - The "timestampOffset" for the start of this segment is less than
  3480. // the currently set timestampOffset
  3481. if (segment.timeline !== this.currentTimeline_ || startOfSegment < this.sourceUpdater_.timestampOffset()) {
  3482. timestampOffset = startOfSegment;
  3483. }
  3484. return {
  3485. // resolve the segment URL relative to the playlist
  3486. uri: segment.resolvedUri,
  3487. // the segment's mediaIndex at the time it was requested
  3488. mediaIndex: mediaIndex,
  3489. // the segment's playlist
  3490. playlist: playlist,
  3491. // unencrypted bytes of the segment
  3492. bytes: null,
  3493. // when a key is defined for this segment, the encrypted bytes
  3494. encryptedBytes: null,
  3495. // the state of the buffer before a segment is appended will be
  3496. // stored here so that the actual segment duration can be
  3497. // determined after it has been appended
  3498. buffered: null,
  3499. // The target timestampOffset for this segment when we append it
  3500. // to the source buffer
  3501. timestampOffset: timestampOffset,
  3502. // The timeline that the segment is in
  3503. timeline: segment.timeline
  3504. };
  3505. }
  3506. /**
  3507. * abort all pending xhr requests and null any pending segements
  3508. *
  3509. * @private
  3510. */
  3511. }, {
  3512. key: 'abort_',
  3513. value: function abort_() {
  3514. if (this.xhr_) {
  3515. this.xhr_.abort();
  3516. }
  3517. // clear out the segment being processed
  3518. this.pendingSegment_ = null;
  3519. }
  3520. /**
  3521. * fill the buffer with segements unless the
  3522. * sourceBuffers are currently updating
  3523. *
  3524. * @private
  3525. */
  3526. }, {
  3527. key: 'fillBuffer_',
  3528. value: function fillBuffer_() {
  3529. if (this.sourceUpdater_.updating()) {
  3530. return;
  3531. }
  3532. // see if we need to begin loading immediately
  3533. var request = this.checkBuffer_(this.sourceUpdater_.buffered(), this.playlist_, this.currentTime_(), this.timestampOffset_);
  3534. if (!request) {
  3535. return;
  3536. }
  3537. // Sanity check the segment-index determining logic by calcuating the
  3538. // percentage of the chosen segment that is buffered. If more than 90%
  3539. // of the segment is buffered then fetching it will likely not help in
  3540. // any way
  3541. var percentBuffered = this.getSegmentBufferedPercent_(this.playlist_, request.mediaIndex, this.currentTime_(), this.sourceUpdater_.buffered());
  3542. if (percentBuffered >= 90) {
  3543. // Increment the timeCorrection_ variable to push the fetcher forward
  3544. // in time and hopefully skip any gaps or flaws in our understanding
  3545. // of the media
  3546. this.incrementTimeCorrection_(this.playlist_.targetDuration);
  3547. if (!this.paused()) {
  3548. this.fillBuffer_();
  3549. }
  3550. return;
  3551. }
  3552. this.loadSegment_(request);
  3553. }
  3554. /**
  3555. * load a specific segment from a request into the buffer
  3556. *
  3557. * @private
  3558. */
  3559. }, {
  3560. key: 'loadSegment_',
  3561. value: function loadSegment_(segmentInfo) {
  3562. var segment = undefined;
  3563. var requestTimeout = undefined;
  3564. var keyXhr = undefined;
  3565. var segmentXhr = undefined;
  3566. var seekable = this.seekable_();
  3567. var currentTime = this.currentTime_();
  3568. var removeToTime = 0;
  3569. // Chrome has a hard limit of 150mb of
  3570. // buffer and a very conservative "garbage collector"
  3571. // We manually clear out the old buffer to ensure
  3572. // we don't trigger the QuotaExceeded error
  3573. // on the source buffer during subsequent appends
  3574. // If we have a seekable range use that as the limit for what can be removed safely
  3575. // otherwise remove anything older than 1 minute before the current play head
  3576. if (seekable.length && seekable.start(0) > 0 && seekable.start(0) < currentTime) {
  3577. removeToTime = seekable.start(0);
  3578. } else {
  3579. removeToTime = currentTime - 60;
  3580. }
  3581. if (removeToTime > 0) {
  3582. this.sourceUpdater_.remove(0, removeToTime);
  3583. }
  3584. segment = segmentInfo.playlist.segments[segmentInfo.mediaIndex];
  3585. // Set xhr timeout to 150% of the segment duration to allow us
  3586. // some time to switch renditions in the event of a catastrophic
  3587. // decrease in network performance or a server issue.
  3588. requestTimeout = segment.duration * 1.5 * 1000;
  3589. if (segment.key) {
  3590. keyXhr = this.hls_.xhr({
  3591. uri: segment.key.resolvedUri,
  3592. responseType: 'arraybuffer',
  3593. withCredentials: this.withCredentials_,
  3594. timeout: requestTimeout
  3595. }, this.handleResponse_.bind(this));
  3596. }
  3597. this.pendingSegment_ = segmentInfo;
  3598. segmentXhr = this.hls_.xhr({
  3599. uri: segmentInfo.uri,
  3600. responseType: 'arraybuffer',
  3601. withCredentials: this.withCredentials_,
  3602. timeout: requestTimeout,
  3603. headers: segmentXhrHeaders(segment)
  3604. }, this.handleResponse_.bind(this));
  3605. this.xhr_ = {
  3606. keyXhr: keyXhr,
  3607. segmentXhr: segmentXhr,
  3608. abort: function abort() {
  3609. if (this.segmentXhr) {
  3610. // Prevent error handler from running.
  3611. this.segmentXhr.onreadystatechange = null;
  3612. this.segmentXhr.abort();
  3613. this.segmentXhr = null;
  3614. }
  3615. if (this.keyXhr) {
  3616. // Prevent error handler from running.
  3617. this.keyXhr.onreadystatechange = null;
  3618. this.keyXhr.abort();
  3619. this.keyXhr = null;
  3620. }
  3621. }
  3622. };
  3623. this.state = 'WAITING';
  3624. }
  3625. /**
  3626. * triggered when a segment response is received
  3627. *
  3628. * @private
  3629. */
  3630. }, {
  3631. key: 'handleResponse_',
  3632. value: function handleResponse_(error, request) {
  3633. var segmentInfo = undefined;
  3634. var segment = undefined;
  3635. var keyXhrRequest = undefined;
  3636. var view = undefined;
  3637. // timeout of previously aborted request
  3638. if (!this.xhr_ || request !== this.xhr_.segmentXhr && request !== this.xhr_.keyXhr) {
  3639. return;
  3640. }
  3641. segmentInfo = this.pendingSegment_;
  3642. segment = segmentInfo.playlist.segments[segmentInfo.mediaIndex];
  3643. // if a request times out, reset bandwidth tracking
  3644. if (request.timedout) {
  3645. this.abort_();
  3646. this.bandwidth = 1;
  3647. this.roundTrip = NaN;
  3648. this.state = 'READY';
  3649. return this.trigger('progress');
  3650. }
  3651. // trigger an event for other errors
  3652. if (!request.aborted && error) {
  3653. // abort will clear xhr_
  3654. keyXhrRequest = this.xhr_.keyXhr;
  3655. this.abort_();
  3656. this.error({
  3657. status: request.status,
  3658. message: request === keyXhrRequest ? 'HLS key request error at URL: ' + segment.key.uri : 'HLS segment request error at URL: ' + segmentInfo.uri,
  3659. code: 2,
  3660. xhr: request
  3661. });
  3662. this.state = 'READY';
  3663. this.pause();
  3664. return this.trigger('error');
  3665. }
  3666. // stop processing if the request was aborted
  3667. if (!request.response) {
  3668. this.abort_();
  3669. return;
  3670. }
  3671. if (request === this.xhr_.segmentXhr) {
  3672. // the segment request is no longer outstanding
  3673. this.xhr_.segmentXhr = null;
  3674. // calculate the download bandwidth based on segment request
  3675. this.roundTrip = request.roundTripTime;
  3676. this.bandwidth = request.bandwidth;
  3677. this.bytesReceived += request.bytesReceived || 0;
  3678. if (segment.key) {
  3679. segmentInfo.encryptedBytes = new Uint8Array(request.response);
  3680. } else {
  3681. segmentInfo.bytes = new Uint8Array(request.response);
  3682. }
  3683. }
  3684. if (request === this.xhr_.keyXhr) {
  3685. keyXhrRequest = this.xhr_.segmentXhr;
  3686. // the key request is no longer outstanding
  3687. this.xhr_.keyXhr = null;
  3688. if (request.response.byteLength !== 16) {
  3689. this.abort_();
  3690. this.error({
  3691. status: request.status,
  3692. message: 'Invalid HLS key at URL: ' + segment.key.uri,
  3693. code: 2,
  3694. xhr: request
  3695. });
  3696. this.state = 'READY';
  3697. this.pause();
  3698. return this.trigger('error');
  3699. }
  3700. view = new DataView(request.response);
  3701. segment.key.bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  3702. // if the media sequence is greater than 2^32, the IV will be incorrect
  3703. // assuming 10s segments, that would be about 1300 years
  3704. segment.key.iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
  3705. }
  3706. if (!this.xhr_.segmentXhr && !this.xhr_.keyXhr) {
  3707. this.xhr_ = null;
  3708. this.processResponse_();
  3709. }
  3710. }
  3711. /**
  3712. * clear anything that is currently in the buffer and throw it away
  3713. */
  3714. }, {
  3715. key: 'clearBuffer',
  3716. value: function clearBuffer() {
  3717. if (this.sourceUpdater_ && this.sourceUpdater_.buffered().length) {
  3718. this.sourceUpdater_.remove(0, Infinity);
  3719. }
  3720. }
  3721. /**
  3722. * Decrypt the segment that is being loaded if necessary
  3723. *
  3724. * @private
  3725. */
  3726. }, {
  3727. key: 'processResponse_',
  3728. value: function processResponse_() {
  3729. var segmentInfo = undefined;
  3730. var segment = undefined;
  3731. this.state = 'DECRYPTING';
  3732. segmentInfo = this.pendingSegment_;
  3733. segment = segmentInfo.playlist.segments[segmentInfo.mediaIndex];
  3734. if (segment.key) {
  3735. // this is an encrypted segment
  3736. // incrementally decrypt the segment
  3737. /* eslint-disable no-new, handle-callback-err */
  3738. new _decrypter.Decrypter(segmentInfo.encryptedBytes, segment.key.bytes, segment.key.iv, (function (err, bytes) {
  3739. // err always null
  3740. segmentInfo.bytes = bytes;
  3741. this.handleSegment_();
  3742. }).bind(this));
  3743. /* eslint-enable */
  3744. } else {
  3745. this.handleSegment_();
  3746. }
  3747. }
  3748. /**
  3749. * append a decrypted segement to the SourceBuffer through a SourceUpdater
  3750. *
  3751. * @private
  3752. */
  3753. }, {
  3754. key: 'handleSegment_',
  3755. value: function handleSegment_() {
  3756. var segmentInfo = undefined;
  3757. this.state = 'APPENDING';
  3758. segmentInfo = this.pendingSegment_;
  3759. segmentInfo.buffered = this.sourceUpdater_.buffered();
  3760. this.currentTimeline_ = segmentInfo.timeline;
  3761. if (segmentInfo.timestampOffset !== this.sourceUpdater_.timestampOffset()) {
  3762. this.sourceUpdater_.timestampOffset(segmentInfo.timestampOffset);
  3763. }
  3764. this.sourceUpdater_.appendBuffer(segmentInfo.bytes, this.handleUpdateEnd_.bind(this));
  3765. }
  3766. /**
  3767. * callback to run when appendBuffer is finished. detects if we are
  3768. * in a good state to do things with the data we got, or if we need
  3769. * to wait for more
  3770. *
  3771. * @private
  3772. */
  3773. }, {
  3774. key: 'handleUpdateEnd_',
  3775. value: function handleUpdateEnd_() {
  3776. var segmentInfo = this.pendingSegment_;
  3777. var currentTime = this.currentTime_();
  3778. this.pendingSegment_ = null;
  3779. // add segment metadata if it we have gained information during the
  3780. // last append
  3781. this.updateTimeline_(segmentInfo);
  3782. this.trigger('progress');
  3783. var currentMediaIndex = segmentInfo.mediaIndex;
  3784. currentMediaIndex += segmentInfo.playlist.mediaSequence - this.playlist_.mediaSequence;
  3785. var currentBuffered = _ranges2['default'].findRange(this.sourceUpdater_.buffered(), currentTime);
  3786. // any time an update finishes and the last segment is in the
  3787. // buffer, end the stream. this ensures the "ended" event will
  3788. // fire if playback reaches that point.
  3789. var isEndOfStream = detectEndOfStream(segmentInfo.playlist, this.mediaSource_, currentMediaIndex, currentBuffered);
  3790. if (isEndOfStream) {
  3791. this.mediaSource_.endOfStream();
  3792. }
  3793. // when seeking to the beginning of the seekable range, it's
  3794. // possible that imprecise timing information may cause the seek to
  3795. // end up earlier than the start of the range
  3796. // in that case, seek again
  3797. var seekable = this.seekable_();
  3798. var next = _ranges2['default'].findNextRange(this.sourceUpdater_.buffered(), currentTime);
  3799. if (this.seeking_() && currentBuffered.length === 0) {
  3800. if (seekable.length && currentTime < seekable.start(0)) {
  3801. if (next.length) {
  3802. _videoJs2['default'].log('tried seeking to', currentTime, 'but that was too early, retrying at', next.start(0));
  3803. this.setCurrentTime_(next.start(0) + _ranges2['default'].TIME_FUDGE_FACTOR);
  3804. }
  3805. }
  3806. }
  3807. this.state = 'READY';
  3808. if (!this.paused()) {
  3809. this.fillBuffer_();
  3810. }
  3811. }
  3812. /**
  3813. * annotate the segment with any start and end time information
  3814. * added by the media processing
  3815. *
  3816. * @private
  3817. * @param {Object} segmentInfo annotate a segment with time info
  3818. */
  3819. }, {
  3820. key: 'updateTimeline_',
  3821. value: function updateTimeline_(segmentInfo) {
  3822. var segment = undefined;
  3823. var segmentEnd = undefined;
  3824. var timelineUpdated = undefined;
  3825. var segmentLength = this.playlist_.targetDuration;
  3826. var playlist = segmentInfo.playlist;
  3827. var currentMediaIndex = segmentInfo.mediaIndex;
  3828. currentMediaIndex += playlist.mediaSequence - this.playlist_.mediaSequence;
  3829. segment = playlist.segments[currentMediaIndex];
  3830. // Update segment meta-data (duration and end-point) based on timeline
  3831. if (segment && segmentInfo && segmentInfo.playlist.uri === this.playlist_.uri) {
  3832. segmentEnd = _ranges2['default'].findSoleUncommonTimeRangesEnd(segmentInfo.buffered, this.sourceUpdater_.buffered());
  3833. timelineUpdated = updateSegmentMetadata(playlist, currentMediaIndex, segmentEnd);
  3834. segmentLength = segment.duration;
  3835. }
  3836. // the last segment append must have been entirely in the
  3837. // already buffered time ranges. adjust the timeCorrection
  3838. // offset to fetch forward until we find a segment that adds
  3839. // to the buffered time ranges and improves subsequent media
  3840. // index calculations.
  3841. if (!timelineUpdated) {
  3842. this.incrementTimeCorrection_(segmentLength);
  3843. } else {
  3844. this.timeCorrection_ = 0;
  3845. }
  3846. }
  3847. /**
  3848. * add a number of seconds to the currentTime when determining which
  3849. * segment to fetch in order to force the fetcher to advance in cases
  3850. * where it may get stuck on the same segment due to buffer gaps or
  3851. * missing segment annotation after a rendition switch (especially
  3852. * during a live stream)
  3853. *
  3854. * @private
  3855. * @param {Number} secondsToIncrement number of seconds to add to the
  3856. * timeCorrection_ variable
  3857. */
  3858. }, {
  3859. key: 'incrementTimeCorrection_',
  3860. value: function incrementTimeCorrection_(secondsToIncrement) {
  3861. // If we have already incremented timeCorrection_ beyond the limit,
  3862. // then stop trying to find a segment, pause fetching, and emit an
  3863. // error event
  3864. if (this.timeCorrection_ >= this.playlist_.targetDuration * 5) {
  3865. this.timeCorrection_ = 0;
  3866. this.pause();
  3867. return this.trigger('error');
  3868. }
  3869. this.timeCorrection_ += secondsToIncrement;
  3870. }
  3871. }]);
  3872. return SegmentLoader;
  3873. })(_videoJs2['default'].EventTarget);
  3874. exports['default'] = SegmentLoader;
  3875. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3876. },{"./decrypter":5,"./playlist":13,"./ranges":14,"./source-updater":17}],17:[function(require,module,exports){
  3877. (function (global){
  3878. /**
  3879. * @file source-updater.js
  3880. */
  3881. 'use strict';
  3882. Object.defineProperty(exports, '__esModule', {
  3883. value: true
  3884. });
  3885. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  3886. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  3887. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  3888. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  3889. var _videoJs2 = _interopRequireDefault(_videoJs);
  3890. /**
  3891. * A queue of callbacks to be serialized and applied when a
  3892. * MediaSource and its associated SourceBuffers are not in the
  3893. * updating state. It is used by the segment loader to update the
  3894. * underlying SourceBuffers when new data is loaded, for instance.
  3895. *
  3896. * @class SourceUpdater
  3897. * @param {MediaSource} mediaSource the MediaSource to create the
  3898. * SourceBuffer from
  3899. * @param {String} mimeType the desired MIME type of the underlying
  3900. * SourceBuffer
  3901. */
  3902. var SourceUpdater = (function () {
  3903. function SourceUpdater(mediaSource, mimeType) {
  3904. var _this = this;
  3905. _classCallCheck(this, SourceUpdater);
  3906. var createSourceBuffer = function createSourceBuffer() {
  3907. _this.sourceBuffer_ = mediaSource.addSourceBuffer(mimeType);
  3908. // run completion handlers and process callbacks as updateend
  3909. // events fire
  3910. _this.sourceBuffer_.addEventListener('updateend', function () {
  3911. var pendingCallback = _this.pendingCallback_;
  3912. _this.pendingCallback_ = null;
  3913. if (pendingCallback) {
  3914. pendingCallback();
  3915. }
  3916. });
  3917. _this.sourceBuffer_.addEventListener('updateend', _this.runCallback_.bind(_this));
  3918. _this.runCallback_();
  3919. };
  3920. this.callbacks_ = [];
  3921. this.pendingCallback_ = null;
  3922. this.timestampOffset_ = 0;
  3923. this.mediaSource = mediaSource;
  3924. if (mediaSource.readyState === 'closed') {
  3925. mediaSource.addEventListener('sourceopen', createSourceBuffer);
  3926. } else {
  3927. createSourceBuffer();
  3928. }
  3929. }
  3930. /**
  3931. * Aborts the current segment and resets the segment parser.
  3932. *
  3933. * @param {Function} done function to call when done
  3934. * @see http://w3c.github.io/media-source/#widl-SourceBuffer-abort-void
  3935. */
  3936. _createClass(SourceUpdater, [{
  3937. key: 'abort',
  3938. value: function abort(done) {
  3939. var _this2 = this;
  3940. this.queueCallback_(function () {
  3941. _this2.sourceBuffer_.abort();
  3942. }, done);
  3943. }
  3944. /**
  3945. * Queue an update to append an ArrayBuffer.
  3946. *
  3947. * @param {ArrayBuffer} bytes
  3948. * @param {Function} done the function to call when done
  3949. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
  3950. */
  3951. }, {
  3952. key: 'appendBuffer',
  3953. value: function appendBuffer(bytes, done) {
  3954. var _this3 = this;
  3955. this.queueCallback_(function () {
  3956. _this3.sourceBuffer_.appendBuffer(bytes);
  3957. }, done);
  3958. }
  3959. /**
  3960. * Indicates what TimeRanges are buffered in the managed SourceBuffer.
  3961. *
  3962. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-buffered
  3963. */
  3964. }, {
  3965. key: 'buffered',
  3966. value: function buffered() {
  3967. if (!this.sourceBuffer_) {
  3968. return _videoJs2['default'].createTimeRanges();
  3969. }
  3970. return this.sourceBuffer_.buffered;
  3971. }
  3972. /**
  3973. * Queue an update to set the duration.
  3974. *
  3975. * @param {Double} duration what to set the duration to
  3976. * @see http://www.w3.org/TR/media-source/#widl-MediaSource-duration
  3977. */
  3978. }, {
  3979. key: 'duration',
  3980. value: function duration(_duration) {
  3981. var _this4 = this;
  3982. this.queueCallback_(function () {
  3983. _this4.sourceBuffer_.duration = _duration;
  3984. });
  3985. }
  3986. /**
  3987. * Queue an update to remove a time range from the buffer.
  3988. *
  3989. * @param {Number} start where to start the removal
  3990. * @param {Number} end where to end the removal
  3991. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  3992. */
  3993. }, {
  3994. key: 'remove',
  3995. value: function remove(start, end) {
  3996. var _this5 = this;
  3997. this.queueCallback_(function () {
  3998. _this5.sourceBuffer_.remove(start, end);
  3999. });
  4000. }
  4001. /**
  4002. * wether the underlying sourceBuffer is updating or not
  4003. *
  4004. * @return {Boolean} the updating status of the SourceBuffer
  4005. */
  4006. }, {
  4007. key: 'updating',
  4008. value: function updating() {
  4009. return !this.sourceBuffer_ || this.sourceBuffer_.updating;
  4010. }
  4011. /**
  4012. * Set/get the timestampoffset on the SourceBuffer
  4013. *
  4014. * @return {Number} the timestamp offset
  4015. */
  4016. }, {
  4017. key: 'timestampOffset',
  4018. value: function timestampOffset(offset) {
  4019. var _this6 = this;
  4020. if (typeof offset !== 'undefined') {
  4021. this.queueCallback_(function () {
  4022. _this6.sourceBuffer_.timestampOffset = offset;
  4023. });
  4024. this.timestampOffset_ = offset;
  4025. }
  4026. return this.timestampOffset_;
  4027. }
  4028. /**
  4029. * que a callback to run
  4030. */
  4031. }, {
  4032. key: 'queueCallback_',
  4033. value: function queueCallback_(callback, done) {
  4034. this.callbacks_.push([callback.bind(this), done]);
  4035. this.runCallback_();
  4036. }
  4037. /**
  4038. * run a queued callback
  4039. */
  4040. }, {
  4041. key: 'runCallback_',
  4042. value: function runCallback_() {
  4043. var callbacks = undefined;
  4044. if (this.sourceBuffer_ && !this.sourceBuffer_.updating && this.callbacks_.length) {
  4045. callbacks = this.callbacks_.shift();
  4046. this.pendingCallback_ = callbacks[1];
  4047. callbacks[0]();
  4048. }
  4049. }
  4050. /**
  4051. * dispose of the source updater and the underlying sourceBuffer
  4052. */
  4053. }, {
  4054. key: 'dispose',
  4055. value: function dispose() {
  4056. if (this.sourceBuffer_ && this.mediaSource.readyState === 'open') {
  4057. this.sourceBuffer_.abort();
  4058. }
  4059. }
  4060. }]);
  4061. return SourceUpdater;
  4062. })();
  4063. exports['default'] = SourceUpdater;
  4064. module.exports = exports['default'];
  4065. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4066. },{}],18:[function(require,module,exports){
  4067. /**
  4068. * @file stream.js
  4069. */
  4070. /**
  4071. * A lightweight readable stream implemention that handles event dispatching.
  4072. *
  4073. * @class Stream
  4074. */
  4075. 'use strict';
  4076. Object.defineProperty(exports, '__esModule', {
  4077. value: true
  4078. });
  4079. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  4080. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  4081. var Stream = (function () {
  4082. function Stream() {
  4083. _classCallCheck(this, Stream);
  4084. this.listeners = {};
  4085. }
  4086. /**
  4087. * Add a listener for a specified event type.
  4088. *
  4089. * @param {String} type the event name
  4090. * @param {Function} listener the callback to be invoked when an event of
  4091. * the specified type occurs
  4092. */
  4093. _createClass(Stream, [{
  4094. key: 'on',
  4095. value: function on(type, listener) {
  4096. if (!this.listeners[type]) {
  4097. this.listeners[type] = [];
  4098. }
  4099. this.listeners[type].push(listener);
  4100. }
  4101. /**
  4102. * Remove a listener for a specified event type.
  4103. *
  4104. * @param {String} type the event name
  4105. * @param {Function} listener a function previously registered for this
  4106. * type of event through `on`
  4107. * @return {Boolean} if we could turn it off or not
  4108. */
  4109. }, {
  4110. key: 'off',
  4111. value: function off(type, listener) {
  4112. var index = undefined;
  4113. if (!this.listeners[type]) {
  4114. return false;
  4115. }
  4116. index = this.listeners[type].indexOf(listener);
  4117. this.listeners[type].splice(index, 1);
  4118. return index > -1;
  4119. }
  4120. /**
  4121. * Trigger an event of the specified type on this stream. Any additional
  4122. * arguments to this function are passed as parameters to event listeners.
  4123. *
  4124. * @param {String} type the event name
  4125. */
  4126. }, {
  4127. key: 'trigger',
  4128. value: function trigger(type) {
  4129. var callbacks = undefined;
  4130. var i = undefined;
  4131. var length = undefined;
  4132. var args = undefined;
  4133. callbacks = this.listeners[type];
  4134. if (!callbacks) {
  4135. return;
  4136. }
  4137. // Slicing the arguments on every invocation of this method
  4138. // can add a significant amount of overhead. Avoid the
  4139. // intermediate object creation for the common case of a
  4140. // single callback argument
  4141. if (arguments.length === 2) {
  4142. length = callbacks.length;
  4143. for (i = 0; i < length; ++i) {
  4144. callbacks[i].call(this, arguments[1]);
  4145. }
  4146. } else {
  4147. args = Array.prototype.slice.call(arguments, 1);
  4148. length = callbacks.length;
  4149. for (i = 0; i < length; ++i) {
  4150. callbacks[i].apply(this, args);
  4151. }
  4152. }
  4153. }
  4154. /**
  4155. * Destroys the stream and cleans up.
  4156. */
  4157. }, {
  4158. key: 'dispose',
  4159. value: function dispose() {
  4160. this.listeners = {};
  4161. }
  4162. /**
  4163. * Forwards all `data` events on this stream to the destination stream. The
  4164. * destination stream should provide a method `push` to receive the data
  4165. * events as they arrive.
  4166. *
  4167. * @param {Stream} destination the stream that will receive all `data` events
  4168. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  4169. */
  4170. }, {
  4171. key: 'pipe',
  4172. value: function pipe(destination) {
  4173. this.on('data', function (data) {
  4174. destination.push(data);
  4175. });
  4176. }
  4177. }]);
  4178. return Stream;
  4179. })();
  4180. exports['default'] = Stream;
  4181. module.exports = exports['default'];
  4182. },{}],19:[function(require,module,exports){
  4183. (function (global){
  4184. /**
  4185. * @file xhr.js
  4186. */
  4187. /**
  4188. * A wrapper for videojs.xhr that tracks bandwidth.
  4189. *
  4190. * @param {Object} options options for the XHR
  4191. * @param {Function} callback the callback to call when done
  4192. * @return {Request} the xhr request that is going to be made
  4193. */
  4194. 'use strict';
  4195. Object.defineProperty(exports, '__esModule', {
  4196. value: true
  4197. });
  4198. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  4199. var xhrFactory = function xhrFactory() {
  4200. var xhr = function XhrFunction(options, callback) {
  4201. // Add a default timeout for all hls requests
  4202. options = (0, _videoJs.mergeOptions)({
  4203. timeout: 45e3
  4204. }, options);
  4205. // Allow an optional user-specified function to modify the option
  4206. // object before we construct the xhr request
  4207. if (XhrFunction.beforeRequest && typeof XhrFunction.beforeRequest === 'function') {
  4208. var newOptions = XhrFunction.beforeRequest(options);
  4209. if (newOptions) {
  4210. options = newOptions;
  4211. }
  4212. }
  4213. var request = (0, _videoJs.xhr)(options, function (error, response) {
  4214. if (!error && request.response) {
  4215. request.responseTime = new Date().getTime();
  4216. request.roundTripTime = request.responseTime - request.requestTime;
  4217. request.bytesReceived = request.response.byteLength || request.response.length;
  4218. if (!request.bandwidth) {
  4219. request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
  4220. }
  4221. }
  4222. // videojs.xhr now uses a specific code
  4223. // on the error object to signal that a request has
  4224. // timed out errors of setting a boolean on the request object
  4225. if (error || request.timedout) {
  4226. request.timedout = request.timedout || error.code === 'ETIMEDOUT';
  4227. } else {
  4228. request.timedout = false;
  4229. }
  4230. // videojs.xhr no longer considers status codes outside of 200 and 0
  4231. // (for file uris) to be errors, but the old XHR did, so emulate that
  4232. // behavior. Status 206 may be used in response to byterange requests.
  4233. if (!error && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
  4234. error = new Error('XHR Failed with a response of: ' + (request && (request.response || request.responseText)));
  4235. }
  4236. callback(error, request);
  4237. });
  4238. request.requestTime = new Date().getTime();
  4239. return request;
  4240. };
  4241. return xhr;
  4242. };
  4243. exports['default'] = xhrFactory;
  4244. module.exports = exports['default'];
  4245. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4246. },{}],20:[function(require,module,exports){
  4247. },{}],21:[function(require,module,exports){
  4248. (function (global){
  4249. var topLevel = typeof global !== 'undefined' ? global :
  4250. typeof window !== 'undefined' ? window : {}
  4251. var minDoc = require('min-document');
  4252. if (typeof document !== 'undefined') {
  4253. module.exports = document;
  4254. } else {
  4255. var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
  4256. if (!doccy) {
  4257. doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
  4258. }
  4259. module.exports = doccy;
  4260. }
  4261. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4262. },{"min-document":20}],22:[function(require,module,exports){
  4263. /*
  4264. * pkcs7.pad
  4265. * https://github.com/brightcove/pkcs7
  4266. *
  4267. * Copyright (c) 2014 Brightcove
  4268. * Licensed under the apache2 license.
  4269. */
  4270. 'use strict';
  4271. var PADDING;
  4272. /**
  4273. * Returns a new Uint8Array that is padded with PKCS#7 padding.
  4274. * @param plaintext {Uint8Array} the input bytes before encryption
  4275. * @return {Uint8Array} the padded bytes
  4276. * @see http://tools.ietf.org/html/rfc5652
  4277. */
  4278. module.exports = function pad(plaintext) {
  4279. var padding = PADDING[(plaintext.byteLength % 16) || 0],
  4280. result = new Uint8Array(plaintext.byteLength + padding.length);
  4281. result.set(plaintext);
  4282. result.set(padding, plaintext.byteLength);
  4283. return result;
  4284. };
  4285. // pre-define the padding values
  4286. PADDING = [
  4287. [16, 16, 16, 16,
  4288. 16, 16, 16, 16,
  4289. 16, 16, 16, 16,
  4290. 16, 16, 16, 16],
  4291. [15, 15, 15, 15,
  4292. 15, 15, 15, 15,
  4293. 15, 15, 15, 15,
  4294. 15, 15, 15],
  4295. [14, 14, 14, 14,
  4296. 14, 14, 14, 14,
  4297. 14, 14, 14, 14,
  4298. 14, 14],
  4299. [13, 13, 13, 13,
  4300. 13, 13, 13, 13,
  4301. 13, 13, 13, 13,
  4302. 13],
  4303. [12, 12, 12, 12,
  4304. 12, 12, 12, 12,
  4305. 12, 12, 12, 12],
  4306. [11, 11, 11, 11,
  4307. 11, 11, 11, 11,
  4308. 11, 11, 11],
  4309. [10, 10, 10, 10,
  4310. 10, 10, 10, 10,
  4311. 10, 10],
  4312. [9, 9, 9, 9,
  4313. 9, 9, 9, 9,
  4314. 9],
  4315. [8, 8, 8, 8,
  4316. 8, 8, 8, 8],
  4317. [7, 7, 7, 7,
  4318. 7, 7, 7],
  4319. [6, 6, 6, 6,
  4320. 6, 6],
  4321. [5, 5, 5, 5,
  4322. 5],
  4323. [4, 4, 4, 4],
  4324. [3, 3, 3],
  4325. [2, 2],
  4326. [1]
  4327. ];
  4328. },{}],23:[function(require,module,exports){
  4329. /*
  4330. * pkcs7
  4331. * https://github.com/brightcove/pkcs7
  4332. *
  4333. * Copyright (c) 2014 Brightcove
  4334. * Licensed under the apache2 license.
  4335. */
  4336. 'use strict';
  4337. exports.pad = require('./pad.js');
  4338. exports.unpad = require('./unpad.js');
  4339. },{"./pad.js":22,"./unpad.js":24}],24:[function(require,module,exports){
  4340. /*
  4341. * pkcs7.unpad
  4342. * https://github.com/brightcove/pkcs7
  4343. *
  4344. * Copyright (c) 2014 Brightcove
  4345. * Licensed under the apache2 license.
  4346. */
  4347. 'use strict';
  4348. /**
  4349. * Returns the subarray of a Uint8Array without PKCS#7 padding.
  4350. * @param padded {Uint8Array} unencrypted bytes that have been padded
  4351. * @return {Uint8Array} the unpadded bytes
  4352. * @see http://tools.ietf.org/html/rfc5652
  4353. */
  4354. module.exports = function unpad(padded) {
  4355. return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
  4356. };
  4357. },{}],25:[function(require,module,exports){
  4358. (function (global){
  4359. /**
  4360. * @file add-text-track-data.js
  4361. */
  4362. 'use strict';
  4363. Object.defineProperty(exports, '__esModule', {
  4364. value: true
  4365. });
  4366. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  4367. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  4368. var _videoJs2 = _interopRequireDefault(_videoJs);
  4369. /**
  4370. * Define properties on a cue for backwards compatability,
  4371. * but warn the user that the way that they are using it
  4372. * is depricated and will be removed at a later date.
  4373. *
  4374. * @param {Cue} cue the cue to add the properties on
  4375. * @private
  4376. */
  4377. var deprecateOldCue = function deprecateOldCue(cue) {
  4378. Object.defineProperties(cue.frame, {
  4379. id: {
  4380. get: function get() {
  4381. _videoJs2['default'].log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
  4382. return cue.value.key;
  4383. }
  4384. },
  4385. value: {
  4386. get: function get() {
  4387. _videoJs2['default'].log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
  4388. return cue.value.data;
  4389. }
  4390. },
  4391. privateData: {
  4392. get: function get() {
  4393. _videoJs2['default'].log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
  4394. return cue.value.data;
  4395. }
  4396. }
  4397. });
  4398. };
  4399. /**
  4400. * Add text track data to a source handler given the captions and
  4401. * metadata from the buffer.
  4402. *
  4403. * @param {Object} sourceHandler the flash or virtual source buffer
  4404. * @param {Array} captionArray an array of caption data
  4405. * @param {Array} cue an array of meta data
  4406. * @private
  4407. */
  4408. var addTextTrackData = function addTextTrackData(sourceHandler, captionArray, metadataArray) {
  4409. var Cue = window.WebKitDataCue || window.VTTCue;
  4410. if (captionArray) {
  4411. captionArray.forEach(function (caption) {
  4412. this.inbandTextTrack_.addCue(new Cue(caption.startTime + this.timestampOffset, caption.endTime + this.timestampOffset, caption.text));
  4413. }, sourceHandler);
  4414. }
  4415. if (metadataArray) {
  4416. metadataArray.forEach(function (metadata) {
  4417. var time = metadata.cueTime + this.timestampOffset;
  4418. metadata.frames.forEach(function (frame) {
  4419. var cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
  4420. cue.frame = frame;
  4421. cue.value = frame;
  4422. deprecateOldCue(cue);
  4423. this.metadataTrack_.addCue(cue);
  4424. }, this);
  4425. }, sourceHandler);
  4426. }
  4427. };
  4428. exports['default'] = addTextTrackData;
  4429. module.exports = exports['default'];
  4430. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4431. },{}],26:[function(require,module,exports){
  4432. /**
  4433. * @file codec-utils.js
  4434. */
  4435. /**
  4436. * Check if a codec string refers to an audio codec.
  4437. *
  4438. * @param {String} codec codec string to check
  4439. * @return {Boolean} if this is an audio codec
  4440. * @private
  4441. */
  4442. 'use strict';
  4443. Object.defineProperty(exports, '__esModule', {
  4444. value: true
  4445. });
  4446. var isAudioCodec = function isAudioCodec(codec) {
  4447. return (/mp4a\.\d+.\d+/i.test(codec)
  4448. );
  4449. };
  4450. /**
  4451. * Check if a codec string refers to a video codec.
  4452. *
  4453. * @param {String} codec codec string to check
  4454. * @return {Boolean} if this is a video codec
  4455. * @private
  4456. */
  4457. var isVideoCodec = function isVideoCodec(codec) {
  4458. return (/avc1\.[\da-f]+/i.test(codec)
  4459. );
  4460. };
  4461. /**
  4462. * Parse a content type header into a type and parameters
  4463. * object
  4464. *
  4465. * @param {String} type the content type header
  4466. * @return {Object} the parsed content-type
  4467. * @private
  4468. */
  4469. var parseContentType = function parseContentType(type) {
  4470. var object = { type: '', parameters: {} };
  4471. var parameters = type.trim().split(';');
  4472. // first parameter should always be content-type
  4473. object.type = parameters.shift().trim();
  4474. parameters.forEach(function (parameter) {
  4475. var pair = parameter.trim().split('=');
  4476. if (pair.length > 1) {
  4477. var _name = pair[0].replace(/"/g, '').trim();
  4478. var value = pair[1].replace(/"/g, '').trim();
  4479. object.parameters[_name] = value;
  4480. }
  4481. });
  4482. return object;
  4483. };
  4484. exports['default'] = {
  4485. isAudioCodec: isAudioCodec,
  4486. parseContentType: parseContentType,
  4487. isVideoCodec: isVideoCodec
  4488. };
  4489. module.exports = exports['default'];
  4490. },{}],27:[function(require,module,exports){
  4491. /**
  4492. * @file create-text-tracks-if-necessary.js
  4493. */
  4494. /**
  4495. * Create text tracks on video.js if they exist on a segment.
  4496. *
  4497. * @param {Object} sourceBuffer the VSB or FSB
  4498. * @param {Object} mediaSource the HTML or Flash media source
  4499. * @param {Object} segment the segment that may contain the text track
  4500. * @private
  4501. */
  4502. 'use strict';
  4503. Object.defineProperty(exports, '__esModule', {
  4504. value: true
  4505. });
  4506. var createTextTracksIfNecessary = function createTextTracksIfNecessary(sourceBuffer, mediaSource, segment) {
  4507. // create an in-band caption track if one is present in the segment
  4508. if (segment.captions && segment.captions.length && !sourceBuffer.inbandTextTrack_) {
  4509. sourceBuffer.inbandTextTrack_ = mediaSource.player_.addTextTrack('captions', 'cc1');
  4510. }
  4511. if (segment.metadata && segment.metadata.length && !sourceBuffer.metadataTrack_) {
  4512. sourceBuffer.metadataTrack_ = mediaSource.player_.addTextTrack('metadata', 'Timed Metadata');
  4513. sourceBuffer.metadataTrack_.inBandMetadataTrackDispatchType = segment.metadata.dispatchType;
  4514. }
  4515. };
  4516. exports['default'] = createTextTracksIfNecessary;
  4517. module.exports = exports['default'];
  4518. },{}],28:[function(require,module,exports){
  4519. /**
  4520. * @file flash-constants.js
  4521. */
  4522. /**
  4523. * The maximum size in bytes for append operations to the video.js
  4524. * SWF. Calling through to Flash blocks and can be expensive so
  4525. * tuning this parameter may improve playback on slower
  4526. * systems. There are two factors to consider:
  4527. * - Each interaction with the SWF must be quick or you risk dropping
  4528. * video frames. To maintain 60fps for the rest of the page, each append
  4529. * must not take longer than 16ms. Given the likelihood that the page
  4530. * will be executing more javascript than just playback, you probably
  4531. * want to aim for less than 8ms. We aim for just 4ms.
  4532. * - Bigger appends significantly increase throughput. The total number of
  4533. * bytes over time delivered to the SWF must exceed the video bitrate or
  4534. * playback will stall.
  4535. *
  4536. * We adaptively tune the size of appends to give the best throughput
  4537. * possible given the performance of the system. To do that we try to append
  4538. * as much as possible in TIME_PER_TICK and while tuning the size of appends
  4539. * dynamically so that we only append about 4-times in that 4ms span.
  4540. *
  4541. * The reason we try to keep the number of appends around four is due to
  4542. * externalities such as Flash load and garbage collection that are highly
  4543. * variable and having 4 iterations allows us to exit the loop early if
  4544. * an iteration takes longer than expected.
  4545. *
  4546. * @private
  4547. */
  4548. "use strict";
  4549. Object.defineProperty(exports, "__esModule", {
  4550. value: true
  4551. });
  4552. var flashConstants = {
  4553. TIME_BETWEEN_TICKS: Math.floor(1000 / 480),
  4554. TIME_PER_TICK: Math.floor(1000 / 240),
  4555. // 1kb
  4556. BYTES_PER_CHUNK: 1 * 1024,
  4557. MIN_CHUNK: 1024,
  4558. MAX_CHUNK: 1024 * 1024
  4559. };
  4560. exports["default"] = flashConstants;
  4561. module.exports = exports["default"];
  4562. },{}],29:[function(require,module,exports){
  4563. (function (global){
  4564. /**
  4565. * @file flash-media-source.js
  4566. */
  4567. 'use strict';
  4568. Object.defineProperty(exports, '__esModule', {
  4569. value: true
  4570. });
  4571. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  4572. var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  4573. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  4574. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  4575. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  4576. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  4577. var _videoJs2 = _interopRequireDefault(_videoJs);
  4578. var _flashSourceBuffer = require('./flash-source-buffer');
  4579. var _flashSourceBuffer2 = _interopRequireDefault(_flashSourceBuffer);
  4580. var _flashConstants = require('./flash-constants');
  4581. var _flashConstants2 = _interopRequireDefault(_flashConstants);
  4582. var _codecUtils = require('./codec-utils');
  4583. /**
  4584. * A flash implmentation of HTML MediaSources and a polyfill
  4585. * for browsers that don't support native or HTML MediaSources..
  4586. *
  4587. * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource
  4588. * @class FlashMediaSource
  4589. * @extends videojs.EventTarget
  4590. */
  4591. var FlashMediaSource = (function (_videojs$EventTarget) {
  4592. _inherits(FlashMediaSource, _videojs$EventTarget);
  4593. function FlashMediaSource() {
  4594. var _this = this;
  4595. _classCallCheck(this, FlashMediaSource);
  4596. _get(Object.getPrototypeOf(FlashMediaSource.prototype), 'constructor', this).call(this);
  4597. this.sourceBuffers = [];
  4598. this.readyState = 'closed';
  4599. this.on(['sourceopen', 'webkitsourceopen'], function (event) {
  4600. // find the swf where we will push media data
  4601. _this.swfObj = document.getElementById(event.swfId);
  4602. _this.player_ = (0, _videoJs2['default'])(_this.swfObj.parentNode);
  4603. _this.tech_ = _this.swfObj.tech;
  4604. _this.readyState = 'open';
  4605. _this.tech_.on('seeking', function () {
  4606. var i = _this.sourceBuffers.length;
  4607. while (i--) {
  4608. _this.sourceBuffers[i].abort();
  4609. }
  4610. });
  4611. // trigger load events
  4612. if (_this.swfObj) {
  4613. _this.swfObj.vjs_load();
  4614. }
  4615. });
  4616. }
  4617. /**
  4618. * Set or return the presentation duration.
  4619. *
  4620. * @param {Double} value the duration of the media in seconds
  4621. * @param {Double} the current presentation duration
  4622. * @link http://www.w3.org/TR/media-source/#widl-MediaSource-duration
  4623. */
  4624. /**
  4625. * We have this function so that the html and flash interfaces
  4626. * are the same.
  4627. *
  4628. * @private
  4629. */
  4630. _createClass(FlashMediaSource, [{
  4631. key: 'addSeekableRange_',
  4632. value: function addSeekableRange_() {}
  4633. // intentional no-op
  4634. /**
  4635. * Create a new flash source buffer and add it to our flash media source.
  4636. *
  4637. * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/addSourceBuffer
  4638. * @param {String} type the content-type of the source
  4639. * @return {Object} the flash source buffer
  4640. */
  4641. }, {
  4642. key: 'addSourceBuffer',
  4643. value: function addSourceBuffer(type) {
  4644. var parsedType = (0, _codecUtils.parseContentType)(type);
  4645. var sourceBuffer = undefined;
  4646. // if this is an FLV type, we'll push data to flash
  4647. if (parsedType.type === 'video/mp2t') {
  4648. // Flash source buffers
  4649. sourceBuffer = new _flashSourceBuffer2['default'](this);
  4650. } else {
  4651. throw new Error('NotSupportedError (Video.js)');
  4652. }
  4653. this.sourceBuffers.push(sourceBuffer);
  4654. return sourceBuffer;
  4655. }
  4656. /**
  4657. * Signals the end of the stream.
  4658. *
  4659. * @link https://w3c.github.io/media-source/#widl-MediaSource-endOfStream-void-EndOfStreamError-error
  4660. * @param {String=} error Signals that a playback error
  4661. * has occurred. If specified, it must be either "network" or
  4662. * "decode".
  4663. */
  4664. }, {
  4665. key: 'endOfStream',
  4666. value: function endOfStream(error) {
  4667. if (error === 'network') {
  4668. // MEDIA_ERR_NETWORK
  4669. this.tech_.error(2);
  4670. } else if (error === 'decode') {
  4671. // MEDIA_ERR_DECODE
  4672. this.tech_.error(3);
  4673. }
  4674. if (this.readyState !== 'ended') {
  4675. this.readyState = 'ended';
  4676. this.swfObj.vjs_endOfStream();
  4677. }
  4678. }
  4679. }]);
  4680. return FlashMediaSource;
  4681. })(_videoJs2['default'].EventTarget);
  4682. exports['default'] = FlashMediaSource;
  4683. try {
  4684. Object.defineProperty(FlashMediaSource.prototype, 'duration', {
  4685. /**
  4686. * Return the presentation duration.
  4687. *
  4688. * @return {Double} the duration of the media in seconds
  4689. * @link http://www.w3.org/TR/media-source/#widl-MediaSource-duration
  4690. */
  4691. get: function get() {
  4692. if (!this.swfObj) {
  4693. return NaN;
  4694. }
  4695. // get the current duration from the SWF
  4696. return this.swfObj.vjs_getProperty('duration');
  4697. },
  4698. /**
  4699. * Set the presentation duration.
  4700. *
  4701. * @param {Double} value the duration of the media in seconds
  4702. * @return {Double} the duration of the media in seconds
  4703. * @link http://www.w3.org/TR/media-source/#widl-MediaSource-duration
  4704. */
  4705. set: function set(value) {
  4706. var i = undefined;
  4707. var oldDuration = this.swfObj.vjs_getProperty('duration');
  4708. this.swfObj.vjs_setProperty('duration', value);
  4709. if (value < oldDuration) {
  4710. // In MSE, this triggers the range removal algorithm which causes
  4711. // an update to occur
  4712. for (i = 0; i < this.sourceBuffers.length; i++) {
  4713. this.sourceBuffers[i].remove(value, oldDuration);
  4714. }
  4715. }
  4716. return value;
  4717. }
  4718. });
  4719. } catch (e) {
  4720. // IE8 throws if defineProperty is called on a non-DOM node. We
  4721. // don't support IE8 but we shouldn't throw an error if loaded
  4722. // there.
  4723. FlashMediaSource.prototype.duration = NaN;
  4724. }
  4725. for (var property in _flashConstants2['default']) {
  4726. FlashMediaSource[property] = _flashConstants2['default'][property];
  4727. }
  4728. module.exports = exports['default'];
  4729. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4730. },{"./codec-utils":26,"./flash-constants":28,"./flash-source-buffer":30}],30:[function(require,module,exports){
  4731. (function (global){
  4732. /**
  4733. * @file flash-source-buffer.js
  4734. */
  4735. 'use strict';
  4736. Object.defineProperty(exports, '__esModule', {
  4737. value: true
  4738. });
  4739. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  4740. var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  4741. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  4742. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  4743. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  4744. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  4745. var _videoJs2 = _interopRequireDefault(_videoJs);
  4746. var _muxJs = require('mux.js');
  4747. var _muxJs2 = _interopRequireDefault(_muxJs);
  4748. var _removeCuesFromTrack = require('./remove-cues-from-track');
  4749. var _removeCuesFromTrack2 = _interopRequireDefault(_removeCuesFromTrack);
  4750. var _createTextTracksIfNecessary = require('./create-text-tracks-if-necessary');
  4751. var _createTextTracksIfNecessary2 = _interopRequireDefault(_createTextTracksIfNecessary);
  4752. var _addTextTrackData = require('./add-text-track-data');
  4753. var _addTextTrackData2 = _interopRequireDefault(_addTextTrackData);
  4754. var _flashConstants = require('./flash-constants');
  4755. var _flashConstants2 = _interopRequireDefault(_flashConstants);
  4756. /**
  4757. * A wrapper around the setTimeout function that uses
  4758. * the flash constant time between ticks value.
  4759. *
  4760. * @param {Function} func the function callback to run
  4761. * @private
  4762. */
  4763. var scheduleTick = function scheduleTick(func) {
  4764. // Chrome doesn't invoke requestAnimationFrame callbacks
  4765. // in background tabs, so use setTimeout.
  4766. window.setTimeout(func, _flashConstants2['default'].TIME_BETWEEN_TICKS);
  4767. };
  4768. /**
  4769. * Round a number to a specified number of places much like
  4770. * toFixed but return a number instead of a string representation.
  4771. *
  4772. * @param {Number} num A number
  4773. * @param {Number} places The number of decimal places which to
  4774. * round
  4775. * @private
  4776. */
  4777. var toDecimalPlaces = function toDecimalPlaces(num, places) {
  4778. if (typeof places !== 'number' || places < 0) {
  4779. places = 0;
  4780. }
  4781. var scale = Math.pow(10, places);
  4782. return Math.round(num * scale) / scale;
  4783. };
  4784. /**
  4785. * A SourceBuffer implementation for Flash rather than HTML.
  4786. *
  4787. * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource
  4788. * @param {Object} mediaSource the flash media source
  4789. * @class FlashSourceBuffer
  4790. * @extends videojs.EventTarget
  4791. */
  4792. var FlashSourceBuffer = (function (_videojs$EventTarget) {
  4793. _inherits(FlashSourceBuffer, _videojs$EventTarget);
  4794. function FlashSourceBuffer(mediaSource) {
  4795. var _this = this;
  4796. _classCallCheck(this, FlashSourceBuffer);
  4797. _get(Object.getPrototypeOf(FlashSourceBuffer.prototype), 'constructor', this).call(this);
  4798. var encodedHeader = undefined;
  4799. // Start off using the globally defined value but refine
  4800. // as we append data into flash
  4801. this.chunkSize_ = _flashConstants2['default'].BYTES_PER_CHUNK;
  4802. // byte arrays queued to be appended
  4803. this.buffer_ = [];
  4804. // the total number of queued bytes
  4805. this.bufferSize_ = 0;
  4806. // to be able to determine the correct position to seek to, we
  4807. // need to retain information about the mapping between the
  4808. // media timeline and PTS values
  4809. this.basePtsOffset_ = NaN;
  4810. this.mediaSource = mediaSource;
  4811. // indicates whether the asynchronous continuation of an operation
  4812. // is still being processed
  4813. // see https://w3c.github.io/media-source/#widl-SourceBuffer-updating
  4814. this.updating = false;
  4815. this.timestampOffset_ = 0;
  4816. // TS to FLV transmuxer
  4817. this.segmentParser_ = new _muxJs2['default'].flv.Transmuxer();
  4818. this.segmentParser_.on('data', this.receiveBuffer_.bind(this));
  4819. encodedHeader = window.btoa(String.fromCharCode.apply(null, Array.prototype.slice.call(this.segmentParser_.getFlvHeader())));
  4820. this.mediaSource.swfObj.vjs_appendBuffer(encodedHeader);
  4821. Object.defineProperty(this, 'timestampOffset', {
  4822. get: function get() {
  4823. return this.timestampOffset_;
  4824. },
  4825. set: function set(val) {
  4826. if (typeof val === 'number' && val >= 0) {
  4827. this.timestampOffset_ = val;
  4828. this.segmentParser_ = new _muxJs2['default'].flv.Transmuxer();
  4829. this.segmentParser_.on('data', this.receiveBuffer_.bind(this));
  4830. // We have to tell flash to expect a discontinuity
  4831. this.mediaSource.swfObj.vjs_discontinuity();
  4832. // the media <-> PTS mapping must be re-established after
  4833. // the discontinuity
  4834. this.basePtsOffset_ = NaN;
  4835. }
  4836. }
  4837. });
  4838. Object.defineProperty(this, 'buffered', {
  4839. get: function get() {
  4840. if (!this.mediaSource || !this.mediaSource.swfObj || !('vjs_getProperty' in this.mediaSource.swfObj)) {
  4841. return _videoJs2['default'].createTimeRange();
  4842. }
  4843. var buffered = this.mediaSource.swfObj.vjs_getProperty('buffered');
  4844. if (buffered && buffered.length) {
  4845. buffered[0][0] = toDecimalPlaces(buffered[0][0], 3);
  4846. buffered[0][1] = toDecimalPlaces(buffered[0][1], 3);
  4847. }
  4848. return _videoJs2['default'].createTimeRanges(buffered);
  4849. }
  4850. });
  4851. // On a seek we remove all text track data since flash has no concept
  4852. // of a buffered-range and everything else is reset on seek
  4853. this.mediaSource.player_.on('seeked', function () {
  4854. (0, _removeCuesFromTrack2['default'])(0, Infinity, _this.metadataTrack_);
  4855. (0, _removeCuesFromTrack2['default'])(0, Infinity, _this.inbandTextTrack_);
  4856. });
  4857. }
  4858. /**
  4859. * Append bytes to the sourcebuffers buffer, in this case we
  4860. * have to append it to swf object.
  4861. *
  4862. * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/appendBuffer
  4863. * @param {Array} bytes
  4864. */
  4865. _createClass(FlashSourceBuffer, [{
  4866. key: 'appendBuffer',
  4867. value: function appendBuffer(bytes) {
  4868. var _this2 = this;
  4869. var error = undefined;
  4870. var chunk = 512 * 1024;
  4871. var i = 0;
  4872. if (this.updating) {
  4873. error = new Error('SourceBuffer.append() cannot be called ' + 'while an update is in progress');
  4874. error.name = 'InvalidStateError';
  4875. error.code = 11;
  4876. throw error;
  4877. }
  4878. this.updating = true;
  4879. this.mediaSource.readyState = 'open';
  4880. this.trigger({ type: 'update' });
  4881. // this is here to use recursion
  4882. var chunkInData = function chunkInData() {
  4883. _this2.segmentParser_.push(bytes.subarray(i, i + chunk));
  4884. i += chunk;
  4885. if (i < bytes.byteLength) {
  4886. scheduleTick(chunkInData);
  4887. } else {
  4888. scheduleTick(_this2.segmentParser_.flush.bind(_this2.segmentParser_));
  4889. }
  4890. };
  4891. chunkInData();
  4892. }
  4893. /**
  4894. * Reset the parser and remove any data queued to be sent to the SWF.
  4895. *
  4896. * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/abort
  4897. */
  4898. }, {
  4899. key: 'abort',
  4900. value: function abort() {
  4901. this.buffer_ = [];
  4902. this.bufferSize_ = 0;
  4903. this.mediaSource.swfObj.vjs_abort();
  4904. // report any outstanding updates have ended
  4905. if (this.updating) {
  4906. this.updating = false;
  4907. this.trigger({ type: 'updateend' });
  4908. }
  4909. }
  4910. /**
  4911. * Flash cannot remove ranges already buffered in the NetStream
  4912. * but seeking clears the buffer entirely. For most purposes,
  4913. * having this operation act as a no-op is acceptable.
  4914. *
  4915. * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/remove
  4916. * @param {Double} start start of the section to remove
  4917. * @param {Double} end end of the section to remove
  4918. */
  4919. }, {
  4920. key: 'remove',
  4921. value: function remove(start, end) {
  4922. (0, _removeCuesFromTrack2['default'])(start, end, this.metadataTrack_);
  4923. (0, _removeCuesFromTrack2['default'])(start, end, this.inbandTextTrack_);
  4924. this.trigger({ type: 'update' });
  4925. this.trigger({ type: 'updateend' });
  4926. }
  4927. /**
  4928. * Receive a buffer from the flv.
  4929. *
  4930. * @param {Object} segment
  4931. * @private
  4932. */
  4933. }, {
  4934. key: 'receiveBuffer_',
  4935. value: function receiveBuffer_(segment) {
  4936. var _this3 = this;
  4937. // create an in-band caption track if one is present in the segment
  4938. (0, _createTextTracksIfNecessary2['default'])(this, this.mediaSource, segment);
  4939. (0, _addTextTrackData2['default'])(this, segment.captions, segment.metadata);
  4940. // Do this asynchronously since convertTagsToData_ can be time consuming
  4941. scheduleTick(function () {
  4942. var flvBytes = _this3.convertTagsToData_(segment);
  4943. if (_this3.buffer_.length === 0) {
  4944. scheduleTick(_this3.processBuffer_.bind(_this3));
  4945. }
  4946. if (flvBytes) {
  4947. _this3.buffer_.push(flvBytes);
  4948. _this3.bufferSize_ += flvBytes.byteLength;
  4949. }
  4950. });
  4951. }
  4952. /**
  4953. * Append a portion of the current buffer to the SWF.
  4954. *
  4955. * @private
  4956. */
  4957. }, {
  4958. key: 'processBuffer_',
  4959. value: function processBuffer_() {
  4960. var chunk = undefined;
  4961. var i = undefined;
  4962. var length = undefined;
  4963. var binary = undefined;
  4964. var b64str = undefined;
  4965. var startByte = 0;
  4966. var appendIterations = 0;
  4967. var startTime = +new Date();
  4968. var appendTime = undefined;
  4969. if (!this.buffer_.length) {
  4970. if (this.updating !== false) {
  4971. this.updating = false;
  4972. this.trigger({ type: 'updateend' });
  4973. }
  4974. // do nothing if the buffer is empty
  4975. return;
  4976. }
  4977. do {
  4978. appendIterations++;
  4979. // concatenate appends up to the max append size
  4980. chunk = this.buffer_[0].subarray(startByte, startByte + this.chunkSize_);
  4981. // requeue any bytes that won't make it this round
  4982. if (chunk.byteLength < this.chunkSize_ || this.buffer_[0].byteLength === startByte + this.chunkSize_) {
  4983. startByte = 0;
  4984. this.buffer_.shift();
  4985. } else {
  4986. startByte += this.chunkSize_;
  4987. }
  4988. this.bufferSize_ -= chunk.byteLength;
  4989. // base64 encode the bytes
  4990. binary = '';
  4991. length = chunk.byteLength;
  4992. for (i = 0; i < length; i++) {
  4993. binary += String.fromCharCode(chunk[i]);
  4994. }
  4995. b64str = window.btoa(binary);
  4996. // bypass normal ExternalInterface calls and pass xml directly
  4997. // IE can be slow by default
  4998. this.mediaSource.swfObj.CallFunction('<invoke name="vjs_appendBuffer"' + 'returntype="javascript"><arguments><string>' + b64str + '</string></arguments></invoke>');
  4999. appendTime = new Date() - startTime;
  5000. } while (this.buffer_.length && appendTime < _flashConstants2['default'].TIME_PER_TICK);
  5001. if (this.buffer_.length && startByte) {
  5002. this.buffer_[0] = this.buffer_[0].subarray(startByte);
  5003. }
  5004. if (appendTime >= _flashConstants2['default'].TIME_PER_TICK) {
  5005. // We want to target 4 iterations per time-slot so that gives us
  5006. // room to adjust to changes in Flash load and other externalities
  5007. // such as garbage collection while still maximizing throughput
  5008. this.chunkSize_ = Math.floor(this.chunkSize_ * (appendIterations / 4));
  5009. }
  5010. // We also make sure that the chunk-size doesn't drop below 1KB or
  5011. // go above 1MB as a sanity check
  5012. this.chunkSize_ = Math.max(_flashConstants2['default'].MIN_CHUNK, Math.min(this.chunkSize_, _flashConstants2['default'].MAX_CHUNK));
  5013. // schedule another append if necessary
  5014. if (this.bufferSize_ !== 0) {
  5015. scheduleTick(this.processBuffer_.bind(this));
  5016. } else {
  5017. this.updating = false;
  5018. this.trigger({ type: 'updateend' });
  5019. }
  5020. }
  5021. /**
  5022. * Turns an array of flv tags into a Uint8Array representing the
  5023. * flv data. Also removes any tags that are before the current
  5024. * time so that playback begins at or slightly after the right
  5025. * place on a seek
  5026. *
  5027. * @private
  5028. * @param {Object} segmentData object of segment data
  5029. */
  5030. }, {
  5031. key: 'convertTagsToData_',
  5032. value: function convertTagsToData_(segmentData) {
  5033. var segmentByteLength = 0;
  5034. var tech = this.mediaSource.tech_;
  5035. var targetPts = 0;
  5036. var i = undefined;
  5037. var j = undefined;
  5038. var segment = undefined;
  5039. var filteredTags = [];
  5040. var tags = this.getOrderedTags_(segmentData);
  5041. // Establish the media timeline to PTS translation if we don't
  5042. // have one already
  5043. if (isNaN(this.basePtsOffset_) && tags.length) {
  5044. this.basePtsOffset_ = tags[0].pts;
  5045. }
  5046. // Trim any tags that are before the end of the end of
  5047. // the current buffer
  5048. if (tech.buffered().length) {
  5049. targetPts = tech.buffered().end(0) - this.timestampOffset;
  5050. }
  5051. // Trim to currentTime if it's ahead of buffered or buffered doesn't exist
  5052. targetPts = Math.max(targetPts, tech.currentTime() - this.timestampOffset);
  5053. // PTS values are represented in milliseconds
  5054. targetPts *= 1e3;
  5055. targetPts += this.basePtsOffset_;
  5056. // skip tags with a presentation time less than the seek target
  5057. for (i = 0; i < tags.length; i++) {
  5058. if (tags[i].pts >= targetPts) {
  5059. filteredTags.push(tags[i]);
  5060. }
  5061. }
  5062. if (filteredTags.length === 0) {
  5063. return;
  5064. }
  5065. // concatenate the bytes into a single segment
  5066. for (i = 0; i < filteredTags.length; i++) {
  5067. segmentByteLength += filteredTags[i].bytes.byteLength;
  5068. }
  5069. segment = new Uint8Array(segmentByteLength);
  5070. for (i = 0, j = 0; i < filteredTags.length; i++) {
  5071. segment.set(filteredTags[i].bytes, j);
  5072. j += filteredTags[i].bytes.byteLength;
  5073. }
  5074. return segment;
  5075. }
  5076. /**
  5077. * Assemble the FLV tags in decoder order.
  5078. *
  5079. * @private
  5080. * @param {Object} segmentData object of segment data
  5081. */
  5082. }, {
  5083. key: 'getOrderedTags_',
  5084. value: function getOrderedTags_(segmentData) {
  5085. var videoTags = segmentData.tags.videoTags;
  5086. var audioTags = segmentData.tags.audioTags;
  5087. var tag = undefined;
  5088. var tags = [];
  5089. while (videoTags.length || audioTags.length) {
  5090. if (!videoTags.length) {
  5091. // only audio tags remain
  5092. tag = audioTags.shift();
  5093. } else if (!audioTags.length) {
  5094. // only video tags remain
  5095. tag = videoTags.shift();
  5096. } else if (audioTags[0].dts < videoTags[0].dts) {
  5097. // audio should be decoded next
  5098. tag = audioTags.shift();
  5099. } else {
  5100. // video should be decoded next
  5101. tag = videoTags.shift();
  5102. }
  5103. tags.push(tag.finalize());
  5104. }
  5105. return tags;
  5106. }
  5107. }]);
  5108. return FlashSourceBuffer;
  5109. })(_videoJs2['default'].EventTarget);
  5110. exports['default'] = FlashSourceBuffer;
  5111. module.exports = exports['default'];
  5112. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  5113. },{"./add-text-track-data":25,"./create-text-tracks-if-necessary":27,"./flash-constants":28,"./remove-cues-from-track":32,"mux.js":43}],31:[function(require,module,exports){
  5114. (function (global){
  5115. /**
  5116. * @file html-media-source.js
  5117. */
  5118. 'use strict';
  5119. Object.defineProperty(exports, '__esModule', {
  5120. value: true
  5121. });
  5122. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  5123. var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  5124. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  5125. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  5126. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  5127. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  5128. var _videoJs2 = _interopRequireDefault(_videoJs);
  5129. var _virtualSourceBuffer = require('./virtual-source-buffer');
  5130. var _virtualSourceBuffer2 = _interopRequireDefault(_virtualSourceBuffer);
  5131. var _codecUtils = require('./codec-utils');
  5132. /**
  5133. * Replace the old apple-style `avc1.<dd>.<dd>` codec string with the standard
  5134. * `avc1.<hhhhhh>`
  5135. *
  5136. * @param {Array} codecs an array of codec strings to fix
  5137. * @return {Array} the translated codec array
  5138. * @private
  5139. */
  5140. var translateLegacyCodecs = function translateLegacyCodecs(codecs) {
  5141. return codecs.map(function (codec) {
  5142. return codec.replace(/avc1\.(\d+)\.(\d+)/i, function (orig, profile, avcLevel) {
  5143. var profileHex = ('00' + Number(profile).toString(16)).slice(-2);
  5144. var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);
  5145. return 'avc1.' + profileHex + '00' + avcLevelHex;
  5146. });
  5147. });
  5148. };
  5149. /**
  5150. * Our MediaSource implementation in HTML, mimics native
  5151. * MediaSource where/if possible.
  5152. *
  5153. * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource
  5154. * @class HtmlMediaSource
  5155. * @extends videojs.EventTarget
  5156. */
  5157. var HtmlMediaSource = (function (_videojs$EventTarget) {
  5158. _inherits(HtmlMediaSource, _videojs$EventTarget);
  5159. function HtmlMediaSource() {
  5160. var _this = this;
  5161. _classCallCheck(this, HtmlMediaSource);
  5162. _get(Object.getPrototypeOf(HtmlMediaSource.prototype), 'constructor', this).call(this);
  5163. var property = undefined;
  5164. this.nativeMediaSource_ = new window.MediaSource();
  5165. // delegate to the native MediaSource's methods by default
  5166. for (property in this.nativeMediaSource_) {
  5167. if (!(property in HtmlMediaSource.prototype) && typeof this.nativeMediaSource_[property] === 'function') {
  5168. this[property] = this.nativeMediaSource_[property].bind(this.nativeMediaSource_);
  5169. }
  5170. }
  5171. // emulate `duration` and `seekable` until seeking can be
  5172. // handled uniformly for live streams
  5173. // see https://github.com/w3c/media-source/issues/5
  5174. this.duration_ = NaN;
  5175. Object.defineProperty(this, 'duration', {
  5176. get: function get() {
  5177. if (this.duration_ === Infinity) {
  5178. return this.duration_;
  5179. }
  5180. return this.nativeMediaSource_.duration;
  5181. },
  5182. set: function set(duration) {
  5183. this.duration_ = duration;
  5184. if (duration !== Infinity) {
  5185. this.nativeMediaSource_.duration = duration;
  5186. return;
  5187. }
  5188. }
  5189. });
  5190. Object.defineProperty(this, 'seekable', {
  5191. get: function get() {
  5192. if (this.duration_ === Infinity) {
  5193. return _videoJs2['default'].createTimeRanges([[0, this.nativeMediaSource_.duration]]);
  5194. }
  5195. return this.nativeMediaSource_.seekable;
  5196. }
  5197. });
  5198. Object.defineProperty(this, 'readyState', {
  5199. get: function get() {
  5200. return this.nativeMediaSource_.readyState;
  5201. }
  5202. });
  5203. Object.defineProperty(this, 'activeSourceBuffers', {
  5204. get: function get() {
  5205. return this.activeSourceBuffers_;
  5206. }
  5207. });
  5208. // the list of virtual and native SourceBuffers created by this
  5209. // MediaSource
  5210. this.sourceBuffers = [];
  5211. this.activeSourceBuffers_ = [];
  5212. /**
  5213. * update the list of active source buffers based upon various
  5214. * imformation from HLS and video.js
  5215. *
  5216. * @private
  5217. */
  5218. this.updateActiveSourceBuffers_ = function () {
  5219. // Retain the reference but empty the array
  5220. _this.activeSourceBuffers_.length = 0;
  5221. // By default, the audio in the combined virtual source buffer is enabled
  5222. // and the audio-only source buffer (if it exists) is disabled.
  5223. var combined = false;
  5224. var audioOnly = true;
  5225. // TODO: maybe we can store the sourcebuffers on the track objects?
  5226. // safari may do something like this
  5227. for (var i = 0; i < _this.player_.audioTracks().length; i++) {
  5228. var track = _this.player_.audioTracks()[i];
  5229. if (track.enabled && track.kind !== 'main') {
  5230. // The enabled track is an alternate audio track so disable the audio in
  5231. // the combined source buffer and enable the audio-only source buffer.
  5232. combined = true;
  5233. audioOnly = false;
  5234. break;
  5235. }
  5236. }
  5237. // Since we currently support a max of two source buffers, add all of the source
  5238. // buffers (in order).
  5239. _this.sourceBuffers.forEach(function (sourceBuffer) {
  5240. /* eslinst-disable */
  5241. // TODO once codecs are required, we can switch to using the codecs to determine
  5242. // what stream is the video stream, rather than relying on videoTracks
  5243. /* eslinst-enable */
  5244. if (sourceBuffer.videoCodec_ && sourceBuffer.audioCodec_) {
  5245. // combined
  5246. sourceBuffer.audioDisabled_ = combined;
  5247. } else if (sourceBuffer.videoCodec_ && !sourceBuffer.audioCodec_) {
  5248. // If the "combined" source buffer is video only, then we do not want
  5249. // disable the audio-only source buffer (this is mostly for demuxed
  5250. // audio and video hls)
  5251. sourceBuffer.audioDisabled_ = true;
  5252. audioOnly = false;
  5253. } else if (!sourceBuffer.videoCodec_ && sourceBuffer.audioCodec_) {
  5254. // audio only
  5255. sourceBuffer.audioDisabled_ = audioOnly;
  5256. if (audioOnly) {
  5257. return;
  5258. }
  5259. }
  5260. _this.activeSourceBuffers_.push(sourceBuffer);
  5261. });
  5262. };
  5263. // Re-emit MediaSource events on the polyfill
  5264. ['sourceopen', 'sourceclose', 'sourceended'].forEach(function (eventName) {
  5265. this.nativeMediaSource_.addEventListener(eventName, this.trigger.bind(this));
  5266. }, this);
  5267. // capture the associated player when the MediaSource is
  5268. // successfully attached
  5269. this.on('sourceopen', function (event) {
  5270. // Get the player this MediaSource is attached to
  5271. var video = document.querySelector('[src="' + _this.url_ + '"]');
  5272. if (!video) {
  5273. return;
  5274. }
  5275. _this.player_ = (0, _videoJs2['default'])(video.parentNode);
  5276. if (_this.player_.audioTracks && _this.player_.audioTracks()) {
  5277. _this.player_.audioTracks().on('change', _this.updateActiveSourceBuffers_);
  5278. _this.player_.audioTracks().on('addtrack', _this.updateActiveSourceBuffers_);
  5279. _this.player_.audioTracks().on('removetrack', _this.updateActiveSourceBuffers_);
  5280. }
  5281. });
  5282. // explicitly terminate any WebWorkers that were created
  5283. // by SourceHandlers
  5284. this.on('sourceclose', function (event) {
  5285. this.sourceBuffers.forEach(function (sourceBuffer) {
  5286. if (sourceBuffer.transmuxer_) {
  5287. sourceBuffer.transmuxer_.terminate();
  5288. }
  5289. });
  5290. this.sourceBuffers.length = 0;
  5291. if (!this.player_) {
  5292. return;
  5293. }
  5294. if (this.player_.audioTracks && this.player_.audioTracks()) {
  5295. this.player_.audioTracks().off('change', this.updateActiveSourceBuffers_);
  5296. this.player_.audioTracks().off('addtrack', this.updateActiveSourceBuffers_);
  5297. this.player_.audioTracks().off('removetrack', this.updateActiveSourceBuffers_);
  5298. }
  5299. });
  5300. }
  5301. /**
  5302. * Add a range that that can now be seeked to.
  5303. *
  5304. * @param {Double} start where to start the addition
  5305. * @param {Double} end where to end the addition
  5306. * @private
  5307. */
  5308. _createClass(HtmlMediaSource, [{
  5309. key: 'addSeekableRange_',
  5310. value: function addSeekableRange_(start, end) {
  5311. var error = undefined;
  5312. if (this.duration !== Infinity) {
  5313. error = new Error('MediaSource.addSeekableRange() can only be invoked ' + 'when the duration is Infinity');
  5314. error.name = 'InvalidStateError';
  5315. error.code = 11;
  5316. throw error;
  5317. }
  5318. if (end > this.nativeMediaSource_.duration || isNaN(this.nativeMediaSource_.duration)) {
  5319. this.nativeMediaSource_.duration = end;
  5320. }
  5321. }
  5322. /**
  5323. * Add a source buffer to the media source.
  5324. *
  5325. * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/addSourceBuffer
  5326. * @param {String} type the content-type of the content
  5327. * @return {Object} the created source buffer
  5328. */
  5329. }, {
  5330. key: 'addSourceBuffer',
  5331. value: function addSourceBuffer(type) {
  5332. var buffer = undefined;
  5333. var parsedType = (0, _codecUtils.parseContentType)(type);
  5334. // Create a VirtualSourceBuffer to transmux MPEG-2 transport
  5335. // stream segments into fragmented MP4s
  5336. if (parsedType.type === 'video/mp2t') {
  5337. var codecs = [];
  5338. if (parsedType.parameters && parsedType.parameters.codecs) {
  5339. codecs = parsedType.parameters.codecs.split(',');
  5340. codecs = translateLegacyCodecs(codecs);
  5341. codecs = codecs.filter(function (codec) {
  5342. return (0, _codecUtils.isAudioCodec)(codec) || (0, _codecUtils.isVideoCodec)(codec);
  5343. });
  5344. }
  5345. if (codecs.length === 0) {
  5346. codecs = ['avc1.4d400d', 'mp4a.40.2'];
  5347. }
  5348. buffer = new _virtualSourceBuffer2['default'](this, codecs);
  5349. if (this.sourceBuffers.length !== 0) {
  5350. // If another VirtualSourceBuffer already exists, then we are creating a
  5351. // SourceBuffer for an alternate audio track and therefore we know that
  5352. // the source has both an audio and video track.
  5353. // That means we should trigger the manual creation of the real
  5354. // SourceBuffers instead of waiting for the transmuxer to return data
  5355. this.sourceBuffers[0].createRealSourceBuffers_();
  5356. buffer.createRealSourceBuffers_();
  5357. // Automatically disable the audio on the first source buffer if
  5358. // a second source buffer is ever created
  5359. this.sourceBuffers[0].audioDisabled_ = true;
  5360. }
  5361. } else {
  5362. // delegate to the native implementation
  5363. buffer = this.nativeMediaSource_.addSourceBuffer(type);
  5364. }
  5365. this.sourceBuffers.push(buffer);
  5366. return buffer;
  5367. }
  5368. }]);
  5369. return HtmlMediaSource;
  5370. })(_videoJs2['default'].EventTarget);
  5371. exports['default'] = HtmlMediaSource;
  5372. module.exports = exports['default'];
  5373. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  5374. },{"./codec-utils":26,"./virtual-source-buffer":35}],32:[function(require,module,exports){
  5375. /**
  5376. * @file remove-cues-from-track.js
  5377. */
  5378. /**
  5379. * Remove cues from a track on video.js.
  5380. *
  5381. * @param {Double} start start of where we should remove the cue
  5382. * @param {Double} end end of where the we should remove the cue
  5383. * @param {Object} track the text track to remove the cues from
  5384. * @private
  5385. */
  5386. "use strict";
  5387. Object.defineProperty(exports, "__esModule", {
  5388. value: true
  5389. });
  5390. var removeCuesFromTrack = function removeCuesFromTrack(start, end, track) {
  5391. var i = undefined;
  5392. var cue = undefined;
  5393. if (!track) {
  5394. return;
  5395. }
  5396. i = track.cues.length;
  5397. while (i--) {
  5398. cue = track.cues[i];
  5399. // Remove any overlapping cue
  5400. if (cue.startTime <= end && cue.endTime >= start) {
  5401. track.removeCue(cue);
  5402. }
  5403. }
  5404. };
  5405. exports["default"] = removeCuesFromTrack;
  5406. module.exports = exports["default"];
  5407. },{}],33:[function(require,module,exports){
  5408. /**
  5409. * @file transmuxer-worker.js
  5410. */
  5411. /**
  5412. * videojs-contrib-media-sources
  5413. *
  5414. * Copyright (c) 2015 Brightcove
  5415. * All rights reserved.
  5416. *
  5417. * Handles communication between the browser-world and the mux.js
  5418. * transmuxer running inside of a WebWorker by exposing a simple
  5419. * message-based interface to a Transmuxer object.
  5420. */
  5421. 'use strict';
  5422. Object.defineProperty(exports, '__esModule', {
  5423. value: true
  5424. });
  5425. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  5426. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  5427. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  5428. var _muxJs = require('mux.js');
  5429. var _muxJs2 = _interopRequireDefault(_muxJs);
  5430. /**
  5431. * Re-emits tranmsuxer events by converting them into messages to the
  5432. * world outside the worker.
  5433. *
  5434. * @param {Object} transmuxer the transmuxer to wire events on
  5435. * @private
  5436. */
  5437. var wireTransmuxerEvents = function wireTransmuxerEvents(transmuxer) {
  5438. transmuxer.on('data', function (segment) {
  5439. // transfer ownership of the underlying ArrayBuffer
  5440. // instead of doing a copy to save memory
  5441. // ArrayBuffers are transferable but generic TypedArrays are not
  5442. // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
  5443. var typedArray = segment.data;
  5444. segment.data = typedArray.buffer;
  5445. postMessage({
  5446. action: 'data',
  5447. segment: segment,
  5448. byteOffset: typedArray.byteOffset,
  5449. byteLength: typedArray.byteLength
  5450. }, [segment.data]);
  5451. });
  5452. if (transmuxer.captionStream) {
  5453. transmuxer.captionStream.on('data', function (caption) {
  5454. postMessage({
  5455. action: 'caption',
  5456. data: caption
  5457. });
  5458. });
  5459. }
  5460. transmuxer.on('done', function (data) {
  5461. postMessage({ action: 'done' });
  5462. });
  5463. };
  5464. /**
  5465. * All incoming messages route through this hash. If no function exists
  5466. * to handle an incoming message, then we ignore the message.
  5467. *
  5468. * @class MessageHandlers
  5469. * @param {Object} options the options to initialize with
  5470. */
  5471. var MessageHandlers = (function () {
  5472. function MessageHandlers(options) {
  5473. _classCallCheck(this, MessageHandlers);
  5474. this.options = options || {};
  5475. this.init();
  5476. }
  5477. /**
  5478. * Our web wroker interface so that things can talk to mux.js
  5479. * that will be running in a web worker. the scope is passed to this by
  5480. * webworkify.
  5481. *
  5482. * @param {Object} self the scope for the web worker
  5483. */
  5484. /**
  5485. * initialize our web worker and wire all the events.
  5486. */
  5487. _createClass(MessageHandlers, [{
  5488. key: 'init',
  5489. value: function init() {
  5490. if (this.transmuxer) {
  5491. this.transmuxer.dispose();
  5492. }
  5493. this.transmuxer = new _muxJs2['default'].mp4.Transmuxer(this.options);
  5494. wireTransmuxerEvents(this.transmuxer);
  5495. }
  5496. /**
  5497. * Adds data (a ts segment) to the start of the transmuxer pipeline for
  5498. * processing.
  5499. *
  5500. * @param {ArrayBuffer} data data to push into the muxer
  5501. */
  5502. }, {
  5503. key: 'push',
  5504. value: function push(data) {
  5505. // Cast array buffer to correct type for transmuxer
  5506. var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  5507. this.transmuxer.push(segment);
  5508. }
  5509. /**
  5510. * Recreate the transmuxer so that the next segment added via `push`
  5511. * start with a fresh transmuxer.
  5512. */
  5513. }, {
  5514. key: 'reset',
  5515. value: function reset() {
  5516. this.init();
  5517. }
  5518. /**
  5519. * Set the value that will be used as the `baseMediaDecodeTime` time for the
  5520. * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
  5521. * set relative to the first based on the PTS values.
  5522. *
  5523. * @param {Object} data used to set the timestamp offset in the muxer
  5524. */
  5525. }, {
  5526. key: 'setTimestampOffset',
  5527. value: function setTimestampOffset(data) {
  5528. var timestampOffset = data.timestampOffset || 0;
  5529. this.transmuxer.setBaseMediaDecodeTime(Math.round(timestampOffset * 90000));
  5530. }
  5531. /**
  5532. * Forces the pipeline to finish processing the last segment and emit it's
  5533. * results.
  5534. *
  5535. * @param {Object} data event data, not really used
  5536. */
  5537. }, {
  5538. key: 'flush',
  5539. value: function flush(data) {
  5540. this.transmuxer.flush();
  5541. }
  5542. }]);
  5543. return MessageHandlers;
  5544. })();
  5545. var Worker = function Worker(self) {
  5546. self.onmessage = function (event) {
  5547. if (event.data.action === 'init' && event.data.options) {
  5548. this.messageHandlers = new MessageHandlers(event.data.options);
  5549. return;
  5550. }
  5551. if (!this.messageHandlers) {
  5552. this.messageHandlers = new MessageHandlers();
  5553. }
  5554. if (event.data && event.data.action && event.data.action !== 'init') {
  5555. if (this.messageHandlers[event.data.action]) {
  5556. this.messageHandlers[event.data.action](event.data);
  5557. }
  5558. }
  5559. };
  5560. };
  5561. exports['default'] = function (self) {
  5562. return new Worker(self);
  5563. };
  5564. module.exports = exports['default'];
  5565. },{"mux.js":43}],34:[function(require,module,exports){
  5566. (function (global){
  5567. /**
  5568. * @file videojs-contrib-media-sources.js
  5569. */
  5570. 'use strict';
  5571. Object.defineProperty(exports, '__esModule', {
  5572. value: true
  5573. });
  5574. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  5575. var _flashMediaSource = require('./flash-media-source');
  5576. var _flashMediaSource2 = _interopRequireDefault(_flashMediaSource);
  5577. var _htmlMediaSource = require('./html-media-source');
  5578. var _htmlMediaSource2 = _interopRequireDefault(_htmlMediaSource);
  5579. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  5580. var _videoJs2 = _interopRequireDefault(_videoJs);
  5581. var urlCount = 0;
  5582. // ------------
  5583. // Media Source
  5584. // ------------
  5585. var defaults = {
  5586. // how to determine the MediaSource implementation to use. There
  5587. // are three available modes:
  5588. // - auto: use native MediaSources where available and Flash
  5589. // everywhere else
  5590. // - html5: always use native MediaSources
  5591. // - flash: always use the Flash MediaSource polyfill
  5592. mode: 'auto'
  5593. };
  5594. // store references to the media sources so they can be connected
  5595. // to a video element (a swf object)
  5596. // TODO: can we store this somewhere local to this module?
  5597. _videoJs2['default'].mediaSources = {};
  5598. /**
  5599. * Provide a method for a swf object to notify JS that a
  5600. * media source is now open.
  5601. *
  5602. * @param {String} msObjectURL string referencing the MSE Object URL
  5603. * @param {String} swfId the swf id
  5604. */
  5605. var open = function open(msObjectURL, swfId) {
  5606. var mediaSource = _videoJs2['default'].mediaSources[msObjectURL];
  5607. if (mediaSource) {
  5608. mediaSource.trigger({ type: 'sourceopen', swfId: swfId });
  5609. } else {
  5610. throw new Error('Media Source not found (Video.js)');
  5611. }
  5612. };
  5613. /**
  5614. * Check to see if the native MediaSource object exists and supports
  5615. * an MP4 container with both H.264 video and AAC-LC audio.
  5616. *
  5617. * @return {Boolean} if native media sources are supported
  5618. */
  5619. var supportsNativeMediaSources = function supportsNativeMediaSources() {
  5620. return !!window.MediaSource && !!window.MediaSource.isTypeSupported && window.MediaSource.isTypeSupported('video/mp4;codecs="avc1.4d400d,mp4a.40.2"');
  5621. };
  5622. /**
  5623. * An emulation of the MediaSource API so that we can support
  5624. * native and non-native functionality such as flash and
  5625. * video/mp2t videos. returns an instance of HtmlMediaSource or
  5626. * FlashMediaSource depending on what is supported and what options
  5627. * are passed in.
  5628. *
  5629. * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/MediaSource
  5630. * @param {Object} options options to use during setup.
  5631. */
  5632. var MediaSource = function MediaSource(options) {
  5633. var settings = _videoJs2['default'].mergeOptions(defaults, options);
  5634. this.MediaSource = {
  5635. open: open,
  5636. supportsNativeMediaSources: supportsNativeMediaSources
  5637. };
  5638. // determine whether HTML MediaSources should be used
  5639. if (settings.mode === 'html5' || settings.mode === 'auto' && supportsNativeMediaSources()) {
  5640. return new _htmlMediaSource2['default']();
  5641. }
  5642. // otherwise, emulate them through the SWF
  5643. return new _flashMediaSource2['default']();
  5644. };
  5645. exports.MediaSource = MediaSource;
  5646. MediaSource.open = open;
  5647. MediaSource.supportsNativeMediaSources = supportsNativeMediaSources;
  5648. /**
  5649. * A wrapper around the native URL for our MSE object
  5650. * implementation, this object is exposed under videojs.URL
  5651. *
  5652. * @link https://developer.mozilla.org/en-US/docs/Web/API/URL/URL
  5653. */
  5654. var URL = {
  5655. /**
  5656. * A wrapper around the native createObjectURL for our objects.
  5657. * This function maps a native or emulated mediaSource to a blob
  5658. * url so that it can be loaded into video.js
  5659. *
  5660. * @link https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
  5661. * @param {MediaSource} object the object to create a blob url to
  5662. */
  5663. createObjectURL: function createObjectURL(object) {
  5664. var objectUrlPrefix = 'blob:vjs-media-source/';
  5665. var url = undefined;
  5666. // use the native MediaSource to generate an object URL
  5667. if (object instanceof _htmlMediaSource2['default']) {
  5668. url = window.URL.createObjectURL(object.nativeMediaSource_);
  5669. object.url_ = url;
  5670. return url;
  5671. }
  5672. // if the object isn't an emulated MediaSource, delegate to the
  5673. // native implementation
  5674. if (!(object instanceof _flashMediaSource2['default'])) {
  5675. url = window.URL.createObjectURL(object);
  5676. object.url_ = url;
  5677. return url;
  5678. }
  5679. // build a URL that can be used to map back to the emulated
  5680. // MediaSource
  5681. url = objectUrlPrefix + urlCount;
  5682. urlCount++;
  5683. // setup the mapping back to object
  5684. _videoJs2['default'].mediaSources[url] = object;
  5685. return url;
  5686. }
  5687. };
  5688. exports.URL = URL;
  5689. _videoJs2['default'].MediaSource = MediaSource;
  5690. _videoJs2['default'].URL = URL;
  5691. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  5692. },{"./flash-media-source":29,"./html-media-source":31}],35:[function(require,module,exports){
  5693. (function (global){
  5694. /**
  5695. * @file virtual-source-buffer.js
  5696. */
  5697. 'use strict';
  5698. Object.defineProperty(exports, '__esModule', {
  5699. value: true
  5700. });
  5701. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  5702. var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  5703. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  5704. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  5705. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  5706. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  5707. var _videoJs2 = _interopRequireDefault(_videoJs);
  5708. var _createTextTracksIfNecessary = require('./create-text-tracks-if-necessary');
  5709. var _createTextTracksIfNecessary2 = _interopRequireDefault(_createTextTracksIfNecessary);
  5710. var _removeCuesFromTrack = require('./remove-cues-from-track');
  5711. var _removeCuesFromTrack2 = _interopRequireDefault(_removeCuesFromTrack);
  5712. var _addTextTrackData = require('./add-text-track-data');
  5713. var _addTextTrackData2 = _interopRequireDefault(_addTextTrackData);
  5714. var _webworkify = require('webworkify');
  5715. var _webworkify2 = _interopRequireDefault(_webworkify);
  5716. var _transmuxerWorker = require('./transmuxer-worker');
  5717. var _transmuxerWorker2 = _interopRequireDefault(_transmuxerWorker);
  5718. var _codecUtils = require('./codec-utils');
  5719. /**
  5720. * VirtualSourceBuffers exist so that we can transmux non native formats
  5721. * into a native format, but keep the same api as a native source buffer.
  5722. * It creates a transmuxer, that works in its own thread (a web worker) and
  5723. * that transmuxer muxes the data into a native format. VirtualSourceBuffer will
  5724. * then send all of that data to the naive sourcebuffer so that it is
  5725. * indestinguishable from a natively supported format.
  5726. *
  5727. * @param {HtmlMediaSource} mediaSource the parent mediaSource
  5728. * @param {Array} codecs array of codecs that we will be dealing with
  5729. * @class VirtualSourceBuffer
  5730. * @extends video.js.EventTarget
  5731. */
  5732. var VirtualSourceBuffer = (function (_videojs$EventTarget) {
  5733. _inherits(VirtualSourceBuffer, _videojs$EventTarget);
  5734. function VirtualSourceBuffer(mediaSource, codecs) {
  5735. var _this = this;
  5736. _classCallCheck(this, VirtualSourceBuffer);
  5737. _get(Object.getPrototypeOf(VirtualSourceBuffer.prototype), 'constructor', this).call(this, _videoJs2['default'].EventTarget);
  5738. this.timestampOffset_ = 0;
  5739. this.pendingBuffers_ = [];
  5740. this.bufferUpdating_ = false;
  5741. this.mediaSource_ = mediaSource;
  5742. this.codecs_ = codecs;
  5743. this.audioCodec_ = null;
  5744. this.videoCodec_ = null;
  5745. this.audioDisabled_ = false;
  5746. var options = {
  5747. remux: false
  5748. };
  5749. this.codecs_.forEach(function (codec) {
  5750. if ((0, _codecUtils.isAudioCodec)(codec)) {
  5751. _this.audioCodec_ = codec;
  5752. } else if ((0, _codecUtils.isVideoCodec)(codec)) {
  5753. _this.videoCodec_ = codec;
  5754. }
  5755. });
  5756. // append muxed segments to their respective native buffers as
  5757. // soon as they are available
  5758. this.transmuxer_ = (0, _webworkify2['default'])(_transmuxerWorker2['default']);
  5759. this.transmuxer_.postMessage({ action: 'init', options: options });
  5760. this.transmuxer_.onmessage = function (event) {
  5761. if (event.data.action === 'data') {
  5762. return _this.data_(event);
  5763. }
  5764. if (event.data.action === 'done') {
  5765. return _this.done_(event);
  5766. }
  5767. };
  5768. // this timestampOffset is a property with the side-effect of resetting
  5769. // baseMediaDecodeTime in the transmuxer on the setter
  5770. Object.defineProperty(this, 'timestampOffset', {
  5771. get: function get() {
  5772. return this.timestampOffset_;
  5773. },
  5774. set: function set(val) {
  5775. if (typeof val === 'number' && val >= 0) {
  5776. this.timestampOffset_ = val;
  5777. // We have to tell the transmuxer to set the baseMediaDecodeTime to
  5778. // the desired timestampOffset for the next segment
  5779. this.transmuxer_.postMessage({
  5780. action: 'setTimestampOffset',
  5781. timestampOffset: val
  5782. });
  5783. }
  5784. }
  5785. });
  5786. // setting the append window affects both source buffers
  5787. Object.defineProperty(this, 'appendWindowStart', {
  5788. get: function get() {
  5789. return (this.videoBuffer_ || this.audioBuffer_).appendWindowStart;
  5790. },
  5791. set: function set(start) {
  5792. if (this.videoBuffer_) {
  5793. this.videoBuffer_.appendWindowStart = start;
  5794. }
  5795. if (this.audioBuffer_) {
  5796. this.audioBuffer_.appendWindowStart = start;
  5797. }
  5798. }
  5799. });
  5800. // this buffer is "updating" if either of its native buffers are
  5801. Object.defineProperty(this, 'updating', {
  5802. get: function get() {
  5803. return !!(this.bufferUpdating_ || !this.audioDisabled_ && this.audioBuffer_ && this.audioBuffer_.updating || this.videoBuffer_ && this.videoBuffer_.updating);
  5804. }
  5805. });
  5806. // the buffered property is the intersection of the buffered
  5807. // ranges of the native source buffers
  5808. Object.defineProperty(this, 'buffered', {
  5809. get: function get() {
  5810. var start = null;
  5811. var end = null;
  5812. var arity = 0;
  5813. var extents = [];
  5814. var ranges = [];
  5815. if (!this.videoBuffer_ && (this.audioDisabled_ || !this.audioBuffer_)) {
  5816. return _videoJs2['default'].createTimeRange();
  5817. }
  5818. // Handle the case where we only have one buffer
  5819. if (!this.videoBuffer_) {
  5820. return this.audioBuffer_.buffered;
  5821. } else if (this.audioDisabled_ || !this.audioBuffer_) {
  5822. return this.videoBuffer_.buffered;
  5823. }
  5824. // Handle the case where there is no buffer data
  5825. if ((!this.videoBuffer_ || this.videoBuffer_.buffered.length === 0) && (!this.audioBuffer_ || this.audioBuffer_.buffered.length === 0)) {
  5826. return _videoJs2['default'].createTimeRange();
  5827. }
  5828. // Handle the case where we have both buffers and create an
  5829. // intersection of the two
  5830. var videoBuffered = this.videoBuffer_.buffered;
  5831. var audioBuffered = this.audioBuffer_.buffered;
  5832. var count = videoBuffered.length;
  5833. // A) Gather up all start and end times
  5834. while (count--) {
  5835. extents.push({ time: videoBuffered.start(count), type: 'start' });
  5836. extents.push({ time: videoBuffered.end(count), type: 'end' });
  5837. }
  5838. count = audioBuffered.length;
  5839. while (count--) {
  5840. extents.push({ time: audioBuffered.start(count), type: 'start' });
  5841. extents.push({ time: audioBuffered.end(count), type: 'end' });
  5842. }
  5843. // B) Sort them by time
  5844. extents.sort(function (a, b) {
  5845. return a.time - b.time;
  5846. });
  5847. // C) Go along one by one incrementing arity for start and decrementing
  5848. // arity for ends
  5849. for (count = 0; count < extents.length; count++) {
  5850. if (extents[count].type === 'start') {
  5851. arity++;
  5852. // D) If arity is ever incremented to 2 we are entering an
  5853. // overlapping range
  5854. if (arity === 2) {
  5855. start = extents[count].time;
  5856. }
  5857. } else if (extents[count].type === 'end') {
  5858. arity--;
  5859. // E) If arity is ever decremented to 1 we leaving an
  5860. // overlapping range
  5861. if (arity === 1) {
  5862. end = extents[count].time;
  5863. }
  5864. }
  5865. // F) Record overlapping ranges
  5866. if (start !== null && end !== null) {
  5867. ranges.push([start, end]);
  5868. start = null;
  5869. end = null;
  5870. }
  5871. }
  5872. return _videoJs2['default'].createTimeRanges(ranges);
  5873. }
  5874. });
  5875. }
  5876. /**
  5877. * When we get a data event from the transmuxer
  5878. * we call this function and handle the data that
  5879. * was sent to us
  5880. *
  5881. * @private
  5882. * @param {Event} event the data event from the transmuxer
  5883. */
  5884. _createClass(VirtualSourceBuffer, [{
  5885. key: 'data_',
  5886. value: function data_(event) {
  5887. var segment = event.data.segment;
  5888. // Cast ArrayBuffer to TypedArray
  5889. segment.data = new Uint8Array(segment.data, event.data.byteOffset, event.data.byteLength);
  5890. (0, _createTextTracksIfNecessary2['default'])(this, this.mediaSource_, segment);
  5891. // Add the segments to the pendingBuffers array
  5892. this.pendingBuffers_.push(segment);
  5893. return;
  5894. }
  5895. /**
  5896. * When we get a done event from the transmuxer
  5897. * we call this function and we process all
  5898. * of the pending data that we have been saving in the
  5899. * data_ function
  5900. *
  5901. * @private
  5902. * @param {Event} event the done event from the transmuxer
  5903. */
  5904. }, {
  5905. key: 'done_',
  5906. value: function done_(event) {
  5907. // All buffers should have been flushed from the muxer
  5908. // start processing anything we have received
  5909. this.processPendingSegments_();
  5910. return;
  5911. }
  5912. /**
  5913. * Create our internal native audio/video source buffers and add
  5914. * event handlers to them with the following conditions:
  5915. * 1. they do not already exist on the mediaSource
  5916. * 2. this VSB has a codec for them
  5917. *
  5918. * @private
  5919. */
  5920. }, {
  5921. key: 'createRealSourceBuffers_',
  5922. value: function createRealSourceBuffers_() {
  5923. var _this2 = this;
  5924. var types = ['audio', 'video'];
  5925. types.forEach(function (type) {
  5926. // Don't create a SourceBuffer of this type if we don't have a
  5927. // codec for it
  5928. if (!_this2[type + 'Codec_']) {
  5929. return;
  5930. }
  5931. // Do nothing if a SourceBuffer of this type already exists
  5932. if (_this2[type + 'Buffer_']) {
  5933. return;
  5934. }
  5935. var buffer = null;
  5936. // If the mediasource already has a SourceBuffer for the codec
  5937. // use that
  5938. if (_this2.mediaSource_[type + 'Buffer_']) {
  5939. buffer = _this2.mediaSource_[type + 'Buffer_'];
  5940. } else {
  5941. buffer = _this2.mediaSource_.nativeMediaSource_.addSourceBuffer(type + '/mp4;codecs="' + _this2[type + 'Codec_'] + '"');
  5942. _this2.mediaSource_[type + 'Buffer_'] = buffer;
  5943. }
  5944. _this2[type + 'Buffer_'] = buffer;
  5945. // Wire up the events to the SourceBuffer
  5946. ['update', 'updatestart', 'updateend'].forEach(function (event) {
  5947. buffer.addEventListener(event, function () {
  5948. // if audio is disabled
  5949. if (type === 'audio' && _this2.audioDisabled_) {
  5950. return;
  5951. }
  5952. var shouldTrigger = types.every(function (t) {
  5953. // skip checking audio's updating status if audio
  5954. // is not enabled
  5955. if (t === 'audio' && _this2.audioDisabled_) {
  5956. return true;
  5957. }
  5958. // if the other type if updating we don't trigger
  5959. if (type !== t && _this2[t + 'Buffer_'] && _this2[t + 'Buffer_'].updating) {
  5960. return false;
  5961. }
  5962. return true;
  5963. });
  5964. if (shouldTrigger) {
  5965. return _this2.trigger(event);
  5966. }
  5967. });
  5968. });
  5969. });
  5970. }
  5971. /**
  5972. * Emulate the native mediasource function, but our function will
  5973. * send all of the proposed segments to the transmuxer so that we
  5974. * can transmux them before we append them to our internal
  5975. * native source buffers in the correct format.
  5976. *
  5977. * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/appendBuffer
  5978. * @param {Uint8Array} segment the segment to append to the buffer
  5979. */
  5980. }, {
  5981. key: 'appendBuffer',
  5982. value: function appendBuffer(segment) {
  5983. // Start the internal "updating" state
  5984. this.bufferUpdating_ = true;
  5985. this.transmuxer_.postMessage({
  5986. action: 'push',
  5987. // Send the typed-array of data as an ArrayBuffer so that
  5988. // it can be sent as a "Transferable" and avoid the costly
  5989. // memory copy
  5990. data: segment.buffer,
  5991. // To recreate the original typed-array, we need information
  5992. // about what portion of the ArrayBuffer it was a view into
  5993. byteOffset: segment.byteOffset,
  5994. byteLength: segment.byteLength
  5995. }, [segment.buffer]);
  5996. this.transmuxer_.postMessage({ action: 'flush' });
  5997. }
  5998. /**
  5999. * Emulate the native mediasource function and remove parts
  6000. * of the buffer from any of our internal buffers that exist
  6001. *
  6002. * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/remove
  6003. * @param {Double} start position to start the remove at
  6004. * @param {Double} end position to end the remove at
  6005. */
  6006. }, {
  6007. key: 'remove',
  6008. value: function remove(start, end) {
  6009. if (this.videoBuffer_) {
  6010. this.videoBuffer_.remove(start, end);
  6011. }
  6012. if (!this.audioDisabled_ && this.audioBuffer_) {
  6013. this.audioBuffer_.remove(start, end);
  6014. }
  6015. // Remove Metadata Cues (id3)
  6016. (0, _removeCuesFromTrack2['default'])(start, end, this.metadataTrack_);
  6017. // Remove Any Captions
  6018. (0, _removeCuesFromTrack2['default'])(start, end, this.inbandTextTrack_);
  6019. }
  6020. /**
  6021. * Process any segments that the muxer has output
  6022. * Concatenate segments together based on type and append them into
  6023. * their respective sourceBuffers
  6024. *
  6025. * @private
  6026. */
  6027. }, {
  6028. key: 'processPendingSegments_',
  6029. value: function processPendingSegments_() {
  6030. var sortedSegments = {
  6031. video: {
  6032. segments: [],
  6033. bytes: 0
  6034. },
  6035. audio: {
  6036. segments: [],
  6037. bytes: 0
  6038. },
  6039. captions: [],
  6040. metadata: []
  6041. };
  6042. // Sort segments into separate video/audio arrays and
  6043. // keep track of their total byte lengths
  6044. sortedSegments = this.pendingBuffers_.reduce(function (segmentObj, segment) {
  6045. var type = segment.type;
  6046. var data = segment.data;
  6047. segmentObj[type].segments.push(data);
  6048. segmentObj[type].bytes += data.byteLength;
  6049. // Gather any captions into a single array
  6050. if (segment.captions) {
  6051. segmentObj.captions = segmentObj.captions.concat(segment.captions);
  6052. }
  6053. if (segment.info) {
  6054. segmentObj[type].info = segment.info;
  6055. }
  6056. // Gather any metadata into a single array
  6057. if (segment.metadata) {
  6058. segmentObj.metadata = segmentObj.metadata.concat(segment.metadata);
  6059. }
  6060. return segmentObj;
  6061. }, sortedSegments);
  6062. // Create the real source buffers if they don't exist by now since we
  6063. // finally are sure what tracks are contained in the source
  6064. if (!this.videoBuffer_ && !this.audioBuffer_) {
  6065. // Remove any codecs that may have been specified by default but
  6066. // are no longer applicable now
  6067. if (sortedSegments.video.bytes === 0) {
  6068. this.videoCodec_ = null;
  6069. }
  6070. if (sortedSegments.audio.bytes === 0) {
  6071. this.audioCodec_ = null;
  6072. }
  6073. this.createRealSourceBuffers_();
  6074. }
  6075. if (sortedSegments.audio.info) {
  6076. this.mediaSource_.trigger({ type: 'audioinfo', info: sortedSegments.audio.info });
  6077. }
  6078. if (sortedSegments.video.info) {
  6079. this.mediaSource_.trigger({ type: 'videoinfo', info: sortedSegments.video.info });
  6080. }
  6081. // Merge multiple video and audio segments into one and append
  6082. if (this.videoBuffer_) {
  6083. this.concatAndAppendSegments_(sortedSegments.video, this.videoBuffer_);
  6084. // TODO: are video tracks the only ones with text tracks?
  6085. (0, _addTextTrackData2['default'])(this, sortedSegments.captions, sortedSegments.metadata);
  6086. }
  6087. if (!this.audioDisabled_ && this.audioBuffer_) {
  6088. this.concatAndAppendSegments_(sortedSegments.audio, this.audioBuffer_);
  6089. }
  6090. this.pendingBuffers_.length = 0;
  6091. // We are no longer in the internal "updating" state
  6092. this.bufferUpdating_ = false;
  6093. }
  6094. /**
  6095. * Combine all segments into a single Uint8Array and then append them
  6096. * to the destination buffer
  6097. *
  6098. * @param {Object} segmentObj
  6099. * @param {SourceBuffer} destinationBuffer native source buffer to append data to
  6100. * @private
  6101. */
  6102. }, {
  6103. key: 'concatAndAppendSegments_',
  6104. value: function concatAndAppendSegments_(segmentObj, destinationBuffer) {
  6105. var offset = 0;
  6106. var tempBuffer = undefined;
  6107. if (segmentObj.bytes) {
  6108. tempBuffer = new Uint8Array(segmentObj.bytes);
  6109. // Combine the individual segments into one large typed-array
  6110. segmentObj.segments.forEach(function (segment) {
  6111. tempBuffer.set(segment, offset);
  6112. offset += segment.byteLength;
  6113. });
  6114. destinationBuffer.appendBuffer(tempBuffer);
  6115. }
  6116. }
  6117. /**
  6118. * Emulate the native mediasource function. abort any soureBuffer
  6119. * actions and throw out any un-appended data.
  6120. *
  6121. * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/abort
  6122. */
  6123. }, {
  6124. key: 'abort',
  6125. value: function abort() {
  6126. if (this.videoBuffer_) {
  6127. this.videoBuffer_.abort();
  6128. }
  6129. if (this.audioBuffer_) {
  6130. this.audioBuffer_.abort();
  6131. }
  6132. if (this.transmuxer_) {
  6133. this.transmuxer_.postMessage({ action: 'reset' });
  6134. }
  6135. this.pendingBuffers_.length = 0;
  6136. this.bufferUpdating_ = false;
  6137. }
  6138. }]);
  6139. return VirtualSourceBuffer;
  6140. })(_videoJs2['default'].EventTarget);
  6141. exports['default'] = VirtualSourceBuffer;
  6142. module.exports = exports['default'];
  6143. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  6144. },{"./add-text-track-data":25,"./codec-utils":26,"./create-text-tracks-if-necessary":27,"./remove-cues-from-track":32,"./transmuxer-worker":33,"webworkify":56}],36:[function(require,module,exports){
  6145. /**
  6146. * mux.js
  6147. *
  6148. * Copyright (c) 2016 Brightcove
  6149. * All rights reserved.
  6150. *
  6151. * A stream-based aac to mp4 converter. This utility can be used to
  6152. * deliver mp4s to a SourceBuffer on platforms that support native
  6153. * Media Source Extensions.
  6154. */
  6155. 'use strict';
  6156. var Stream = require('../utils/stream.js');
  6157. // Constants
  6158. var AacStream;
  6159. /**
  6160. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  6161. */
  6162. AacStream = function() {
  6163. var
  6164. everything = new Uint8Array(),
  6165. receivedTimeStamp = false,
  6166. timeStamp = 0;
  6167. AacStream.prototype.init.call(this);
  6168. this.setTimestamp = function (timestamp) {
  6169. timeStamp = timestamp;
  6170. };
  6171. this.parseId3TagSize = function(header, byteIndex) {
  6172. var
  6173. returnSize = (header[byteIndex + 6] << 21) |
  6174. (header[byteIndex + 7] << 14) |
  6175. (header[byteIndex + 8] << 7) |
  6176. (header[byteIndex + 9]),
  6177. flags = header[byteIndex + 5],
  6178. footerPresent = (flags & 16) >> 4;
  6179. if (footerPresent) {
  6180. return returnSize + 20;
  6181. }
  6182. return returnSize + 10;
  6183. };
  6184. this.parseAdtsSize = function(header, byteIndex) {
  6185. var
  6186. lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  6187. middle = header[byteIndex + 4] << 3,
  6188. highTwo = header[byteIndex + 3] & 0x3 << 11;
  6189. return (highTwo | middle) | lowThree;
  6190. };
  6191. this.push = function(bytes) {
  6192. var
  6193. frameSize = 0,
  6194. byteIndex = 0,
  6195. bytesLeft,
  6196. chunk,
  6197. packet,
  6198. tempLength;
  6199. // If there are bytes remaining from the last segment, prepend them to the
  6200. // bytes that were pushed in
  6201. if (everything.length) {
  6202. tempLength = everything.length;
  6203. everything = new Uint8Array(bytes.byteLength + tempLength);
  6204. everything.set(everything.subarray(0, tempLength));
  6205. everything.set(bytes, tempLength);
  6206. } else {
  6207. everything = bytes;
  6208. }
  6209. while (everything.length - byteIndex >= 3) {
  6210. if ((everything[byteIndex] === 'I'.charCodeAt(0)) &&
  6211. (everything[byteIndex + 1] === 'D'.charCodeAt(0)) &&
  6212. (everything[byteIndex + 2] === '3'.charCodeAt(0))) {
  6213. // Exit early because we don't have enough to parse
  6214. // the ID3 tag header
  6215. if (everything.length - byteIndex < 10) {
  6216. break;
  6217. }
  6218. // check framesize
  6219. frameSize = this.parseId3TagSize(everything, byteIndex);
  6220. // Exit early if we don't have enough in the buffer
  6221. // to emit a full packet
  6222. if (frameSize > everything.length) {
  6223. break;
  6224. }
  6225. chunk = {
  6226. type: 'timed-metadata',
  6227. data: everything.subarray(byteIndex, byteIndex + frameSize)
  6228. };
  6229. this.trigger('data', chunk);
  6230. byteIndex += frameSize;
  6231. continue;
  6232. } else if ((everything[byteIndex] & 0xff === 0xff) &&
  6233. ((everything[byteIndex + 1] & 0xf0) === 0xf0)) {
  6234. // Exit early because we don't have enough to parse
  6235. // the ADTS frame header
  6236. if (everything.length - byteIndex < 7) {
  6237. break;
  6238. }
  6239. frameSize = this.parseAdtsSize(everything, byteIndex);
  6240. // Exit early if we don't have enough in the buffer
  6241. // to emit a full packet
  6242. if (frameSize > everything.length) {
  6243. break;
  6244. }
  6245. packet = {
  6246. type: 'audio',
  6247. data: everything.subarray(byteIndex, byteIndex + frameSize),
  6248. pts: timeStamp,
  6249. dts: timeStamp,
  6250. };
  6251. this.trigger('data', packet);
  6252. byteIndex += frameSize;
  6253. continue;
  6254. }
  6255. byteIndex++;
  6256. }
  6257. bytesLeft = everything.length - byteIndex;
  6258. if (bytesLeft > 0) {
  6259. everything = everything.subarray(byteIndex);
  6260. } else {
  6261. everything = new Uint8Array();
  6262. }
  6263. };
  6264. };
  6265. AacStream.prototype = new Stream();
  6266. module.exports = AacStream;
  6267. },{"../utils/stream.js":55}],37:[function(require,module,exports){
  6268. 'use strict';
  6269. var Stream = require('../utils/stream.js');
  6270. var AdtsStream;
  6271. var
  6272. ADTS_SAMPLING_FREQUENCIES = [
  6273. 96000,
  6274. 88200,
  6275. 64000,
  6276. 48000,
  6277. 44100,
  6278. 32000,
  6279. 24000,
  6280. 22050,
  6281. 16000,
  6282. 12000,
  6283. 11025,
  6284. 8000,
  6285. 7350
  6286. ];
  6287. /*
  6288. * Accepts a ElementaryStream and emits data events with parsed
  6289. * AAC Audio Frames of the individual packets. Input audio in ADTS
  6290. * format is unpacked and re-emitted as AAC frames.
  6291. *
  6292. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  6293. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  6294. */
  6295. AdtsStream = function() {
  6296. var self, buffer;
  6297. AdtsStream.prototype.init.call(this);
  6298. self = this;
  6299. this.push = function(packet) {
  6300. var
  6301. i = 0,
  6302. frameNum = 0,
  6303. frameLength,
  6304. protectionSkipBytes,
  6305. frameEnd,
  6306. oldBuffer,
  6307. numFrames,
  6308. sampleCount,
  6309. adtsFrameDuration;
  6310. if (packet.type !== 'audio') {
  6311. // ignore non-audio data
  6312. return;
  6313. }
  6314. // Prepend any data in the buffer to the input data so that we can parse
  6315. // aac frames the cross a PES packet boundary
  6316. if (buffer) {
  6317. oldBuffer = buffer;
  6318. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  6319. buffer.set(oldBuffer);
  6320. buffer.set(packet.data, oldBuffer.byteLength);
  6321. } else {
  6322. buffer = packet.data;
  6323. }
  6324. // unpack any ADTS frames which have been fully received
  6325. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  6326. while (i + 5 < buffer.length) {
  6327. // Loook for the start of an ADTS header..
  6328. if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
  6329. // If a valid header was not found, jump one forward and attempt to
  6330. // find a valid ADTS header starting at the next byte
  6331. i++;
  6332. continue;
  6333. }
  6334. // The protection skip bit tells us if we have 2 bytes of CRC data at the
  6335. // end of the ADTS header
  6336. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2;
  6337. // Frame length is a 13 bit integer starting 16 bits from the
  6338. // end of the sync sequence
  6339. frameLength = ((buffer[i + 3] & 0x03) << 11) |
  6340. (buffer[i + 4] << 3) |
  6341. ((buffer[i + 5] & 0xe0) >> 5);
  6342. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  6343. adtsFrameDuration = (sampleCount * 90000) /
  6344. ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2];
  6345. frameEnd = i + frameLength;
  6346. // If we don't have enough data to actually finish this ADTS frame, return
  6347. // and wait for more data
  6348. if (buffer.byteLength < frameEnd) {
  6349. return;
  6350. }
  6351. // Otherwise, deliver the complete AAC frame
  6352. this.trigger('data', {
  6353. pts: packet.pts + (frameNum * adtsFrameDuration),
  6354. dts: packet.dts + (frameNum * adtsFrameDuration),
  6355. sampleCount: sampleCount,
  6356. audioobjecttype: ((buffer[i + 2] >>> 6) & 0x03) + 1,
  6357. channelcount: ((buffer[i + 2] & 1) << 2) |
  6358. ((buffer[i + 3] & 0xc0) >>> 6),
  6359. samplerate: ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2],
  6360. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  6361. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  6362. samplesize: 16,
  6363. data: buffer.subarray(i + 7 + protectionSkipBytes, frameEnd)
  6364. });
  6365. // If the buffer is empty, clear it and return
  6366. if (buffer.byteLength === frameEnd) {
  6367. buffer = undefined;
  6368. return;
  6369. }
  6370. frameNum++;
  6371. // Remove the finished frame from the buffer and start the process again
  6372. buffer = buffer.subarray(frameEnd);
  6373. }
  6374. };
  6375. this.flush = function() {
  6376. this.trigger('done');
  6377. };
  6378. };
  6379. AdtsStream.prototype = new Stream();
  6380. module.exports = AdtsStream;
  6381. },{"../utils/stream.js":55}],38:[function(require,module,exports){
  6382. 'use strict';
  6383. var Stream = require('../utils/stream.js');
  6384. var ExpGolomb = require('../utils/exp-golomb.js');
  6385. var H264Stream, NalByteStream;
  6386. /**
  6387. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  6388. */
  6389. NalByteStream = function() {
  6390. var
  6391. syncPoint = 0,
  6392. i,
  6393. buffer;
  6394. NalByteStream.prototype.init.call(this);
  6395. this.push = function(data) {
  6396. var swapBuffer;
  6397. if (!buffer) {
  6398. buffer = data.data;
  6399. } else {
  6400. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  6401. swapBuffer.set(buffer);
  6402. swapBuffer.set(data.data, buffer.byteLength);
  6403. buffer = swapBuffer;
  6404. }
  6405. // Rec. ITU-T H.264, Annex B
  6406. // scan for NAL unit boundaries
  6407. // a match looks like this:
  6408. // 0 0 1 .. NAL .. 0 0 1
  6409. // ^ sync point ^ i
  6410. // or this:
  6411. // 0 0 1 .. NAL .. 0 0 0
  6412. // ^ sync point ^ i
  6413. // advance the sync point to a NAL start, if necessary
  6414. for (; syncPoint < buffer.byteLength - 3; syncPoint++) {
  6415. if (buffer[syncPoint + 2] === 1) {
  6416. // the sync point is properly aligned
  6417. i = syncPoint + 5;
  6418. break;
  6419. }
  6420. }
  6421. while (i < buffer.byteLength) {
  6422. // look at the current byte to determine if we've hit the end of
  6423. // a NAL unit boundary
  6424. switch (buffer[i]) {
  6425. case 0:
  6426. // skip past non-sync sequences
  6427. if (buffer[i - 1] !== 0) {
  6428. i += 2;
  6429. break;
  6430. } else if (buffer[i - 2] !== 0) {
  6431. i++;
  6432. break;
  6433. }
  6434. // deliver the NAL unit if it isn't empty
  6435. if (syncPoint + 3 !== i - 2) {
  6436. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  6437. }
  6438. // drop trailing zeroes
  6439. do {
  6440. i++;
  6441. } while (buffer[i] !== 1 && i < buffer.length);
  6442. syncPoint = i - 2;
  6443. i += 3;
  6444. break;
  6445. case 1:
  6446. // skip past non-sync sequences
  6447. if (buffer[i - 1] !== 0 ||
  6448. buffer[i - 2] !== 0) {
  6449. i += 3;
  6450. break;
  6451. }
  6452. // deliver the NAL unit
  6453. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  6454. syncPoint = i - 2;
  6455. i += 3;
  6456. break;
  6457. default:
  6458. // the current byte isn't a one or zero, so it cannot be part
  6459. // of a sync sequence
  6460. i += 3;
  6461. break;
  6462. }
  6463. }
  6464. // filter out the NAL units that were delivered
  6465. buffer = buffer.subarray(syncPoint);
  6466. i -= syncPoint;
  6467. syncPoint = 0;
  6468. };
  6469. this.flush = function() {
  6470. // deliver the last buffered NAL unit
  6471. if (buffer && buffer.byteLength > 3) {
  6472. this.trigger('data', buffer.subarray(syncPoint + 3));
  6473. }
  6474. // reset the stream state
  6475. buffer = null;
  6476. syncPoint = 0;
  6477. this.trigger('done');
  6478. };
  6479. };
  6480. NalByteStream.prototype = new Stream();
  6481. /**
  6482. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  6483. * events.
  6484. */
  6485. H264Stream = function() {
  6486. var
  6487. nalByteStream = new NalByteStream(),
  6488. self,
  6489. trackId,
  6490. currentPts,
  6491. currentDts,
  6492. discardEmulationPreventionBytes,
  6493. readSequenceParameterSet,
  6494. skipScalingList;
  6495. H264Stream.prototype.init.call(this);
  6496. self = this;
  6497. this.push = function(packet) {
  6498. if (packet.type !== 'video') {
  6499. return;
  6500. }
  6501. trackId = packet.trackId;
  6502. currentPts = packet.pts;
  6503. currentDts = packet.dts;
  6504. nalByteStream.push(packet);
  6505. };
  6506. nalByteStream.on('data', function(data) {
  6507. var
  6508. event = {
  6509. trackId: trackId,
  6510. pts: currentPts,
  6511. dts: currentDts,
  6512. data: data
  6513. };
  6514. switch (data[0] & 0x1f) {
  6515. case 0x05:
  6516. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  6517. break;
  6518. case 0x06:
  6519. event.nalUnitType = 'sei_rbsp';
  6520. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  6521. break;
  6522. case 0x07:
  6523. event.nalUnitType = 'seq_parameter_set_rbsp';
  6524. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  6525. event.config = readSequenceParameterSet(event.escapedRBSP);
  6526. break;
  6527. case 0x08:
  6528. event.nalUnitType = 'pic_parameter_set_rbsp';
  6529. break;
  6530. case 0x09:
  6531. event.nalUnitType = 'access_unit_delimiter_rbsp';
  6532. break;
  6533. default:
  6534. break;
  6535. }
  6536. self.trigger('data', event);
  6537. });
  6538. nalByteStream.on('done', function() {
  6539. self.trigger('done');
  6540. });
  6541. this.flush = function() {
  6542. nalByteStream.flush();
  6543. };
  6544. /**
  6545. * Advance the ExpGolomb decoder past a scaling list. The scaling
  6546. * list is optionally transmitted as part of a sequence parameter
  6547. * set and is not relevant to transmuxing.
  6548. * @param count {number} the number of entries in this scaling list
  6549. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  6550. * start of a scaling list
  6551. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  6552. */
  6553. skipScalingList = function(count, expGolombDecoder) {
  6554. var
  6555. lastScale = 8,
  6556. nextScale = 8,
  6557. j,
  6558. deltaScale;
  6559. for (j = 0; j < count; j++) {
  6560. if (nextScale !== 0) {
  6561. deltaScale = expGolombDecoder.readExpGolomb();
  6562. nextScale = (lastScale + deltaScale + 256) % 256;
  6563. }
  6564. lastScale = (nextScale === 0) ? lastScale : nextScale;
  6565. }
  6566. };
  6567. /**
  6568. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  6569. * Sequence Payload"
  6570. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  6571. * unit
  6572. * @return {Uint8Array} the RBSP without any Emulation
  6573. * Prevention Bytes
  6574. */
  6575. discardEmulationPreventionBytes = function(data) {
  6576. var
  6577. length = data.byteLength,
  6578. emulationPreventionBytesPositions = [],
  6579. i = 1,
  6580. newLength, newData;
  6581. // Find all `Emulation Prevention Bytes`
  6582. while (i < length - 2) {
  6583. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  6584. emulationPreventionBytesPositions.push(i + 2);
  6585. i += 2;
  6586. } else {
  6587. i++;
  6588. }
  6589. }
  6590. // If no Emulation Prevention Bytes were found just return the original
  6591. // array
  6592. if (emulationPreventionBytesPositions.length === 0) {
  6593. return data;
  6594. }
  6595. // Create a new array to hold the NAL unit data
  6596. newLength = length - emulationPreventionBytesPositions.length;
  6597. newData = new Uint8Array(newLength);
  6598. var sourceIndex = 0;
  6599. for (i = 0; i < newLength; sourceIndex++, i++) {
  6600. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  6601. // Skip this byte
  6602. sourceIndex++;
  6603. // Remove this position index
  6604. emulationPreventionBytesPositions.shift();
  6605. }
  6606. newData[i] = data[sourceIndex];
  6607. }
  6608. return newData;
  6609. };
  6610. /**
  6611. * Read a sequence parameter set and return some interesting video
  6612. * properties. A sequence parameter set is the H264 metadata that
  6613. * describes the properties of upcoming video frames.
  6614. * @param data {Uint8Array} the bytes of a sequence parameter set
  6615. * @return {object} an object with configuration parsed from the
  6616. * sequence parameter set, including the dimensions of the
  6617. * associated video frames.
  6618. */
  6619. readSequenceParameterSet = function(data) {
  6620. var
  6621. frameCropLeftOffset = 0,
  6622. frameCropRightOffset = 0,
  6623. frameCropTopOffset = 0,
  6624. frameCropBottomOffset = 0,
  6625. sarScale = 1,
  6626. expGolombDecoder, profileIdc, levelIdc, profileCompatibility,
  6627. chromaFormatIdc, picOrderCntType,
  6628. numRefFramesInPicOrderCntCycle, picWidthInMbsMinus1,
  6629. picHeightInMapUnitsMinus1,
  6630. frameMbsOnlyFlag,
  6631. scalingListCount,
  6632. sarRatio,
  6633. aspectRatioIdc,
  6634. i;
  6635. expGolombDecoder = new ExpGolomb(data);
  6636. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  6637. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  6638. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  6639. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  6640. // some profiles have more optional data we don't need
  6641. if (profileIdc === 100 ||
  6642. profileIdc === 110 ||
  6643. profileIdc === 122 ||
  6644. profileIdc === 244 ||
  6645. profileIdc === 44 ||
  6646. profileIdc === 83 ||
  6647. profileIdc === 86 ||
  6648. profileIdc === 118 ||
  6649. profileIdc === 128 ||
  6650. profileIdc === 138 ||
  6651. profileIdc === 139 ||
  6652. profileIdc === 134) {
  6653. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  6654. if (chromaFormatIdc === 3) {
  6655. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  6656. }
  6657. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  6658. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  6659. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  6660. if (expGolombDecoder.readBoolean()) { // seq_scaling_matrix_present_flag
  6661. scalingListCount = (chromaFormatIdc !== 3) ? 8 : 12;
  6662. for (i = 0; i < scalingListCount; i++) {
  6663. if (expGolombDecoder.readBoolean()) { // seq_scaling_list_present_flag[ i ]
  6664. if (i < 6) {
  6665. skipScalingList(16, expGolombDecoder);
  6666. } else {
  6667. skipScalingList(64, expGolombDecoder);
  6668. }
  6669. }
  6670. }
  6671. }
  6672. }
  6673. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  6674. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  6675. if (picOrderCntType === 0) {
  6676. expGolombDecoder.readUnsignedExpGolomb(); //log2_max_pic_order_cnt_lsb_minus4
  6677. } else if (picOrderCntType === 1) {
  6678. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  6679. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  6680. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  6681. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  6682. for(i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  6683. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  6684. }
  6685. }
  6686. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  6687. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  6688. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  6689. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  6690. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  6691. if (frameMbsOnlyFlag === 0) {
  6692. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  6693. }
  6694. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  6695. if (expGolombDecoder.readBoolean()) { // frame_cropping_flag
  6696. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  6697. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  6698. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  6699. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  6700. }
  6701. if (expGolombDecoder.readBoolean()) {
  6702. // vui_parameters_present_flag
  6703. if (expGolombDecoder.readBoolean()) {
  6704. // aspect_ratio_info_present_flag
  6705. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  6706. switch (aspectRatioIdc) {
  6707. case 1: sarRatio = [1,1]; break;
  6708. case 2: sarRatio = [12,11]; break;
  6709. case 3: sarRatio = [10,11]; break;
  6710. case 4: sarRatio = [16,11]; break;
  6711. case 5: sarRatio = [40,33]; break;
  6712. case 6: sarRatio = [24,11]; break;
  6713. case 7: sarRatio = [20,11]; break;
  6714. case 8: sarRatio = [32,11]; break;
  6715. case 9: sarRatio = [80,33]; break;
  6716. case 10: sarRatio = [18,11]; break;
  6717. case 11: sarRatio = [15,11]; break;
  6718. case 12: sarRatio = [64,33]; break;
  6719. case 13: sarRatio = [160,99]; break;
  6720. case 14: sarRatio = [4,3]; break;
  6721. case 15: sarRatio = [3,2]; break;
  6722. case 16: sarRatio = [2,1]; break;
  6723. case 255: {
  6724. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 |
  6725. expGolombDecoder.readUnsignedByte(),
  6726. expGolombDecoder.readUnsignedByte() << 8 |
  6727. expGolombDecoder.readUnsignedByte() ];
  6728. break;
  6729. }
  6730. }
  6731. if (sarRatio) {
  6732. sarScale = sarRatio[0] / sarRatio[1];
  6733. }
  6734. }
  6735. }
  6736. return {
  6737. profileIdc: profileIdc,
  6738. levelIdc: levelIdc,
  6739. profileCompatibility: profileCompatibility,
  6740. width: Math.ceil((((picWidthInMbsMinus1 + 1) * 16) - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale),
  6741. height: ((2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16) - (frameCropTopOffset * 2) - (frameCropBottomOffset * 2)
  6742. };
  6743. };
  6744. };
  6745. H264Stream.prototype = new Stream();
  6746. module.exports = {
  6747. H264Stream: H264Stream,
  6748. NalByteStream: NalByteStream,
  6749. };
  6750. },{"../utils/exp-golomb.js":54,"../utils/stream.js":55}],39:[function(require,module,exports){
  6751. module.exports = {
  6752. adts: require('./adts'),
  6753. h264: require('./h264'),
  6754. };
  6755. },{"./adts":37,"./h264":38}],40:[function(require,module,exports){
  6756. /**
  6757. * An object that stores the bytes of an FLV tag and methods for
  6758. * querying and manipulating that data.
  6759. * @see http://download.macromedia.com/f4v/video_file_format_spec_v10_1.pdf
  6760. */
  6761. 'use strict';
  6762. var FlvTag;
  6763. // (type:uint, extraData:Boolean = false) extends ByteArray
  6764. FlvTag = function(type, extraData) {
  6765. var
  6766. // Counter if this is a metadata tag, nal start marker if this is a video
  6767. // tag. unused if this is an audio tag
  6768. adHoc = 0, // :uint
  6769. // The default size is 16kb but this is not enough to hold iframe
  6770. // data and the resizing algorithm costs a bit so we create a larger
  6771. // starting buffer for video tags
  6772. bufferStartSize = 16384,
  6773. // checks whether the FLV tag has enough capacity to accept the proposed
  6774. // write and re-allocates the internal buffers if necessary
  6775. prepareWrite = function(flv, count) {
  6776. var
  6777. bytes,
  6778. minLength = flv.position + count;
  6779. if (minLength < flv.bytes.byteLength) {
  6780. // there's enough capacity so do nothing
  6781. return;
  6782. }
  6783. // allocate a new buffer and copy over the data that will not be modified
  6784. bytes = new Uint8Array(minLength * 2);
  6785. bytes.set(flv.bytes.subarray(0, flv.position), 0);
  6786. flv.bytes = bytes;
  6787. flv.view = new DataView(flv.bytes.buffer);
  6788. },
  6789. // commonly used metadata properties
  6790. widthBytes = FlvTag.widthBytes || new Uint8Array('width'.length),
  6791. heightBytes = FlvTag.heightBytes || new Uint8Array('height'.length),
  6792. videocodecidBytes = FlvTag.videocodecidBytes || new Uint8Array('videocodecid'.length),
  6793. i;
  6794. if (!FlvTag.widthBytes) {
  6795. // calculating the bytes of common metadata names ahead of time makes the
  6796. // corresponding writes faster because we don't have to loop over the
  6797. // characters
  6798. // re-test with test/perf.html if you're planning on changing this
  6799. for (i = 0; i < 'width'.length; i++) {
  6800. widthBytes[i] = 'width'.charCodeAt(i);
  6801. }
  6802. for (i = 0; i < 'height'.length; i++) {
  6803. heightBytes[i] = 'height'.charCodeAt(i);
  6804. }
  6805. for (i = 0; i < 'videocodecid'.length; i++) {
  6806. videocodecidBytes[i] = 'videocodecid'.charCodeAt(i);
  6807. }
  6808. FlvTag.widthBytes = widthBytes;
  6809. FlvTag.heightBytes = heightBytes;
  6810. FlvTag.videocodecidBytes = videocodecidBytes;
  6811. }
  6812. this.keyFrame = false; // :Boolean
  6813. switch(type) {
  6814. case FlvTag.VIDEO_TAG:
  6815. this.length = 16;
  6816. // Start the buffer at 256k
  6817. bufferStartSize *= 6;
  6818. break;
  6819. case FlvTag.AUDIO_TAG:
  6820. this.length = 13;
  6821. this.keyFrame = true;
  6822. break;
  6823. case FlvTag.METADATA_TAG:
  6824. this.length = 29;
  6825. this.keyFrame = true;
  6826. break;
  6827. default:
  6828. throw("Error Unknown TagType");
  6829. }
  6830. this.bytes = new Uint8Array(bufferStartSize);
  6831. this.view = new DataView(this.bytes.buffer);
  6832. this.bytes[0] = type;
  6833. this.position = this.length;
  6834. this.keyFrame = extraData; // Defaults to false
  6835. // presentation timestamp
  6836. this.pts = 0;
  6837. // decoder timestamp
  6838. this.dts = 0;
  6839. // ByteArray#writeBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0)
  6840. this.writeBytes = function(bytes, offset, length) {
  6841. var
  6842. start = offset || 0,
  6843. end;
  6844. length = length || bytes.byteLength;
  6845. end = start + length;
  6846. prepareWrite(this, length);
  6847. this.bytes.set(bytes.subarray(start, end), this.position);
  6848. this.position += length;
  6849. this.length = Math.max(this.length, this.position);
  6850. };
  6851. // ByteArray#writeByte(value:int):void
  6852. this.writeByte = function(byte) {
  6853. prepareWrite(this, 1);
  6854. this.bytes[this.position] = byte;
  6855. this.position++;
  6856. this.length = Math.max(this.length, this.position);
  6857. };
  6858. // ByteArray#writeShort(value:int):void
  6859. this.writeShort = function(short) {
  6860. prepareWrite(this, 2);
  6861. this.view.setUint16(this.position, short);
  6862. this.position += 2;
  6863. this.length = Math.max(this.length, this.position);
  6864. };
  6865. // Negative index into array
  6866. // (pos:uint):int
  6867. this.negIndex = function(pos) {
  6868. return this.bytes[this.length - pos];
  6869. };
  6870. // The functions below ONLY work when this[0] == VIDEO_TAG.
  6871. // We are not going to check for that because we dont want the overhead
  6872. // (nal:ByteArray = null):int
  6873. this.nalUnitSize = function() {
  6874. if (adHoc === 0) {
  6875. return 0;
  6876. }
  6877. return this.length - (adHoc + 4);
  6878. };
  6879. this.startNalUnit = function() {
  6880. // remember position and add 4 bytes
  6881. if (adHoc > 0) {
  6882. throw new Error("Attempted to create new NAL wihout closing the old one");
  6883. }
  6884. // reserve 4 bytes for nal unit size
  6885. adHoc = this.length;
  6886. this.length += 4;
  6887. this.position = this.length;
  6888. };
  6889. // (nal:ByteArray = null):void
  6890. this.endNalUnit = function(nalContainer) {
  6891. var
  6892. nalStart, // :uint
  6893. nalLength; // :uint
  6894. // Rewind to the marker and write the size
  6895. if (this.length === adHoc + 4) {
  6896. // we started a nal unit, but didnt write one, so roll back the 4 byte size value
  6897. this.length -= 4;
  6898. } else if (adHoc > 0) {
  6899. nalStart = adHoc + 4;
  6900. nalLength = this.length - nalStart;
  6901. this.position = adHoc;
  6902. this.view.setUint32(this.position, nalLength);
  6903. this.position = this.length;
  6904. if (nalContainer) {
  6905. // Add the tag to the NAL unit
  6906. nalContainer.push(this.bytes.subarray(nalStart, nalStart + nalLength));
  6907. }
  6908. }
  6909. adHoc = 0;
  6910. };
  6911. /**
  6912. * Write out a 64-bit floating point valued metadata property. This method is
  6913. * called frequently during a typical parse and needs to be fast.
  6914. */
  6915. // (key:String, val:Number):void
  6916. this.writeMetaDataDouble = function(key, val) {
  6917. var i;
  6918. prepareWrite(this, 2 + key.length + 9);
  6919. // write size of property name
  6920. this.view.setUint16(this.position, key.length);
  6921. this.position += 2;
  6922. // this next part looks terrible but it improves parser throughput by
  6923. // 10kB/s in my testing
  6924. // write property name
  6925. if (key === 'width') {
  6926. this.bytes.set(widthBytes, this.position);
  6927. this.position += 5;
  6928. } else if (key === 'height') {
  6929. this.bytes.set(heightBytes, this.position);
  6930. this.position += 6;
  6931. } else if (key === 'videocodecid') {
  6932. this.bytes.set(videocodecidBytes, this.position);
  6933. this.position += 12;
  6934. } else {
  6935. for (i = 0; i < key.length; i++) {
  6936. this.bytes[this.position] = key.charCodeAt(i);
  6937. this.position++;
  6938. }
  6939. }
  6940. // skip null byte
  6941. this.position++;
  6942. // write property value
  6943. this.view.setFloat64(this.position, val);
  6944. this.position += 8;
  6945. // update flv tag length
  6946. this.length = Math.max(this.length, this.position);
  6947. ++adHoc;
  6948. };
  6949. // (key:String, val:Boolean):void
  6950. this.writeMetaDataBoolean = function(key, val) {
  6951. var i;
  6952. prepareWrite(this, 2);
  6953. this.view.setUint16(this.position, key.length);
  6954. this.position += 2;
  6955. for (i = 0; i < key.length; i++) {
  6956. // if key.charCodeAt(i) >= 255, handle error
  6957. prepareWrite(this, 1);
  6958. this.bytes[this.position] = key.charCodeAt(i);
  6959. this.position++;
  6960. }
  6961. prepareWrite(this, 2);
  6962. this.view.setUint8(this.position, 0x01);
  6963. this.position++;
  6964. this.view.setUint8(this.position, val ? 0x01 : 0x00);
  6965. this.position++;
  6966. this.length = Math.max(this.length, this.position);
  6967. ++adHoc;
  6968. };
  6969. // ():ByteArray
  6970. this.finalize = function() {
  6971. var
  6972. dtsDelta, // :int
  6973. len; // :int
  6974. switch(this.bytes[0]) {
  6975. // Video Data
  6976. case FlvTag.VIDEO_TAG:
  6977. this.bytes[11] = ((this.keyFrame || extraData) ? 0x10 : 0x20 ) | 0x07; // We only support AVC, 1 = key frame (for AVC, a seekable frame), 2 = inter frame (for AVC, a non-seekable frame)
  6978. this.bytes[12] = extraData ? 0x00 : 0x01;
  6979. dtsDelta = this.pts - this.dts;
  6980. this.bytes[13] = (dtsDelta & 0x00FF0000) >>> 16;
  6981. this.bytes[14] = (dtsDelta & 0x0000FF00) >>> 8;
  6982. this.bytes[15] = (dtsDelta & 0x000000FF) >>> 0;
  6983. break;
  6984. case FlvTag.AUDIO_TAG:
  6985. this.bytes[11] = 0xAF; // 44 kHz, 16-bit stereo
  6986. this.bytes[12] = extraData ? 0x00 : 0x01;
  6987. break;
  6988. case FlvTag.METADATA_TAG:
  6989. this.position = 11;
  6990. this.view.setUint8(this.position, 0x02); // String type
  6991. this.position++;
  6992. this.view.setUint16(this.position, 0x0A); // 10 Bytes
  6993. this.position += 2;
  6994. // set "onMetaData"
  6995. this.bytes.set([0x6f, 0x6e, 0x4d, 0x65,
  6996. 0x74, 0x61, 0x44, 0x61,
  6997. 0x74, 0x61], this.position);
  6998. this.position += 10;
  6999. this.bytes[this.position] = 0x08; // Array type
  7000. this.position++;
  7001. this.view.setUint32(this.position, adHoc);
  7002. this.position = this.length;
  7003. this.bytes.set([0, 0, 9], this.position);
  7004. this.position += 3; // End Data Tag
  7005. this.length = this.position;
  7006. break;
  7007. }
  7008. len = this.length - 11;
  7009. // write the DataSize field
  7010. this.bytes[ 1] = (len & 0x00FF0000) >>> 16;
  7011. this.bytes[ 2] = (len & 0x0000FF00) >>> 8;
  7012. this.bytes[ 3] = (len & 0x000000FF) >>> 0;
  7013. // write the Timestamp
  7014. this.bytes[ 4] = (this.dts & 0x00FF0000) >>> 16;
  7015. this.bytes[ 5] = (this.dts & 0x0000FF00) >>> 8;
  7016. this.bytes[ 6] = (this.dts & 0x000000FF) >>> 0;
  7017. this.bytes[ 7] = (this.dts & 0xFF000000) >>> 24;
  7018. // write the StreamID
  7019. this.bytes[ 8] = 0;
  7020. this.bytes[ 9] = 0;
  7021. this.bytes[10] = 0;
  7022. // Sometimes we're at the end of the view and have one slot to write a
  7023. // uint32, so, prepareWrite of count 4, since, view is uint8
  7024. prepareWrite(this, 4);
  7025. this.view.setUint32(this.length, this.length);
  7026. this.length += 4;
  7027. this.position += 4;
  7028. // trim down the byte buffer to what is actually being used
  7029. this.bytes = this.bytes.subarray(0, this.length);
  7030. this.frameTime = FlvTag.frameTime(this.bytes);
  7031. // if bytes.bytelength isn't equal to this.length, handle error
  7032. return this;
  7033. };
  7034. };
  7035. FlvTag.AUDIO_TAG = 0x08; // == 8, :uint
  7036. FlvTag.VIDEO_TAG = 0x09; // == 9, :uint
  7037. FlvTag.METADATA_TAG = 0x12; // == 18, :uint
  7038. // (tag:ByteArray):Boolean {
  7039. FlvTag.isAudioFrame = function(tag) {
  7040. return FlvTag.AUDIO_TAG === tag[0];
  7041. };
  7042. // (tag:ByteArray):Boolean {
  7043. FlvTag.isVideoFrame = function(tag) {
  7044. return FlvTag.VIDEO_TAG === tag[0];
  7045. };
  7046. // (tag:ByteArray):Boolean {
  7047. FlvTag.isMetaData = function(tag) {
  7048. return FlvTag.METADATA_TAG === tag[0];
  7049. };
  7050. // (tag:ByteArray):Boolean {
  7051. FlvTag.isKeyFrame = function(tag) {
  7052. if (FlvTag.isVideoFrame(tag)) {
  7053. return tag[11] === 0x17;
  7054. }
  7055. if (FlvTag.isAudioFrame(tag)) {
  7056. return true;
  7057. }
  7058. if (FlvTag.isMetaData(tag)) {
  7059. return true;
  7060. }
  7061. return false;
  7062. };
  7063. // (tag:ByteArray):uint {
  7064. FlvTag.frameTime = function(tag) {
  7065. var pts = tag[ 4] << 16; // :uint
  7066. pts |= tag[ 5] << 8;
  7067. pts |= tag[ 6] << 0;
  7068. pts |= tag[ 7] << 24;
  7069. return pts;
  7070. };
  7071. module.exports = FlvTag;
  7072. },{}],41:[function(require,module,exports){
  7073. module.exports = {
  7074. tag: require('./flv-tag'),
  7075. Transmuxer: require('./transmuxer'),
  7076. tools: require('../tools/flv-inspector'),
  7077. };
  7078. },{"../tools/flv-inspector":52,"./flv-tag":40,"./transmuxer":42}],42:[function(require,module,exports){
  7079. 'use strict';
  7080. var Stream = require('../utils/stream.js');
  7081. var FlvTag = require('./flv-tag.js');
  7082. var m2ts = require('../m2ts/m2ts.js');
  7083. var AdtsStream = require('../codecs/adts.js');
  7084. var H264Stream = require('../codecs/h264').H264Stream;
  7085. var
  7086. MetadataStream,
  7087. Transmuxer,
  7088. VideoSegmentStream,
  7089. AudioSegmentStream,
  7090. CoalesceStream,
  7091. collectTimelineInfo,
  7092. metaDataTag,
  7093. extraDataTag;
  7094. /**
  7095. * Store information about the start and end of the tracka and the
  7096. * duration for each frame/sample we process in order to calculate
  7097. * the baseMediaDecodeTime
  7098. */
  7099. collectTimelineInfo = function (track, data) {
  7100. if (typeof data.pts === 'number') {
  7101. if (track.timelineStartInfo.pts === undefined) {
  7102. track.timelineStartInfo.pts = data.pts;
  7103. } else {
  7104. track.timelineStartInfo.pts =
  7105. Math.min(track.timelineStartInfo.pts, data.pts);
  7106. }
  7107. }
  7108. if (typeof data.dts === 'number') {
  7109. if (track.timelineStartInfo.dts === undefined) {
  7110. track.timelineStartInfo.dts = data.dts;
  7111. } else {
  7112. track.timelineStartInfo.dts =
  7113. Math.min(track.timelineStartInfo.dts, data.dts);
  7114. }
  7115. }
  7116. };
  7117. metaDataTag = function(track, pts) {
  7118. var
  7119. tag = new FlvTag(FlvTag.METADATA_TAG); // :FlvTag
  7120. tag.dts = pts;
  7121. tag.pts = pts;
  7122. tag.writeMetaDataDouble("videocodecid", 7);
  7123. tag.writeMetaDataDouble("width", track.width);
  7124. tag.writeMetaDataDouble("height", track.height);
  7125. return tag;
  7126. };
  7127. extraDataTag = function(track, pts) {
  7128. var
  7129. i,
  7130. tag = new FlvTag(FlvTag.VIDEO_TAG, true);
  7131. tag.dts = pts;
  7132. tag.pts = pts;
  7133. tag.writeByte(0x01);// version
  7134. tag.writeByte(track.profileIdc);// profile
  7135. tag.writeByte(track.profileCompatibility);// compatibility
  7136. tag.writeByte(track.levelIdc);// level
  7137. tag.writeByte(0xFC | 0x03); // reserved (6 bits), NULA length size - 1 (2 bits)
  7138. tag.writeByte(0xE0 | 0x01 ); // reserved (3 bits), num of SPS (5 bits)
  7139. tag.writeShort( track.sps[0].length ); // data of SPS
  7140. tag.writeBytes( track.sps[0] ); // SPS
  7141. tag.writeByte(track.pps.length); // num of PPS (will there ever be more that 1 PPS?)
  7142. for (i = 0 ; i < track.pps.length ; ++i) {
  7143. tag.writeShort(track.pps[i].length); // 2 bytes for length of PPS
  7144. tag.writeBytes(track.pps[i]); // data of PPS
  7145. }
  7146. return tag;
  7147. };
  7148. /**
  7149. * Constructs a single-track, media segment from AAC data
  7150. * events. The output of this stream can be fed to flash.
  7151. */
  7152. AudioSegmentStream = function(track) {
  7153. var
  7154. adtsFrames = [],
  7155. adtsFramesLength = 0,
  7156. sequenceNumber = 0,
  7157. earliestAllowedDts = 0,
  7158. oldExtraData;
  7159. AudioSegmentStream.prototype.init.call(this);
  7160. this.push = function(data) {
  7161. collectTimelineInfo(track, data);
  7162. if (track && track.channelcount === undefined) {
  7163. track.audioobjecttype = data.audioobjecttype;
  7164. track.channelcount = data.channelcount;
  7165. track.samplerate = data.samplerate;
  7166. track.samplingfrequencyindex = data.samplingfrequencyindex;
  7167. track.samplesize = data.samplesize;
  7168. track.extraData = (track.audioobjecttype << 11) |
  7169. (track.samplingfrequencyindex << 7) |
  7170. (track.channelcount << 3);
  7171. }
  7172. data.pts = Math.round(data.pts / 90);
  7173. data.dts = Math.round(data.dts / 90);
  7174. // buffer audio data until end() is called
  7175. adtsFrames.push(data);
  7176. };
  7177. this.flush = function() {
  7178. var currentFrame, adtsFrame, deltaDts,lastMetaPts, tags = [];
  7179. // return early if no audio data has been observed
  7180. if (adtsFrames.length === 0) {
  7181. this.trigger('done');
  7182. return;
  7183. }
  7184. lastMetaPts = -Infinity;
  7185. while (adtsFrames.length) {
  7186. currentFrame = adtsFrames.shift();
  7187. // write out metadata tags every 1 second so that the decoder
  7188. // is re-initialized quickly after seeking into a different
  7189. // audio configuration
  7190. if (track.extraData !== oldExtraData || currentFrame.pts - lastMetaPts >= 1000) {
  7191. adtsFrame = new FlvTag(FlvTag.METADATA_TAG);
  7192. adtsFrame.pts = currentFrame.pts;
  7193. adtsFrame.dts = currentFrame.dts;
  7194. // AAC is always 10
  7195. adtsFrame.writeMetaDataDouble("audiocodecid", 10);
  7196. adtsFrame.writeMetaDataBoolean("stereo", 2 === track.channelcount);
  7197. adtsFrame.writeMetaDataDouble ("audiosamplerate", track.samplerate);
  7198. // Is AAC always 16 bit?
  7199. adtsFrame.writeMetaDataDouble ("audiosamplesize", 16);
  7200. tags.push(adtsFrame);
  7201. oldExtraData = track.extraData;
  7202. adtsFrame = new FlvTag(FlvTag.AUDIO_TAG, true);
  7203. // For audio, DTS is always the same as PTS. We want to set the DTS
  7204. // however so we can compare with video DTS to determine approximate
  7205. // packet order
  7206. adtsFrame.pts = currentFrame.pts;
  7207. adtsFrame.dts = currentFrame.dts;
  7208. adtsFrame.view.setUint16(adtsFrame.position, track.extraData);
  7209. adtsFrame.position += 2;
  7210. adtsFrame.length = Math.max(adtsFrame.length, adtsFrame.position);
  7211. tags.push(adtsFrame);
  7212. lastMetaPts = currentFrame.pts;
  7213. }
  7214. adtsFrame = new FlvTag(FlvTag.AUDIO_TAG);
  7215. adtsFrame.pts = currentFrame.pts;
  7216. adtsFrame.dts = currentFrame.dts;
  7217. adtsFrame.writeBytes(currentFrame.data);
  7218. tags.push(adtsFrame);
  7219. }
  7220. oldExtraData = null;
  7221. this.trigger('data', {track: track, tags: tags});
  7222. this.trigger('done');
  7223. };
  7224. };
  7225. AudioSegmentStream.prototype = new Stream();
  7226. /**
  7227. * Store FlvTags for the h264 stream
  7228. * @param track {object} track metadata configuration
  7229. */
  7230. VideoSegmentStream = function(track) {
  7231. var
  7232. sequenceNumber = 0,
  7233. nalUnits = [],
  7234. nalUnitsLength = 0,
  7235. config,
  7236. h264Frame;
  7237. VideoSegmentStream.prototype.init.call(this);
  7238. this.finishFrame = function(tags, frame) {
  7239. if (!frame) {
  7240. return;
  7241. }
  7242. // Check if keyframe and the length of tags.
  7243. // This makes sure we write metadata on the first frame of a segment.
  7244. if (config && track && track.newMetadata &&
  7245. (frame.keyFrame || tags.length === 0)) {
  7246. // Push extra data on every IDR frame in case we did a stream change + seek
  7247. tags.push(metaDataTag(config, frame.pts));
  7248. tags.push(extraDataTag(track, frame.pts));
  7249. track.newMetadata = false;
  7250. }
  7251. frame.endNalUnit();
  7252. tags.push(frame);
  7253. };
  7254. this.push = function(data) {
  7255. collectTimelineInfo(track, data);
  7256. data.pts = Math.round(data.pts / 90);
  7257. data.dts = Math.round(data.dts / 90);
  7258. // buffer video until flush() is called
  7259. nalUnits.push(data);
  7260. };
  7261. this.flush = function() {
  7262. var
  7263. currentNal,
  7264. tags = [];
  7265. // Throw away nalUnits at the start of the byte stream until we find
  7266. // the first AUD
  7267. while (nalUnits.length) {
  7268. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  7269. break;
  7270. }
  7271. nalUnits.shift();
  7272. }
  7273. // return early if no video data has been observed
  7274. if (nalUnits.length === 0) {
  7275. this.trigger('done');
  7276. return;
  7277. }
  7278. while (nalUnits.length) {
  7279. currentNal = nalUnits.shift();
  7280. // record the track config
  7281. if (currentNal.nalUnitType === 'seq_parameter_set_rbsp') {
  7282. track.newMetadata = true;
  7283. config = currentNal.config;
  7284. track.width = config.width;
  7285. track.height = config.height;
  7286. track.sps = [currentNal.data];
  7287. track.profileIdc = config.profileIdc;
  7288. track.levelIdc = config.levelIdc;
  7289. track.profileCompatibility = config.profileCompatibility;
  7290. h264Frame.endNalUnit();
  7291. } else if (currentNal.nalUnitType === 'pic_parameter_set_rbsp') {
  7292. track.newMetadata = true;
  7293. track.pps = [currentNal.data];
  7294. h264Frame.endNalUnit();
  7295. } else if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  7296. if (h264Frame) {
  7297. this.finishFrame(tags, h264Frame);
  7298. }
  7299. h264Frame = new FlvTag(FlvTag.VIDEO_TAG);
  7300. h264Frame.pts = currentNal.pts;
  7301. h264Frame.dts = currentNal.dts;
  7302. } else {
  7303. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  7304. // the current sample is a key frame
  7305. h264Frame.keyFrame = true;
  7306. }
  7307. h264Frame.endNalUnit();
  7308. }
  7309. h264Frame.startNalUnit();
  7310. h264Frame.writeBytes(currentNal.data);
  7311. }
  7312. if (h264Frame) {
  7313. this.finishFrame(tags, h264Frame);
  7314. }
  7315. this.trigger('data', {track: track, tags: tags});
  7316. // Continue with the flush process now
  7317. this.trigger('done');
  7318. };
  7319. };
  7320. VideoSegmentStream.prototype = new Stream();
  7321. /**
  7322. * The final stage of the transmuxer that emits the flv tags
  7323. * for audio, video, and metadata. Also tranlates in time and
  7324. * outputs caption data and id3 cues.
  7325. */
  7326. CoalesceStream = function(options) {
  7327. // Number of Tracks per output segment
  7328. // If greater than 1, we combine multiple
  7329. // tracks into a single segment
  7330. this.numberOfTracks = 0;
  7331. this.metadataStream = options.metadataStream;
  7332. this.videoTags = [];
  7333. this.audioTags = [];
  7334. this.videoTrack = null;
  7335. this.audioTrack = null;
  7336. this.pendingCaptions = [];
  7337. this.pendingMetadata = [];
  7338. this.pendingTracks = 0;
  7339. CoalesceStream.prototype.init.call(this);
  7340. // Take output from multiple
  7341. this.push = function(output) {
  7342. // buffer incoming captions until the associated video segment
  7343. // finishes
  7344. if (output.text) {
  7345. return this.pendingCaptions.push(output);
  7346. }
  7347. // buffer incoming id3 tags until the final flush
  7348. if (output.frames) {
  7349. return this.pendingMetadata.push(output);
  7350. }
  7351. if (output.track.type === 'video') {
  7352. this.videoTrack = output.track;
  7353. this.videoTags = output.tags;
  7354. this.pendingTracks++;
  7355. }
  7356. if (output.track.type === 'audio') {
  7357. this.audioTrack = output.track;
  7358. this.audioTags = output.tags;
  7359. this.pendingTracks++;
  7360. }
  7361. };
  7362. };
  7363. CoalesceStream.prototype = new Stream();
  7364. CoalesceStream.prototype.flush = function() {
  7365. var
  7366. id3,
  7367. caption,
  7368. i,
  7369. timelineStartPts,
  7370. event = {
  7371. tags: {},
  7372. captions: [],
  7373. metadata: []
  7374. };
  7375. if (this.pendingTracks < this.numberOfTracks) {
  7376. return;
  7377. }
  7378. if (this.videoTrack) {
  7379. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  7380. } else if (this.audioTrack) {
  7381. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  7382. }
  7383. event.tags.videoTags = this.videoTags;
  7384. event.tags.audioTags = this.audioTags;
  7385. // Translate caption PTS times into second offsets into the
  7386. // video timeline for the segment
  7387. for (i = 0; i < this.pendingCaptions.length; i++) {
  7388. caption = this.pendingCaptions[i];
  7389. caption.startTime = caption.startPts - timelineStartPts;
  7390. caption.startTime /= 90e3;
  7391. caption.endTime = caption.endPts - timelineStartPts;
  7392. caption.endTime /= 90e3;
  7393. event.captions.push(caption);
  7394. }
  7395. // Translate ID3 frame PTS times into second offsets into the
  7396. // video timeline for the segment
  7397. for (i = 0; i < this.pendingMetadata.length; i++) {
  7398. id3 = this.pendingMetadata[i];
  7399. id3.cueTime = id3.pts - timelineStartPts;
  7400. id3.cueTime /= 90e3;
  7401. event.metadata.push(id3);
  7402. }
  7403. // We add this to every single emitted segment even though we only need
  7404. // it for the first
  7405. event.metadata.dispatchType = this.metadataStream.dispatchType;
  7406. // Reset stream state
  7407. this.videoTrack = null;
  7408. this.audioTrack = null;
  7409. this.videoTags = [];
  7410. this.audioTags = [];
  7411. this.pendingCaptions.length = 0;
  7412. this.pendingMetadata.length = 0;
  7413. this.pendingTracks = 0;
  7414. // Emit the final segment
  7415. this.trigger('data', event);
  7416. this.trigger('done');
  7417. };
  7418. /**
  7419. * An object that incrementally transmuxes MPEG2 Trasport Stream
  7420. * chunks into an FLV.
  7421. */
  7422. Transmuxer = function(options) {
  7423. var
  7424. self = this,
  7425. videoTrack,
  7426. audioTrack,
  7427. packetStream, parseStream, elementaryStream,
  7428. adtsStream, h264Stream,
  7429. videoSegmentStream, audioSegmentStream, captionStream,
  7430. coalesceStream;
  7431. Transmuxer.prototype.init.call(this);
  7432. options = options || {};
  7433. // expose the metadata stream
  7434. this.metadataStream = new m2ts.MetadataStream();
  7435. options.metadataStream = this.metadataStream;
  7436. // set up the parsing pipeline
  7437. packetStream = new m2ts.TransportPacketStream();
  7438. parseStream = new m2ts.TransportParseStream();
  7439. elementaryStream = new m2ts.ElementaryStream();
  7440. adtsStream = new AdtsStream();
  7441. h264Stream = new H264Stream();
  7442. coalesceStream = new CoalesceStream(options);
  7443. // disassemble MPEG2-TS packets into elementary streams
  7444. packetStream
  7445. .pipe(parseStream)
  7446. .pipe(elementaryStream);
  7447. // !!THIS ORDER IS IMPORTANT!!
  7448. // demux the streams
  7449. elementaryStream
  7450. .pipe(h264Stream);
  7451. elementaryStream
  7452. .pipe(adtsStream);
  7453. elementaryStream
  7454. .pipe(this.metadataStream)
  7455. .pipe(coalesceStream);
  7456. // if CEA-708 parsing is available, hook up a caption stream
  7457. captionStream = new m2ts.CaptionStream();
  7458. h264Stream.pipe(captionStream)
  7459. .pipe(coalesceStream);
  7460. // hook up the segment streams once track metadata is delivered
  7461. elementaryStream.on('data', function(data) {
  7462. var i, videoTrack, audioTrack;
  7463. if (data.type === 'metadata') {
  7464. i = data.tracks.length;
  7465. // scan the tracks listed in the metadata
  7466. while (i--) {
  7467. if (data.tracks[i].type === 'video') {
  7468. videoTrack = data.tracks[i];
  7469. } else if (data.tracks[i].type === 'audio') {
  7470. audioTrack = data.tracks[i];
  7471. }
  7472. }
  7473. // hook up the video segment stream to the first track with h264 data
  7474. if (videoTrack && !videoSegmentStream) {
  7475. coalesceStream.numberOfTracks++;
  7476. videoSegmentStream = new VideoSegmentStream(videoTrack);
  7477. // Set up the final part of the video pipeline
  7478. h264Stream
  7479. .pipe(videoSegmentStream)
  7480. .pipe(coalesceStream);
  7481. }
  7482. if (audioTrack && !audioSegmentStream) {
  7483. // hook up the audio segment stream to the first track with aac data
  7484. coalesceStream.numberOfTracks++;
  7485. audioSegmentStream = new AudioSegmentStream(audioTrack);
  7486. // Set up the final part of the audio pipeline
  7487. adtsStream
  7488. .pipe(audioSegmentStream)
  7489. .pipe(coalesceStream);
  7490. }
  7491. }
  7492. });
  7493. // feed incoming data to the front of the parsing pipeline
  7494. this.push = function(data) {
  7495. packetStream.push(data);
  7496. };
  7497. // flush any buffered data
  7498. this.flush = function() {
  7499. // Start at the top of the pipeline and flush all pending work
  7500. packetStream.flush();
  7501. };
  7502. // Re-emit any data coming from the coalesce stream to the outside world
  7503. coalesceStream.on('data', function (event) {
  7504. self.trigger('data', event);
  7505. });
  7506. // Let the consumer know we have finished flushing the entire pipeline
  7507. coalesceStream.on('done', function () {
  7508. self.trigger('done');
  7509. });
  7510. // For information on the FLV format, see
  7511. // http://download.macromedia.com/f4v/video_file_format_spec_v10_1.pdf.
  7512. // Technically, this function returns the header and a metadata FLV tag
  7513. // if duration is greater than zero
  7514. // duration in seconds
  7515. // @return {object} the bytes of the FLV header as a Uint8Array
  7516. this.getFlvHeader = function(duration, audio, video) { // :ByteArray {
  7517. var
  7518. headBytes = new Uint8Array(3 + 1 + 1 + 4),
  7519. head = new DataView(headBytes.buffer),
  7520. metadata,
  7521. result,
  7522. metadataLength;
  7523. // default arguments
  7524. duration = duration || 0;
  7525. audio = audio === undefined? true : audio;
  7526. video = video === undefined? true : video;
  7527. // signature
  7528. head.setUint8(0, 0x46); // 'F'
  7529. head.setUint8(1, 0x4c); // 'L'
  7530. head.setUint8(2, 0x56); // 'V'
  7531. // version
  7532. head.setUint8(3, 0x01);
  7533. // flags
  7534. head.setUint8(4, (audio ? 0x04 : 0x00) | (video ? 0x01 : 0x00));
  7535. // data offset, should be 9 for FLV v1
  7536. head.setUint32(5, headBytes.byteLength);
  7537. // init the first FLV tag
  7538. if (duration <= 0) {
  7539. // no duration available so just write the first field of the first
  7540. // FLV tag
  7541. result = new Uint8Array(headBytes.byteLength + 4);
  7542. result.set(headBytes);
  7543. result.set([0, 0, 0, 0], headBytes.byteLength);
  7544. return result;
  7545. }
  7546. // write out the duration metadata tag
  7547. metadata = new FlvTag(FlvTag.METADATA_TAG);
  7548. metadata.pts = metadata.dts = 0;
  7549. metadata.writeMetaDataDouble("duration", duration);
  7550. metadataLength = metadata.finalize().length;
  7551. result = new Uint8Array(headBytes.byteLength + metadataLength);
  7552. result.set(headBytes);
  7553. result.set(head.byteLength, metadataLength);
  7554. return result;
  7555. };
  7556. };
  7557. Transmuxer.prototype = new Stream();
  7558. // forward compatibility
  7559. module.exports = Transmuxer;
  7560. },{"../codecs/adts.js":37,"../codecs/h264":38,"../m2ts/m2ts.js":46,"../utils/stream.js":55,"./flv-tag.js":40}],43:[function(require,module,exports){
  7561. 'use strict';
  7562. var muxjs = {
  7563. codecs: require('./codecs'),
  7564. mp4: require('./mp4'),
  7565. flv: require('./flv'),
  7566. mp2t: require('./m2ts'),
  7567. };
  7568. module.exports = muxjs;
  7569. },{"./codecs":39,"./flv":41,"./m2ts":45,"./mp4":49}],44:[function(require,module,exports){
  7570. /**
  7571. * mux.js
  7572. *
  7573. * Copyright (c) 2015 Brightcove
  7574. * All rights reserved.
  7575. *
  7576. * Reads in-band caption information from a video elementary
  7577. * stream. Captions must follow the CEA-708 standard for injection
  7578. * into an MPEG-2 transport streams.
  7579. * @see https://en.wikipedia.org/wiki/CEA-708
  7580. */
  7581. 'use strict';
  7582. // -----------------
  7583. // Link To Transport
  7584. // -----------------
  7585. // Supplemental enhancement information (SEI) NAL units have a
  7586. // payload type field to indicate how they are to be
  7587. // interpreted. CEAS-708 caption content is always transmitted with
  7588. // payload type 0x04.
  7589. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  7590. RBSP_TRAILING_BITS = 128,
  7591. Stream = require('../utils/stream');
  7592. /**
  7593. * Parse a supplemental enhancement information (SEI) NAL unit.
  7594. * Stops parsing once a message of type ITU T T35 has been found.
  7595. *
  7596. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  7597. * @return {object} the parsed SEI payload
  7598. * @see Rec. ITU-T H.264, 7.3.2.3.1
  7599. */
  7600. var parseSei = function(bytes) {
  7601. var
  7602. i = 0,
  7603. result = {
  7604. payloadType: -1,
  7605. payloadSize: 0,
  7606. },
  7607. payloadType = 0,
  7608. payloadSize = 0;
  7609. // go through the sei_rbsp parsing each each individual sei_message
  7610. while (i < bytes.byteLength) {
  7611. // stop once we have hit the end of the sei_rbsp
  7612. if (bytes[i] === RBSP_TRAILING_BITS) {
  7613. break;
  7614. }
  7615. // Parse payload type
  7616. while (bytes[i] === 0xFF) {
  7617. payloadType += 255;
  7618. i++;
  7619. }
  7620. payloadType += bytes[i++];
  7621. // Parse payload size
  7622. while (bytes[i] === 0xFF) {
  7623. payloadSize += 255;
  7624. i++;
  7625. }
  7626. payloadSize += bytes[i++];
  7627. // this sei_message is a 608/708 caption so save it and break
  7628. // there can only ever be one caption message in a frame's sei
  7629. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  7630. result.payloadType = payloadType;
  7631. result.payloadSize = payloadSize;
  7632. result.payload = bytes.subarray(i, i + payloadSize);
  7633. break;
  7634. }
  7635. // skip the payload and parse the next message
  7636. i += payloadSize;
  7637. payloadType = 0;
  7638. payloadSize = 0;
  7639. }
  7640. return result;
  7641. };
  7642. // see ANSI/SCTE 128-1 (2013), section 8.1
  7643. var parseUserData = function(sei) {
  7644. // itu_t_t35_contry_code must be 181 (United States) for
  7645. // captions
  7646. if (sei.payload[0] !== 181) {
  7647. return null;
  7648. }
  7649. // itu_t_t35_provider_code should be 49 (ATSC) for captions
  7650. if (((sei.payload[1] << 8) | sei.payload[2]) !== 49) {
  7651. return null;
  7652. }
  7653. // the user_identifier should be "GA94" to indicate ATSC1 data
  7654. if (String.fromCharCode(sei.payload[3],
  7655. sei.payload[4],
  7656. sei.payload[5],
  7657. sei.payload[6]) !== 'GA94') {
  7658. return null;
  7659. }
  7660. // finally, user_data_type_code should be 0x03 for caption data
  7661. if (sei.payload[7] !== 0x03) {
  7662. return null;
  7663. }
  7664. // return the user_data_type_structure and strip the trailing
  7665. // marker bits
  7666. return sei.payload.subarray(8, sei.payload.length - 1);
  7667. };
  7668. // see CEA-708-D, section 4.4
  7669. var parseCaptionPackets = function(pts, userData) {
  7670. var results = [], i, count, offset, data;
  7671. // if this is just filler, return immediately
  7672. if (!(userData[0] & 0x40)) {
  7673. return results;
  7674. }
  7675. // parse out the cc_data_1 and cc_data_2 fields
  7676. count = userData[0] & 0x1f;
  7677. for (i = 0; i < count; i++) {
  7678. offset = i * 3;
  7679. data = {
  7680. type: userData[offset + 2] & 0x03,
  7681. pts: pts
  7682. };
  7683. // capture cc data when cc_valid is 1
  7684. if (userData[offset + 2] & 0x04) {
  7685. data.ccData = (userData[offset + 3] << 8) | userData[offset + 4];
  7686. results.push(data);
  7687. }
  7688. }
  7689. return results;
  7690. };
  7691. var CaptionStream = function() {
  7692. var self = this;
  7693. CaptionStream.prototype.init.call(this);
  7694. this.captionPackets_ = [];
  7695. this.field1_ = new Cea608Stream();
  7696. // forward data and done events from field1_ to this CaptionStream
  7697. this.field1_.on('data', this.trigger.bind(this, 'data'));
  7698. this.field1_.on('done', this.trigger.bind(this, 'done'));
  7699. };
  7700. CaptionStream.prototype = new Stream();
  7701. CaptionStream.prototype.push = function(event) {
  7702. var sei, userData, captionPackets;
  7703. // only examine SEI NALs
  7704. if (event.nalUnitType !== 'sei_rbsp') {
  7705. return;
  7706. }
  7707. // parse the sei
  7708. sei = parseSei(event.escapedRBSP);
  7709. // ignore everything but user_data_registered_itu_t_t35
  7710. if (sei.payloadType !== USER_DATA_REGISTERED_ITU_T_T35) {
  7711. return;
  7712. }
  7713. // parse out the user data payload
  7714. userData = parseUserData(sei);
  7715. // ignore unrecognized userData
  7716. if (!userData) {
  7717. return;
  7718. }
  7719. // parse out CC data packets and save them for later
  7720. this.captionPackets_ = this.captionPackets_.concat(parseCaptionPackets(event.pts, userData));
  7721. };
  7722. CaptionStream.prototype.flush = function () {
  7723. // make sure we actually parsed captions before proceeding
  7724. if (!this.captionPackets_.length) {
  7725. this.field1_.flush();
  7726. return;
  7727. }
  7728. // sort caption byte-pairs based on their PTS values
  7729. this.captionPackets_.sort(function(a, b) {
  7730. return a.pts - b.pts;
  7731. });
  7732. // Push each caption into Cea608Stream
  7733. this.captionPackets_.forEach(this.field1_.push, this.field1_);
  7734. this.captionPackets_.length = 0;
  7735. this.field1_.flush();
  7736. return;
  7737. };
  7738. // ----------------------
  7739. // Session to Application
  7740. // ----------------------
  7741. var BASIC_CHARACTER_TRANSLATION = {
  7742. 0x2a: 0xe1,
  7743. 0x5c: 0xe9,
  7744. 0x5e: 0xed,
  7745. 0x5f: 0xf3,
  7746. 0x60: 0xfa,
  7747. 0x7b: 0xe7,
  7748. 0x7c: 0xf7,
  7749. 0x7d: 0xd1,
  7750. 0x7e: 0xf1,
  7751. 0x7f: 0x2588
  7752. };
  7753. var getCharFromCode = function(code) {
  7754. if(code === null) {
  7755. return '';
  7756. }
  7757. code = BASIC_CHARACTER_TRANSLATION[code] || code;
  7758. return String.fromCharCode(code);
  7759. };
  7760. // Constants for the byte codes recognized by Cea608Stream. This
  7761. // list is not exhaustive. For a more comprehensive listing and
  7762. // semantics see
  7763. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  7764. var PADDING = 0x0000,
  7765. // Pop-on Mode
  7766. RESUME_CAPTION_LOADING = 0x1420,
  7767. END_OF_CAPTION = 0x142f,
  7768. // Roll-up Mode
  7769. ROLL_UP_2_ROWS = 0x1425,
  7770. ROLL_UP_3_ROWS = 0x1426,
  7771. ROLL_UP_4_ROWS = 0x1427,
  7772. RESUME_DIRECT_CAPTIONING = 0x1429,
  7773. CARRIAGE_RETURN = 0x142d,
  7774. // Erasure
  7775. BACKSPACE = 0x1421,
  7776. ERASE_DISPLAYED_MEMORY = 0x142c,
  7777. ERASE_NON_DISPLAYED_MEMORY = 0x142e;
  7778. // the index of the last row in a CEA-608 display buffer
  7779. var BOTTOM_ROW = 14;
  7780. // CEA-608 captions are rendered onto a 34x15 matrix of character
  7781. // cells. The "bottom" row is the last element in the outer array.
  7782. var createDisplayBuffer = function() {
  7783. var result = [], i = BOTTOM_ROW + 1;
  7784. while (i--) {
  7785. result.push('');
  7786. }
  7787. return result;
  7788. };
  7789. var Cea608Stream = function() {
  7790. Cea608Stream.prototype.init.call(this);
  7791. this.mode_ = 'popOn';
  7792. // When in roll-up mode, the index of the last row that will
  7793. // actually display captions. If a caption is shifted to a row
  7794. // with a lower index than this, it is cleared from the display
  7795. // buffer
  7796. this.topRow_ = 0;
  7797. this.startPts_ = 0;
  7798. this.displayed_ = createDisplayBuffer();
  7799. this.nonDisplayed_ = createDisplayBuffer();
  7800. this.lastControlCode_ = null;
  7801. this.push = function(packet) {
  7802. // Ignore other channels
  7803. if (packet.type !== 0) {
  7804. return;
  7805. }
  7806. var data, swap, char0, char1;
  7807. // remove the parity bits
  7808. data = packet.ccData & 0x7f7f;
  7809. // ignore duplicate control codes
  7810. if (data === this.lastControlCode_) {
  7811. this.lastControlCode_ = null;
  7812. return;
  7813. }
  7814. // Store control codes
  7815. if ((data & 0xf000) === 0x1000) {
  7816. this.lastControlCode_ = data;
  7817. } else {
  7818. this.lastControlCode_ = null;
  7819. }
  7820. switch (data) {
  7821. case PADDING:
  7822. break;
  7823. case RESUME_CAPTION_LOADING:
  7824. this.mode_ = 'popOn';
  7825. break;
  7826. case END_OF_CAPTION:
  7827. // if a caption was being displayed, it's gone now
  7828. this.flushDisplayed(packet.pts);
  7829. // flip memory
  7830. swap = this.displayed_;
  7831. this.displayed_ = this.nonDisplayed_;
  7832. this.nonDisplayed_ = swap;
  7833. // start measuring the time to display the caption
  7834. this.startPts_ = packet.pts;
  7835. break;
  7836. case ROLL_UP_2_ROWS:
  7837. this.topRow_ = BOTTOM_ROW - 1;
  7838. this.mode_ = 'rollUp';
  7839. break;
  7840. case ROLL_UP_3_ROWS:
  7841. this.topRow_ = BOTTOM_ROW - 2;
  7842. this.mode_ = 'rollUp';
  7843. break;
  7844. case ROLL_UP_4_ROWS:
  7845. this.topRow_ = BOTTOM_ROW - 3;
  7846. this.mode_ = 'rollUp';
  7847. break;
  7848. case CARRIAGE_RETURN:
  7849. this.flushDisplayed(packet.pts);
  7850. this.shiftRowsUp_();
  7851. this.startPts_ = packet.pts;
  7852. break;
  7853. case BACKSPACE:
  7854. if (this.mode_ === 'popOn') {
  7855. this.nonDisplayed_[BOTTOM_ROW] = this.nonDisplayed_[BOTTOM_ROW].slice(0, -1);
  7856. } else {
  7857. this.displayed_[BOTTOM_ROW] = this.displayed_[BOTTOM_ROW].slice(0, -1);
  7858. }
  7859. break;
  7860. case ERASE_DISPLAYED_MEMORY:
  7861. this.flushDisplayed(packet.pts);
  7862. this.displayed_ = createDisplayBuffer();
  7863. break;
  7864. case ERASE_NON_DISPLAYED_MEMORY:
  7865. this.nonDisplayed_ = createDisplayBuffer();
  7866. break;
  7867. default:
  7868. char0 = data >>> 8;
  7869. char1 = data & 0xff;
  7870. // Look for a Channel 1 Preamble Address Code
  7871. if (char0 >= 0x10 && char0 <= 0x17 &&
  7872. char1 >= 0x40 && char1 <= 0x7F &&
  7873. (char0 !== 0x10 || char1 < 0x60)) {
  7874. // Follow Safari's lead and replace the PAC with a space
  7875. char0 = 0x20;
  7876. // we only want one space so make the second character null
  7877. // which will get become '' in getCharFromCode
  7878. char1 = null;
  7879. }
  7880. // Look for special character sets
  7881. if ((char0 === 0x11 || char0 === 0x19) &&
  7882. (char1 >= 0x30 && char1 <= 0x3F)) {
  7883. // Put in eigth note and space
  7884. char0 = 0x266A;
  7885. char1 = '';
  7886. }
  7887. // ignore unsupported control codes
  7888. if ((char0 & 0xf0) === 0x10) {
  7889. return;
  7890. }
  7891. // character handling is dependent on the current mode
  7892. this[this.mode_](packet.pts, char0, char1);
  7893. break;
  7894. }
  7895. };
  7896. };
  7897. Cea608Stream.prototype = new Stream();
  7898. // Trigger a cue point that captures the current state of the
  7899. // display buffer
  7900. Cea608Stream.prototype.flushDisplayed = function(pts) {
  7901. var content = this.displayed_
  7902. // remove spaces from the start and end of the string
  7903. .map(function(row) { return row.trim(); })
  7904. // remove empty rows
  7905. .filter(function(row) { return row.length; })
  7906. // combine all text rows to display in one cue
  7907. .join('\n');
  7908. if (content.length) {
  7909. this.trigger('data', {
  7910. startPts: this.startPts_,
  7911. endPts: pts,
  7912. text: content
  7913. });
  7914. }
  7915. };
  7916. // Mode Implementations
  7917. Cea608Stream.prototype.popOn = function(pts, char0, char1) {
  7918. var baseRow = this.nonDisplayed_[BOTTOM_ROW];
  7919. // buffer characters
  7920. baseRow += getCharFromCode(char0);
  7921. baseRow += getCharFromCode(char1);
  7922. this.nonDisplayed_[BOTTOM_ROW] = baseRow;
  7923. };
  7924. Cea608Stream.prototype.rollUp = function(pts, char0, char1) {
  7925. var baseRow = this.displayed_[BOTTOM_ROW];
  7926. if (baseRow === '') {
  7927. // we're starting to buffer new display input, so flush out the
  7928. // current display
  7929. this.flushDisplayed(pts);
  7930. this.startPts_ = pts;
  7931. }
  7932. baseRow += getCharFromCode(char0);
  7933. baseRow += getCharFromCode(char1);
  7934. this.displayed_[BOTTOM_ROW] = baseRow;
  7935. };
  7936. Cea608Stream.prototype.shiftRowsUp_ = function() {
  7937. var i;
  7938. // clear out inactive rows
  7939. for (i = 0; i < this.topRow_; i++) {
  7940. this.displayed_[i] = '';
  7941. }
  7942. // shift displayed rows up
  7943. for (i = this.topRow_; i < BOTTOM_ROW; i++) {
  7944. this.displayed_[i] = this.displayed_[i + 1];
  7945. }
  7946. // clear out the bottom row
  7947. this.displayed_[BOTTOM_ROW] = '';
  7948. };
  7949. // exports
  7950. module.exports = {
  7951. CaptionStream: CaptionStream,
  7952. Cea608Stream: Cea608Stream,
  7953. };
  7954. },{"../utils/stream":55}],45:[function(require,module,exports){
  7955. module.exports = require('./m2ts');
  7956. },{"./m2ts":46}],46:[function(require,module,exports){
  7957. /**
  7958. * mux.js
  7959. *
  7960. * Copyright (c) 2015 Brightcove
  7961. * All rights reserved.
  7962. *
  7963. * A stream-based mp2t to mp4 converter. This utility can be used to
  7964. * deliver mp4s to a SourceBuffer on platforms that support native
  7965. * Media Source Extensions.
  7966. */
  7967. 'use strict';
  7968. var Stream = require('../utils/stream.js'),
  7969. CaptionStream = require('./caption-stream'),
  7970. StreamTypes = require('./stream-types');
  7971. var Stream = require('../utils/stream.js');
  7972. var m2tsStreamTypes = require('./stream-types.js');
  7973. // object types
  7974. var
  7975. TransportPacketStream, TransportParseStream, ElementaryStream,
  7976. AacStream, H264Stream, NalByteStream;
  7977. // constants
  7978. var
  7979. MP2T_PACKET_LENGTH = 188, // bytes
  7980. SYNC_BYTE = 0x47,
  7981. /**
  7982. * Splits an incoming stream of binary data into MPEG-2 Transport
  7983. * Stream packets.
  7984. */
  7985. TransportPacketStream = function() {
  7986. var
  7987. buffer = new Uint8Array(MP2T_PACKET_LENGTH),
  7988. bytesInBuffer = 0;
  7989. TransportPacketStream.prototype.init.call(this);
  7990. // Deliver new bytes to the stream.
  7991. this.push = function(bytes) {
  7992. var
  7993. i = 0,
  7994. startIndex = 0,
  7995. endIndex = MP2T_PACKET_LENGTH,
  7996. everything;
  7997. // If there are bytes remaining from the last segment, prepend them to the
  7998. // bytes that were pushed in
  7999. if (bytesInBuffer) {
  8000. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  8001. everything.set(buffer.subarray(0, bytesInBuffer));
  8002. everything.set(bytes, bytesInBuffer);
  8003. bytesInBuffer = 0;
  8004. } else {
  8005. everything = bytes;
  8006. }
  8007. // While we have enough data for a packet
  8008. while (endIndex < everything.byteLength) {
  8009. // Look for a pair of start and end sync bytes in the data..
  8010. if (everything[startIndex] === SYNC_BYTE && everything[endIndex] === SYNC_BYTE) {
  8011. // We found a packet so emit it and jump one whole packet forward in
  8012. // the stream
  8013. this.trigger('data', everything.subarray(startIndex, endIndex));
  8014. startIndex += MP2T_PACKET_LENGTH;
  8015. endIndex += MP2T_PACKET_LENGTH;
  8016. continue;
  8017. }
  8018. // If we get here, we have somehow become de-synchronized and we need to step
  8019. // forward one byte at a time until we find a pair of sync bytes that denote
  8020. // a packet
  8021. startIndex++;
  8022. endIndex++;
  8023. }
  8024. // If there was some data left over at the end of the segment that couldn't
  8025. // possibly be a whole packet, keep it because it might be the start of a packet
  8026. // that continues in the next segment
  8027. if (startIndex < everything.byteLength) {
  8028. buffer.set(everything.subarray(startIndex), 0);
  8029. bytesInBuffer = everything.byteLength - startIndex;
  8030. }
  8031. };
  8032. this.flush = function () {
  8033. // If the buffer contains a whole packet when we are being flushed, emit it
  8034. // and empty the buffer. Otherwise hold onto the data because it may be
  8035. // important for decoding the next segment
  8036. if (bytesInBuffer === MP2T_PACKET_LENGTH && buffer[0] === SYNC_BYTE) {
  8037. this.trigger('data', buffer);
  8038. bytesInBuffer = 0;
  8039. }
  8040. this.trigger('done');
  8041. };
  8042. };
  8043. TransportPacketStream.prototype = new Stream();
  8044. /**
  8045. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  8046. * forms of the individual transport stream packets.
  8047. */
  8048. TransportParseStream = function() {
  8049. var parsePsi, parsePat, parsePmt, parsePes, self;
  8050. TransportParseStream.prototype.init.call(this);
  8051. self = this;
  8052. this.packetsWaitingForPmt = [];
  8053. this.programMapTable = undefined;
  8054. parsePsi = function(payload, psi) {
  8055. var offset = 0;
  8056. // PSI packets may be split into multiple sections and those
  8057. // sections may be split into multiple packets. If a PSI
  8058. // section starts in this packet, the payload_unit_start_indicator
  8059. // will be true and the first byte of the payload will indicate
  8060. // the offset from the current position to the start of the
  8061. // section.
  8062. if (psi.payloadUnitStartIndicator) {
  8063. offset += payload[offset] + 1;
  8064. }
  8065. if (psi.type === 'pat') {
  8066. parsePat(payload.subarray(offset), psi);
  8067. } else {
  8068. parsePmt(payload.subarray(offset), psi);
  8069. }
  8070. };
  8071. parsePat = function(payload, pat) {
  8072. pat.section_number = payload[7];
  8073. pat.last_section_number = payload[8];
  8074. // skip the PSI header and parse the first PMT entry
  8075. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  8076. pat.pmtPid = self.pmtPid;
  8077. };
  8078. /**
  8079. * Parse out the relevant fields of a Program Map Table (PMT).
  8080. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  8081. * packet. The first byte in this array should be the table_id
  8082. * field.
  8083. * @param pmt {object} the object that should be decorated with
  8084. * fields parsed from the PMT.
  8085. */
  8086. parsePmt = function(payload, pmt) {
  8087. var sectionLength, tableEnd, programInfoLength, offset;
  8088. // PMTs can be sent ahead of the time when they should actually
  8089. // take effect. We don't believe this should ever be the case
  8090. // for HLS but we'll ignore "forward" PMT declarations if we see
  8091. // them. Future PMT declarations have the current_next_indicator
  8092. // set to zero.
  8093. if (!(payload[5] & 0x01)) {
  8094. return;
  8095. }
  8096. // overwrite any existing program map table
  8097. self.programMapTable = {};
  8098. // the mapping table ends at the end of the current section
  8099. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  8100. tableEnd = 3 + sectionLength - 4;
  8101. // to determine where the table is, we have to figure out how
  8102. // long the program info descriptors are
  8103. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11];
  8104. // advance the offset to the first entry in the mapping table
  8105. offset = 12 + programInfoLength;
  8106. while (offset < tableEnd) {
  8107. // add an entry that maps the elementary_pid to the stream_type
  8108. self.programMapTable[(payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]] = payload[offset];
  8109. // move to the next table entry
  8110. // skip past the elementary stream descriptors, if present
  8111. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  8112. }
  8113. // record the map on the packet as well
  8114. pmt.programMapTable = self.programMapTable;
  8115. // if there are any packets waiting for a PMT to be found, process them now
  8116. while (self.packetsWaitingForPmt.length) {
  8117. self.processPes_.apply(self, self.packetsWaitingForPmt.shift());
  8118. }
  8119. };
  8120. /**
  8121. * Deliver a new MP2T packet to the stream.
  8122. */
  8123. this.push = function(packet) {
  8124. var
  8125. result = {},
  8126. offset = 4;
  8127. result.payloadUnitStartIndicator = !!(packet[1] & 0x40);
  8128. // pid is a 13-bit field starting at the last bit of packet[1]
  8129. result.pid = packet[1] & 0x1f;
  8130. result.pid <<= 8;
  8131. result.pid |= packet[2];
  8132. // if an adaption field is present, its length is specified by the
  8133. // fifth byte of the TS packet header. The adaptation field is
  8134. // used to add stuffing to PES packets that don't fill a complete
  8135. // TS packet, and to specify some forms of timing and control data
  8136. // that we do not currently use.
  8137. if (((packet[3] & 0x30) >>> 4) > 0x01) {
  8138. offset += packet[offset] + 1;
  8139. }
  8140. // parse the rest of the packet based on the type
  8141. if (result.pid === 0) {
  8142. result.type = 'pat';
  8143. parsePsi(packet.subarray(offset), result);
  8144. this.trigger('data', result);
  8145. } else if (result.pid === this.pmtPid) {
  8146. result.type = 'pmt';
  8147. parsePsi(packet.subarray(offset), result);
  8148. this.trigger('data', result);
  8149. } else if (this.programMapTable === undefined) {
  8150. // When we have not seen a PMT yet, defer further processing of
  8151. // PES packets until one has been parsed
  8152. this.packetsWaitingForPmt.push([packet, offset, result]);
  8153. } else {
  8154. this.processPes_(packet, offset, result);
  8155. }
  8156. };
  8157. this.processPes_ = function (packet, offset, result) {
  8158. result.streamType = this.programMapTable[result.pid];
  8159. result.type = 'pes';
  8160. result.data = packet.subarray(offset);
  8161. this.trigger('data', result);
  8162. };
  8163. };
  8164. TransportParseStream.prototype = new Stream();
  8165. TransportParseStream.STREAM_TYPES = {
  8166. h264: 0x1b,
  8167. adts: 0x0f
  8168. };
  8169. /**
  8170. * Reconsistutes program elementary stream (PES) packets from parsed
  8171. * transport stream packets. That is, if you pipe an
  8172. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  8173. * events will be events which capture the bytes for individual PES
  8174. * packets plus relevant metadata that has been extracted from the
  8175. * container.
  8176. */
  8177. ElementaryStream = function() {
  8178. var
  8179. // PES packet fragments
  8180. video = {
  8181. data: [],
  8182. size: 0
  8183. },
  8184. audio = {
  8185. data: [],
  8186. size: 0
  8187. },
  8188. timedMetadata = {
  8189. data: [],
  8190. size: 0
  8191. },
  8192. parsePes = function(payload, pes) {
  8193. var ptsDtsFlags;
  8194. // find out if this packets starts a new keyframe
  8195. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0;
  8196. // PES packets may be annotated with a PTS value, or a PTS value
  8197. // and a DTS value. Determine what combination of values is
  8198. // available to work with.
  8199. ptsDtsFlags = payload[7];
  8200. // PTS and DTS are normally stored as a 33-bit number. Javascript
  8201. // performs all bitwise operations on 32-bit integers but javascript
  8202. // supports a much greater range (52-bits) of integer using standard
  8203. // mathematical operations.
  8204. // We construct a 31-bit value using bitwise operators over the 31
  8205. // most significant bits and then multiply by 4 (equal to a left-shift
  8206. // of 2) before we add the final 2 least significant bits of the
  8207. // timestamp (equal to an OR.)
  8208. if (ptsDtsFlags & 0xC0) {
  8209. // the PTS and DTS are not written out directly. For information
  8210. // on how they are encoded, see
  8211. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  8212. pes.pts = (payload[9] & 0x0E) << 27
  8213. | (payload[10] & 0xFF) << 20
  8214. | (payload[11] & 0xFE) << 12
  8215. | (payload[12] & 0xFF) << 5
  8216. | (payload[13] & 0xFE) >>> 3;
  8217. pes.pts *= 4; // Left shift by 2
  8218. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  8219. pes.dts = pes.pts;
  8220. if (ptsDtsFlags & 0x40) {
  8221. pes.dts = (payload[14] & 0x0E ) << 27
  8222. | (payload[15] & 0xFF ) << 20
  8223. | (payload[16] & 0xFE ) << 12
  8224. | (payload[17] & 0xFF ) << 5
  8225. | (payload[18] & 0xFE ) >>> 3;
  8226. pes.dts *= 4; // Left shift by 2
  8227. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  8228. }
  8229. }
  8230. // the data section starts immediately after the PES header.
  8231. // pes_header_data_length specifies the number of header bytes
  8232. // that follow the last byte of the field.
  8233. pes.data = payload.subarray(9 + payload[8]);
  8234. },
  8235. flushStream = function(stream, type) {
  8236. var
  8237. packetData = new Uint8Array(stream.size),
  8238. event = {
  8239. type: type
  8240. },
  8241. i = 0,
  8242. fragment;
  8243. // do nothing if there is no buffered data
  8244. if (!stream.data.length) {
  8245. return;
  8246. }
  8247. event.trackId = stream.data[0].pid;
  8248. // reassemble the packet
  8249. while (stream.data.length) {
  8250. fragment = stream.data.shift();
  8251. packetData.set(fragment.data, i);
  8252. i += fragment.data.byteLength;
  8253. }
  8254. // parse assembled packet's PES header
  8255. parsePes(packetData, event);
  8256. stream.size = 0;
  8257. self.trigger('data', event);
  8258. },
  8259. self;
  8260. ElementaryStream.prototype.init.call(this);
  8261. self = this;
  8262. this.push = function(data) {
  8263. ({
  8264. pat: function() {
  8265. // we have to wait for the PMT to arrive as well before we
  8266. // have any meaningful metadata
  8267. },
  8268. pes: function() {
  8269. var stream, streamType;
  8270. switch (data.streamType) {
  8271. case StreamTypes.H264_STREAM_TYPE:
  8272. case m2tsStreamTypes.H264_STREAM_TYPE:
  8273. stream = video;
  8274. streamType = 'video';
  8275. break;
  8276. case StreamTypes.ADTS_STREAM_TYPE:
  8277. stream = audio;
  8278. streamType = 'audio';
  8279. break;
  8280. case StreamTypes.METADATA_STREAM_TYPE:
  8281. stream = timedMetadata;
  8282. streamType = 'timed-metadata';
  8283. break;
  8284. default:
  8285. // ignore unknown stream types
  8286. return;
  8287. }
  8288. // if a new packet is starting, we can flush the completed
  8289. // packet
  8290. if (data.payloadUnitStartIndicator) {
  8291. flushStream(stream, streamType);
  8292. }
  8293. // buffer this fragment until we are sure we've received the
  8294. // complete payload
  8295. stream.data.push(data);
  8296. stream.size += data.data.byteLength;
  8297. },
  8298. pmt: function() {
  8299. var
  8300. event = {
  8301. type: 'metadata',
  8302. tracks: []
  8303. },
  8304. programMapTable = data.programMapTable,
  8305. k,
  8306. track;
  8307. // translate streams to tracks
  8308. for (k in programMapTable) {
  8309. if (programMapTable.hasOwnProperty(k)) {
  8310. track = {
  8311. timelineStartInfo: {
  8312. baseMediaDecodeTime: 0
  8313. }
  8314. };
  8315. track.id = +k;
  8316. if (programMapTable[k] === m2tsStreamTypes.H264_STREAM_TYPE) {
  8317. track.codec = 'avc';
  8318. track.type = 'video';
  8319. } else if (programMapTable[k] === m2tsStreamTypes.ADTS_STREAM_TYPE) {
  8320. track.codec = 'adts';
  8321. track.type = 'audio';
  8322. }
  8323. event.tracks.push(track);
  8324. }
  8325. }
  8326. self.trigger('data', event);
  8327. }
  8328. })[data.type]();
  8329. };
  8330. /**
  8331. * Flush any remaining input. Video PES packets may be of variable
  8332. * length. Normally, the start of a new video packet can trigger the
  8333. * finalization of the previous packet. That is not possible if no
  8334. * more video is forthcoming, however. In that case, some other
  8335. * mechanism (like the end of the file) has to be employed. When it is
  8336. * clear that no additional data is forthcoming, calling this method
  8337. * will flush the buffered packets.
  8338. */
  8339. this.flush = function() {
  8340. // !!THIS ORDER IS IMPORTANT!!
  8341. // video first then audio
  8342. flushStream(video, 'video');
  8343. flushStream(audio, 'audio');
  8344. flushStream(timedMetadata, 'timed-metadata');
  8345. this.trigger('done');
  8346. };
  8347. };
  8348. ElementaryStream.prototype = new Stream();
  8349. var m2ts = {
  8350. PAT_PID: 0x0000,
  8351. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH,
  8352. TransportPacketStream: TransportPacketStream,
  8353. TransportParseStream: TransportParseStream,
  8354. ElementaryStream: ElementaryStream,
  8355. CaptionStream: CaptionStream.CaptionStream,
  8356. Cea608Stream: CaptionStream.Cea608Stream,
  8357. MetadataStream: require('./metadata-stream'),
  8358. };
  8359. for (var type in StreamTypes) {
  8360. if (StreamTypes.hasOwnProperty(type)) {
  8361. m2ts[type] = StreamTypes[type];
  8362. }
  8363. }
  8364. module.exports = m2ts;
  8365. },{"../utils/stream.js":55,"./caption-stream":44,"./metadata-stream":47,"./stream-types":48,"./stream-types.js":48}],47:[function(require,module,exports){
  8366. /**
  8367. * Accepts program elementary stream (PES) data events and parses out
  8368. * ID3 metadata from them, if present.
  8369. * @see http://id3.org/id3v2.3.0
  8370. */
  8371. 'use strict';
  8372. var
  8373. Stream = require('../utils/stream'),
  8374. StreamTypes = require('./stream-types'),
  8375. // return a percent-encoded representation of the specified byte range
  8376. // @see http://en.wikipedia.org/wiki/Percent-encoding
  8377. percentEncode = function(bytes, start, end) {
  8378. var i, result = '';
  8379. for (i = start; i < end; i++) {
  8380. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  8381. }
  8382. return result;
  8383. },
  8384. // return the string representation of the specified byte range,
  8385. // interpreted as UTf-8.
  8386. parseUtf8 = function(bytes, start, end) {
  8387. return decodeURIComponent(percentEncode(bytes, start, end));
  8388. },
  8389. // return the string representation of the specified byte range,
  8390. // interpreted as ISO-8859-1.
  8391. parseIso88591 = function(bytes, start, end) {
  8392. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  8393. },
  8394. parseSyncSafeInteger = function (data) {
  8395. return (data[0] << 21) |
  8396. (data[1] << 14) |
  8397. (data[2] << 7) |
  8398. (data[3]);
  8399. },
  8400. tagParsers = {
  8401. 'TXXX': function(tag) {
  8402. var i;
  8403. if (tag.data[0] !== 3) {
  8404. // ignore frames with unrecognized character encodings
  8405. return;
  8406. }
  8407. for (i = 1; i < tag.data.length; i++) {
  8408. if (tag.data[i] === 0) {
  8409. // parse the text fields
  8410. tag.description = parseUtf8(tag.data, 1, i);
  8411. // do not include the null terminator in the tag value
  8412. tag.value = parseUtf8(tag.data, i + 1, tag.data.length - 1);
  8413. break;
  8414. }
  8415. }
  8416. tag.data = tag.value;
  8417. },
  8418. 'WXXX': function(tag) {
  8419. var i;
  8420. if (tag.data[0] !== 3) {
  8421. // ignore frames with unrecognized character encodings
  8422. return;
  8423. }
  8424. for (i = 1; i < tag.data.length; i++) {
  8425. if (tag.data[i] === 0) {
  8426. // parse the description and URL fields
  8427. tag.description = parseUtf8(tag.data, 1, i);
  8428. tag.url = parseUtf8(tag.data, i + 1, tag.data.length);
  8429. break;
  8430. }
  8431. }
  8432. },
  8433. 'PRIV': function(tag) {
  8434. var i;
  8435. for (i = 0; i < tag.data.length; i++) {
  8436. if (tag.data[i] === 0) {
  8437. // parse the description and URL fields
  8438. tag.owner = parseIso88591(tag.data, 0, i);
  8439. break;
  8440. }
  8441. }
  8442. tag.privateData = tag.data.subarray(i + 1);
  8443. tag.data = tag.privateData;
  8444. }
  8445. },
  8446. MetadataStream;
  8447. MetadataStream = function(options) {
  8448. var
  8449. settings = {
  8450. debug: !!(options && options.debug),
  8451. // the bytes of the program-level descriptor field in MP2T
  8452. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  8453. // program element descriptors"
  8454. descriptor: options && options.descriptor
  8455. },
  8456. // the total size in bytes of the ID3 tag being parsed
  8457. tagSize = 0,
  8458. // tag data that is not complete enough to be parsed
  8459. buffer = [],
  8460. // the total number of bytes currently in the buffer
  8461. bufferSize = 0,
  8462. i;
  8463. MetadataStream.prototype.init.call(this);
  8464. // calculate the text track in-band metadata track dispatch type
  8465. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  8466. this.dispatchType = StreamTypes.METADATA_STREAM_TYPE.toString(16);
  8467. if (settings.descriptor) {
  8468. for (i = 0; i < settings.descriptor.length; i++) {
  8469. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  8470. }
  8471. }
  8472. this.push = function(chunk) {
  8473. var tag, frameStart, frameSize, frame, i, frameHeader;
  8474. if (chunk.type !== 'timed-metadata') {
  8475. return;
  8476. }
  8477. // if data_alignment_indicator is set in the PES header,
  8478. // we must have the start of a new ID3 tag. Assume anything
  8479. // remaining in the buffer was malformed and throw it out
  8480. if (chunk.dataAlignmentIndicator) {
  8481. bufferSize = 0;
  8482. buffer.length = 0;
  8483. }
  8484. // ignore events that don't look like ID3 data
  8485. if (buffer.length === 0 &&
  8486. (chunk.data.length < 10 ||
  8487. chunk.data[0] !== 'I'.charCodeAt(0) ||
  8488. chunk.data[1] !== 'D'.charCodeAt(0) ||
  8489. chunk.data[2] !== '3'.charCodeAt(0))) {
  8490. if (settings.debug) {
  8491. console.log('Skipping unrecognized metadata packet');
  8492. }
  8493. return;
  8494. }
  8495. // add this chunk to the data we've collected so far
  8496. buffer.push(chunk);
  8497. bufferSize += chunk.data.byteLength;
  8498. // grab the size of the entire frame from the ID3 header
  8499. if (buffer.length === 1) {
  8500. // the frame size is transmitted as a 28-bit integer in the
  8501. // last four bytes of the ID3 header.
  8502. // The most significant bit of each byte is dropped and the
  8503. // results concatenated to recover the actual value.
  8504. tagSize = parseSyncSafeInteger(chunk.data.subarray(6, 10));
  8505. // ID3 reports the tag size excluding the header but it's more
  8506. // convenient for our comparisons to include it
  8507. tagSize += 10;
  8508. }
  8509. // if the entire frame has not arrived, wait for more data
  8510. if (bufferSize < tagSize) {
  8511. return;
  8512. }
  8513. // collect the entire frame so it can be parsed
  8514. tag = {
  8515. data: new Uint8Array(tagSize),
  8516. frames: [],
  8517. pts: buffer[0].pts,
  8518. dts: buffer[0].dts
  8519. };
  8520. for (i = 0; i < tagSize;) {
  8521. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  8522. i += buffer[0].data.byteLength;
  8523. bufferSize -= buffer[0].data.byteLength;
  8524. buffer.shift();
  8525. }
  8526. // find the start of the first frame and the end of the tag
  8527. frameStart = 10;
  8528. if (tag.data[5] & 0x40) {
  8529. // advance the frame start past the extended header
  8530. frameStart += 4; // header size field
  8531. frameStart += parseSyncSafeInteger(tag.data.subarray(10, 14));
  8532. // clip any padding off the end
  8533. tagSize -= parseSyncSafeInteger(tag.data.subarray(16, 20));
  8534. }
  8535. // parse one or more ID3 frames
  8536. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  8537. do {
  8538. // determine the number of bytes in this frame
  8539. frameSize = parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
  8540. if (frameSize < 1) {
  8541. return console.log('Malformed ID3 frame encountered. Skipping metadata parsing.');
  8542. }
  8543. frameHeader = String.fromCharCode(tag.data[frameStart],
  8544. tag.data[frameStart + 1],
  8545. tag.data[frameStart + 2],
  8546. tag.data[frameStart + 3]);
  8547. frame = {
  8548. id: frameHeader,
  8549. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  8550. };
  8551. frame.key = frame.id;
  8552. if (tagParsers[frame.id]) {
  8553. tagParsers[frame.id](frame);
  8554. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  8555. var
  8556. d = frame.data,
  8557. size = ((d[3] & 0x01) << 30) |
  8558. (d[4] << 22) |
  8559. (d[5] << 14) |
  8560. (d[6] << 6) |
  8561. (d[7] >>> 2);
  8562. size *= 4;
  8563. size += d[7] & 0x03;
  8564. frame.timeStamp = size;
  8565. this.trigger('timestamp', frame);
  8566. }
  8567. }
  8568. tag.frames.push(frame);
  8569. frameStart += 10; // advance past the frame header
  8570. frameStart += frameSize; // advance past the frame body
  8571. } while (frameStart < tagSize);
  8572. this.trigger('data', tag);
  8573. };
  8574. };
  8575. MetadataStream.prototype = new Stream();
  8576. module.exports = MetadataStream;
  8577. },{"../utils/stream":55,"./stream-types":48}],48:[function(require,module,exports){
  8578. 'use strict';
  8579. module.exports = {
  8580. H264_STREAM_TYPE: 0x1B,
  8581. ADTS_STREAM_TYPE: 0x0F,
  8582. METADATA_STREAM_TYPE: 0x15
  8583. };
  8584. },{}],49:[function(require,module,exports){
  8585. module.exports = {
  8586. generator: require('./mp4-generator'),
  8587. Transmuxer: require('./transmuxer').Transmuxer,
  8588. AudioSegmentStream: require('./transmuxer').AudioSegmentStream,
  8589. VideoSegmentStream: require('./transmuxer').VideoSegmentStream,
  8590. tools: require('../tools/mp4-inspector'),
  8591. };
  8592. },{"../tools/mp4-inspector":53,"./mp4-generator":50,"./transmuxer":51}],50:[function(require,module,exports){
  8593. /**
  8594. * mux.js
  8595. *
  8596. * Copyright (c) 2015 Brightcove
  8597. * All rights reserved.
  8598. *
  8599. * Functions that generate fragmented MP4s suitable for use with Media
  8600. * Source Extensions.
  8601. */
  8602. 'use strict';
  8603. var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd, trak,
  8604. tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, styp, traf, trex, trun,
  8605. types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR,
  8606. AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS;
  8607. // pre-calculate constants
  8608. (function() {
  8609. var i;
  8610. types = {
  8611. avc1: [], // codingname
  8612. avcC: [],
  8613. btrt: [],
  8614. dinf: [],
  8615. dref: [],
  8616. esds: [],
  8617. ftyp: [],
  8618. hdlr: [],
  8619. mdat: [],
  8620. mdhd: [],
  8621. mdia: [],
  8622. mfhd: [],
  8623. minf: [],
  8624. moof: [],
  8625. moov: [],
  8626. mp4a: [], // codingname
  8627. mvex: [],
  8628. mvhd: [],
  8629. sdtp: [],
  8630. smhd: [],
  8631. stbl: [],
  8632. stco: [],
  8633. stsc: [],
  8634. stsd: [],
  8635. stsz: [],
  8636. stts: [],
  8637. styp: [],
  8638. tfdt: [],
  8639. tfhd: [],
  8640. traf: [],
  8641. trak: [],
  8642. trun: [],
  8643. trex: [],
  8644. tkhd: [],
  8645. vmhd: []
  8646. };
  8647. // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  8648. // don't throw an error
  8649. if (typeof Uint8Array === 'undefined') {
  8650. return;
  8651. }
  8652. for (i in types) {
  8653. if (types.hasOwnProperty(i)) {
  8654. types[i] = [
  8655. i.charCodeAt(0),
  8656. i.charCodeAt(1),
  8657. i.charCodeAt(2),
  8658. i.charCodeAt(3)
  8659. ];
  8660. }
  8661. }
  8662. MAJOR_BRAND = new Uint8Array([
  8663. 'i'.charCodeAt(0),
  8664. 's'.charCodeAt(0),
  8665. 'o'.charCodeAt(0),
  8666. 'm'.charCodeAt(0)
  8667. ]);
  8668. AVC1_BRAND = new Uint8Array([
  8669. 'a'.charCodeAt(0),
  8670. 'v'.charCodeAt(0),
  8671. 'c'.charCodeAt(0),
  8672. '1'.charCodeAt(0)
  8673. ]);
  8674. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  8675. VIDEO_HDLR = new Uint8Array([
  8676. 0x00, // version 0
  8677. 0x00, 0x00, 0x00, // flags
  8678. 0x00, 0x00, 0x00, 0x00, // pre_defined
  8679. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  8680. 0x00, 0x00, 0x00, 0x00, // reserved
  8681. 0x00, 0x00, 0x00, 0x00, // reserved
  8682. 0x00, 0x00, 0x00, 0x00, // reserved
  8683. 0x56, 0x69, 0x64, 0x65,
  8684. 0x6f, 0x48, 0x61, 0x6e,
  8685. 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  8686. ]);
  8687. AUDIO_HDLR = new Uint8Array([
  8688. 0x00, // version 0
  8689. 0x00, 0x00, 0x00, // flags
  8690. 0x00, 0x00, 0x00, 0x00, // pre_defined
  8691. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  8692. 0x00, 0x00, 0x00, 0x00, // reserved
  8693. 0x00, 0x00, 0x00, 0x00, // reserved
  8694. 0x00, 0x00, 0x00, 0x00, // reserved
  8695. 0x53, 0x6f, 0x75, 0x6e,
  8696. 0x64, 0x48, 0x61, 0x6e,
  8697. 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  8698. ]);
  8699. HDLR_TYPES = {
  8700. "video":VIDEO_HDLR,
  8701. "audio": AUDIO_HDLR
  8702. };
  8703. DREF = new Uint8Array([
  8704. 0x00, // version 0
  8705. 0x00, 0x00, 0x00, // flags
  8706. 0x00, 0x00, 0x00, 0x01, // entry_count
  8707. 0x00, 0x00, 0x00, 0x0c, // entry_size
  8708. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  8709. 0x00, // version 0
  8710. 0x00, 0x00, 0x01 // entry_flags
  8711. ]);
  8712. SMHD = new Uint8Array([
  8713. 0x00, // version
  8714. 0x00, 0x00, 0x00, // flags
  8715. 0x00, 0x00, // balance, 0 means centered
  8716. 0x00, 0x00 // reserved
  8717. ]);
  8718. STCO = new Uint8Array([
  8719. 0x00, // version
  8720. 0x00, 0x00, 0x00, // flags
  8721. 0x00, 0x00, 0x00, 0x00 // entry_count
  8722. ]);
  8723. STSC = STCO;
  8724. STSZ = new Uint8Array([
  8725. 0x00, // version
  8726. 0x00, 0x00, 0x00, // flags
  8727. 0x00, 0x00, 0x00, 0x00, // sample_size
  8728. 0x00, 0x00, 0x00, 0x00, // sample_count
  8729. ]);
  8730. STTS = STCO;
  8731. VMHD = new Uint8Array([
  8732. 0x00, // version
  8733. 0x00, 0x00, 0x01, // flags
  8734. 0x00, 0x00, // graphicsmode
  8735. 0x00, 0x00,
  8736. 0x00, 0x00,
  8737. 0x00, 0x00 // opcolor
  8738. ]);
  8739. })();
  8740. box = function(type) {
  8741. var
  8742. payload = [],
  8743. size = 0,
  8744. i,
  8745. result,
  8746. view;
  8747. for (i = 1; i < arguments.length; i++) {
  8748. payload.push(arguments[i]);
  8749. }
  8750. i = payload.length;
  8751. // calculate the total size we need to allocate
  8752. while (i--) {
  8753. size += payload[i].byteLength;
  8754. }
  8755. result = new Uint8Array(size + 8);
  8756. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  8757. view.setUint32(0, result.byteLength);
  8758. result.set(type, 4);
  8759. // copy the payload into the result
  8760. for (i = 0, size = 8; i < payload.length; i++) {
  8761. result.set(payload[i], size);
  8762. size += payload[i].byteLength;
  8763. }
  8764. return result;
  8765. };
  8766. dinf = function() {
  8767. return box(types.dinf, box(types.dref, DREF));
  8768. };
  8769. esds = function(track) {
  8770. return box(types.esds, new Uint8Array([
  8771. 0x00, // version
  8772. 0x00, 0x00, 0x00, // flags
  8773. // ES_Descriptor
  8774. 0x03, // tag, ES_DescrTag
  8775. 0x19, // length
  8776. 0x00, 0x00, // ES_ID
  8777. 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
  8778. // DecoderConfigDescriptor
  8779. 0x04, // tag, DecoderConfigDescrTag
  8780. 0x11, // length
  8781. 0x40, // object type
  8782. 0x15, // streamType
  8783. 0x00, 0x06, 0x00, // bufferSizeDB
  8784. 0x00, 0x00, 0xda, 0xc0, // maxBitrate
  8785. 0x00, 0x00, 0xda, 0xc0, // avgBitrate
  8786. // DecoderSpecificInfo
  8787. 0x05, // tag, DecoderSpecificInfoTag
  8788. 0x02, // length
  8789. // ISO/IEC 14496-3, AudioSpecificConfig
  8790. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  8791. (track.audioobjecttype << 3) | (track.samplingfrequencyindex >>> 1),
  8792. (track.samplingfrequencyindex << 7) | (track.channelcount << 3),
  8793. 0x06, 0x01, 0x02 // GASpecificConfig
  8794. ]));
  8795. };
  8796. ftyp = function() {
  8797. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  8798. };
  8799. hdlr = function(type) {
  8800. return box(types.hdlr, HDLR_TYPES[type]);
  8801. };
  8802. mdat = function(data) {
  8803. return box(types.mdat, data);
  8804. };
  8805. mdhd = function(track) {
  8806. var result = new Uint8Array([
  8807. 0x00, // version 0
  8808. 0x00, 0x00, 0x00, // flags
  8809. 0x00, 0x00, 0x00, 0x02, // creation_time
  8810. 0x00, 0x00, 0x00, 0x03, // modification_time
  8811. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  8812. (track.duration >>> 24) & 0xFF,
  8813. (track.duration >>> 16) & 0xFF,
  8814. (track.duration >>> 8) & 0xFF,
  8815. track.duration & 0xFF, // duration
  8816. 0x55, 0xc4, // 'und' language (undetermined)
  8817. 0x00, 0x00
  8818. ]);
  8819. // Use the sample rate from the track metadata, when it is
  8820. // defined. The sample rate can be parsed out of an ADTS header, for
  8821. // instance.
  8822. if (track.samplerate) {
  8823. result[12] = (track.samplerate >>> 24) & 0xFF;
  8824. result[13] = (track.samplerate >>> 16) & 0xFF;
  8825. result[14] = (track.samplerate >>> 8) & 0xFF;
  8826. result[15] = (track.samplerate) & 0xFF;
  8827. }
  8828. return box(types.mdhd, result);
  8829. };
  8830. mdia = function(track) {
  8831. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  8832. };
  8833. mfhd = function(sequenceNumber) {
  8834. return box(types.mfhd, new Uint8Array([
  8835. 0x00,
  8836. 0x00, 0x00, 0x00, // flags
  8837. (sequenceNumber & 0xFF000000) >> 24,
  8838. (sequenceNumber & 0xFF0000) >> 16,
  8839. (sequenceNumber & 0xFF00) >> 8,
  8840. sequenceNumber & 0xFF, // sequence_number
  8841. ]));
  8842. };
  8843. minf = function(track) {
  8844. return box(types.minf,
  8845. track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD),
  8846. dinf(),
  8847. stbl(track));
  8848. };
  8849. moof = function(sequenceNumber, tracks) {
  8850. var
  8851. trackFragments = [],
  8852. i = tracks.length;
  8853. // build traf boxes for each track fragment
  8854. while (i--) {
  8855. trackFragments[i] = traf(tracks[i]);
  8856. }
  8857. return box.apply(null, [
  8858. types.moof,
  8859. mfhd(sequenceNumber)
  8860. ].concat(trackFragments));
  8861. };
  8862. /**
  8863. * Returns a movie box.
  8864. * @param tracks {array} the tracks associated with this movie
  8865. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  8866. */
  8867. moov = function(tracks) {
  8868. var
  8869. i = tracks.length,
  8870. boxes = [];
  8871. while (i--) {
  8872. boxes[i] = trak(tracks[i]);
  8873. }
  8874. return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
  8875. };
  8876. mvex = function(tracks) {
  8877. var
  8878. i = tracks.length,
  8879. boxes = [];
  8880. while (i--) {
  8881. boxes[i] = trex(tracks[i]);
  8882. }
  8883. return box.apply(null, [types.mvex].concat(boxes));
  8884. };
  8885. mvhd = function(duration) {
  8886. var
  8887. bytes = new Uint8Array([
  8888. 0x00, // version 0
  8889. 0x00, 0x00, 0x00, // flags
  8890. 0x00, 0x00, 0x00, 0x01, // creation_time
  8891. 0x00, 0x00, 0x00, 0x02, // modification_time
  8892. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  8893. (duration & 0xFF000000) >> 24,
  8894. (duration & 0xFF0000) >> 16,
  8895. (duration & 0xFF00) >> 8,
  8896. duration & 0xFF, // duration
  8897. 0x00, 0x01, 0x00, 0x00, // 1.0 rate
  8898. 0x01, 0x00, // 1.0 volume
  8899. 0x00, 0x00, // reserved
  8900. 0x00, 0x00, 0x00, 0x00, // reserved
  8901. 0x00, 0x00, 0x00, 0x00, // reserved
  8902. 0x00, 0x01, 0x00, 0x00,
  8903. 0x00, 0x00, 0x00, 0x00,
  8904. 0x00, 0x00, 0x00, 0x00,
  8905. 0x00, 0x00, 0x00, 0x00,
  8906. 0x00, 0x01, 0x00, 0x00,
  8907. 0x00, 0x00, 0x00, 0x00,
  8908. 0x00, 0x00, 0x00, 0x00,
  8909. 0x00, 0x00, 0x00, 0x00,
  8910. 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  8911. 0x00, 0x00, 0x00, 0x00,
  8912. 0x00, 0x00, 0x00, 0x00,
  8913. 0x00, 0x00, 0x00, 0x00,
  8914. 0x00, 0x00, 0x00, 0x00,
  8915. 0x00, 0x00, 0x00, 0x00,
  8916. 0x00, 0x00, 0x00, 0x00, // pre_defined
  8917. 0xff, 0xff, 0xff, 0xff // next_track_ID
  8918. ]);
  8919. return box(types.mvhd, bytes);
  8920. };
  8921. sdtp = function(track) {
  8922. var
  8923. samples = track.samples || [],
  8924. bytes = new Uint8Array(4 + samples.length),
  8925. flags,
  8926. i;
  8927. // leave the full box header (4 bytes) all zero
  8928. // write the sample table
  8929. for (i = 0; i < samples.length; i++) {
  8930. flags = samples[i].flags;
  8931. bytes[i + 4] = (flags.dependsOn << 4) |
  8932. (flags.isDependedOn << 2) |
  8933. (flags.hasRedundancy);
  8934. }
  8935. return box(types.sdtp,
  8936. bytes);
  8937. };
  8938. stbl = function(track) {
  8939. return box(types.stbl,
  8940. stsd(track),
  8941. box(types.stts, STTS),
  8942. box(types.stsc, STSC),
  8943. box(types.stsz, STSZ),
  8944. box(types.stco, STCO));
  8945. };
  8946. (function() {
  8947. var videoSample, audioSample;
  8948. stsd = function(track) {
  8949. return box(types.stsd, new Uint8Array([
  8950. 0x00, // version 0
  8951. 0x00, 0x00, 0x00, // flags
  8952. 0x00, 0x00, 0x00, 0x01
  8953. ]), track.type === 'video' ? videoSample(track) : audioSample(track));
  8954. };
  8955. videoSample = function(track) {
  8956. var
  8957. sps = track.sps || [],
  8958. pps = track.pps || [],
  8959. sequenceParameterSets = [],
  8960. pictureParameterSets = [],
  8961. i;
  8962. // assemble the SPSs
  8963. for (i = 0; i < sps.length; i++) {
  8964. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  8965. sequenceParameterSets.push((sps[i].byteLength & 0xFF)); // sequenceParameterSetLength
  8966. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  8967. }
  8968. // assemble the PPSs
  8969. for (i = 0; i < pps.length; i++) {
  8970. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  8971. pictureParameterSets.push((pps[i].byteLength & 0xFF));
  8972. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  8973. }
  8974. return box(types.avc1, new Uint8Array([
  8975. 0x00, 0x00, 0x00,
  8976. 0x00, 0x00, 0x00, // reserved
  8977. 0x00, 0x01, // data_reference_index
  8978. 0x00, 0x00, // pre_defined
  8979. 0x00, 0x00, // reserved
  8980. 0x00, 0x00, 0x00, 0x00,
  8981. 0x00, 0x00, 0x00, 0x00,
  8982. 0x00, 0x00, 0x00, 0x00, // pre_defined
  8983. (track.width & 0xff00) >> 8,
  8984. track.width & 0xff, // width
  8985. (track.height & 0xff00) >> 8,
  8986. track.height & 0xff, // height
  8987. 0x00, 0x48, 0x00, 0x00, // horizresolution
  8988. 0x00, 0x48, 0x00, 0x00, // vertresolution
  8989. 0x00, 0x00, 0x00, 0x00, // reserved
  8990. 0x00, 0x01, // frame_count
  8991. 0x13,
  8992. 0x76, 0x69, 0x64, 0x65,
  8993. 0x6f, 0x6a, 0x73, 0x2d,
  8994. 0x63, 0x6f, 0x6e, 0x74,
  8995. 0x72, 0x69, 0x62, 0x2d,
  8996. 0x68, 0x6c, 0x73, 0x00,
  8997. 0x00, 0x00, 0x00, 0x00,
  8998. 0x00, 0x00, 0x00, 0x00,
  8999. 0x00, 0x00, 0x00, // compressorname
  9000. 0x00, 0x18, // depth = 24
  9001. 0x11, 0x11 // pre_defined = -1
  9002. ]), box(types.avcC, new Uint8Array([
  9003. 0x01, // configurationVersion
  9004. track.profileIdc, // AVCProfileIndication
  9005. track.profileCompatibility, // profile_compatibility
  9006. track.levelIdc, // AVCLevelIndication
  9007. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  9008. ].concat([
  9009. sps.length // numOfSequenceParameterSets
  9010. ]).concat(sequenceParameterSets).concat([
  9011. pps.length // numOfPictureParameterSets
  9012. ]).concat(pictureParameterSets))), // "PPS"
  9013. box(types.btrt, new Uint8Array([
  9014. 0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  9015. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  9016. 0x00, 0x2d, 0xc6, 0xc0
  9017. ])) // avgBitrate
  9018. );
  9019. };
  9020. audioSample = function(track) {
  9021. return box(types.mp4a, new Uint8Array([
  9022. // SampleEntry, ISO/IEC 14496-12
  9023. 0x00, 0x00, 0x00,
  9024. 0x00, 0x00, 0x00, // reserved
  9025. 0x00, 0x01, // data_reference_index
  9026. // AudioSampleEntry, ISO/IEC 14496-12
  9027. 0x00, 0x00, 0x00, 0x00, // reserved
  9028. 0x00, 0x00, 0x00, 0x00, // reserved
  9029. (track.channelcount & 0xff00) >> 8,
  9030. (track.channelcount & 0xff), // channelcount
  9031. (track.samplesize & 0xff00) >> 8,
  9032. (track.samplesize & 0xff), // samplesize
  9033. 0x00, 0x00, // pre_defined
  9034. 0x00, 0x00, // reserved
  9035. (track.samplerate & 0xff00) >> 8,
  9036. (track.samplerate & 0xff),
  9037. 0x00, 0x00 // samplerate, 16.16
  9038. // MP4AudioSampleEntry, ISO/IEC 14496-14
  9039. ]), esds(track));
  9040. };
  9041. })();
  9042. styp = function() {
  9043. return box(types.styp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND);
  9044. };
  9045. tkhd = function(track) {
  9046. var result = new Uint8Array([
  9047. 0x00, // version 0
  9048. 0x00, 0x00, 0x07, // flags
  9049. 0x00, 0x00, 0x00, 0x00, // creation_time
  9050. 0x00, 0x00, 0x00, 0x00, // modification_time
  9051. (track.id & 0xFF000000) >> 24,
  9052. (track.id & 0xFF0000) >> 16,
  9053. (track.id & 0xFF00) >> 8,
  9054. track.id & 0xFF, // track_ID
  9055. 0x00, 0x00, 0x00, 0x00, // reserved
  9056. (track.duration & 0xFF000000) >> 24,
  9057. (track.duration & 0xFF0000) >> 16,
  9058. (track.duration & 0xFF00) >> 8,
  9059. track.duration & 0xFF, // duration
  9060. 0x00, 0x00, 0x00, 0x00,
  9061. 0x00, 0x00, 0x00, 0x00, // reserved
  9062. 0x00, 0x00, // layer
  9063. 0x00, 0x00, // alternate_group
  9064. 0x01, 0x00, // non-audio track volume
  9065. 0x00, 0x00, // reserved
  9066. 0x00, 0x01, 0x00, 0x00,
  9067. 0x00, 0x00, 0x00, 0x00,
  9068. 0x00, 0x00, 0x00, 0x00,
  9069. 0x00, 0x00, 0x00, 0x00,
  9070. 0x00, 0x01, 0x00, 0x00,
  9071. 0x00, 0x00, 0x00, 0x00,
  9072. 0x00, 0x00, 0x00, 0x00,
  9073. 0x00, 0x00, 0x00, 0x00,
  9074. 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  9075. (track.width & 0xFF00) >> 8,
  9076. track.width & 0xFF,
  9077. 0x00, 0x00, // width
  9078. (track.height & 0xFF00) >> 8,
  9079. track.height & 0xFF,
  9080. 0x00, 0x00 // height
  9081. ]);
  9082. return box(types.tkhd, result);
  9083. };
  9084. /**
  9085. * Generate a track fragment (traf) box. A traf box collects metadata
  9086. * about tracks in a movie fragment (moof) box.
  9087. */
  9088. traf = function(track) {
  9089. var trackFragmentHeader, trackFragmentDecodeTime,
  9090. trackFragmentRun, sampleDependencyTable, dataOffset;
  9091. trackFragmentHeader = box(types.tfhd, new Uint8Array([
  9092. 0x00, // version 0
  9093. 0x00, 0x00, 0x3a, // flags
  9094. (track.id & 0xFF000000) >> 24,
  9095. (track.id & 0xFF0000) >> 16,
  9096. (track.id & 0xFF00) >> 8,
  9097. (track.id & 0xFF), // track_ID
  9098. 0x00, 0x00, 0x00, 0x01, // sample_description_index
  9099. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  9100. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  9101. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  9102. ]));
  9103. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([
  9104. 0x00, // version 0
  9105. 0x00, 0x00, 0x00, // flags
  9106. // baseMediaDecodeTime
  9107. (track.baseMediaDecodeTime >>> 24) & 0xFF,
  9108. (track.baseMediaDecodeTime >>> 16) & 0xFF,
  9109. (track.baseMediaDecodeTime >>> 8) & 0xFF,
  9110. track.baseMediaDecodeTime & 0xFF
  9111. ]));
  9112. // the data offset specifies the number of bytes from the start of
  9113. // the containing moof to the first payload byte of the associated
  9114. // mdat
  9115. dataOffset = (32 + // tfhd
  9116. 16 + // tfdt
  9117. 8 + // traf header
  9118. 16 + // mfhd
  9119. 8 + // moof header
  9120. 8); // mdat header
  9121. // audio tracks require less metadata
  9122. if (track.type === 'audio') {
  9123. trackFragmentRun = trun(track, dataOffset);
  9124. return box(types.traf,
  9125. trackFragmentHeader,
  9126. trackFragmentDecodeTime,
  9127. trackFragmentRun);
  9128. }
  9129. // video tracks should contain an independent and disposable samples
  9130. // box (sdtp)
  9131. // generate one and adjust offsets to match
  9132. sampleDependencyTable = sdtp(track);
  9133. trackFragmentRun = trun(track,
  9134. sampleDependencyTable.length + dataOffset);
  9135. return box(types.traf,
  9136. trackFragmentHeader,
  9137. trackFragmentDecodeTime,
  9138. trackFragmentRun,
  9139. sampleDependencyTable);
  9140. };
  9141. /**
  9142. * Generate a track box.
  9143. * @param track {object} a track definition
  9144. * @return {Uint8Array} the track box
  9145. */
  9146. trak = function(track) {
  9147. track.duration = track.duration || 0xffffffff;
  9148. return box(types.trak,
  9149. tkhd(track),
  9150. mdia(track));
  9151. };
  9152. trex = function(track) {
  9153. var result = new Uint8Array([
  9154. 0x00, // version 0
  9155. 0x00, 0x00, 0x00, // flags
  9156. (track.id & 0xFF000000) >> 24,
  9157. (track.id & 0xFF0000) >> 16,
  9158. (track.id & 0xFF00) >> 8,
  9159. (track.id & 0xFF), // track_ID
  9160. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  9161. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  9162. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  9163. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  9164. ]);
  9165. // the last two bytes of default_sample_flags is the sample
  9166. // degradation priority, a hint about the importance of this sample
  9167. // relative to others. Lower the degradation priority for all sample
  9168. // types other than video.
  9169. if (track.type !== 'video') {
  9170. result[result.length - 1] = 0x00;
  9171. }
  9172. return box(types.trex, result);
  9173. };
  9174. (function() {
  9175. var audioTrun, videoTrun, trunHeader;
  9176. // This method assumes all samples are uniform. That is, if a
  9177. // duration is present for the first sample, it will be present for
  9178. // all subsequent samples.
  9179. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  9180. trunHeader = function(samples, offset) {
  9181. var durationPresent = 0, sizePresent = 0,
  9182. flagsPresent = 0, compositionTimeOffset = 0;
  9183. // trun flag constants
  9184. if (samples.length) {
  9185. if (samples[0].duration !== undefined) {
  9186. durationPresent = 0x1;
  9187. }
  9188. if (samples[0].size !== undefined) {
  9189. sizePresent = 0x2;
  9190. }
  9191. if (samples[0].flags !== undefined) {
  9192. flagsPresent = 0x4;
  9193. }
  9194. if (samples[0].compositionTimeOffset !== undefined) {
  9195. compositionTimeOffset = 0x8;
  9196. }
  9197. }
  9198. return [
  9199. 0x00, // version 0
  9200. 0x00,
  9201. durationPresent | sizePresent | flagsPresent | compositionTimeOffset,
  9202. 0x01, // flags
  9203. (samples.length & 0xFF000000) >>> 24,
  9204. (samples.length & 0xFF0000) >>> 16,
  9205. (samples.length & 0xFF00) >>> 8,
  9206. samples.length & 0xFF, // sample_count
  9207. (offset & 0xFF000000) >>> 24,
  9208. (offset & 0xFF0000) >>> 16,
  9209. (offset & 0xFF00) >>> 8,
  9210. offset & 0xFF // data_offset
  9211. ];
  9212. };
  9213. videoTrun = function(track, offset) {
  9214. var bytes, samples, sample, i;
  9215. samples = track.samples || [];
  9216. offset += 8 + 12 + (16 * samples.length);
  9217. bytes = trunHeader(samples, offset);
  9218. for (i = 0; i < samples.length; i++) {
  9219. sample = samples[i];
  9220. bytes = bytes.concat([
  9221. (sample.duration & 0xFF000000) >>> 24,
  9222. (sample.duration & 0xFF0000) >>> 16,
  9223. (sample.duration & 0xFF00) >>> 8,
  9224. sample.duration & 0xFF, // sample_duration
  9225. (sample.size & 0xFF000000) >>> 24,
  9226. (sample.size & 0xFF0000) >>> 16,
  9227. (sample.size & 0xFF00) >>> 8,
  9228. sample.size & 0xFF, // sample_size
  9229. (sample.flags.isLeading << 2) | sample.flags.dependsOn,
  9230. (sample.flags.isDependedOn << 6) |
  9231. (sample.flags.hasRedundancy << 4) |
  9232. (sample.flags.paddingValue << 1) |
  9233. sample.flags.isNonSyncSample,
  9234. sample.flags.degradationPriority & 0xF0 << 8,
  9235. sample.flags.degradationPriority & 0x0F, // sample_flags
  9236. (sample.compositionTimeOffset & 0xFF000000) >>> 24,
  9237. (sample.compositionTimeOffset & 0xFF0000) >>> 16,
  9238. (sample.compositionTimeOffset & 0xFF00) >>> 8,
  9239. sample.compositionTimeOffset & 0xFF // sample_composition_time_offset
  9240. ]);
  9241. }
  9242. return box(types.trun, new Uint8Array(bytes));
  9243. };
  9244. audioTrun = function(track, offset) {
  9245. var bytes, samples, sample, i;
  9246. samples = track.samples || [];
  9247. offset += 8 + 12 + (8 * samples.length);
  9248. bytes = trunHeader(samples, offset);
  9249. for (i = 0; i < samples.length; i++) {
  9250. sample = samples[i];
  9251. bytes = bytes.concat([
  9252. (sample.duration & 0xFF000000) >>> 24,
  9253. (sample.duration & 0xFF0000) >>> 16,
  9254. (sample.duration & 0xFF00) >>> 8,
  9255. sample.duration & 0xFF, // sample_duration
  9256. (sample.size & 0xFF000000) >>> 24,
  9257. (sample.size & 0xFF0000) >>> 16,
  9258. (sample.size & 0xFF00) >>> 8,
  9259. sample.size & 0xFF]); // sample_size
  9260. }
  9261. return box(types.trun, new Uint8Array(bytes));
  9262. };
  9263. trun = function(track, offset) {
  9264. if (track.type === 'audio') {
  9265. return audioTrun(track, offset);
  9266. } else {
  9267. return videoTrun(track, offset);
  9268. }
  9269. };
  9270. })();
  9271. module.exports = {
  9272. ftyp: ftyp,
  9273. mdat: mdat,
  9274. moof: moof,
  9275. moov: moov,
  9276. initSegment: function(tracks) {
  9277. var
  9278. fileType = ftyp(),
  9279. movie = moov(tracks),
  9280. result;
  9281. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  9282. result.set(fileType);
  9283. result.set(movie, fileType.byteLength);
  9284. return result;
  9285. }
  9286. };
  9287. },{}],51:[function(require,module,exports){
  9288. /**
  9289. * mux.js
  9290. *
  9291. * Copyright (c) 2015 Brightcove
  9292. * All rights reserved.
  9293. *
  9294. * A stream-based mp2t to mp4 converter. This utility can be used to
  9295. * deliver mp4s to a SourceBuffer on platforms that support native
  9296. * Media Source Extensions.
  9297. */
  9298. 'use strict';
  9299. var Stream = require('../utils/stream.js');
  9300. var mp4 = require('./mp4-generator.js');
  9301. var m2ts = require('../m2ts/m2ts.js');
  9302. var AdtsStream = require('../codecs/adts.js');
  9303. var H264Stream = require('../codecs/h264').H264Stream;
  9304. var AacStream = require('../aac');
  9305. // constants
  9306. var AUDIO_PROPERTIES = [
  9307. 'audioobjecttype',
  9308. 'channelcount',
  9309. 'samplerate',
  9310. 'samplingfrequencyindex',
  9311. 'samplesize'
  9312. ];
  9313. var VIDEO_PROPERTIES = [
  9314. 'width',
  9315. 'height',
  9316. 'profileIdc',
  9317. 'levelIdc',
  9318. 'profileCompatibility',
  9319. ];
  9320. // object types
  9321. var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;
  9322. // Helper functions
  9323. var
  9324. createDefaultSample,
  9325. isLikelyAacData,
  9326. collectDtsInfo,
  9327. clearDtsInfo,
  9328. calculateTrackBaseMediaDecodeTime,
  9329. arrayEquals,
  9330. sumFrameByteLengths;
  9331. /**
  9332. * Default sample object
  9333. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  9334. */
  9335. createDefaultSample = function () {
  9336. return {
  9337. size: 0,
  9338. flags: {
  9339. isLeading: 0,
  9340. dependsOn: 1,
  9341. isDependedOn: 0,
  9342. hasRedundancy: 0,
  9343. degradationPriority: 0
  9344. }
  9345. };
  9346. };
  9347. isLikelyAacData = function (data) {
  9348. if ((data[0] === 'I'.charCodeAt(0)) &&
  9349. (data[1] === 'D'.charCodeAt(0)) &&
  9350. (data[2] === '3'.charCodeAt(0))) {
  9351. return true;
  9352. }
  9353. return false;
  9354. };
  9355. /**
  9356. * Compare two arrays (even typed) for same-ness
  9357. */
  9358. arrayEquals = function(a, b) {
  9359. var
  9360. i;
  9361. if (a.length !== b.length) {
  9362. return false;
  9363. }
  9364. // compare the value of each element in the array
  9365. for (i = 0; i < a.length; i++) {
  9366. if (a[i] !== b[i]) {
  9367. return false;
  9368. }
  9369. }
  9370. return true;
  9371. };
  9372. /**
  9373. * Sum the `byteLength` properties of the data in each AAC frame
  9374. */
  9375. sumFrameByteLengths = function(array) {
  9376. var
  9377. i,
  9378. currentObj,
  9379. sum = 0;
  9380. // sum the byteLength's all each nal unit in the frame
  9381. for (i = 0; i < array.length; i++) {
  9382. currentObj = array[i];
  9383. sum += currentObj.data.byteLength;
  9384. }
  9385. return sum;
  9386. };
  9387. /**
  9388. * Constructs a single-track, ISO BMFF media segment from AAC data
  9389. * events. The output of this stream can be fed to a SourceBuffer
  9390. * configured with a suitable initialization segment.
  9391. */
  9392. AudioSegmentStream = function(track) {
  9393. var
  9394. adtsFrames = [],
  9395. sequenceNumber = 0,
  9396. earliestAllowedDts = 0;
  9397. AudioSegmentStream.prototype.init.call(this);
  9398. this.push = function(data) {
  9399. collectDtsInfo(track, data);
  9400. if (track) {
  9401. AUDIO_PROPERTIES.forEach(function(prop) {
  9402. track[prop] = data[prop];
  9403. });
  9404. }
  9405. // buffer audio data until end() is called
  9406. adtsFrames.push(data);
  9407. };
  9408. this.setEarliestDts = function(earliestDts) {
  9409. earliestAllowedDts = earliestDts - track.timelineStartInfo.baseMediaDecodeTime;
  9410. };
  9411. this.flush = function() {
  9412. var
  9413. frames,
  9414. moof,
  9415. mdat,
  9416. boxes;
  9417. // return early if no audio data has been observed
  9418. if (adtsFrames.length === 0) {
  9419. this.trigger('done', 'AudioSegmentStream');
  9420. return;
  9421. }
  9422. frames = this.trimAdtsFramesByEarliestDts_(adtsFrames);
  9423. // we have to build the index from byte locations to
  9424. // samples (that is, adts frames) in the audio data
  9425. track.samples = this.generateSampleTable_(frames);
  9426. // concatenate the audio data to constuct the mdat
  9427. mdat = mp4.mdat(this.concatenateFrameData_(frames));
  9428. adtsFrames = [];
  9429. calculateTrackBaseMediaDecodeTime(track);
  9430. moof = mp4.moof(sequenceNumber, [track]);
  9431. boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
  9432. // bump the sequence number for next time
  9433. sequenceNumber++;
  9434. boxes.set(moof);
  9435. boxes.set(mdat, moof.byteLength);
  9436. clearDtsInfo(track);
  9437. this.trigger('data', {track: track, boxes: boxes});
  9438. this.trigger('done', 'AudioSegmentStream');
  9439. };
  9440. // If the audio segment extends before the earliest allowed dts
  9441. // value, remove AAC frames until starts at or after the earliest
  9442. // allowed DTS so that we don't end up with a negative baseMedia-
  9443. // DecodeTime for the audio track
  9444. this.trimAdtsFramesByEarliestDts_ = function(adtsFrames) {
  9445. if (track.minSegmentDts >= earliestAllowedDts) {
  9446. return adtsFrames;
  9447. }
  9448. // We will need to recalculate the earliest segment Dts
  9449. track.minSegmentDts = Infinity;
  9450. return adtsFrames.filter(function(currentFrame) {
  9451. // If this is an allowed frame, keep it and record it's Dts
  9452. if (currentFrame.dts >= earliestAllowedDts) {
  9453. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  9454. track.minSegmentPts = track.minSegmentDts;
  9455. return true;
  9456. }
  9457. // Otherwise, discard it
  9458. return false;
  9459. });
  9460. };
  9461. // generate the track's raw mdat data from an array of frames
  9462. this.generateSampleTable_ = function(frames) {
  9463. var
  9464. i,
  9465. currentFrame,
  9466. samples = [];
  9467. for (i = 0; i < frames.length; i++) {
  9468. currentFrame = frames[i];
  9469. samples.push({
  9470. size: currentFrame.data.byteLength,
  9471. duration: 1024 // For AAC audio, all samples contain 1024 samples
  9472. });
  9473. }
  9474. return samples;
  9475. };
  9476. // generate the track's sample table from an array of frames
  9477. this.concatenateFrameData_ = function(frames) {
  9478. var
  9479. i,
  9480. currentFrame,
  9481. dataOffset = 0,
  9482. data = new Uint8Array(sumFrameByteLengths(frames));
  9483. for (i = 0; i < frames.length; i++) {
  9484. currentFrame = frames[i];
  9485. data.set(currentFrame.data, dataOffset);
  9486. dataOffset += currentFrame.data.byteLength;
  9487. }
  9488. return data;
  9489. };
  9490. };
  9491. AudioSegmentStream.prototype = new Stream();
  9492. /**
  9493. * Constructs a single-track, ISO BMFF media segment from H264 data
  9494. * events. The output of this stream can be fed to a SourceBuffer
  9495. * configured with a suitable initialization segment.
  9496. * @param track {object} track metadata configuration
  9497. */
  9498. VideoSegmentStream = function(track) {
  9499. var
  9500. sequenceNumber = 0,
  9501. nalUnits = [],
  9502. config,
  9503. pps;
  9504. VideoSegmentStream.prototype.init.call(this);
  9505. delete track.minPTS;
  9506. this.gopCache_ = [];
  9507. this.push = function(nalUnit) {
  9508. collectDtsInfo(track, nalUnit);
  9509. // record the track config
  9510. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  9511. config = nalUnit.config;
  9512. track.sps = [nalUnit.data];
  9513. VIDEO_PROPERTIES.forEach(function(prop) {
  9514. track[prop] = config[prop];
  9515. }, this);
  9516. }
  9517. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' &&
  9518. !pps) {
  9519. pps = nalUnit.data;
  9520. track.pps = [nalUnit.data];
  9521. }
  9522. // buffer video until flush() is called
  9523. nalUnits.push(nalUnit);
  9524. };
  9525. this.flush = function() {
  9526. var
  9527. frames,
  9528. gopForFusion,
  9529. gops,
  9530. moof,
  9531. mdat,
  9532. boxes;
  9533. // Throw away nalUnits at the start of the byte stream until
  9534. // we find the first AUD
  9535. while (nalUnits.length) {
  9536. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  9537. break;
  9538. }
  9539. nalUnits.shift();
  9540. }
  9541. // Return early if no video data has been observed
  9542. if (nalUnits.length === 0) {
  9543. this.resetStream_();
  9544. this.trigger('done', 'VideoSegmentStream');
  9545. return;
  9546. }
  9547. // Organize the raw nal-units into arrays that represent
  9548. // higher-level constructs such as frames and gops
  9549. // (group-of-pictures)
  9550. frames = this.groupNalsIntoFrames_(nalUnits);
  9551. gops = this.groupFramesIntoGops_(frames);
  9552. // If the first frame of this fragment is not a keyframe we have
  9553. // a problem since MSE (on Chrome) requires a leading keyframe.
  9554. //
  9555. // We have two approaches to repairing this situation:
  9556. // 1) GOP-FUSION:
  9557. // This is where we keep track of the GOPS (group-of-pictures)
  9558. // from previous fragments and attempt to find one that we can
  9559. // prepend to the current fragment in order to create a valid
  9560. // fragment.
  9561. // 2) KEYFRAME-PULLING:
  9562. // Here we search for the first keyframe in the fragment and
  9563. // throw away all the frames between the start of the fragment
  9564. // and that keyframe. We then extend the duration and pull the
  9565. // PTS of the keyframe forward so that it covers the time range
  9566. // of the frames that were disposed of.
  9567. //
  9568. // #1 is far prefereable over #2 which can cause "stuttering" but
  9569. // requires more things to be just right.
  9570. if (!gops[0][0].keyFrame) {
  9571. // Search for a gop for fusion from our gopCache
  9572. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  9573. if (gopForFusion) {
  9574. gops.unshift(gopForFusion);
  9575. // Adjust Gops' metadata to account for the inclusion of the
  9576. // new gop at the beginning
  9577. gops.byteLength += gopForFusion.byteLength;
  9578. gops.nalCount += gopForFusion.nalCount;
  9579. gops.pts = gopForFusion.pts;
  9580. gops.dts = gopForFusion.dts;
  9581. gops.duration += gopForFusion.duration;
  9582. } else {
  9583. // If we didn't find a candidate gop fall back to keyrame-pulling
  9584. gops = this.extendFirstKeyFrame_(gops);
  9585. }
  9586. }
  9587. collectDtsInfo(track, gops);
  9588. // First, we have to build the index from byte locations to
  9589. // samples (that is, frames) in the video data
  9590. track.samples = this.generateSampleTable_(gops);
  9591. // Concatenate the video data and construct the mdat
  9592. mdat = mp4.mdat(this.concatenateNalData_(gops));
  9593. // save all the nals in the last GOP into the gop cache
  9594. this.gopCache_.unshift({
  9595. gop: gops.pop(),
  9596. pps: track.pps,
  9597. sps: track.sps
  9598. });
  9599. // Keep a maximum of 6 GOPs in the cache
  9600. this.gopCache_.length = Math.min(6, this.gopCache_.length);
  9601. // Clear nalUnits
  9602. nalUnits = [];
  9603. calculateTrackBaseMediaDecodeTime(track);
  9604. this.trigger('timelineStartInfo', track.timelineStartInfo);
  9605. moof = mp4.moof(sequenceNumber, [track]);
  9606. // it would be great to allocate this array up front instead of
  9607. // throwing away hundreds of media segment fragments
  9608. boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
  9609. // Bump the sequence number for next time
  9610. sequenceNumber++;
  9611. boxes.set(moof);
  9612. boxes.set(mdat, moof.byteLength);
  9613. this.trigger('data', {track: track, boxes: boxes});
  9614. this.resetStream_();
  9615. // Continue with the flush process now
  9616. this.trigger('done', 'VideoSegmentStream');
  9617. };
  9618. this.resetStream_ = function() {
  9619. clearDtsInfo(track);
  9620. // reset config and pps because they may differ across segments
  9621. // for instance, when we are rendition switching
  9622. config = undefined;
  9623. pps = undefined;
  9624. };
  9625. // Search for a candidate Gop for gop-fusion from the gop cache and
  9626. // return it or return null if no good candidate was found
  9627. this.getGopForFusion_ = function (nalUnit) {
  9628. var
  9629. halfSecond = 45000, // Half-a-second in a 90khz clock
  9630. allowableOverlap = 10000, // About 3 frames @ 30fps
  9631. nearestDistance = Infinity,
  9632. dtsDistance,
  9633. nearestGopObj,
  9634. currentGop,
  9635. currentGopObj,
  9636. i;
  9637. // Search for the GOP nearest to the beginning of this nal unit
  9638. for (i = 0; i < this.gopCache_.length; i++) {
  9639. currentGopObj = this.gopCache_[i];
  9640. currentGop = currentGopObj.gop;
  9641. // Reject Gops with different SPS or PPS
  9642. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) ||
  9643. !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  9644. continue;
  9645. }
  9646. // Reject Gops that would require a negative baseMediaDecodeTime
  9647. if (currentGop.dts < track.timelineStartInfo.dts) {
  9648. continue;
  9649. }
  9650. // The distance between the end of the gop and the start of the nalUnit
  9651. dtsDistance = (nalUnit.dts - currentGop.dts) - currentGop.duration;
  9652. // Only consider GOPS that start before the nal unit and end within
  9653. // a half-second of the nal unit
  9654. if (dtsDistance >= -allowableOverlap &&
  9655. dtsDistance <= halfSecond) {
  9656. // Always use the closest GOP we found if there is more than
  9657. // one candidate
  9658. if (!nearestGopObj ||
  9659. nearestDistance > dtsDistance) {
  9660. nearestGopObj = currentGopObj;
  9661. nearestDistance = dtsDistance;
  9662. }
  9663. }
  9664. }
  9665. if (nearestGopObj) {
  9666. return nearestGopObj.gop;
  9667. }
  9668. return null;
  9669. };
  9670. this.extendFirstKeyFrame_ = function(gops) {
  9671. var
  9672. h, i,
  9673. currentGop,
  9674. newGops;
  9675. if (!gops[0][0].keyFrame) {
  9676. // Remove the first GOP
  9677. currentGop = gops.shift();
  9678. gops.byteLength -= currentGop.byteLength;
  9679. gops.nalCount -= currentGop.nalCount;
  9680. // Extend the first frame of what is now the
  9681. // first gop to cover the time period of the
  9682. // frames we just removed
  9683. gops[0][0].dts = currentGop.dts;
  9684. gops[0][0].pts = currentGop.pts;
  9685. gops[0][0].duration += currentGop.duration;
  9686. }
  9687. return gops;
  9688. };
  9689. // Convert an array of nal units into an array of frames with each frame being
  9690. // composed of the nal units that make up that frame
  9691. // Also keep track of cummulative data about the frame from the nal units such
  9692. // as the frame duration, starting pts, etc.
  9693. this.groupNalsIntoFrames_ = function(nalUnits) {
  9694. var
  9695. i,
  9696. currentNal,
  9697. startPts,
  9698. startDts,
  9699. currentFrame = [],
  9700. frames = [];
  9701. currentFrame.byteLength = 0;
  9702. for (i = 0; i < nalUnits.length; i++) {
  9703. currentNal = nalUnits[i];
  9704. // Split on 'aud'-type nal units
  9705. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  9706. // Since the very first nal unit is expected to be an AUD
  9707. // only push to the frames array when currentFrame is not empty
  9708. if (currentFrame.length) {
  9709. currentFrame.duration = currentNal.dts - currentFrame.dts;
  9710. frames.push(currentFrame);
  9711. }
  9712. currentFrame = [currentNal];
  9713. currentFrame.byteLength = currentNal.data.byteLength;
  9714. currentFrame.pts = currentNal.pts;
  9715. currentFrame.dts = currentNal.dts;
  9716. } else {
  9717. // Specifically flag key frames for ease of use later
  9718. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  9719. currentFrame.keyFrame = true;
  9720. }
  9721. currentFrame.duration = currentNal.dts - currentFrame.dts;
  9722. currentFrame.byteLength += currentNal.data.byteLength;
  9723. currentFrame.push(currentNal);
  9724. }
  9725. }
  9726. // For the last frame, use the duration of the previous frame if we
  9727. // have nothing better to go on
  9728. if (frames.length &&
  9729. (!currentFrame.duration ||
  9730. currentFrame.duration <= 0)) {
  9731. currentFrame.duration = frames[frames.length - 1].duration;
  9732. }
  9733. // Push the final frame
  9734. frames.push(currentFrame);
  9735. return frames;
  9736. };
  9737. // Convert an array of frames into an array of Gop with each Gop being composed
  9738. // of the frames that make up that Gop
  9739. // Also keep track of cummulative data about the Gop from the frames such as the
  9740. // Gop duration, starting pts, etc.
  9741. this.groupFramesIntoGops_ = function(frames) {
  9742. var
  9743. i,
  9744. currentFrame,
  9745. currentGop = [],
  9746. gops = [];
  9747. // We must pre-set some of the values on the Gop since we
  9748. // keep running totals of these values
  9749. currentGop.byteLength = 0;
  9750. currentGop.nalCount = 0;
  9751. currentGop.duration = 0;
  9752. currentGop.pts = frames[0].pts;
  9753. currentGop.dts = frames[0].dts;
  9754. // store some metadata about all the Gops
  9755. gops.byteLength = 0;
  9756. gops.nalCount = 0;
  9757. gops.duration = 0;
  9758. gops.pts = frames[0].pts;
  9759. gops.dts = frames[0].dts;
  9760. for (i = 0; i < frames.length; i++) {
  9761. currentFrame = frames[i];
  9762. if (currentFrame.keyFrame) {
  9763. // Since the very first frame is expected to be an keyframe
  9764. // only push to the gops array when currentGop is not empty
  9765. if (currentGop.length) {
  9766. gops.push(currentGop);
  9767. gops.byteLength += currentGop.byteLength;
  9768. gops.nalCount += currentGop.nalCount;
  9769. gops.duration += currentGop.duration;
  9770. }
  9771. currentGop = [currentFrame];
  9772. currentGop.nalCount = currentFrame.length;
  9773. currentGop.byteLength = currentFrame.byteLength;
  9774. currentGop.pts = currentFrame.pts;
  9775. currentGop.dts = currentFrame.dts;
  9776. currentGop.duration = currentFrame.duration;
  9777. } else {
  9778. currentGop.duration += currentFrame.duration;
  9779. currentGop.nalCount += currentFrame.length;
  9780. currentGop.byteLength += currentFrame.byteLength;
  9781. currentGop.push(currentFrame);
  9782. }
  9783. }
  9784. if (gops.length && currentGop.duration <= 0) {
  9785. currentGop.duration = gops[gops.length - 1].duration;
  9786. }
  9787. gops.byteLength += currentGop.byteLength;
  9788. gops.nalCount += currentGop.nalCount;
  9789. gops.duration += currentGop.duration;
  9790. // push the final Gop
  9791. gops.push(currentGop);
  9792. return gops;
  9793. };
  9794. // generate the track's sample table from an array of gops
  9795. this.generateSampleTable_ = function(gops, baseDataOffset) {
  9796. var
  9797. h, i,
  9798. sample,
  9799. currentGop,
  9800. currentFrame,
  9801. currentSample,
  9802. dataOffset = baseDataOffset || 0,
  9803. samples = [];
  9804. for (h = 0; h < gops.length; h++) {
  9805. currentGop = gops[h];
  9806. for (i = 0; i < currentGop.length; i++) {
  9807. currentFrame = currentGop[i];
  9808. sample = createDefaultSample();
  9809. sample.dataOffset = dataOffset;
  9810. sample.compositionTimeOffset = currentFrame.pts - currentFrame.dts;
  9811. sample.duration = currentFrame.duration;
  9812. sample.size = 4 * currentFrame.length; // Space for nal unit size
  9813. sample.size += currentFrame.byteLength;
  9814. if (currentFrame.keyFrame) {
  9815. sample.flags.dependsOn = 2;
  9816. }
  9817. dataOffset += sample.size;
  9818. samples.push(sample);
  9819. }
  9820. }
  9821. return samples;
  9822. };
  9823. // generate the track's raw mdat data from an array of gops
  9824. this.concatenateNalData_ = function (gops) {
  9825. var
  9826. h, i, j,
  9827. currentGop,
  9828. currentFrame,
  9829. currentNal,
  9830. dataOffset = 0,
  9831. nalsByteLength = gops.byteLength,
  9832. numberOfNals = gops.nalCount,
  9833. totalByteLength = nalsByteLength + 4 * numberOfNals,
  9834. data = new Uint8Array(totalByteLength),
  9835. view = new DataView(data.buffer);
  9836. // For each Gop..
  9837. for (h = 0; h < gops.length; h++) {
  9838. currentGop = gops[h];
  9839. // For each Frame..
  9840. for (i = 0; i < currentGop.length; i++) {
  9841. currentFrame = currentGop[i];
  9842. // For each NAL..
  9843. for (j = 0; j < currentFrame.length; j++) {
  9844. currentNal = currentFrame[j];
  9845. view.setUint32(dataOffset, currentNal.data.byteLength);
  9846. dataOffset += 4;
  9847. data.set(currentNal.data, dataOffset);
  9848. dataOffset += currentNal.data.byteLength;
  9849. }
  9850. }
  9851. }
  9852. return data;
  9853. };
  9854. };
  9855. VideoSegmentStream.prototype = new Stream();
  9856. /**
  9857. * Store information about the start and end of the track and the
  9858. * duration for each frame/sample we process in order to calculate
  9859. * the baseMediaDecodeTime
  9860. */
  9861. collectDtsInfo = function (track, data) {
  9862. if (typeof data.pts === 'number') {
  9863. if (track.timelineStartInfo.pts === undefined) {
  9864. track.timelineStartInfo.pts = data.pts;
  9865. }
  9866. if (track.minSegmentPts === undefined) {
  9867. track.minSegmentPts = data.pts;
  9868. } else {
  9869. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  9870. }
  9871. if (track.maxSegmentPts === undefined) {
  9872. track.maxSegmentPts = data.pts;
  9873. } else {
  9874. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  9875. }
  9876. }
  9877. if (typeof data.dts === 'number') {
  9878. if (track.timelineStartInfo.dts === undefined) {
  9879. track.timelineStartInfo.dts = data.dts;
  9880. }
  9881. if (track.minSegmentDts === undefined) {
  9882. track.minSegmentDts = data.dts;
  9883. } else {
  9884. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  9885. }
  9886. if (track.maxSegmentDts === undefined) {
  9887. track.maxSegmentDts = data.dts;
  9888. } else {
  9889. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  9890. }
  9891. }
  9892. };
  9893. /**
  9894. * Clear values used to calculate the baseMediaDecodeTime between
  9895. * tracks
  9896. */
  9897. clearDtsInfo = function (track) {
  9898. delete track.minSegmentDts;
  9899. delete track.maxSegmentDts;
  9900. delete track.minSegmentPts;
  9901. delete track.maxSegmentPts;
  9902. };
  9903. /**
  9904. * Calculate the track's baseMediaDecodeTime based on the earliest
  9905. * DTS the transmuxer has ever seen and the minimum DTS for the
  9906. * current track
  9907. */
  9908. calculateTrackBaseMediaDecodeTime = function (track) {
  9909. var
  9910. oneSecondInPTS = 90000, // 90kHz clock
  9911. scale,
  9912. // Calculate the distance, in time, that this segment starts from the start
  9913. // of the timeline (earliest time seen since the transmuxer initialized)
  9914. timeSinceStartOfTimeline = track.minSegmentDts - track.timelineStartInfo.dts,
  9915. // Calculate the first sample's effective compositionTimeOffset
  9916. firstSampleCompositionOffset = track.minSegmentPts - track.minSegmentDts;
  9917. // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  9918. // we want the start of the first segment to be placed
  9919. track.baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime;
  9920. // Add to that the distance this segment is from the very first
  9921. track.baseMediaDecodeTime += timeSinceStartOfTimeline;
  9922. // Subtract this segment's "compositionTimeOffset" so that the first frame of
  9923. // this segment is displayed exactly at the `baseMediaDecodeTime` or at the
  9924. // end of the previous segment
  9925. track.baseMediaDecodeTime -= firstSampleCompositionOffset;
  9926. // baseMediaDecodeTime must not become negative
  9927. track.baseMediaDecodeTime = Math.max(0, track.baseMediaDecodeTime);
  9928. if (track.type === 'audio') {
  9929. // Audio has a different clock equal to the sampling_rate so we need to
  9930. // scale the PTS values into the clock rate of the track
  9931. scale = track.samplerate / oneSecondInPTS;
  9932. track.baseMediaDecodeTime *= scale;
  9933. track.baseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime);
  9934. }
  9935. };
  9936. /**
  9937. * A Stream that can combine multiple streams (ie. audio & video)
  9938. * into a single output segment for MSE. Also supports audio-only
  9939. * and video-only streams.
  9940. */
  9941. CoalesceStream = function(options, metadataStream) {
  9942. // Number of Tracks per output segment
  9943. // If greater than 1, we combine multiple
  9944. // tracks into a single segment
  9945. this.numberOfTracks = 0;
  9946. this.metadataStream = metadataStream;
  9947. if (typeof options.remux !== 'undefined') {
  9948. this.remuxTracks = !!options.remux;
  9949. } else {
  9950. this.remuxTracks = true;
  9951. }
  9952. this.pendingTracks = [];
  9953. this.videoTrack = null;
  9954. this.pendingBoxes = [];
  9955. this.pendingCaptions = [];
  9956. this.pendingMetadata = [];
  9957. this.pendingBytes = 0;
  9958. this.emittedTracks = 0;
  9959. CoalesceStream.prototype.init.call(this);
  9960. // Take output from multiple
  9961. this.push = function(output) {
  9962. // buffer incoming captions until the associated video segment
  9963. // finishes
  9964. if (output.text) {
  9965. return this.pendingCaptions.push(output);
  9966. }
  9967. // buffer incoming id3 tags until the final flush
  9968. if (output.frames) {
  9969. return this.pendingMetadata.push(output);
  9970. }
  9971. // Add this track to the list of pending tracks and store
  9972. // important information required for the construction of
  9973. // the final segment
  9974. this.pendingTracks.push(output.track);
  9975. this.pendingBoxes.push(output.boxes);
  9976. this.pendingBytes += output.boxes.byteLength;
  9977. if (output.track.type === 'video') {
  9978. this.videoTrack = output.track;
  9979. }
  9980. if (output.track.type === 'audio') {
  9981. this.audioTrack = output.track;
  9982. }
  9983. };
  9984. };
  9985. CoalesceStream.prototype = new Stream();
  9986. CoalesceStream.prototype.flush = function(flushSource) {
  9987. var
  9988. offset = 0,
  9989. event = {
  9990. captions: [],
  9991. metadata: [],
  9992. info: {}
  9993. },
  9994. caption,
  9995. id3,
  9996. initSegment,
  9997. timelineStartPts = 0,
  9998. i;
  9999. if (this.pendingTracks.length < this.numberOfTracks) {
  10000. if (flushSource !== 'VideoSegmentStream' &&
  10001. flushSource !== 'AudioSegmentStream') {
  10002. // Return because we haven't received a flush from a data-generating
  10003. // portion of the segment (meaning that we have only recieved meta-data
  10004. // or captions.)
  10005. return;
  10006. } else if (this.remuxTracks) {
  10007. // Return until we have enough tracks from the pipeline to remux (if we
  10008. // are remuxing audio and video into a single MP4)
  10009. return;
  10010. } else if (this.pendingTracks.length === 0) {
  10011. // In the case where we receive a flush without any data having been
  10012. // received we consider it an emitted track for the purposes of coalescing
  10013. // `done` events.
  10014. // We do this for the case where there is an audio and video track in the
  10015. // segment but no audio data. (seen in several playlists with alternate
  10016. // audio tracks and no audio present in the main TS segments.)
  10017. this.emittedTracks++;
  10018. if (this.emittedTracks >= this.numberOfTracks) {
  10019. this.trigger('done');
  10020. this.emittedTracks = 0;
  10021. }
  10022. return;
  10023. }
  10024. }
  10025. if (this.videoTrack) {
  10026. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  10027. VIDEO_PROPERTIES.forEach(function(prop) {
  10028. event.info[prop] = this.videoTrack[prop];
  10029. }, this);
  10030. } else if (this.audioTrack) {
  10031. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  10032. AUDIO_PROPERTIES.forEach(function(prop) {
  10033. event.info[prop] = this.audioTrack[prop];
  10034. }, this);
  10035. }
  10036. if (this.pendingTracks.length === 1) {
  10037. event.type = this.pendingTracks[0].type;
  10038. } else {
  10039. event.type = 'combined';
  10040. }
  10041. this.emittedTracks += this.pendingTracks.length;
  10042. initSegment = mp4.initSegment(this.pendingTracks);
  10043. // Create a new typed array large enough to hold the init
  10044. // segment and all tracks
  10045. event.data = new Uint8Array(initSegment.byteLength +
  10046. this.pendingBytes);
  10047. // Create an init segment containing a moov
  10048. // and track definitions
  10049. event.data.set(initSegment);
  10050. offset += initSegment.byteLength;
  10051. // Append each moof+mdat (one per track) after the init segment
  10052. for (i = 0; i < this.pendingBoxes.length; i++) {
  10053. event.data.set(this.pendingBoxes[i], offset);
  10054. offset += this.pendingBoxes[i].byteLength;
  10055. }
  10056. // Translate caption PTS times into second offsets into the
  10057. // video timeline for the segment
  10058. for (i = 0; i < this.pendingCaptions.length; i++) {
  10059. caption = this.pendingCaptions[i];
  10060. caption.startTime = (caption.startPts - timelineStartPts);
  10061. caption.startTime /= 90e3;
  10062. caption.endTime = (caption.endPts - timelineStartPts);
  10063. caption.endTime /= 90e3;
  10064. event.captions.push(caption);
  10065. }
  10066. // Translate ID3 frame PTS times into second offsets into the
  10067. // video timeline for the segment
  10068. for (i = 0; i < this.pendingMetadata.length; i++) {
  10069. id3 = this.pendingMetadata[i];
  10070. id3.cueTime = (id3.pts - timelineStartPts);
  10071. id3.cueTime /= 90e3;
  10072. event.metadata.push(id3);
  10073. }
  10074. // We add this to every single emitted segment even though we only need
  10075. // it for the first
  10076. event.metadata.dispatchType = this.metadataStream.dispatchType;
  10077. // Reset stream state
  10078. this.pendingTracks.length = 0;
  10079. this.videoTrack = null;
  10080. this.pendingBoxes.length = 0;
  10081. this.pendingCaptions.length = 0;
  10082. this.pendingBytes = 0;
  10083. this.pendingMetadata.length = 0;
  10084. // Emit the built segment
  10085. this.trigger('data', event);
  10086. // Only emit `done` if all tracks have been flushed and emitted
  10087. if (this.emittedTracks >= this.numberOfTracks) {
  10088. this.trigger('done');
  10089. this.emittedTracks = 0;
  10090. }
  10091. };
  10092. /**
  10093. * A Stream that expects MP2T binary data as input and produces
  10094. * corresponding media segments, suitable for use with Media Source
  10095. * Extension (MSE) implementations that support the ISO BMFF byte
  10096. * stream format, like Chrome.
  10097. */
  10098. Transmuxer = function(options) {
  10099. var
  10100. self = this,
  10101. hasFlushed = true,
  10102. videoTrack,
  10103. audioTrack;
  10104. Transmuxer.prototype.init.call(this);
  10105. options = options || {};
  10106. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  10107. this.transmuxPipeline_ = {};
  10108. this.setupAacPipeline = function() {
  10109. var pipeline = {};
  10110. this.transmuxPipeline_ = pipeline;
  10111. pipeline.type = 'aac';
  10112. pipeline.metadataStream = new m2ts.MetadataStream();
  10113. // set up the parsing pipeline
  10114. pipeline.aacStream = new AacStream();
  10115. pipeline.adtsStream = new AdtsStream();
  10116. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  10117. pipeline.headOfPipeline = pipeline.aacStream;
  10118. pipeline.aacStream.pipe(pipeline.adtsStream);
  10119. pipeline.aacStream.pipe(pipeline.metadataStream);
  10120. pipeline.metadataStream.pipe(pipeline.coalesceStream);
  10121. pipeline.metadataStream.on('timestamp', function(frame) {
  10122. pipeline.aacStream.setTimestamp(frame.timeStamp);
  10123. });
  10124. pipeline.aacStream.on('data', function(data) {
  10125. var i;
  10126. if (data.type === 'timed-metadata' && !pipeline.audioSegmentStream) {
  10127. audioTrack = audioTrack || {
  10128. timelineStartInfo: {
  10129. baseMediaDecodeTime: self.baseMediaDecodeTime
  10130. },
  10131. codec: 'adts',
  10132. type: 'audio'
  10133. };
  10134. // hook up the audio segment stream to the first track with aac data
  10135. pipeline.coalesceStream.numberOfTracks++;
  10136. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack);
  10137. // Set up the final part of the audio pipeline
  10138. pipeline.adtsStream
  10139. .pipe(pipeline.audioSegmentStream)
  10140. .pipe(pipeline.coalesceStream);
  10141. }
  10142. });
  10143. // Re-emit any data coming from the coalesce stream to the outside world
  10144. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  10145. // Let the consumer know we have finished flushing the entire pipeline
  10146. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  10147. };
  10148. this.setupTsPipeline = function() {
  10149. var pipeline = {};
  10150. this.transmuxPipeline_ = pipeline;
  10151. pipeline.type = 'ts';
  10152. pipeline.metadataStream = new m2ts.MetadataStream();
  10153. // set up the parsing pipeline
  10154. pipeline.packetStream = new m2ts.TransportPacketStream();
  10155. pipeline.parseStream = new m2ts.TransportParseStream();
  10156. pipeline.elementaryStream = new m2ts.ElementaryStream();
  10157. pipeline.adtsStream = new AdtsStream();
  10158. pipeline.h264Stream = new H264Stream();
  10159. pipeline.captionStream = new m2ts.CaptionStream();
  10160. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  10161. pipeline.headOfPipeline = pipeline.packetStream;
  10162. // disassemble MPEG2-TS packets into elementary streams
  10163. pipeline.packetStream
  10164. .pipe(pipeline.parseStream)
  10165. .pipe(pipeline.elementaryStream);
  10166. // !!THIS ORDER IS IMPORTANT!!
  10167. // demux the streams
  10168. pipeline.elementaryStream
  10169. .pipe(pipeline.h264Stream);
  10170. pipeline.elementaryStream
  10171. .pipe(pipeline.adtsStream);
  10172. pipeline.elementaryStream
  10173. .pipe(pipeline.metadataStream)
  10174. .pipe(pipeline.coalesceStream);
  10175. // Hook up CEA-608/708 caption stream
  10176. pipeline.h264Stream.pipe(pipeline.captionStream)
  10177. .pipe(pipeline.coalesceStream);
  10178. pipeline.elementaryStream.on('data', function(data) {
  10179. var i;
  10180. if (data.type === 'metadata') {
  10181. i = data.tracks.length;
  10182. // scan the tracks listed in the metadata
  10183. while (i--) {
  10184. if (!videoTrack && data.tracks[i].type === 'video') {
  10185. videoTrack = data.tracks[i];
  10186. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  10187. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  10188. audioTrack = data.tracks[i];
  10189. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  10190. }
  10191. }
  10192. // hook up the video segment stream to the first track with h264 data
  10193. if (videoTrack && !pipeline.videoSegmentStream) {
  10194. pipeline.coalesceStream.numberOfTracks++;
  10195. pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack);
  10196. pipeline.videoSegmentStream.on('timelineStartInfo', function(timelineStartInfo){
  10197. // When video emits timelineStartInfo data after a flush, we forward that
  10198. // info to the AudioSegmentStream, if it exists, because video timeline
  10199. // data takes precedence.
  10200. if (audioTrack) {
  10201. audioTrack.timelineStartInfo = timelineStartInfo;
  10202. // On the first segment we trim AAC frames that exist before the
  10203. // very earliest DTS we have seen in video because Chrome will
  10204. // interpret any video track with a baseMediaDecodeTime that is
  10205. // non-zero as a gap.
  10206. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts);
  10207. }
  10208. });
  10209. // Set up the final part of the video pipeline
  10210. pipeline.h264Stream
  10211. .pipe(pipeline.videoSegmentStream)
  10212. .pipe(pipeline.coalesceStream);
  10213. }
  10214. if (audioTrack && !pipeline.audioSegmentStream) {
  10215. // hook up the audio segment stream to the first track with aac data
  10216. pipeline.coalesceStream.numberOfTracks++;
  10217. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack);
  10218. // Set up the final part of the audio pipeline
  10219. pipeline.adtsStream
  10220. .pipe(pipeline.audioSegmentStream)
  10221. .pipe(pipeline.coalesceStream);
  10222. }
  10223. }
  10224. });
  10225. // Re-emit any data coming from the coalesce stream to the outside world
  10226. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  10227. // Let the consumer know we have finished flushing the entire pipeline
  10228. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  10229. };
  10230. // hook up the segment streams once track metadata is delivered
  10231. this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  10232. var pipeline = this.transmuxPipeline_;
  10233. this.baseMediaDecodeTime = baseMediaDecodeTime;
  10234. if (audioTrack) {
  10235. audioTrack.timelineStartInfo.dts = undefined;
  10236. audioTrack.timelineStartInfo.pts = undefined;
  10237. clearDtsInfo(audioTrack);
  10238. audioTrack.timelineStartInfo.baseMediaDecodeTime = baseMediaDecodeTime;
  10239. }
  10240. if (videoTrack) {
  10241. if (pipeline.videoSegmentStream) {
  10242. pipeline.videoSegmentStream.gopCache_ = [];
  10243. }
  10244. videoTrack.timelineStartInfo.dts = undefined;
  10245. videoTrack.timelineStartInfo.pts = undefined;
  10246. clearDtsInfo(videoTrack);
  10247. videoTrack.timelineStartInfo.baseMediaDecodeTime = baseMediaDecodeTime;
  10248. }
  10249. };
  10250. // feed incoming data to the front of the parsing pipeline
  10251. this.push = function(data) {
  10252. if (hasFlushed) {
  10253. var isAac = isLikelyAacData(data);
  10254. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  10255. this.setupAacPipeline();
  10256. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  10257. this.setupTsPipeline();
  10258. }
  10259. hasFlushed = false;
  10260. }
  10261. this.transmuxPipeline_.headOfPipeline.push(data);
  10262. };
  10263. // flush any buffered data
  10264. this.flush = function() {
  10265. hasFlushed = true;
  10266. // Start at the top of the pipeline and flush all pending work
  10267. this.transmuxPipeline_.headOfPipeline.flush();
  10268. };
  10269. };
  10270. Transmuxer.prototype = new Stream();
  10271. module.exports = {
  10272. Transmuxer: Transmuxer,
  10273. VideoSegmentStream: VideoSegmentStream,
  10274. AudioSegmentStream: AudioSegmentStream,
  10275. AUDIO_PROPERTIES: AUDIO_PROPERTIES,
  10276. VIDEO_PROPERTIES: VIDEO_PROPERTIES
  10277. };
  10278. },{"../aac":36,"../codecs/adts.js":37,"../codecs/h264":38,"../m2ts/m2ts.js":46,"../utils/stream.js":55,"./mp4-generator.js":50}],52:[function(require,module,exports){
  10279. 'use strict';
  10280. var
  10281. tagTypes = {
  10282. 0x08: 'audio',
  10283. 0x09: 'video',
  10284. 0x12: 'metadata'
  10285. },
  10286. hex = function (val) {
  10287. return '0x' + ('00' + val.toString(16)).slice(-2).toUpperCase();
  10288. },
  10289. hexStringList = function (data) {
  10290. var arr = [], i;
  10291. /* jshint -W086 */
  10292. while(data.byteLength > 0) {
  10293. i = 0;
  10294. switch(data.byteLength) {
  10295. default:
  10296. arr.push(hex(data[i++]));
  10297. case 7:
  10298. arr.push(hex(data[i++]));
  10299. case 6:
  10300. arr.push(hex(data[i++]));
  10301. case 5:
  10302. arr.push(hex(data[i++]));
  10303. case 4:
  10304. arr.push(hex(data[i++]));
  10305. case 3:
  10306. arr.push(hex(data[i++]));
  10307. case 2:
  10308. arr.push(hex(data[i++]));
  10309. case 1:
  10310. arr.push(hex(data[i++]));
  10311. }
  10312. data = data.subarray(i);
  10313. }
  10314. /* jshint +W086 */
  10315. return arr.join(' ');
  10316. },
  10317. parseAVCTag = function (tag, obj) {
  10318. var
  10319. avcPacketTypes = [
  10320. 'AVC Sequence Header',
  10321. 'AVC NALU',
  10322. 'AVC End-of-Sequence'
  10323. ],
  10324. nalUnitTypes = [
  10325. 'unspecified',
  10326. 'slice_layer_without_partitioning',
  10327. 'slice_data_partition_a_layer',
  10328. 'slice_data_partition_b_layer',
  10329. 'slice_data_partition_c_layer',
  10330. 'slice_layer_without_partitioning_idr',
  10331. 'sei',
  10332. 'seq_parameter_set',
  10333. 'pic_parameter_set',
  10334. 'access_unit_delimiter',
  10335. 'end_of_seq',
  10336. 'end_of_stream',
  10337. 'filler',
  10338. 'seq_parameter_set_ext',
  10339. 'prefix_nal_unit',
  10340. 'subset_seq_parameter_set',
  10341. 'reserved',
  10342. 'reserved',
  10343. 'reserved'
  10344. ],
  10345. compositionTime = (tag[1] & parseInt('01111111', 2) << 16) | (tag[2] << 8) | tag[3];
  10346. obj = obj || {};
  10347. obj.avcPacketType = avcPacketTypes[tag[0]];
  10348. obj.CompositionTime = (tag[1] & parseInt('10000000', 2)) ? -compositionTime : compositionTime;
  10349. if (tag[0] === 1) {
  10350. obj.nalUnitTypeRaw = hexStringList(tag.subarray(4, 100));
  10351. } else {
  10352. obj.data = hexStringList(tag.subarray(4));
  10353. }
  10354. return obj;
  10355. },
  10356. parseVideoTag = function (tag, obj) {
  10357. var
  10358. frameTypes = [
  10359. 'Unknown',
  10360. 'Keyframe (for AVC, a seekable frame)',
  10361. 'Inter frame (for AVC, a nonseekable frame)',
  10362. 'Disposable inter frame (H.263 only)',
  10363. 'Generated keyframe (reserved for server use only)',
  10364. 'Video info/command frame'
  10365. ],
  10366. codecIDs = [
  10367. 'JPEG (currently unused)',
  10368. 'Sorenson H.263',
  10369. 'Screen video',
  10370. 'On2 VP6',
  10371. 'On2 VP6 with alpha channel',
  10372. 'Screen video version 2',
  10373. 'AVC'
  10374. ],
  10375. codecID = tag[0] & parseInt('00001111', 2);
  10376. obj = obj || {};
  10377. obj.frameType = frameTypes[(tag[0] & parseInt('11110000', 2)) >>> 4];
  10378. obj.codecID = codecID;
  10379. if (codecID === 7) {
  10380. return parseAVCTag(tag.subarray(1), obj);
  10381. }
  10382. return obj;
  10383. },
  10384. parseAACTag = function (tag, obj) {
  10385. var packetTypes = [
  10386. 'AAC Sequence Header',
  10387. 'AAC Raw'
  10388. ];
  10389. obj = obj || {};
  10390. obj.aacPacketType = packetTypes[tag[0]];
  10391. obj.data = hexStringList(tag.subarray(1));
  10392. return obj;
  10393. },
  10394. parseAudioTag = function (tag, obj) {
  10395. var
  10396. formatTable = [
  10397. 'Linear PCM, platform endian',
  10398. 'ADPCM',
  10399. 'MP3',
  10400. 'Linear PCM, little endian',
  10401. 'Nellymoser 16-kHz mono',
  10402. 'Nellymoser 8-kHz mono',
  10403. 'Nellymoser',
  10404. 'G.711 A-law logarithmic PCM',
  10405. 'G.711 mu-law logarithmic PCM',
  10406. 'reserved',
  10407. 'AAC',
  10408. 'Speex',
  10409. 'MP3 8-Khz',
  10410. 'Device-specific sound'
  10411. ],
  10412. samplingRateTable = [
  10413. '5.5-kHz',
  10414. '11-kHz',
  10415. '22-kHz',
  10416. '44-kHz'
  10417. ],
  10418. soundFormat = (tag[0] & parseInt('11110000', 2)) >>> 4;
  10419. obj = obj || {};
  10420. obj.soundFormat = formatTable[soundFormat];
  10421. obj.soundRate = samplingRateTable[(tag[0] & parseInt('00001100', 2)) >>> 2];
  10422. obj.soundSize = ((tag[0] & parseInt('00000010', 2)) >>> 1) ? '16-bit' : '8-bit';
  10423. obj.soundType = (tag[0] & parseInt('00000001', 2)) ? 'Stereo' : 'Mono';
  10424. if (soundFormat === 10) {
  10425. return parseAACTag(tag.subarray(1), obj);
  10426. }
  10427. return obj;
  10428. },
  10429. parseGenericTag = function (tag) {
  10430. return {
  10431. tagType: tagTypes[tag[0]],
  10432. dataSize: (tag[1] << 16) | (tag[2] << 8) | tag[3],
  10433. timestamp: (tag[7] << 24) | (tag[4] << 16) | (tag[5] << 8) | tag[6],
  10434. streamID: (tag[8] << 16) | (tag[9] << 8) | tag[10]
  10435. };
  10436. },
  10437. inspectFlvTag = function (tag) {
  10438. var header = parseGenericTag(tag);
  10439. switch (tag[0]) {
  10440. case 0x08:
  10441. parseAudioTag(tag.subarray(11), header);
  10442. break;
  10443. case 0x09:
  10444. parseVideoTag(tag.subarray(11), header);
  10445. break;
  10446. case 0x12:
  10447. }
  10448. return header;
  10449. },
  10450. inspectFlv = function (bytes) {
  10451. var i = 9, // header
  10452. dataSize,
  10453. parsedResults = [],
  10454. tag;
  10455. // traverse the tags
  10456. i += 4; // skip previous tag size
  10457. while (i < bytes.byteLength) {
  10458. dataSize = bytes[i + 1] << 16;
  10459. dataSize |= bytes[i + 2] << 8;
  10460. dataSize |= bytes[i + 3];
  10461. dataSize += 11;
  10462. tag = bytes.subarray(i, i + dataSize);
  10463. parsedResults.push(inspectFlvTag(tag));
  10464. i += dataSize + 4;
  10465. }
  10466. return parsedResults;
  10467. },
  10468. textifyFlv = function (flvTagArray) {
  10469. return JSON.stringify(flvTagArray, null, 2);
  10470. };
  10471. module.exports = {
  10472. inspectTag: inspectFlvTag,
  10473. inspect: inspectFlv,
  10474. textify: textifyFlv
  10475. };
  10476. },{}],53:[function(require,module,exports){
  10477. (function (global){
  10478. 'use strict';
  10479. var
  10480. inspectMp4,
  10481. textifyMp4,
  10482. /**
  10483. * Returns the string representation of an ASCII encoded four byte buffer.
  10484. * @param buffer {Uint8Array} a four-byte buffer to translate
  10485. * @return {string} the corresponding string
  10486. */
  10487. parseType = function(buffer) {
  10488. var result = '';
  10489. result += String.fromCharCode(buffer[0]);
  10490. result += String.fromCharCode(buffer[1]);
  10491. result += String.fromCharCode(buffer[2]);
  10492. result += String.fromCharCode(buffer[3]);
  10493. return result;
  10494. },
  10495. parseMp4Date = function(seconds) {
  10496. return new Date(seconds * 1000 - 2082844800000);
  10497. },
  10498. parseSampleFlags = function(flags) {
  10499. return {
  10500. isLeading: (flags[0] & 0x0c) >>> 2,
  10501. dependsOn: flags[0] & 0x03,
  10502. isDependedOn: (flags[1] & 0xc0) >>> 6,
  10503. hasRedundancy: (flags[1] & 0x30) >>> 4,
  10504. paddingValue: (flags[1] & 0x0e) >>> 1,
  10505. isNonSyncSample: flags[1] & 0x01,
  10506. degradationPriority: (flags[2] << 8) | flags[3]
  10507. };
  10508. },
  10509. nalParse = function(avcStream) {
  10510. var
  10511. avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  10512. result = [],
  10513. i,
  10514. length;
  10515. for (i = 0; i + 4 < avcStream.length; i += length) {
  10516. length = avcView.getUint32(i);
  10517. i += 4;
  10518. // bail if this doesn't appear to be an H264 stream
  10519. if (length <= 0) {
  10520. result.push('<span style=\'color:red;\'>MALFORMED DATA</span>');
  10521. continue;
  10522. }
  10523. switch(avcStream[i] & 0x1F) {
  10524. case 0x01:
  10525. result.push('slice_layer_without_partitioning_rbsp');
  10526. break;
  10527. case 0x05:
  10528. result.push('slice_layer_without_partitioning_rbsp_idr');
  10529. break;
  10530. case 0x06:
  10531. result.push('sei_rbsp');
  10532. break;
  10533. case 0x07:
  10534. result.push('seq_parameter_set_rbsp');
  10535. break;
  10536. case 0x08:
  10537. result.push('pic_parameter_set_rbsp');
  10538. break;
  10539. case 0x09:
  10540. result.push('access_unit_delimiter_rbsp');
  10541. break;
  10542. default:
  10543. result.push('UNKNOWN NAL - ' + avcStream[i] & 0x1F);
  10544. break;
  10545. }
  10546. }
  10547. return result;
  10548. },
  10549. // registry of handlers for individual mp4 box types
  10550. parse = {
  10551. // codingname, not a first-class box type. stsd entries share the
  10552. // same format as real boxes so the parsing infrastructure can be
  10553. // shared
  10554. avc1: function(data) {
  10555. var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  10556. return {
  10557. dataReferenceIndex: view.getUint16(6),
  10558. width: view.getUint16(24),
  10559. height: view.getUint16(26),
  10560. horizresolution: view.getUint16(28) + (view.getUint16(30) / 16),
  10561. vertresolution: view.getUint16(32) + (view.getUint16(34) / 16),
  10562. frameCount: view.getUint16(40),
  10563. depth: view.getUint16(74),
  10564. config: inspectMp4(data.subarray(78, data.byteLength))
  10565. };
  10566. },
  10567. avcC: function(data) {
  10568. var
  10569. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10570. result = {
  10571. configurationVersion: data[0],
  10572. avcProfileIndication: data[1],
  10573. profileCompatibility: data[2],
  10574. avcLevelIndication: data[3],
  10575. lengthSizeMinusOne: data[4] & 0x03,
  10576. sps: [],
  10577. pps: []
  10578. },
  10579. numOfSequenceParameterSets = data[5] & 0x1f,
  10580. numOfPictureParameterSets,
  10581. nalSize,
  10582. offset,
  10583. i;
  10584. // iterate past any SPSs
  10585. offset = 6;
  10586. for (i = 0; i < numOfSequenceParameterSets; i++) {
  10587. nalSize = view.getUint16(offset);
  10588. offset += 2;
  10589. result.sps.push(new Uint8Array(data.subarray(offset, offset + nalSize)));
  10590. offset += nalSize;
  10591. }
  10592. // iterate past any PPSs
  10593. numOfPictureParameterSets = data[offset];
  10594. offset++;
  10595. for (i = 0; i < numOfPictureParameterSets; i++) {
  10596. nalSize = view.getUint16(offset);
  10597. offset += 2;
  10598. result.pps.push(new Uint8Array(data.subarray(offset, offset + nalSize)));
  10599. offset += nalSize;
  10600. }
  10601. return result;
  10602. },
  10603. btrt: function(data) {
  10604. var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  10605. return {
  10606. bufferSizeDB: view.getUint32(0),
  10607. maxBitrate: view.getUint32(4),
  10608. avgBitrate: view.getUint32(8)
  10609. };
  10610. },
  10611. esds: function(data) {
  10612. return {
  10613. version: data[0],
  10614. flags: new Uint8Array(data.subarray(1, 4)),
  10615. esId: (data[6] << 8) | data[7],
  10616. streamPriority: data[8] & 0x1f,
  10617. decoderConfig: {
  10618. objectProfileIndication: data[11],
  10619. streamType: (data[12] >>> 2) & 0x3f,
  10620. bufferSize: (data[13] << 16) | (data[14] << 8) | data[15],
  10621. maxBitrate: (data[16] << 24) |
  10622. (data[17] << 16) |
  10623. (data[18] << 8) |
  10624. data[19],
  10625. avgBitrate: (data[20] << 24) |
  10626. (data[21] << 16) |
  10627. (data[22] << 8) |
  10628. data[23],
  10629. decoderConfigDescriptor: {
  10630. tag: data[24],
  10631. length: data[25],
  10632. audioObjectType: (data[26] >>> 3) & 0x1f,
  10633. samplingFrequencyIndex: ((data[26] & 0x07) << 1) |
  10634. ((data[27] >>> 7) & 0x01),
  10635. channelConfiguration: (data[27] >>> 3) & 0x0f
  10636. }
  10637. }
  10638. };
  10639. },
  10640. ftyp: function(data) {
  10641. var
  10642. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10643. result = {
  10644. majorBrand: parseType(data.subarray(0, 4)),
  10645. minorVersion: view.getUint32(4),
  10646. compatibleBrands: []
  10647. },
  10648. i = 8;
  10649. while (i < data.byteLength) {
  10650. result.compatibleBrands.push(parseType(data.subarray(i, i + 4)));
  10651. i += 4;
  10652. }
  10653. return result;
  10654. },
  10655. dinf: function(data) {
  10656. return {
  10657. boxes: inspectMp4(data)
  10658. };
  10659. },
  10660. dref: function(data) {
  10661. return {
  10662. version: data[0],
  10663. flags: new Uint8Array(data.subarray(1, 4)),
  10664. dataReferences: inspectMp4(data.subarray(8))
  10665. };
  10666. },
  10667. hdlr: function(data) {
  10668. var
  10669. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10670. language,
  10671. result = {
  10672. version: view.getUint8(0),
  10673. flags: new Uint8Array(data.subarray(1, 4)),
  10674. handlerType: parseType(data.subarray(8, 12)),
  10675. name: ''
  10676. },
  10677. i = 8;
  10678. // parse out the name field
  10679. for (i = 24; i < data.byteLength; i++) {
  10680. if (data[i] === 0x00) {
  10681. // the name field is null-terminated
  10682. i++;
  10683. break;
  10684. }
  10685. result.name += String.fromCharCode(data[i]);
  10686. }
  10687. // decode UTF-8 to javascript's internal representation
  10688. // see http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html
  10689. result.name = decodeURIComponent(global.escape(result.name));
  10690. return result;
  10691. },
  10692. mdat: function(data) {
  10693. return {
  10694. byteLength: data.byteLength,
  10695. nals: nalParse(data)
  10696. };
  10697. },
  10698. mdhd: function(data) {
  10699. var
  10700. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10701. i = 4,
  10702. language,
  10703. result = {
  10704. version: view.getUint8(0),
  10705. flags: new Uint8Array(data.subarray(1, 4)),
  10706. language: ''
  10707. };
  10708. if (result.version === 1) {
  10709. i += 4;
  10710. result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  10711. i += 8;
  10712. result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  10713. i += 4;
  10714. result.timescale = view.getUint32(i);
  10715. i += 8;
  10716. result.duration = view.getUint32(i); // truncating top 4 bytes
  10717. } else {
  10718. result.creationTime = parseMp4Date(view.getUint32(i));
  10719. i += 4;
  10720. result.modificationTime = parseMp4Date(view.getUint32(i));
  10721. i += 4;
  10722. result.timescale = view.getUint32(i);
  10723. i += 4;
  10724. result.duration = view.getUint32(i);
  10725. }
  10726. i += 4;
  10727. // language is stored as an ISO-639-2/T code in an array of three 5-bit fields
  10728. // each field is the packed difference between its ASCII value and 0x60
  10729. language = view.getUint16(i);
  10730. result.language += String.fromCharCode((language >> 10) + 0x60);
  10731. result.language += String.fromCharCode(((language & 0x03c0) >> 5) + 0x60);
  10732. result.language += String.fromCharCode((language & 0x1f) + 0x60);
  10733. return result;
  10734. },
  10735. mdia: function(data) {
  10736. return {
  10737. boxes: inspectMp4(data)
  10738. };
  10739. },
  10740. mfhd: function(data) {
  10741. return {
  10742. version: data[0],
  10743. flags: new Uint8Array(data.subarray(1, 4)),
  10744. sequenceNumber: (data[4] << 24) |
  10745. (data[5] << 16) |
  10746. (data[6] << 8) |
  10747. (data[7])
  10748. };
  10749. },
  10750. minf: function(data) {
  10751. return {
  10752. boxes: inspectMp4(data)
  10753. };
  10754. },
  10755. // codingname, not a first-class box type. stsd entries share the
  10756. // same format as real boxes so the parsing infrastructure can be
  10757. // shared
  10758. mp4a: function(data) {
  10759. var
  10760. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10761. result = {
  10762. // 6 bytes reserved
  10763. dataReferenceIndex: view.getUint16(6),
  10764. // 4 + 4 bytes reserved
  10765. channelcount: view.getUint16(16),
  10766. samplesize: view.getUint16(18),
  10767. // 2 bytes pre_defined
  10768. // 2 bytes reserved
  10769. samplerate: view.getUint16(24) + (view.getUint16(26) / 65536)
  10770. };
  10771. // if there are more bytes to process, assume this is an ISO/IEC
  10772. // 14496-14 MP4AudioSampleEntry and parse the ESDBox
  10773. if (data.byteLength > 28) {
  10774. result.streamDescriptor = inspectMp4(data.subarray(28))[0];
  10775. }
  10776. return result;
  10777. },
  10778. moof: function(data) {
  10779. return {
  10780. boxes: inspectMp4(data)
  10781. };
  10782. },
  10783. moov: function(data) {
  10784. return {
  10785. boxes: inspectMp4(data)
  10786. };
  10787. },
  10788. mvex: function(data) {
  10789. return {
  10790. boxes: inspectMp4(data)
  10791. };
  10792. },
  10793. mvhd: function(data) {
  10794. var
  10795. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10796. i = 4,
  10797. result = {
  10798. version: view.getUint8(0),
  10799. flags: new Uint8Array(data.subarray(1, 4))
  10800. };
  10801. if (result.version === 1) {
  10802. i += 4;
  10803. result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  10804. i += 8;
  10805. result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  10806. i += 4;
  10807. result.timescale = view.getUint32(i);
  10808. i += 8;
  10809. result.duration = view.getUint32(i); // truncating top 4 bytes
  10810. } else {
  10811. result.creationTime = parseMp4Date(view.getUint32(i));
  10812. i += 4;
  10813. result.modificationTime = parseMp4Date(view.getUint32(i));
  10814. i += 4;
  10815. result.timescale = view.getUint32(i);
  10816. i += 4;
  10817. result.duration = view.getUint32(i);
  10818. }
  10819. i += 4;
  10820. // convert fixed-point, base 16 back to a number
  10821. result.rate = view.getUint16(i) + (view.getUint16(i + 2) / 16);
  10822. i += 4;
  10823. result.volume = view.getUint8(i) + (view.getUint8(i + 1) / 8);
  10824. i += 2;
  10825. i += 2;
  10826. i += 2 * 4;
  10827. result.matrix = new Uint32Array(data.subarray(i, i + (9 * 4)));
  10828. i += 9 * 4;
  10829. i += 6 * 4;
  10830. result.nextTrackId = view.getUint32(i);
  10831. return result;
  10832. },
  10833. pdin: function(data) {
  10834. var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  10835. return {
  10836. version: view.getUint8(0),
  10837. flags: new Uint8Array(data.subarray(1, 4)),
  10838. rate: view.getUint32(4),
  10839. initialDelay: view.getUint32(8)
  10840. };
  10841. },
  10842. sdtp: function(data) {
  10843. var
  10844. result = {
  10845. version: data[0],
  10846. flags: new Uint8Array(data.subarray(1, 4)),
  10847. samples: []
  10848. }, i;
  10849. for (i = 4; i < data.byteLength; i++) {
  10850. result.samples.push({
  10851. dependsOn: (data[i] & 0x30) >> 4,
  10852. isDependedOn: (data[i] & 0x0c) >> 2,
  10853. hasRedundancy: data[i] & 0x03
  10854. });
  10855. }
  10856. return result;
  10857. },
  10858. sidx: function(data) {
  10859. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10860. result = {
  10861. version: data[0],
  10862. flags: new Uint8Array(data.subarray(1, 4)),
  10863. references: [],
  10864. referenceId: view.getUint32(4),
  10865. timescale: view.getUint32(8),
  10866. earliestPresentationTime: view.getUint32(12),
  10867. firstOffset: view.getUint32(16)
  10868. },
  10869. referenceCount = view.getUint16(22),
  10870. i;
  10871. for (i = 24; referenceCount; i += 12, referenceCount-- ) {
  10872. result.references.push({
  10873. referenceType: (data[i] & 0x80) >>> 7,
  10874. referencedSize: view.getUint32(i) & 0x7FFFFFFF,
  10875. subsegmentDuration: view.getUint32(i + 4),
  10876. startsWithSap: !!(data[i + 8] & 0x80),
  10877. sapType: (data[i + 8] & 0x70) >>> 4,
  10878. sapDeltaTime: view.getUint32(i + 8) & 0x0FFFFFFF
  10879. });
  10880. }
  10881. return result;
  10882. },
  10883. smhd: function(data) {
  10884. return {
  10885. version: data[0],
  10886. flags: new Uint8Array(data.subarray(1, 4)),
  10887. balance: data[4] + (data[5] / 256)
  10888. };
  10889. },
  10890. stbl: function(data) {
  10891. return {
  10892. boxes: inspectMp4(data)
  10893. };
  10894. },
  10895. stco: function(data) {
  10896. var
  10897. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10898. result = {
  10899. version: data[0],
  10900. flags: new Uint8Array(data.subarray(1, 4)),
  10901. chunkOffsets: []
  10902. },
  10903. entryCount = view.getUint32(4),
  10904. i;
  10905. for (i = 8; entryCount; i += 4, entryCount--) {
  10906. result.chunkOffsets.push(view.getUint32(i));
  10907. }
  10908. return result;
  10909. },
  10910. stsc: function(data) {
  10911. var
  10912. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10913. entryCount = view.getUint32(4),
  10914. result = {
  10915. version: data[0],
  10916. flags: new Uint8Array(data.subarray(1, 4)),
  10917. sampleToChunks: []
  10918. },
  10919. i;
  10920. for (i = 8; entryCount; i += 12, entryCount--) {
  10921. result.sampleToChunks.push({
  10922. firstChunk: view.getUint32(i),
  10923. samplesPerChunk: view.getUint32(i + 4),
  10924. sampleDescriptionIndex: view.getUint32(i + 8)
  10925. });
  10926. }
  10927. return result;
  10928. },
  10929. stsd: function(data) {
  10930. return {
  10931. version: data[0],
  10932. flags: new Uint8Array(data.subarray(1, 4)),
  10933. sampleDescriptions: inspectMp4(data.subarray(8))
  10934. };
  10935. },
  10936. stsz: function(data) {
  10937. var
  10938. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10939. result = {
  10940. version: data[0],
  10941. flags: new Uint8Array(data.subarray(1, 4)),
  10942. sampleSize: view.getUint32(4),
  10943. entries: []
  10944. },
  10945. i;
  10946. for (i = 12; i < data.byteLength; i += 4) {
  10947. result.entries.push(view.getUint32(i));
  10948. }
  10949. return result;
  10950. },
  10951. stts: function(data) {
  10952. var
  10953. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10954. result = {
  10955. version: data[0],
  10956. flags: new Uint8Array(data.subarray(1, 4)),
  10957. timeToSamples: []
  10958. },
  10959. entryCount = view.getUint32(4),
  10960. i;
  10961. for (i = 8; entryCount; i += 8, entryCount--) {
  10962. result.timeToSamples.push({
  10963. sampleCount: view.getUint32(i),
  10964. sampleDelta: view.getUint32(i + 4)
  10965. });
  10966. }
  10967. return result;
  10968. },
  10969. styp: function(data) {
  10970. return parse.ftyp(data);
  10971. },
  10972. tfdt: function(data) {
  10973. return {
  10974. version: data[0],
  10975. flags: new Uint8Array(data.subarray(1, 4)),
  10976. baseMediaDecodeTime: data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]
  10977. };
  10978. },
  10979. tfhd: function(data) {
  10980. var
  10981. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10982. result = {
  10983. version: data[0],
  10984. flags: new Uint8Array(data.subarray(1, 4)),
  10985. trackId: view.getUint32(4)
  10986. },
  10987. baseDataOffsetPresent = result.flags[2] & 0x01,
  10988. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  10989. defaultSampleDurationPresent = result.flags[2] & 0x08,
  10990. defaultSampleSizePresent = result.flags[2] & 0x10,
  10991. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  10992. i;
  10993. i = 8;
  10994. if (baseDataOffsetPresent) {
  10995. i += 4; // truncate top 4 bytes
  10996. result.baseDataOffset = view.getUint32(12);
  10997. i += 4;
  10998. }
  10999. if (sampleDescriptionIndexPresent) {
  11000. result.sampleDescriptionIndex = view.getUint32(i);
  11001. i += 4;
  11002. }
  11003. if (defaultSampleDurationPresent) {
  11004. result.defaultSampleDuration = view.getUint32(i);
  11005. i += 4;
  11006. }
  11007. if (defaultSampleSizePresent) {
  11008. result.defaultSampleSize = view.getUint32(i);
  11009. i += 4;
  11010. }
  11011. if (defaultSampleFlagsPresent) {
  11012. result.defaultSampleFlags = view.getUint32(i);
  11013. }
  11014. return result;
  11015. },
  11016. tkhd: function(data) {
  11017. var
  11018. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  11019. i = 4,
  11020. result = {
  11021. version: view.getUint8(0),
  11022. flags: new Uint8Array(data.subarray(1, 4)),
  11023. };
  11024. if (result.version === 1) {
  11025. i += 4;
  11026. result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  11027. i += 8;
  11028. result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  11029. i += 4;
  11030. result.trackId = view.getUint32(i);
  11031. i += 4;
  11032. i += 8;
  11033. result.duration = view.getUint32(i); // truncating top 4 bytes
  11034. } else {
  11035. result.creationTime = parseMp4Date(view.getUint32(i));
  11036. i += 4;
  11037. result.modificationTime = parseMp4Date(view.getUint32(i));
  11038. i += 4;
  11039. result.trackId = view.getUint32(i);
  11040. i += 4;
  11041. i += 4;
  11042. result.duration = view.getUint32(i);
  11043. }
  11044. i += 4;
  11045. i += 2 * 4;
  11046. result.layer = view.getUint16(i);
  11047. i += 2;
  11048. result.alternateGroup = view.getUint16(i);
  11049. i += 2;
  11050. // convert fixed-point, base 16 back to a number
  11051. result.volume = view.getUint8(i) + (view.getUint8(i + 1) / 8);
  11052. i += 2;
  11053. i += 2;
  11054. result.matrix = new Uint32Array(data.subarray(i, i + (9 * 4)));
  11055. i += 9 * 4;
  11056. result.width = view.getUint16(i) + (view.getUint16(i + 2) / 16);
  11057. i += 4;
  11058. result.height = view.getUint16(i) + (view.getUint16(i + 2) / 16);
  11059. return result;
  11060. },
  11061. traf: function(data) {
  11062. return {
  11063. boxes: inspectMp4(data)
  11064. };
  11065. },
  11066. trak: function(data) {
  11067. return {
  11068. boxes: inspectMp4(data)
  11069. };
  11070. },
  11071. trex: function(data) {
  11072. var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  11073. return {
  11074. version: data[0],
  11075. flags: new Uint8Array(data.subarray(1, 4)),
  11076. trackId: view.getUint32(4),
  11077. defaultSampleDescriptionIndex: view.getUint32(8),
  11078. defaultSampleDuration: view.getUint32(12),
  11079. defaultSampleSize: view.getUint32(16),
  11080. sampleDependsOn: data[20] & 0x03,
  11081. sampleIsDependedOn: (data[21] & 0xc0) >> 6,
  11082. sampleHasRedundancy: (data[21] & 0x30) >> 4,
  11083. samplePaddingValue: (data[21] & 0x0e) >> 1,
  11084. sampleIsDifferenceSample: !!(data[21] & 0x01),
  11085. sampleDegradationPriority: view.getUint16(22)
  11086. };
  11087. },
  11088. trun: function(data) {
  11089. var
  11090. result = {
  11091. version: data[0],
  11092. flags: new Uint8Array(data.subarray(1, 4)),
  11093. samples: []
  11094. },
  11095. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  11096. dataOffsetPresent = result.flags[2] & 0x01,
  11097. firstSampleFlagsPresent = result.flags[2] & 0x04,
  11098. sampleDurationPresent = result.flags[1] & 0x01,
  11099. sampleSizePresent = result.flags[1] & 0x02,
  11100. sampleFlagsPresent = result.flags[1] & 0x04,
  11101. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
  11102. sampleCount = view.getUint32(4),
  11103. offset = 8,
  11104. sample;
  11105. if (dataOffsetPresent) {
  11106. result.dataOffset = view.getUint32(offset);
  11107. offset += 4;
  11108. }
  11109. if (firstSampleFlagsPresent && sampleCount) {
  11110. sample = {
  11111. flags: parseSampleFlags(data.subarray(offset, offset + 4))
  11112. };
  11113. offset += 4;
  11114. if (sampleDurationPresent) {
  11115. sample.duration = view.getUint32(offset);
  11116. offset += 4;
  11117. }
  11118. if (sampleSizePresent) {
  11119. sample.size = view.getUint32(offset);
  11120. offset += 4;
  11121. }
  11122. if (sampleCompositionTimeOffsetPresent) {
  11123. sample.compositionTimeOffset = view.getUint32(offset);
  11124. offset += 4;
  11125. }
  11126. result.samples.push(sample);
  11127. sampleCount--;
  11128. }
  11129. while (sampleCount--) {
  11130. sample = {};
  11131. if (sampleDurationPresent) {
  11132. sample.duration = view.getUint32(offset);
  11133. offset += 4;
  11134. }
  11135. if (sampleSizePresent) {
  11136. sample.size = view.getUint32(offset);
  11137. offset += 4;
  11138. }
  11139. if (sampleFlagsPresent) {
  11140. sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
  11141. offset += 4;
  11142. }
  11143. if (sampleCompositionTimeOffsetPresent) {
  11144. sample.compositionTimeOffset = view.getUint32(offset);
  11145. offset += 4;
  11146. }
  11147. result.samples.push(sample);
  11148. }
  11149. return result;
  11150. },
  11151. 'url ': function(data) {
  11152. return {
  11153. version: data[0],
  11154. flags: new Uint8Array(data.subarray(1, 4))
  11155. };
  11156. },
  11157. vmhd: function(data) {
  11158. var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  11159. return {
  11160. version: data[0],
  11161. flags: new Uint8Array(data.subarray(1, 4)),
  11162. graphicsmode: view.getUint16(4),
  11163. opcolor: new Uint16Array([view.getUint16(6),
  11164. view.getUint16(8),
  11165. view.getUint16(10)])
  11166. };
  11167. }
  11168. };
  11169. /**
  11170. * Return a javascript array of box objects parsed from an ISO base
  11171. * media file.
  11172. * @param data {Uint8Array} the binary data of the media to be inspected
  11173. * @return {array} a javascript array of potentially nested box objects
  11174. */
  11175. inspectMp4 = function(data) {
  11176. var
  11177. i = 0,
  11178. result = [],
  11179. view,
  11180. size,
  11181. type,
  11182. end,
  11183. box;
  11184. // Convert data from Uint8Array to ArrayBuffer, to follow Dataview API
  11185. var ab = new ArrayBuffer(data.length);
  11186. var v = new Uint8Array(ab);
  11187. for (var z = 0; z < data.length; ++z) {
  11188. v[z] = data[z];
  11189. }
  11190. view = new DataView(ab);
  11191. while (i < data.byteLength) {
  11192. // parse box data
  11193. size = view.getUint32(i);
  11194. type = parseType(data.subarray(i + 4, i + 8));
  11195. end = size > 1 ? i + size : data.byteLength;
  11196. // parse type-specific data
  11197. box = (parse[type] || function(data) {
  11198. return {
  11199. data: data
  11200. };
  11201. })(data.subarray(i + 8, end));
  11202. box.size = size;
  11203. box.type = type;
  11204. // store this box and move to the next
  11205. result.push(box);
  11206. i = end;
  11207. }
  11208. return result;
  11209. };
  11210. /**
  11211. * Returns a textual representation of the javascript represtentation
  11212. * of an MP4 file. You can use it as an alternative to
  11213. * JSON.stringify() to compare inspected MP4s.
  11214. * @param inspectedMp4 {array} the parsed array of boxes in an MP4
  11215. * file
  11216. * @param depth {number} (optional) the number of ancestor boxes of
  11217. * the elements of inspectedMp4. Assumed to be zero if unspecified.
  11218. * @return {string} a text representation of the parsed MP4
  11219. */
  11220. textifyMp4 = function(inspectedMp4, depth) {
  11221. var indent;
  11222. depth = depth || 0;
  11223. indent = new Array(depth * 2 + 1).join(' ');
  11224. // iterate over all the boxes
  11225. return inspectedMp4.map(function(box, index) {
  11226. // list the box type first at the current indentation level
  11227. return indent + box.type + '\n' +
  11228. // the type is already included and handle child boxes separately
  11229. Object.keys(box).filter(function(key) {
  11230. return key !== 'type' && key !== 'boxes';
  11231. // output all the box properties
  11232. }).map(function(key) {
  11233. var prefix = indent + ' ' + key + ': ',
  11234. value = box[key];
  11235. // print out raw bytes as hexademical
  11236. if (value instanceof Uint8Array || value instanceof Uint32Array) {
  11237. var bytes = Array.prototype.slice.call(new Uint8Array(value.buffer, value.byteOffset, value.byteLength))
  11238. .map(function(byte) {
  11239. return ' ' + ('00' + byte.toString(16)).slice(-2);
  11240. }).join('').match(/.{1,24}/g);
  11241. if (!bytes) {
  11242. return prefix + '<>';
  11243. }
  11244. if (bytes.length === 1) {
  11245. return prefix + '<' + bytes.join('').slice(1) + '>';
  11246. }
  11247. return prefix + '<\n' + bytes.map(function(line) {
  11248. return indent + ' ' + line;
  11249. }).join('\n') + '\n' + indent + ' >';
  11250. }
  11251. // stringify generic objects
  11252. return prefix +
  11253. JSON.stringify(value, null, 2)
  11254. .split('\n').map(function(line, index) {
  11255. if (index === 0) {
  11256. return line;
  11257. }
  11258. return indent + ' ' + line;
  11259. }).join('\n');
  11260. }).join('\n') +
  11261. // recursively textify the child boxes
  11262. (box.boxes ? '\n' + textifyMp4(box.boxes, depth + 1) : '');
  11263. }).join('\n');
  11264. };
  11265. module.exports = {
  11266. inspect: inspectMp4,
  11267. textify: textifyMp4
  11268. };
  11269. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11270. },{}],54:[function(require,module,exports){
  11271. 'use strict';
  11272. var ExpGolomb;
  11273. /**
  11274. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  11275. * scheme used by h264.
  11276. */
  11277. ExpGolomb = function(workingData) {
  11278. var
  11279. // the number of bytes left to examine in workingData
  11280. workingBytesAvailable = workingData.byteLength,
  11281. // the current word being examined
  11282. workingWord = 0, // :uint
  11283. // the number of bits left to examine in the current word
  11284. workingBitsAvailable = 0; // :uint;
  11285. // ():uint
  11286. this.length = function() {
  11287. return (8 * workingBytesAvailable);
  11288. };
  11289. // ():uint
  11290. this.bitsAvailable = function() {
  11291. return (8 * workingBytesAvailable) + workingBitsAvailable;
  11292. };
  11293. // ():void
  11294. this.loadWord = function() {
  11295. var
  11296. position = workingData.byteLength - workingBytesAvailable,
  11297. workingBytes = new Uint8Array(4),
  11298. availableBytes = Math.min(4, workingBytesAvailable);
  11299. if (availableBytes === 0) {
  11300. throw new Error('no bytes available');
  11301. }
  11302. workingBytes.set(workingData.subarray(position,
  11303. position + availableBytes));
  11304. workingWord = new DataView(workingBytes.buffer).getUint32(0);
  11305. // track the amount of workingData that has been processed
  11306. workingBitsAvailable = availableBytes * 8;
  11307. workingBytesAvailable -= availableBytes;
  11308. };
  11309. // (count:int):void
  11310. this.skipBits = function(count) {
  11311. var skipBytes; // :int
  11312. if (workingBitsAvailable > count) {
  11313. workingWord <<= count;
  11314. workingBitsAvailable -= count;
  11315. } else {
  11316. count -= workingBitsAvailable;
  11317. skipBytes = Math.floor(count / 8);
  11318. count -= (skipBytes * 8);
  11319. workingBytesAvailable -= skipBytes;
  11320. this.loadWord();
  11321. workingWord <<= count;
  11322. workingBitsAvailable -= count;
  11323. }
  11324. };
  11325. // (size:int):uint
  11326. this.readBits = function(size) {
  11327. var
  11328. bits = Math.min(workingBitsAvailable, size), // :uint
  11329. valu = workingWord >>> (32 - bits); // :uint
  11330. // if size > 31, handle error
  11331. workingBitsAvailable -= bits;
  11332. if (workingBitsAvailable > 0) {
  11333. workingWord <<= bits;
  11334. } else if (workingBytesAvailable > 0) {
  11335. this.loadWord();
  11336. }
  11337. bits = size - bits;
  11338. if (bits > 0) {
  11339. return valu << bits | this.readBits(bits);
  11340. } else {
  11341. return valu;
  11342. }
  11343. };
  11344. // ():uint
  11345. this.skipLeadingZeros = function() {
  11346. var leadingZeroCount; // :uint
  11347. for (leadingZeroCount = 0 ; leadingZeroCount < workingBitsAvailable ; ++leadingZeroCount) {
  11348. if (0 !== (workingWord & (0x80000000 >>> leadingZeroCount))) {
  11349. // the first bit of working word is 1
  11350. workingWord <<= leadingZeroCount;
  11351. workingBitsAvailable -= leadingZeroCount;
  11352. return leadingZeroCount;
  11353. }
  11354. }
  11355. // we exhausted workingWord and still have not found a 1
  11356. this.loadWord();
  11357. return leadingZeroCount + this.skipLeadingZeros();
  11358. };
  11359. // ():void
  11360. this.skipUnsignedExpGolomb = function() {
  11361. this.skipBits(1 + this.skipLeadingZeros());
  11362. };
  11363. // ():void
  11364. this.skipExpGolomb = function() {
  11365. this.skipBits(1 + this.skipLeadingZeros());
  11366. };
  11367. // ():uint
  11368. this.readUnsignedExpGolomb = function() {
  11369. var clz = this.skipLeadingZeros(); // :uint
  11370. return this.readBits(clz + 1) - 1;
  11371. };
  11372. // ():int
  11373. this.readExpGolomb = function() {
  11374. var valu = this.readUnsignedExpGolomb(); // :int
  11375. if (0x01 & valu) {
  11376. // the number is odd if the low order bit is set
  11377. return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2
  11378. } else {
  11379. return -1 * (valu >>> 1); // divide by two then make it negative
  11380. }
  11381. };
  11382. // Some convenience functions
  11383. // :Boolean
  11384. this.readBoolean = function() {
  11385. return 1 === this.readBits(1);
  11386. };
  11387. // ():int
  11388. this.readUnsignedByte = function() {
  11389. return this.readBits(8);
  11390. };
  11391. this.loadWord();
  11392. };
  11393. module.exports = ExpGolomb;
  11394. },{}],55:[function(require,module,exports){
  11395. /**
  11396. * mux.js
  11397. *
  11398. * Copyright (c) 2014 Brightcove
  11399. * All rights reserved.
  11400. *
  11401. * A lightweight readable stream implemention that handles event dispatching.
  11402. * Objects that inherit from streams should call init in their constructors.
  11403. */
  11404. 'use strict';
  11405. var Stream = function() {
  11406. this.init = function() {
  11407. var listeners = {};
  11408. /**
  11409. * Add a listener for a specified event type.
  11410. * @param type {string} the event name
  11411. * @param listener {function} the callback to be invoked when an event of
  11412. * the specified type occurs
  11413. */
  11414. this.on = function(type, listener) {
  11415. if (!listeners[type]) {
  11416. listeners[type] = [];
  11417. }
  11418. listeners[type].push(listener);
  11419. };
  11420. /**
  11421. * Remove a listener for a specified event type.
  11422. * @param type {string} the event name
  11423. * @param listener {function} a function previously registered for this
  11424. * type of event through `on`
  11425. */
  11426. this.off = function(type, listener) {
  11427. var index;
  11428. if (!listeners[type]) {
  11429. return false;
  11430. }
  11431. index = listeners[type].indexOf(listener);
  11432. listeners[type].splice(index, 1);
  11433. return index > -1;
  11434. };
  11435. /**
  11436. * Trigger an event of the specified type on this stream. Any additional
  11437. * arguments to this function are passed as parameters to event listeners.
  11438. * @param type {string} the event name
  11439. */
  11440. this.trigger = function(type) {
  11441. var callbacks, i, length, args;
  11442. callbacks = listeners[type];
  11443. if (!callbacks) {
  11444. return;
  11445. }
  11446. // Slicing the arguments on every invocation of this method
  11447. // can add a significant amount of overhead. Avoid the
  11448. // intermediate object creation for the common case of a
  11449. // single callback argument
  11450. if (arguments.length === 2) {
  11451. length = callbacks.length;
  11452. for (i = 0; i < length; ++i) {
  11453. callbacks[i].call(this, arguments[1]);
  11454. }
  11455. } else {
  11456. args = [];
  11457. i = arguments.length;
  11458. for (i = 1; i < arguments.length; ++i) {
  11459. args.push(arguments[i]);
  11460. }
  11461. length = callbacks.length;
  11462. for (i = 0; i < length; ++i) {
  11463. callbacks[i].apply(this, args);
  11464. }
  11465. }
  11466. };
  11467. /**
  11468. * Destroys the stream and cleans up.
  11469. */
  11470. this.dispose = function() {
  11471. listeners = {};
  11472. };
  11473. };
  11474. };
  11475. /**
  11476. * Forwards all `data` events on this stream to the destination stream. The
  11477. * destination stream should provide a method `push` to receive the data
  11478. * events as they arrive.
  11479. * @param destination {stream} the stream that will receive all `data` events
  11480. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  11481. * when the current stream emits a 'done' event
  11482. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  11483. */
  11484. Stream.prototype.pipe = function(destination) {
  11485. this.on('data', function(data) {
  11486. destination.push(data);
  11487. });
  11488. this.on('done', function(flushSource) {
  11489. destination.flush(flushSource);
  11490. });
  11491. return destination;
  11492. };
  11493. // Default stream functions that are expected to be overridden to perform
  11494. // actual work. These are provided by the prototype as a sort of no-op
  11495. // implementation so that we don't have to check for their existence in the
  11496. // `pipe` function above.
  11497. Stream.prototype.push = function(data) {
  11498. this.trigger('data', data);
  11499. };
  11500. Stream.prototype.flush = function(flushSource) {
  11501. this.trigger('done', flushSource);
  11502. };
  11503. module.exports = Stream;
  11504. },{}],56:[function(require,module,exports){
  11505. var bundleFn = arguments[3];
  11506. var sources = arguments[4];
  11507. var cache = arguments[5];
  11508. var stringify = JSON.stringify;
  11509. module.exports = function (fn) {
  11510. var keys = [];
  11511. var wkey;
  11512. var cacheKeys = Object.keys(cache);
  11513. for (var i = 0, l = cacheKeys.length; i < l; i++) {
  11514. var key = cacheKeys[i];
  11515. if (cache[key].exports === fn) {
  11516. wkey = key;
  11517. break;
  11518. }
  11519. }
  11520. if (!wkey) {
  11521. wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
  11522. var wcache = {};
  11523. for (var i = 0, l = cacheKeys.length; i < l; i++) {
  11524. var key = cacheKeys[i];
  11525. wcache[key] = key;
  11526. }
  11527. sources[wkey] = [
  11528. Function(['require','module','exports'], '(' + fn + ')(self)'),
  11529. wcache
  11530. ];
  11531. }
  11532. var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
  11533. var scache = {}; scache[wkey] = wkey;
  11534. sources[skey] = [
  11535. Function(['require'],'require(' + stringify(wkey) + ')(self)'),
  11536. scache
  11537. ];
  11538. var src = '(' + bundleFn + ')({'
  11539. + Object.keys(sources).map(function (key) {
  11540. return stringify(key) + ':['
  11541. + sources[key][0]
  11542. + ',' + stringify(sources[key][1]) + ']'
  11543. ;
  11544. }).join(',')
  11545. + '},{},[' + stringify(skey) + '])'
  11546. ;
  11547. var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  11548. return new Worker(URL.createObjectURL(
  11549. new Blob([src], { type: 'text/javascript' })
  11550. ));
  11551. };
  11552. },{}],57:[function(require,module,exports){
  11553. (function (global){
  11554. /**
  11555. * @file videojs-contrib-hls.js
  11556. *
  11557. * The main file for the HLS project.
  11558. * License: https://github.com/videojs/videojs-contrib-hls/blob/master/LICENSE
  11559. */
  11560. 'use strict';
  11561. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  11562. var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  11563. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  11564. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  11565. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  11566. var _globalDocument = require('global/document');
  11567. var _globalDocument2 = _interopRequireDefault(_globalDocument);
  11568. var _playlistLoader = require('./playlist-loader');
  11569. var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
  11570. var _playlist = require('./playlist');
  11571. var _playlist2 = _interopRequireDefault(_playlist);
  11572. var _xhr = require('./xhr');
  11573. var _xhr2 = _interopRequireDefault(_xhr);
  11574. var _decrypter = require('./decrypter');
  11575. var _binUtils = require('./bin-utils');
  11576. var _binUtils2 = _interopRequireDefault(_binUtils);
  11577. var _videojsContribMediaSources = require('videojs-contrib-media-sources');
  11578. var _m3u8 = require('./m3u8');
  11579. var _m3u82 = _interopRequireDefault(_m3u8);
  11580. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  11581. var _videoJs2 = _interopRequireDefault(_videoJs);
  11582. var _masterPlaylistController = require('./master-playlist-controller');
  11583. var _masterPlaylistController2 = _interopRequireDefault(_masterPlaylistController);
  11584. /**
  11585. * determine if an object a is differnt from
  11586. * and object b. both only having one dimensional
  11587. * properties
  11588. *
  11589. * @param {Object} a object one
  11590. * @param {Object} b object two
  11591. * @return {Boolean} if the object has changed or not
  11592. */
  11593. var objectChanged = function objectChanged(a, b) {
  11594. if (typeof a !== typeof b) {
  11595. return true;
  11596. }
  11597. // if we have a different number of elements
  11598. // something has changed
  11599. if (Object.keys(a).length !== Object.keys(b).length) {
  11600. return true;
  11601. }
  11602. for (var prop in a) {
  11603. if (!b[prop] || a[prop] !== b[prop]) {
  11604. return true;
  11605. }
  11606. }
  11607. return false;
  11608. };
  11609. var Hls = {
  11610. PlaylistLoader: _playlistLoader2['default'],
  11611. Playlist: _playlist2['default'],
  11612. Decrypter: _decrypter.Decrypter,
  11613. AsyncStream: _decrypter.AsyncStream,
  11614. decrypt: _decrypter.decrypt,
  11615. utils: _binUtils2['default'],
  11616. xhr: (0, _xhr2['default'])()
  11617. };
  11618. // the desired length of video to maintain in the buffer, in seconds
  11619. Hls.GOAL_BUFFER_LENGTH = 30;
  11620. // A fudge factor to apply to advertised playlist bitrates to account for
  11621. // temporary flucations in client bandwidth
  11622. var BANDWIDTH_VARIANCE = 1.2;
  11623. /**
  11624. * Returns the CSS value for the specified property on an element
  11625. * using `getComputedStyle`. Firefox has a long-standing issue where
  11626. * getComputedStyle() may return null when running in an iframe with
  11627. * `display: none`.
  11628. *
  11629. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  11630. * @param {HTMLElement} el the htmlelement to work on
  11631. * @param {string} the proprety to get the style for
  11632. */
  11633. var safeGetComputedStyle = function safeGetComputedStyle(el, property) {
  11634. var result = undefined;
  11635. if (!el) {
  11636. return '';
  11637. }
  11638. result = getComputedStyle(el);
  11639. if (!result) {
  11640. return '';
  11641. }
  11642. return result[property];
  11643. };
  11644. /**
  11645. * Chooses the appropriate media playlist based on the current
  11646. * bandwidth estimate and the player size.
  11647. *
  11648. * @return {Playlist} the highest bitrate playlist less than the currently detected
  11649. * bandwidth, accounting for some amount of bandwidth variance
  11650. */
  11651. Hls.STANDARD_PLAYLIST_SELECTOR = function () {
  11652. var effectiveBitrate = undefined;
  11653. var sortedPlaylists = this.playlists.master.playlists.slice();
  11654. var bandwidthPlaylists = [];
  11655. var now = +new Date();
  11656. var i = undefined;
  11657. var variant = undefined;
  11658. var bandwidthBestVariant = undefined;
  11659. var resolutionPlusOne = undefined;
  11660. var resolutionPlusOneAttribute = undefined;
  11661. var resolutionBestVariant = undefined;
  11662. var width = undefined;
  11663. var height = undefined;
  11664. sortedPlaylists.sort(Hls.comparePlaylistBandwidth);
  11665. // filter out any playlists that have been excluded due to
  11666. // incompatible configurations or playback errors
  11667. sortedPlaylists = sortedPlaylists.filter(function (localVariant) {
  11668. if (typeof localVariant.excludeUntil !== 'undefined') {
  11669. return now >= localVariant.excludeUntil;
  11670. }
  11671. return true;
  11672. });
  11673. // filter out any variant that has greater effective bitrate
  11674. // than the current estimated bandwidth
  11675. i = sortedPlaylists.length;
  11676. while (i--) {
  11677. variant = sortedPlaylists[i];
  11678. // ignore playlists without bandwidth information
  11679. if (!variant.attributes || !variant.attributes.BANDWIDTH) {
  11680. continue;
  11681. }
  11682. effectiveBitrate = variant.attributes.BANDWIDTH * BANDWIDTH_VARIANCE;
  11683. if (effectiveBitrate < this.bandwidth) {
  11684. bandwidthPlaylists.push(variant);
  11685. // since the playlists are sorted in ascending order by
  11686. // bandwidth, the first viable variant is the best
  11687. if (!bandwidthBestVariant) {
  11688. bandwidthBestVariant = variant;
  11689. }
  11690. }
  11691. }
  11692. i = bandwidthPlaylists.length;
  11693. // sort variants by resolution
  11694. bandwidthPlaylists.sort(Hls.comparePlaylistResolution);
  11695. // forget our old variant from above,
  11696. // or we might choose that in high-bandwidth scenarios
  11697. // (this could be the lowest bitrate rendition as we go through all of them above)
  11698. variant = null;
  11699. width = parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10);
  11700. height = parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10);
  11701. // iterate through the bandwidth-filtered playlists and find
  11702. // best rendition by player dimension
  11703. while (i--) {
  11704. variant = bandwidthPlaylists[i];
  11705. // ignore playlists without resolution information
  11706. if (!variant.attributes || !variant.attributes.RESOLUTION || !variant.attributes.RESOLUTION.width || !variant.attributes.RESOLUTION.height) {
  11707. continue;
  11708. }
  11709. // since the playlists are sorted, the first variant that has
  11710. // dimensions less than or equal to the player size is the best
  11711. var variantResolution = variant.attributes.RESOLUTION;
  11712. if (variantResolution.width === width && variantResolution.height === height) {
  11713. // if we have the exact resolution as the player use it
  11714. resolutionPlusOne = null;
  11715. resolutionBestVariant = variant;
  11716. break;
  11717. } else if (variantResolution.width < width && variantResolution.height < height) {
  11718. // if both dimensions are less than the player use the
  11719. // previous (next-largest) variant
  11720. break;
  11721. } else if (!resolutionPlusOne || variantResolution.width < resolutionPlusOneAttribute.width && variantResolution.height < resolutionPlusOneAttribute.height) {
  11722. // If we still haven't found a good match keep a
  11723. // reference to the previous variant for the next loop
  11724. // iteration
  11725. // By only saving variants if they are smaller than the
  11726. // previously saved variant, we ensure that we also pick
  11727. // the highest bandwidth variant that is just-larger-than
  11728. // the video player
  11729. resolutionPlusOne = variant;
  11730. resolutionPlusOneAttribute = resolutionPlusOne.attributes.RESOLUTION;
  11731. }
  11732. }
  11733. // fallback chain of variants
  11734. return resolutionPlusOne || resolutionBestVariant || bandwidthBestVariant || sortedPlaylists[0];
  11735. };
  11736. // HLS is a source handler, not a tech. Make sure attempts to use it
  11737. // as one do not cause exceptions.
  11738. Hls.canPlaySource = function () {
  11739. return _videoJs2['default'].log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  11740. };
  11741. /**
  11742. * Whether the browser has built-in HLS support.
  11743. */
  11744. Hls.supportsNativeHls = (function () {
  11745. var video = _globalDocument2['default'].createElement('video');
  11746. // native HLS is definitely not supported if HTML5 video isn't
  11747. if (!_videoJs2['default'].getComponent('Html5').isSupported()) {
  11748. return false;
  11749. }
  11750. // HLS manifests can go by many mime-types
  11751. var canPlay = [
  11752. // Apple santioned
  11753. 'application/vnd.apple.mpegurl',
  11754. // Apple sanctioned for backwards compatibility
  11755. 'audio/mpegurl',
  11756. // Very common
  11757. 'audio/x-mpegurl',
  11758. // Very common
  11759. 'application/x-mpegurl',
  11760. // Included for completeness
  11761. 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
  11762. return canPlay.some(function (canItPlay) {
  11763. return (/maybe|probably/i.test(video.canPlayType(canItPlay))
  11764. );
  11765. });
  11766. })();
  11767. /**
  11768. * HLS is a source handler, not a tech. Make sure attempts to use it
  11769. * as one do not cause exceptions.
  11770. */
  11771. Hls.isSupported = function () {
  11772. return _videoJs2['default'].log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  11773. };
  11774. var Component = _videoJs2['default'].getComponent('Component');
  11775. /**
  11776. * The Hls Handler object, where we orchestrate all of the parts
  11777. * of HLS to interact with video.js
  11778. *
  11779. * @class HlsHandler
  11780. * @extends videojs.Component
  11781. * @param {Object} source the soruce object
  11782. * @param {Tech} tech the parent tech object
  11783. * @param {Object} options optional and required options
  11784. */
  11785. var HlsHandler = (function (_Component) {
  11786. _inherits(HlsHandler, _Component);
  11787. function HlsHandler(source, tech, options) {
  11788. var _this = this;
  11789. _classCallCheck(this, HlsHandler);
  11790. _get(Object.getPrototypeOf(HlsHandler.prototype), 'constructor', this).call(this, tech);
  11791. // tech.player() is deprecated but setup a reference to HLS for
  11792. // backwards-compatibility
  11793. if (tech.options_ && tech.options_.playerId) {
  11794. var _player = (0, _videoJs2['default'])(tech.options_.playerId);
  11795. if (!_player.hasOwnProperty('hls')) {
  11796. Object.defineProperty(_player, 'hls', {
  11797. get: function get() {
  11798. _videoJs2['default'].log.warn('player.hls is deprecated. Use player.tech.hls instead.');
  11799. return _this;
  11800. }
  11801. });
  11802. }
  11803. }
  11804. this.options_ = _videoJs2['default'].mergeOptions(_videoJs2['default'].options.hls || {}, options.hls);
  11805. this.tech_ = tech;
  11806. this.source_ = source;
  11807. // start playlist selection at a reasonable bandwidth for
  11808. // broadband internet
  11809. // 0.5 Mbps
  11810. this.bandwidth = this.options_.bandwidth || 4194304;
  11811. this.bytesReceived = 0;
  11812. // listen for fullscreenchange events for this player so that we
  11813. // can adjust our quality selection quickly
  11814. this.on(_globalDocument2['default'], ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], function (event) {
  11815. var fullscreenElement = _globalDocument2['default'].fullscreenElement || _globalDocument2['default'].webkitFullscreenElement || _globalDocument2['default'].mozFullScreenElement || _globalDocument2['default'].msFullscreenElement;
  11816. if (fullscreenElement && fullscreenElement.contains(_this.tech_.el())) {
  11817. _this.masterPlaylistController_.fastQualityChange_();
  11818. }
  11819. });
  11820. this.on(this.tech_, 'seeking', function () {
  11821. this.setCurrentTime(this.tech_.currentTime());
  11822. });
  11823. this.on(this.tech_, 'error', function () {
  11824. if (this.masterPlaylistController_) {
  11825. this.masterPlaylistController_.pauseLoading();
  11826. }
  11827. });
  11828. this.audioTrackChange_ = function () {
  11829. _this.masterPlaylistController_.useAudio();
  11830. };
  11831. this.on(this.tech_, 'play', this.play);
  11832. }
  11833. /**
  11834. * The Source Handler object, which informs video.js what additional
  11835. * MIME types are supported and sets up playback. It is registered
  11836. * automatically to the appropriate tech based on the capabilities of
  11837. * the browser it is running in. It is not necessary to use or modify
  11838. * this object in normal usage.
  11839. */
  11840. /**
  11841. * called when player.src gets called, handle a new source
  11842. *
  11843. * @param {Object} src the source object to handle
  11844. */
  11845. _createClass(HlsHandler, [{
  11846. key: 'src',
  11847. value: function src(_src) {
  11848. var _this2 = this;
  11849. // do nothing if the src is falsey
  11850. if (!_src) {
  11851. return;
  11852. }
  11853. ['withCredentials', 'bandwidth'].forEach(function (option) {
  11854. if (typeof _this2.source_[option] !== 'undefined') {
  11855. _this2.options_[option] = _this2.source_[option];
  11856. }
  11857. });
  11858. this.options_.url = this.source_.src;
  11859. this.options_.tech = this.tech_;
  11860. this.options_.externHls = Hls;
  11861. this.options_.bandwidth = this.bandwidth;
  11862. this.masterPlaylistController_ = new _masterPlaylistController2['default'](this.options_);
  11863. // `this` in selectPlaylist should be the HlsHandler for backwards
  11864. // compatibility with < v2
  11865. this.masterPlaylistController_.selectPlaylist = Hls.STANDARD_PLAYLIST_SELECTOR.bind(this);
  11866. // re-expose some internal objects for backwards compatibility with < v2
  11867. this.playlists = this.masterPlaylistController_.masterPlaylistLoader_;
  11868. this.mediaSource = this.masterPlaylistController_.mediaSource;
  11869. // Proxy assignment of some properties to the master playlist
  11870. // controller. Using a custom property for backwards compatibility
  11871. // with < v2
  11872. Object.defineProperties(this, {
  11873. selectPlaylist: {
  11874. get: function get() {
  11875. return this.masterPlaylistController_.selectPlaylist;
  11876. },
  11877. set: function set(selectPlaylist) {
  11878. this.masterPlaylistController_.selectPlaylist = selectPlaylist.bind(this);
  11879. }
  11880. },
  11881. bandwidth: {
  11882. get: function get() {
  11883. return this.masterPlaylistController_.mainSegmentLoader_.bandwidth;
  11884. },
  11885. set: function set(bandwidth) {
  11886. this.masterPlaylistController_.mainSegmentLoader_.bandwidth = bandwidth;
  11887. }
  11888. }
  11889. });
  11890. this.tech_.one('canplay', this.masterPlaylistController_.setupFirstPlay.bind(this.masterPlaylistController_));
  11891. this.masterPlaylistController_.on('sourceopen', function () {
  11892. _this2.tech_.audioTracks().addEventListener('change', _this2.audioTrackChange_);
  11893. });
  11894. this.masterPlaylistController_.on('audioinfo', function (e) {
  11895. if (!_videoJs2['default'].browser.IS_FIREFOX || !_this2.audioInfo_ || !objectChanged(_this2.audioInfo_, e.info)) {
  11896. _this2.audioInfo_ = e.info;
  11897. return;
  11898. }
  11899. var error = 'had different audio properties (channels, sample rate, etc.) ' + 'or changed in some other way. This behavior is currently ' + 'unsupported in Firefox due to an issue: \n\n' + 'https://bugzilla.mozilla.org/show_bug.cgi?id=1247138\n\n';
  11900. var enabledTrack = undefined;
  11901. var defaultTrack = undefined;
  11902. _this2.masterPlaylistController_.audioTracks_.forEach(function (t) {
  11903. if (!defaultTrack && t['default']) {
  11904. defaultTrack = t;
  11905. }
  11906. if (!enabledTrack && t.enabled) {
  11907. enabledTrack = t;
  11908. }
  11909. });
  11910. // they did not switch audiotracks
  11911. // blacklist the current playlist
  11912. if (!enabledTrack.getLoader(_this2.activeAudioGroup_())) {
  11913. error = 'The rendition that we tried to switch to ' + error + 'Unfortunately that means we will have to blacklist ' + 'the current playlist and switch to another. Sorry!';
  11914. _this2.masterPlaylistController_.blacklistCurrentPlaylist();
  11915. } else {
  11916. error = 'The audio track \'' + enabledTrack.label + '\' that we tried to ' + ('switch to ' + error + ' Unfortunately this means we will have to ') + ('return you to the main track \'' + defaultTrack.label + '\'. Sorry!');
  11917. defaultTrack.enabled = true;
  11918. _this2.tech_.audioTracks().removeTrack(enabledTrack);
  11919. }
  11920. _videoJs2['default'].log.warn(error);
  11921. _this2.masterPlaylistController_.useAudio();
  11922. });
  11923. this.masterPlaylistController_.on('selectedinitialmedia', function () {
  11924. // clear current audioTracks
  11925. _this2.tech_.clearTracks('audio');
  11926. _this2.masterPlaylistController_.audioTracks_.forEach(function (track) {
  11927. _this2.tech_.audioTracks().addTrack(track);
  11928. });
  11929. });
  11930. // the bandwidth of the primary segment loader is our best
  11931. // estimate of overall bandwidth
  11932. this.on(this.masterPlaylistController_, 'progress', function () {
  11933. this.bandwidth = this.masterPlaylistController_.mainSegmentLoader_.bandwidth;
  11934. this.tech_.trigger('progress');
  11935. });
  11936. // do nothing if the tech has been disposed already
  11937. // this can occur if someone sets the src in player.ready(), for instance
  11938. if (!this.tech_.el()) {
  11939. return;
  11940. }
  11941. this.tech_.src(_videoJs2['default'].URL.createObjectURL(this.masterPlaylistController_.mediaSource));
  11942. }
  11943. /**
  11944. * a helper for grabbing the active audio group from MasterPlaylistController
  11945. *
  11946. * @private
  11947. */
  11948. }, {
  11949. key: 'activeAudioGroup_',
  11950. value: function activeAudioGroup_() {
  11951. return this.masterPlaylistController_.activeAudioGroup();
  11952. }
  11953. /**
  11954. * Begin playing the video.
  11955. */
  11956. }, {
  11957. key: 'play',
  11958. value: function play() {
  11959. this.masterPlaylistController_.play();
  11960. }
  11961. /**
  11962. * a wrapper around the function in MasterPlaylistController
  11963. */
  11964. }, {
  11965. key: 'setCurrentTime',
  11966. value: function setCurrentTime(currentTime) {
  11967. this.masterPlaylistController_.setCurrentTime(currentTime);
  11968. }
  11969. /**
  11970. * a wrapper around the function in MasterPlaylistController
  11971. */
  11972. }, {
  11973. key: 'duration',
  11974. value: function duration() {
  11975. return this.masterPlaylistController_.duration();
  11976. }
  11977. /**
  11978. * a wrapper around the function in MasterPlaylistController
  11979. */
  11980. }, {
  11981. key: 'seekable',
  11982. value: function seekable() {
  11983. return this.masterPlaylistController_.seekable();
  11984. }
  11985. /**
  11986. * Abort all outstanding work and cleanup.
  11987. */
  11988. }, {
  11989. key: 'dispose',
  11990. value: function dispose() {
  11991. if (this.masterPlaylistController_) {
  11992. this.masterPlaylistController_.dispose();
  11993. }
  11994. this.tech_.audioTracks().removeEventListener('change', this.audioTrackChange_);
  11995. _get(Object.getPrototypeOf(HlsHandler.prototype), 'dispose', this).call(this);
  11996. }
  11997. }]);
  11998. return HlsHandler;
  11999. })(Component);
  12000. var HlsSourceHandler = function HlsSourceHandler(mode) {
  12001. return {
  12002. canHandleSource: function canHandleSource(srcObj) {
  12003. // this forces video.js to skip this tech/mode if its not the one we have been
  12004. // overriden to use, by returing that we cannot handle the source.
  12005. if (_videoJs2['default'].options.hls && _videoJs2['default'].options.hls.mode && _videoJs2['default'].options.hls.mode !== mode) {
  12006. return false;
  12007. }
  12008. return HlsSourceHandler.canPlayType(srcObj.type);
  12009. },
  12010. handleSource: function handleSource(source, tech, options) {
  12011. if (mode === 'flash') {
  12012. // We need to trigger this asynchronously to give others the chance
  12013. // to bind to the event when a source is set at player creation
  12014. tech.setTimeout(function () {
  12015. tech.trigger('loadstart');
  12016. }, 1);
  12017. }
  12018. var settings = _videoJs2['default'].mergeOptions(options, { hls: { mode: mode } });
  12019. tech.hls = new HlsHandler(source, tech, settings);
  12020. tech.hls.xhr = (0, _xhr2['default'])();
  12021. // Use a global `before` function if specified on videojs.Hls.xhr
  12022. // but still allow for a per-player override
  12023. if (_videoJs2['default'].Hls.xhr.beforeRequest) {
  12024. tech.hls.xhr.beforeRequest = _videoJs2['default'].Hls.xhr.beforeRequest;
  12025. }
  12026. tech.hls.src(source.src);
  12027. return tech.hls;
  12028. },
  12029. canPlayType: function canPlayType(type) {
  12030. if (HlsSourceHandler.canPlayType(type)) {
  12031. return 'maybe';
  12032. }
  12033. return '';
  12034. }
  12035. };
  12036. };
  12037. /**
  12038. * A comparator function to sort two playlist object by bandwidth.
  12039. *
  12040. * @param {Object} left a media playlist object
  12041. * @param {Object} right a media playlist object
  12042. * @return {Number} Greater than zero if the bandwidth attribute of
  12043. * left is greater than the corresponding attribute of right. Less
  12044. * than zero if the bandwidth of right is greater than left and
  12045. * exactly zero if the two are equal.
  12046. */
  12047. Hls.comparePlaylistBandwidth = function (left, right) {
  12048. var leftBandwidth = undefined;
  12049. var rightBandwidth = undefined;
  12050. if (left.attributes && left.attributes.BANDWIDTH) {
  12051. leftBandwidth = left.attributes.BANDWIDTH;
  12052. }
  12053. leftBandwidth = leftBandwidth || window.Number.MAX_VALUE;
  12054. if (right.attributes && right.attributes.BANDWIDTH) {
  12055. rightBandwidth = right.attributes.BANDWIDTH;
  12056. }
  12057. rightBandwidth = rightBandwidth || window.Number.MAX_VALUE;
  12058. return leftBandwidth - rightBandwidth;
  12059. };
  12060. /**
  12061. * A comparator function to sort two playlist object by resolution (width).
  12062. * @param {Object} left a media playlist object
  12063. * @param {Object} right a media playlist object
  12064. * @return {Number} Greater than zero if the resolution.width attribute of
  12065. * left is greater than the corresponding attribute of right. Less
  12066. * than zero if the resolution.width of right is greater than left and
  12067. * exactly zero if the two are equal.
  12068. */
  12069. Hls.comparePlaylistResolution = function (left, right) {
  12070. var leftWidth = undefined;
  12071. var rightWidth = undefined;
  12072. if (left.attributes && left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
  12073. leftWidth = left.attributes.RESOLUTION.width;
  12074. }
  12075. leftWidth = leftWidth || window.Number.MAX_VALUE;
  12076. if (right.attributes && right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
  12077. rightWidth = right.attributes.RESOLUTION.width;
  12078. }
  12079. rightWidth = rightWidth || window.Number.MAX_VALUE;
  12080. // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
  12081. // have the same media dimensions/ resolution
  12082. if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
  12083. return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
  12084. }
  12085. return leftWidth - rightWidth;
  12086. };
  12087. HlsSourceHandler.canPlayType = function (type) {
  12088. var mpegurlRE = /^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i;
  12089. // favor native HLS support if it's available
  12090. if (Hls.supportsNativeHls) {
  12091. return false;
  12092. }
  12093. return mpegurlRE.test(type);
  12094. };
  12095. if (typeof _videoJs2['default'].MediaSource === 'undefined' || typeof _videoJs2['default'].URL === 'undefined') {
  12096. _videoJs2['default'].MediaSource = _videojsContribMediaSources.MediaSource;
  12097. _videoJs2['default'].URL = _videojsContribMediaSources.URL;
  12098. }
  12099. // register source handlers with the appropriate techs
  12100. if (_videojsContribMediaSources.MediaSource.supportsNativeMediaSources()) {
  12101. _videoJs2['default'].getComponent('Html5').registerSourceHandler(HlsSourceHandler('html5'));
  12102. }
  12103. if (window.Uint8Array) {
  12104. _videoJs2['default'].getComponent('Flash').registerSourceHandler(HlsSourceHandler('flash'));
  12105. }
  12106. _videoJs2['default'].HlsHandler = HlsHandler;
  12107. _videoJs2['default'].HlsSourceHandler = HlsSourceHandler;
  12108. _videoJs2['default'].Hls = Hls;
  12109. _videoJs2['default'].m3u8 = _m3u82['default'];
  12110. _videoJs2['default'].registerComponent('Hls', Hls);
  12111. _videoJs2['default'].options.hls = _videoJs2['default'].options.hls || {};
  12112. module.exports = {
  12113. Hls: Hls,
  12114. HlsHandler: HlsHandler,
  12115. HlsSourceHandler: HlsSourceHandler
  12116. };
  12117. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12118. },{"./bin-utils":1,"./decrypter":5,"./m3u8":7,"./master-playlist-controller":11,"./playlist":13,"./playlist-loader":12,"./xhr":19,"global/document":21,"videojs-contrib-media-sources":34}]},{},[57])(57)
  12119. });