videojs-contrib-hls.js 456 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077
  1. /**
  2. * videojs-contrib-hls
  3. * @version 3.0.2
  4. * @copyright 2016 Brightcove, Inc
  5. * @license Apache-2.0
  6. */
  7. (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){
  8. /**
  9. * @file bin-utils.js
  10. */
  11. /**
  12. * convert a TimeRange to text
  13. *
  14. * @param {TimeRange} range the timerange to use for conversion
  15. * @param {Number} i the iterator on the range to convert
  16. */
  17. 'use strict';
  18. Object.defineProperty(exports, '__esModule', {
  19. value: true
  20. });
  21. var textRange = function textRange(range, i) {
  22. return range.start(i) + '-' + range.end(i);
  23. };
  24. /**
  25. * format a number as hex string
  26. *
  27. * @param {Number} e The number
  28. * @param {Number} i the iterator
  29. */
  30. var formatHexString = function formatHexString(e, i) {
  31. var value = e.toString(16);
  32. return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
  33. };
  34. var formatAsciiString = function formatAsciiString(e) {
  35. if (e >= 0x20 && e < 0x7e) {
  36. return String.fromCharCode(e);
  37. }
  38. return '.';
  39. };
  40. /**
  41. * utils to help dump binary data to the console
  42. */
  43. var utils = {
  44. hexDump: function hexDump(data) {
  45. var bytes = Array.prototype.slice.call(data);
  46. var step = 16;
  47. var result = '';
  48. var hex = undefined;
  49. var ascii = undefined;
  50. for (var j = 0; j < bytes.length / step; j++) {
  51. hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
  52. ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
  53. result += hex + ' ' + ascii + '\n';
  54. }
  55. return result;
  56. },
  57. tagDump: function tagDump(tag) {
  58. return utils.hexDump(tag.bytes);
  59. },
  60. textRanges: function textRanges(ranges) {
  61. var result = '';
  62. var i = undefined;
  63. for (i = 0; i < ranges.length; i++) {
  64. result += textRange(ranges, i) + ' ';
  65. }
  66. return result;
  67. }
  68. };
  69. exports['default'] = utils;
  70. module.exports = exports['default'];
  71. },{}],2:[function(require,module,exports){
  72. /**
  73. * @file decrypter/aes.js
  74. *
  75. * This file contains an adaptation of the AES decryption algorithm
  76. * from the Standford Javascript Cryptography Library. That work is
  77. * covered by the following copyright and permissions notice:
  78. *
  79. * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  80. * All rights reserved.
  81. *
  82. * Redistribution and use in source and binary forms, with or without
  83. * modification, are permitted provided that the following conditions are
  84. * met:
  85. *
  86. * 1. Redistributions of source code must retain the above copyright
  87. * notice, this list of conditions and the following disclaimer.
  88. *
  89. * 2. Redistributions in binary form must reproduce the above
  90. * copyright notice, this list of conditions and the following
  91. * disclaimer in the documentation and/or other materials provided
  92. * with the distribution.
  93. *
  94. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  95. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  96. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  97. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  98. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  99. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  100. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  101. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  102. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  103. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  104. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  105. *
  106. * The views and conclusions contained in the software and documentation
  107. * are those of the authors and should not be interpreted as representing
  108. * official policies, either expressed or implied, of the authors.
  109. */
  110. /**
  111. * Expand the S-box tables.
  112. *
  113. * @private
  114. */
  115. 'use strict';
  116. Object.defineProperty(exports, '__esModule', {
  117. value: true
  118. });
  119. 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; }; })();
  120. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  121. var precompute = function precompute() {
  122. var tables = [[[], [], [], [], []], [[], [], [], [], []]];
  123. var encTable = tables[0];
  124. var decTable = tables[1];
  125. var sbox = encTable[4];
  126. var sboxInv = decTable[4];
  127. var i = undefined;
  128. var x = undefined;
  129. var xInv = undefined;
  130. var d = [];
  131. var th = [];
  132. var x2 = undefined;
  133. var x4 = undefined;
  134. var x8 = undefined;
  135. var s = undefined;
  136. var tEnc = undefined;
  137. var tDec = undefined;
  138. // Compute double and third tables
  139. for (i = 0; i < 256; i++) {
  140. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  141. }
  142. for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  143. // Compute sbox
  144. s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  145. s = s >> 8 ^ s & 255 ^ 99;
  146. sbox[x] = s;
  147. sboxInv[s] = x;
  148. // Compute MixColumns
  149. x8 = d[x4 = d[x2 = d[x]]];
  150. tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  151. tEnc = d[s] * 0x101 ^ s * 0x1010100;
  152. for (i = 0; i < 4; i++) {
  153. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  154. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  155. }
  156. }
  157. // Compactify. Considerable speedup on Firefox.
  158. for (i = 0; i < 5; i++) {
  159. encTable[i] = encTable[i].slice(0);
  160. decTable[i] = decTable[i].slice(0);
  161. }
  162. return tables;
  163. };
  164. var aesTables = null;
  165. /**
  166. * Schedule out an AES key for both encryption and decryption. This
  167. * is a low-level class. Use a cipher mode to do bulk encryption.
  168. *
  169. * @class AES
  170. * @param key {Array} The key as an array of 4, 6 or 8 words.
  171. */
  172. var AES = (function () {
  173. function AES(key) {
  174. _classCallCheck(this, AES);
  175. /**
  176. * The expanded S-box and inverse S-box tables. These will be computed
  177. * on the client so that we don't have to send them down the wire.
  178. *
  179. * There are two tables, _tables[0] is for encryption and
  180. * _tables[1] is for decryption.
  181. *
  182. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  183. * last (_tables[01][4]) is the S-box itself.
  184. *
  185. * @private
  186. */
  187. // if we have yet to precompute the S-box tables
  188. // do so now
  189. if (!aesTables) {
  190. aesTables = precompute();
  191. }
  192. // then make a copy of that object for use
  193. 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()]];
  194. var i = undefined;
  195. var j = undefined;
  196. var tmp = undefined;
  197. var encKey = undefined;
  198. var decKey = undefined;
  199. var sbox = this._tables[0][4];
  200. var decTable = this._tables[1];
  201. var keyLen = key.length;
  202. var rcon = 1;
  203. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  204. throw new Error('Invalid aes key size');
  205. }
  206. encKey = key.slice(0);
  207. decKey = [];
  208. this._key = [encKey, decKey];
  209. // schedule encryption keys
  210. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  211. tmp = encKey[i - 1];
  212. // apply sbox
  213. if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
  214. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255];
  215. // shift rows and add rcon
  216. if (i % keyLen === 0) {
  217. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  218. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  219. }
  220. }
  221. encKey[i] = encKey[i - keyLen] ^ tmp;
  222. }
  223. // schedule decryption keys
  224. for (j = 0; i; j++, i--) {
  225. tmp = encKey[j & 3 ? i : i - 4];
  226. if (i <= 4 || j < 4) {
  227. decKey[j] = tmp;
  228. } else {
  229. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
  230. }
  231. }
  232. }
  233. /**
  234. * Decrypt 16 bytes, specified as four 32-bit words.
  235. *
  236. * @param {Number} encrypted0 the first word to decrypt
  237. * @param {Number} encrypted1 the second word to decrypt
  238. * @param {Number} encrypted2 the third word to decrypt
  239. * @param {Number} encrypted3 the fourth word to decrypt
  240. * @param {Int32Array} out the array to write the decrypted words
  241. * into
  242. * @param {Number} offset the offset into the output array to start
  243. * writing results
  244. * @return {Array} The plaintext.
  245. */
  246. _createClass(AES, [{
  247. key: 'decrypt',
  248. value: function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
  249. var key = this._key[1];
  250. // state variables a,b,c,d are loaded with pre-whitened data
  251. var a = encrypted0 ^ key[0];
  252. var b = encrypted3 ^ key[1];
  253. var c = encrypted2 ^ key[2];
  254. var d = encrypted1 ^ key[3];
  255. var a2 = undefined;
  256. var b2 = undefined;
  257. var c2 = undefined;
  258. // key.length === 2 ?
  259. var nInnerRounds = key.length / 4 - 2;
  260. var i = undefined;
  261. var kIndex = 4;
  262. var table = this._tables[1];
  263. // load up the tables
  264. var table0 = table[0];
  265. var table1 = table[1];
  266. var table2 = table[2];
  267. var table3 = table[3];
  268. var sbox = table[4];
  269. // Inner rounds. Cribbed from OpenSSL.
  270. for (i = 0; i < nInnerRounds; i++) {
  271. a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
  272. b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
  273. c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
  274. d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
  275. kIndex += 4;
  276. a = a2;b = b2;c = c2;
  277. }
  278. // Last round.
  279. for (i = 0; i < 4; i++) {
  280. out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
  281. a2 = a;a = b;b = c;c = d;d = a2;
  282. }
  283. }
  284. }]);
  285. return AES;
  286. })();
  287. exports['default'] = AES;
  288. module.exports = exports['default'];
  289. },{}],3:[function(require,module,exports){
  290. /**
  291. * @file decrypter/async-stream.js
  292. */
  293. 'use strict';
  294. Object.defineProperty(exports, '__esModule', {
  295. value: true
  296. });
  297. 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; }; })();
  298. 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); } } };
  299. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  300. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  301. 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; }
  302. var _stream = require('../stream');
  303. var _stream2 = _interopRequireDefault(_stream);
  304. /**
  305. * A wrapper around the Stream class to use setTiemout
  306. * and run stream "jobs" Asynchronously
  307. *
  308. * @class AsyncStream
  309. * @extends Stream
  310. */
  311. var AsyncStream = (function (_Stream) {
  312. _inherits(AsyncStream, _Stream);
  313. function AsyncStream() {
  314. _classCallCheck(this, AsyncStream);
  315. _get(Object.getPrototypeOf(AsyncStream.prototype), 'constructor', this).call(this, _stream2['default']);
  316. this.jobs = [];
  317. this.delay = 1;
  318. this.timeout_ = null;
  319. }
  320. /**
  321. * process an async job
  322. *
  323. * @private
  324. */
  325. _createClass(AsyncStream, [{
  326. key: 'processJob_',
  327. value: function processJob_() {
  328. this.jobs.shift()();
  329. if (this.jobs.length) {
  330. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  331. } else {
  332. this.timeout_ = null;
  333. }
  334. }
  335. /**
  336. * push a job into the stream
  337. *
  338. * @param {Function} job the job to push into the stream
  339. */
  340. }, {
  341. key: 'push',
  342. value: function push(job) {
  343. this.jobs.push(job);
  344. if (!this.timeout_) {
  345. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  346. }
  347. }
  348. }]);
  349. return AsyncStream;
  350. })(_stream2['default']);
  351. exports['default'] = AsyncStream;
  352. module.exports = exports['default'];
  353. },{"../stream":18}],4:[function(require,module,exports){
  354. /**
  355. * @file decrypter/decrypter.js
  356. *
  357. * An asynchronous implementation of AES-128 CBC decryption with
  358. * PKCS#7 padding.
  359. */
  360. 'use strict';
  361. Object.defineProperty(exports, '__esModule', {
  362. value: true
  363. });
  364. 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; }; })();
  365. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  366. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  367. var _aes = require('./aes');
  368. var _aes2 = _interopRequireDefault(_aes);
  369. var _asyncStream = require('./async-stream');
  370. var _asyncStream2 = _interopRequireDefault(_asyncStream);
  371. var _pkcs7 = require('pkcs7');
  372. /**
  373. * Convert network-order (big-endian) bytes into their little-endian
  374. * representation.
  375. */
  376. var ntoh = function ntoh(word) {
  377. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  378. };
  379. /**
  380. * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
  381. *
  382. * @param {Uint8Array} encrypted the encrypted bytes
  383. * @param {Uint32Array} key the bytes of the decryption key
  384. * @param {Uint32Array} initVector the initialization vector (IV) to
  385. * use for the first round of CBC.
  386. * @return {Uint8Array} the decrypted bytes
  387. *
  388. * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  389. * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
  390. * @see https://tools.ietf.org/html/rfc2315
  391. */
  392. var decrypt = function decrypt(encrypted, key, initVector) {
  393. // word-level access to the encrypted bytes
  394. var encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
  395. var decipher = new _aes2['default'](Array.prototype.slice.call(key));
  396. // byte and word-level access for the decrypted output
  397. var decrypted = new Uint8Array(encrypted.byteLength);
  398. var decrypted32 = new Int32Array(decrypted.buffer);
  399. // temporary variables for working with the IV, encrypted, and
  400. // decrypted data
  401. var init0 = undefined;
  402. var init1 = undefined;
  403. var init2 = undefined;
  404. var init3 = undefined;
  405. var encrypted0 = undefined;
  406. var encrypted1 = undefined;
  407. var encrypted2 = undefined;
  408. var encrypted3 = undefined;
  409. // iteration variable
  410. var wordIx = undefined;
  411. // pull out the words of the IV to ensure we don't modify the
  412. // passed-in reference and easier access
  413. init0 = initVector[0];
  414. init1 = initVector[1];
  415. init2 = initVector[2];
  416. init3 = initVector[3];
  417. // decrypt four word sequences, applying cipher-block chaining (CBC)
  418. // to each decrypted block
  419. for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
  420. // convert big-endian (network order) words into little-endian
  421. // (javascript order)
  422. encrypted0 = ntoh(encrypted32[wordIx]);
  423. encrypted1 = ntoh(encrypted32[wordIx + 1]);
  424. encrypted2 = ntoh(encrypted32[wordIx + 2]);
  425. encrypted3 = ntoh(encrypted32[wordIx + 3]);
  426. // decrypt the block
  427. decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx);
  428. // XOR with the IV, and restore network byte-order to obtain the
  429. // plaintext
  430. decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
  431. decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
  432. decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
  433. decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3);
  434. // setup the IV for the next round
  435. init0 = encrypted0;
  436. init1 = encrypted1;
  437. init2 = encrypted2;
  438. init3 = encrypted3;
  439. }
  440. return decrypted;
  441. };
  442. exports.decrypt = decrypt;
  443. /**
  444. * The `Decrypter` class that manages decryption of AES
  445. * data through `AsyncStream` objects and the `decrypt`
  446. * function
  447. *
  448. * @param {Uint8Array} encrypted the encrypted bytes
  449. * @param {Uint32Array} key the bytes of the decryption key
  450. * @param {Uint32Array} initVector the initialization vector (IV) to
  451. * @param {Function} done the function to run when done
  452. * @class Decrypter
  453. */
  454. var Decrypter = (function () {
  455. function Decrypter(encrypted, key, initVector, done) {
  456. _classCallCheck(this, Decrypter);
  457. var step = Decrypter.STEP;
  458. var encrypted32 = new Int32Array(encrypted.buffer);
  459. var decrypted = new Uint8Array(encrypted.byteLength);
  460. var i = 0;
  461. this.asyncStream_ = new _asyncStream2['default']();
  462. // split up the encryption job and do the individual chunks asynchronously
  463. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  464. for (i = step; i < encrypted32.length; i += step) {
  465. initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
  466. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  467. }
  468. // invoke the done() callback when everything is finished
  469. this.asyncStream_.push(function () {
  470. // remove pkcs#7 padding from the decrypted bytes
  471. done(null, (0, _pkcs7.unpad)(decrypted));
  472. });
  473. }
  474. /**
  475. * a getter for step the maximum number of bytes to process at one time
  476. *
  477. * @return {Number} the value of step 32000
  478. */
  479. _createClass(Decrypter, [{
  480. key: 'decryptChunk_',
  481. /**
  482. * @private
  483. */
  484. value: function decryptChunk_(encrypted, key, initVector, decrypted) {
  485. return function () {
  486. var bytes = decrypt(encrypted, key, initVector);
  487. decrypted.set(bytes, encrypted.byteOffset);
  488. };
  489. }
  490. }], [{
  491. key: 'STEP',
  492. get: function get() {
  493. // 4 * 8000;
  494. return 32000;
  495. }
  496. }]);
  497. return Decrypter;
  498. })();
  499. exports.Decrypter = Decrypter;
  500. exports['default'] = {
  501. Decrypter: Decrypter,
  502. decrypt: decrypt
  503. };
  504. },{"./aes":2,"./async-stream":3,"pkcs7":23}],5:[function(require,module,exports){
  505. /**
  506. * @file decrypter/index.js
  507. *
  508. * Index module to easily import the primary components of AES-128
  509. * decryption. Like this:
  510. *
  511. * ```js
  512. * import {Decrypter, decrypt, AsyncStream} from './src/decrypter';
  513. * ```
  514. */
  515. 'use strict';
  516. Object.defineProperty(exports, '__esModule', {
  517. value: true
  518. });
  519. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  520. var _decrypter = require('./decrypter');
  521. var _asyncStream = require('./async-stream');
  522. var _asyncStream2 = _interopRequireDefault(_asyncStream);
  523. exports['default'] = {
  524. decrypt: _decrypter.decrypt,
  525. Decrypter: _decrypter.Decrypter,
  526. AsyncStream: _asyncStream2['default']
  527. };
  528. module.exports = exports['default'];
  529. },{"./async-stream":3,"./decrypter":4}],6:[function(require,module,exports){
  530. (function (global){
  531. /**
  532. * @file hls-audio-track.js
  533. */
  534. 'use strict';
  535. Object.defineProperty(exports, '__esModule', {
  536. value: true
  537. });
  538. 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; }; })();
  539. 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); } } };
  540. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  541. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  542. 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; }
  543. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  544. var _playlistLoader = require('./playlist-loader');
  545. var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
  546. /**
  547. * HlsAudioTrack extends video.js audio tracks but adds HLS
  548. * specific data storage such as playlist loaders, mediaGroups
  549. * and default/autoselect
  550. *
  551. * @param {Object} options options to create HlsAudioTrack with
  552. * @class HlsAudioTrack
  553. * @extends AudioTrack
  554. */
  555. var HlsAudioTrack = (function (_AudioTrack) {
  556. _inherits(HlsAudioTrack, _AudioTrack);
  557. function HlsAudioTrack(options) {
  558. _classCallCheck(this, HlsAudioTrack);
  559. _get(Object.getPrototypeOf(HlsAudioTrack.prototype), 'constructor', this).call(this, {
  560. kind: options['default'] ? 'main' : 'alternative',
  561. enabled: options['default'] || false,
  562. language: options.language,
  563. label: options.label
  564. });
  565. this.hls = options.hls;
  566. this.autoselect = options.autoselect || false;
  567. this['default'] = options['default'] || false;
  568. this.withCredentials = options.withCredentials || false;
  569. this.mediaGroups_ = [];
  570. this.addLoader(options.mediaGroup, options.resolvedUri);
  571. }
  572. /**
  573. * get a PlaylistLoader from this track given a mediaGroup name
  574. *
  575. * @param {String} mediaGroup the mediaGroup to get the loader for
  576. * @return {PlaylistLoader|Null} the PlaylistLoader or null
  577. */
  578. _createClass(HlsAudioTrack, [{
  579. key: 'getLoader',
  580. value: function getLoader(mediaGroup) {
  581. for (var i = 0; i < this.mediaGroups_.length; i++) {
  582. var mgl = this.mediaGroups_[i];
  583. if (mgl.mediaGroup === mediaGroup) {
  584. return mgl.loader;
  585. }
  586. }
  587. }
  588. /**
  589. * add a PlaylistLoader given a mediaGroup, and a uri. for a combined track
  590. * we store null for the playlistloader
  591. *
  592. * @param {String} mediaGroup the mediaGroup to get the loader for
  593. * @param {String} uri the uri to get the audio track/mediaGroup from
  594. */
  595. }, {
  596. key: 'addLoader',
  597. value: function addLoader(mediaGroup) {
  598. var uri = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  599. var loader = null;
  600. if (uri) {
  601. // TODO: this should probably happen upstream in Master Playlist
  602. // Controller when we can switch PlaylistLoader sources
  603. // then we can just store the uri here instead
  604. loader = new _playlistLoader2['default'](uri, this.hls, this.withCredentials);
  605. }
  606. this.mediaGroups_.push({ mediaGroup: mediaGroup, loader: loader });
  607. }
  608. /**
  609. * remove a playlist loader from a track given the mediaGroup
  610. *
  611. * @param {String} mediaGroup the mediaGroup to remove
  612. */
  613. }, {
  614. key: 'removeLoader',
  615. value: function removeLoader(mediaGroup) {
  616. for (var i = 0; i < this.mediaGroups_.length; i++) {
  617. var mgl = this.mediaGroups_[i];
  618. if (mgl.mediaGroup === mediaGroup) {
  619. if (mgl.loader) {
  620. mgl.loader.dispose();
  621. }
  622. this.mediaGroups_.splice(i, 1);
  623. return;
  624. }
  625. }
  626. }
  627. /**
  628. * Dispose of this audio track and
  629. * the playlist loader that it holds inside
  630. */
  631. }, {
  632. key: 'dispose',
  633. value: function dispose() {
  634. var i = this.mediaGroups_.length;
  635. while (i--) {
  636. this.removeLoader(this.mediaGroups_[i].mediaGroup);
  637. }
  638. }
  639. }]);
  640. return HlsAudioTrack;
  641. })(_videoJs.AudioTrack);
  642. exports['default'] = HlsAudioTrack;
  643. module.exports = exports['default'];
  644. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  645. },{"./playlist-loader":12}],7:[function(require,module,exports){
  646. /**
  647. * @file m3u8/index.js
  648. *
  649. * Utilities for parsing M3U8 files. If the entire manifest is available,
  650. * `Parser` will create an object representation with enough detail for managing
  651. * playback. `ParseStream` and `LineStream` are lower-level parsing primitives
  652. * that do not assume the entirety of the manifest is ready and expose a
  653. * ReadableStream-like interface.
  654. */
  655. 'use strict';
  656. Object.defineProperty(exports, '__esModule', {
  657. value: true
  658. });
  659. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  660. var _lineStream = require('./line-stream');
  661. var _lineStream2 = _interopRequireDefault(_lineStream);
  662. var _parseStream = require('./parse-stream');
  663. var _parseStream2 = _interopRequireDefault(_parseStream);
  664. var _parser = require('./parser');
  665. var _parser2 = _interopRequireDefault(_parser);
  666. exports['default'] = {
  667. LineStream: _lineStream2['default'],
  668. ParseStream: _parseStream2['default'],
  669. Parser: _parser2['default']
  670. };
  671. module.exports = exports['default'];
  672. },{"./line-stream":8,"./parse-stream":9,"./parser":10}],8:[function(require,module,exports){
  673. /**
  674. * @file m3u8/line-stream.js
  675. */
  676. 'use strict';
  677. Object.defineProperty(exports, '__esModule', {
  678. value: true
  679. });
  680. 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; }; })();
  681. 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); } } };
  682. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  683. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  684. 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; }
  685. var _stream = require('../stream');
  686. var _stream2 = _interopRequireDefault(_stream);
  687. /**
  688. * A stream that buffers string input and generates a `data` event for each
  689. * line.
  690. *
  691. * @class LineStream
  692. * @extends Stream
  693. */
  694. var LineStream = (function (_Stream) {
  695. _inherits(LineStream, _Stream);
  696. function LineStream() {
  697. _classCallCheck(this, LineStream);
  698. _get(Object.getPrototypeOf(LineStream.prototype), 'constructor', this).call(this);
  699. this.buffer = '';
  700. }
  701. /**
  702. * Add new data to be parsed.
  703. *
  704. * @param {String} data the text to process
  705. */
  706. _createClass(LineStream, [{
  707. key: 'push',
  708. value: function push(data) {
  709. var nextNewline = undefined;
  710. this.buffer += data;
  711. nextNewline = this.buffer.indexOf('\n');
  712. for (; nextNewline > -1; nextNewline = this.buffer.indexOf('\n')) {
  713. this.trigger('data', this.buffer.substring(0, nextNewline));
  714. this.buffer = this.buffer.substring(nextNewline + 1);
  715. }
  716. }
  717. }]);
  718. return LineStream;
  719. })(_stream2['default']);
  720. exports['default'] = LineStream;
  721. module.exports = exports['default'];
  722. },{"../stream":18}],9:[function(require,module,exports){
  723. /**
  724. * @file m3u8/parse-stream.js
  725. */
  726. 'use strict';
  727. Object.defineProperty(exports, '__esModule', {
  728. value: true
  729. });
  730. 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; }; })();
  731. 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); } } };
  732. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  733. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  734. 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; }
  735. var _stream = require('../stream');
  736. var _stream2 = _interopRequireDefault(_stream);
  737. /**
  738. * "forgiving" attribute list psuedo-grammar:
  739. * attributes -> keyvalue (',' keyvalue)*
  740. * keyvalue -> key '=' value
  741. * key -> [^=]*
  742. * value -> '"' [^"]* '"' | [^,]*
  743. */
  744. var attributeSeparator = function attributeSeparator() {
  745. var key = '[^=]*';
  746. var value = '"[^"]*"|[^,]*';
  747. var keyvalue = '(?:' + key + ')=(?:' + value + ')';
  748. return new RegExp('(?:^|,)(' + keyvalue + ')');
  749. };
  750. /**
  751. * Parse attributes from a line given the seperator
  752. *
  753. * @param {String} attributes the attibute line to parse
  754. */
  755. var parseAttributes = function parseAttributes(attributes) {
  756. // split the string using attributes as the separator
  757. var attrs = attributes.split(attributeSeparator());
  758. var i = attrs.length;
  759. var result = {};
  760. var attr = undefined;
  761. while (i--) {
  762. // filter out unmatched portions of the string
  763. if (attrs[i] === '') {
  764. continue;
  765. }
  766. // split the key and value
  767. attr = /([^=]*)=(.*)/.exec(attrs[i]).slice(1);
  768. // trim whitespace and remove optional quotes around the value
  769. attr[0] = attr[0].replace(/^\s+|\s+$/g, '');
  770. attr[1] = attr[1].replace(/^\s+|\s+$/g, '');
  771. attr[1] = attr[1].replace(/^['"](.*)['"]$/g, '$1');
  772. result[attr[0]] = attr[1];
  773. }
  774. return result;
  775. };
  776. /**
  777. * A line-level M3U8 parser event stream. It expects to receive input one
  778. * line at a time and performs a context-free parse of its contents. A stream
  779. * interpretation of a manifest can be useful if the manifest is expected to
  780. * be too large to fit comfortably into memory or the entirety of the input
  781. * is not immediately available. Otherwise, it's probably much easier to work
  782. * with a regular `Parser` object.
  783. *
  784. * Produces `data` events with an object that captures the parser's
  785. * interpretation of the input. That object has a property `tag` that is one
  786. * of `uri`, `comment`, or `tag`. URIs only have a single additional
  787. * property, `line`, which captures the entirety of the input without
  788. * interpretation. Comments similarly have a single additional property
  789. * `text` which is the input without the leading `#`.
  790. *
  791. * Tags always have a property `tagType` which is the lower-cased version of
  792. * the M3U8 directive without the `#EXT` or `#EXT-X-` prefix. For instance,
  793. * `#EXT-X-MEDIA-SEQUENCE` becomes `media-sequence` when parsed. Unrecognized
  794. * tags are given the tag type `unknown` and a single additional property
  795. * `data` with the remainder of the input.
  796. *
  797. * @class ParseStream
  798. * @extends Stream
  799. */
  800. var ParseStream = (function (_Stream) {
  801. _inherits(ParseStream, _Stream);
  802. function ParseStream() {
  803. _classCallCheck(this, ParseStream);
  804. _get(Object.getPrototypeOf(ParseStream.prototype), 'constructor', this).call(this);
  805. }
  806. /**
  807. * Parses an additional line of input.
  808. *
  809. * @param {String} line a single line of an M3U8 file to parse
  810. */
  811. _createClass(ParseStream, [{
  812. key: 'push',
  813. value: function push(line) {
  814. var match = undefined;
  815. var event = undefined;
  816. // strip whitespace
  817. line = line.replace(/^[\u0000\s]+|[\u0000\s]+$/g, '');
  818. if (line.length === 0) {
  819. // ignore empty lines
  820. return;
  821. }
  822. // URIs
  823. if (line[0] !== '#') {
  824. this.trigger('data', {
  825. type: 'uri',
  826. uri: line
  827. });
  828. return;
  829. }
  830. // Comments
  831. if (line.indexOf('#EXT') !== 0) {
  832. this.trigger('data', {
  833. type: 'comment',
  834. text: line.slice(1)
  835. });
  836. return;
  837. }
  838. // strip off any carriage returns here so the regex matching
  839. // doesn't have to account for them.
  840. line = line.replace('\r', '');
  841. // Tags
  842. match = /^#EXTM3U/.exec(line);
  843. if (match) {
  844. this.trigger('data', {
  845. type: 'tag',
  846. tagType: 'm3u'
  847. });
  848. return;
  849. }
  850. match = /^#EXTINF:?([0-9\.]*)?,?(.*)?$/.exec(line);
  851. if (match) {
  852. event = {
  853. type: 'tag',
  854. tagType: 'inf'
  855. };
  856. if (match[1]) {
  857. event.duration = parseFloat(match[1]);
  858. }
  859. if (match[2]) {
  860. event.title = match[2];
  861. }
  862. this.trigger('data', event);
  863. return;
  864. }
  865. match = /^#EXT-X-TARGETDURATION:?([0-9.]*)?/.exec(line);
  866. if (match) {
  867. event = {
  868. type: 'tag',
  869. tagType: 'targetduration'
  870. };
  871. if (match[1]) {
  872. event.duration = parseInt(match[1], 10);
  873. }
  874. this.trigger('data', event);
  875. return;
  876. }
  877. match = /^#ZEN-TOTAL-DURATION:?([0-9.]*)?/.exec(line);
  878. if (match) {
  879. event = {
  880. type: 'tag',
  881. tagType: 'totalduration'
  882. };
  883. if (match[1]) {
  884. event.duration = parseInt(match[1], 10);
  885. }
  886. this.trigger('data', event);
  887. return;
  888. }
  889. match = /^#EXT-X-VERSION:?([0-9.]*)?/.exec(line);
  890. if (match) {
  891. event = {
  892. type: 'tag',
  893. tagType: 'version'
  894. };
  895. if (match[1]) {
  896. event.version = parseInt(match[1], 10);
  897. }
  898. this.trigger('data', event);
  899. return;
  900. }
  901. match = /^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(line);
  902. if (match) {
  903. event = {
  904. type: 'tag',
  905. tagType: 'media-sequence'
  906. };
  907. if (match[1]) {
  908. event.number = parseInt(match[1], 10);
  909. }
  910. this.trigger('data', event);
  911. return;
  912. }
  913. match = /^#EXT-X-DISCONTINUITY-SEQUENCE:?(\-?[0-9.]*)?/.exec(line);
  914. if (match) {
  915. event = {
  916. type: 'tag',
  917. tagType: 'discontinuity-sequence'
  918. };
  919. if (match[1]) {
  920. event.number = parseInt(match[1], 10);
  921. }
  922. this.trigger('data', event);
  923. return;
  924. }
  925. match = /^#EXT-X-PLAYLIST-TYPE:?(.*)?$/.exec(line);
  926. if (match) {
  927. event = {
  928. type: 'tag',
  929. tagType: 'playlist-type'
  930. };
  931. if (match[1]) {
  932. event.playlistType = match[1];
  933. }
  934. this.trigger('data', event);
  935. return;
  936. }
  937. match = /^#EXT-X-BYTERANGE:?([0-9.]*)?@?([0-9.]*)?/.exec(line);
  938. if (match) {
  939. event = {
  940. type: 'tag',
  941. tagType: 'byterange'
  942. };
  943. if (match[1]) {
  944. event.length = parseInt(match[1], 10);
  945. }
  946. if (match[2]) {
  947. event.offset = parseInt(match[2], 10);
  948. }
  949. this.trigger('data', event);
  950. return;
  951. }
  952. match = /^#EXT-X-ALLOW-CACHE:?(YES|NO)?/.exec(line);
  953. if (match) {
  954. event = {
  955. type: 'tag',
  956. tagType: 'allow-cache'
  957. };
  958. if (match[1]) {
  959. event.allowed = !/NO/.test(match[1]);
  960. }
  961. this.trigger('data', event);
  962. return;
  963. }
  964. match = /^#EXT-X-STREAM-INF:?(.*)$/.exec(line);
  965. if (match) {
  966. event = {
  967. type: 'tag',
  968. tagType: 'stream-inf'
  969. };
  970. if (match[1]) {
  971. event.attributes = parseAttributes(match[1]);
  972. if (event.attributes.RESOLUTION) {
  973. var split = event.attributes.RESOLUTION.split('x');
  974. var resolution = {};
  975. if (split[0]) {
  976. resolution.width = parseInt(split[0], 10);
  977. }
  978. if (split[1]) {
  979. resolution.height = parseInt(split[1], 10);
  980. }
  981. event.attributes.RESOLUTION = resolution;
  982. }
  983. if (event.attributes.BANDWIDTH) {
  984. event.attributes.BANDWIDTH = parseInt(event.attributes.BANDWIDTH, 10);
  985. }
  986. if (event.attributes['PROGRAM-ID']) {
  987. event.attributes['PROGRAM-ID'] = parseInt(event.attributes['PROGRAM-ID'], 10);
  988. }
  989. }
  990. this.trigger('data', event);
  991. return;
  992. }
  993. match = /^#EXT-X-MEDIA:?(.*)$/.exec(line);
  994. if (match) {
  995. event = {
  996. type: 'tag',
  997. tagType: 'media'
  998. };
  999. if (match[1]) {
  1000. event.attributes = parseAttributes(match[1]);
  1001. }
  1002. this.trigger('data', event);
  1003. return;
  1004. }
  1005. match = /^#EXT-X-ENDLIST/.exec(line);
  1006. if (match) {
  1007. this.trigger('data', {
  1008. type: 'tag',
  1009. tagType: 'endlist'
  1010. });
  1011. return;
  1012. }
  1013. match = /^#EXT-X-DISCONTINUITY/.exec(line);
  1014. if (match) {
  1015. this.trigger('data', {
  1016. type: 'tag',
  1017. tagType: 'discontinuity'
  1018. });
  1019. return;
  1020. }
  1021. match = /^#EXT-X-KEY:?(.*)$/.exec(line);
  1022. if (match) {
  1023. event = {
  1024. type: 'tag',
  1025. tagType: 'key'
  1026. };
  1027. if (match[1]) {
  1028. event.attributes = parseAttributes(match[1]);
  1029. // parse the IV string into a Uint32Array
  1030. if (event.attributes.IV) {
  1031. if (event.attributes.IV.substring(0, 2).toLowerCase() === '0x') {
  1032. event.attributes.IV = event.attributes.IV.substring(2);
  1033. }
  1034. event.attributes.IV = event.attributes.IV.match(/.{8}/g);
  1035. event.attributes.IV[0] = parseInt(event.attributes.IV[0], 16);
  1036. event.attributes.IV[1] = parseInt(event.attributes.IV[1], 16);
  1037. event.attributes.IV[2] = parseInt(event.attributes.IV[2], 16);
  1038. event.attributes.IV[3] = parseInt(event.attributes.IV[3], 16);
  1039. event.attributes.IV = new Uint32Array(event.attributes.IV);
  1040. }
  1041. }
  1042. this.trigger('data', event);
  1043. return;
  1044. }
  1045. // unknown tag type
  1046. this.trigger('data', {
  1047. type: 'tag',
  1048. data: line.slice(4, line.length)
  1049. });
  1050. }
  1051. }]);
  1052. return ParseStream;
  1053. })(_stream2['default']);
  1054. exports['default'] = ParseStream;
  1055. module.exports = exports['default'];
  1056. },{"../stream":18}],10:[function(require,module,exports){
  1057. (function (global){
  1058. /**
  1059. * @file m3u8/parser.js
  1060. */
  1061. 'use strict';
  1062. Object.defineProperty(exports, '__esModule', {
  1063. value: true
  1064. });
  1065. 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; }; })();
  1066. 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); } } };
  1067. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  1068. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  1069. 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; }
  1070. var _stream = require('../stream');
  1071. var _stream2 = _interopRequireDefault(_stream);
  1072. var _lineStream = require('./line-stream');
  1073. var _lineStream2 = _interopRequireDefault(_lineStream);
  1074. var _parseStream = require('./parse-stream');
  1075. var _parseStream2 = _interopRequireDefault(_parseStream);
  1076. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  1077. /**
  1078. * A parser for M3U8 files. The current interpretation of the input is
  1079. * exposed as a property `manifest` on parser objects. It's just two lines to
  1080. * create and parse a manifest once you have the contents available as a string:
  1081. *
  1082. * ```js
  1083. * var parser = new videojs.m3u8.Parser();
  1084. * parser.push(xhr.responseText);
  1085. * ```
  1086. *
  1087. * New input can later be applied to update the manifest object by calling
  1088. * `push` again.
  1089. *
  1090. * The parser attempts to create a usable manifest object even if the
  1091. * underlying input is somewhat nonsensical. It emits `info` and `warning`
  1092. * events during the parse if it encounters input that seems invalid or
  1093. * requires some property of the manifest object to be defaulted.
  1094. *
  1095. * @class Parser
  1096. * @extends Stream
  1097. */
  1098. var Parser = (function (_Stream) {
  1099. _inherits(Parser, _Stream);
  1100. function Parser() {
  1101. _classCallCheck(this, Parser);
  1102. _get(Object.getPrototypeOf(Parser.prototype), 'constructor', this).call(this);
  1103. this.lineStream = new _lineStream2['default']();
  1104. this.parseStream = new _parseStream2['default']();
  1105. this.lineStream.pipe(this.parseStream);
  1106. /* eslint-disable consistent-this */
  1107. var self = this;
  1108. /* eslint-enable consistent-this */
  1109. var uris = [];
  1110. var currentUri = {};
  1111. var _key = undefined;
  1112. var noop = function noop() {};
  1113. var defaultMediaGroups = {
  1114. 'AUDIO': {},
  1115. 'VIDEO': {},
  1116. 'CLOSED-CAPTIONS': {},
  1117. 'SUBTITLES': {}
  1118. };
  1119. // group segments into numbered timelines delineated by discontinuities
  1120. var currentTimeline = 0;
  1121. // the manifest is empty until the parse stream begins delivering data
  1122. this.manifest = {
  1123. allowCache: true,
  1124. discontinuityStarts: []
  1125. };
  1126. // update the manifest with the m3u8 entry from the parse stream
  1127. this.parseStream.on('data', function (entry) {
  1128. var mediaGroup = undefined;
  1129. var rendition = undefined;
  1130. ({
  1131. tag: function tag() {
  1132. // switch based on the tag type
  1133. (({
  1134. 'allow-cache': function allowCache() {
  1135. this.manifest.allowCache = entry.allowed;
  1136. if (!('allowed' in entry)) {
  1137. this.trigger('info', {
  1138. message: 'defaulting allowCache to YES'
  1139. });
  1140. this.manifest.allowCache = true;
  1141. }
  1142. },
  1143. byterange: function byterange() {
  1144. var byterange = {};
  1145. if ('length' in entry) {
  1146. currentUri.byterange = byterange;
  1147. byterange.length = entry.length;
  1148. if (!('offset' in entry)) {
  1149. this.trigger('info', {
  1150. message: 'defaulting offset to zero'
  1151. });
  1152. entry.offset = 0;
  1153. }
  1154. }
  1155. if ('offset' in entry) {
  1156. currentUri.byterange = byterange;
  1157. byterange.offset = entry.offset;
  1158. }
  1159. },
  1160. endlist: function endlist() {
  1161. this.manifest.endList = true;
  1162. },
  1163. inf: function inf() {
  1164. if (!('mediaSequence' in this.manifest)) {
  1165. this.manifest.mediaSequence = 0;
  1166. this.trigger('info', {
  1167. message: 'defaulting media sequence to zero'
  1168. });
  1169. }
  1170. if (!('discontinuitySequence' in this.manifest)) {
  1171. this.manifest.discontinuitySequence = 0;
  1172. this.trigger('info', {
  1173. message: 'defaulting discontinuity sequence to zero'
  1174. });
  1175. }
  1176. if (entry.duration >= 0) {
  1177. currentUri.duration = entry.duration;
  1178. }
  1179. this.manifest.segments = uris;
  1180. },
  1181. key: function key() {
  1182. if (!entry.attributes) {
  1183. this.trigger('warn', {
  1184. message: 'ignoring key declaration without attribute list'
  1185. });
  1186. return;
  1187. }
  1188. // clear the active encryption key
  1189. if (entry.attributes.METHOD === 'NONE') {
  1190. _key = null;
  1191. return;
  1192. }
  1193. if (!entry.attributes.URI) {
  1194. this.trigger('warn', {
  1195. message: 'ignoring key declaration without URI'
  1196. });
  1197. return;
  1198. }
  1199. if (!entry.attributes.METHOD) {
  1200. this.trigger('warn', {
  1201. message: 'defaulting key method to AES-128'
  1202. });
  1203. }
  1204. // setup an encryption key for upcoming segments
  1205. _key = {
  1206. method: entry.attributes.METHOD || 'AES-128',
  1207. uri: entry.attributes.URI
  1208. };
  1209. if (typeof entry.attributes.IV !== 'undefined') {
  1210. _key.iv = entry.attributes.IV;
  1211. }
  1212. },
  1213. 'media-sequence': function mediaSequence() {
  1214. if (!isFinite(entry.number)) {
  1215. this.trigger('warn', {
  1216. message: 'ignoring invalid media sequence: ' + entry.number
  1217. });
  1218. return;
  1219. }
  1220. this.manifest.mediaSequence = entry.number;
  1221. },
  1222. 'discontinuity-sequence': function discontinuitySequence() {
  1223. if (!isFinite(entry.number)) {
  1224. this.trigger('warn', {
  1225. message: 'ignoring invalid discontinuity sequence: ' + entry.number
  1226. });
  1227. return;
  1228. }
  1229. this.manifest.discontinuitySequence = entry.number;
  1230. currentTimeline = entry.number;
  1231. },
  1232. 'playlist-type': function playlistType() {
  1233. if (!/VOD|EVENT/.test(entry.playlistType)) {
  1234. this.trigger('warn', {
  1235. message: 'ignoring unknown playlist type: ' + entry.playlist
  1236. });
  1237. return;
  1238. }
  1239. this.manifest.playlistType = entry.playlistType;
  1240. },
  1241. 'stream-inf': function streamInf() {
  1242. this.manifest.playlists = uris;
  1243. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  1244. if (!entry.attributes) {
  1245. this.trigger('warn', {
  1246. message: 'ignoring empty stream-inf attributes'
  1247. });
  1248. return;
  1249. }
  1250. if (!currentUri.attributes) {
  1251. currentUri.attributes = {};
  1252. }
  1253. currentUri.attributes = (0, _videoJs.mergeOptions)(currentUri.attributes, entry.attributes);
  1254. },
  1255. media: function media() {
  1256. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  1257. if (!(entry.attributes && entry.attributes.TYPE && entry.attributes['GROUP-ID'] && entry.attributes.NAME)) {
  1258. this.trigger('warn', {
  1259. message: 'ignoring incomplete or missing media group'
  1260. });
  1261. return;
  1262. }
  1263. // find the media group, creating defaults as necessary
  1264. var mediaGroupType = this.manifest.mediaGroups[entry.attributes.TYPE];
  1265. mediaGroupType[entry.attributes['GROUP-ID']] = mediaGroupType[entry.attributes['GROUP-ID']] || {};
  1266. mediaGroup = mediaGroupType[entry.attributes['GROUP-ID']];
  1267. // collect the rendition metadata
  1268. rendition = {
  1269. 'default': /yes/i.test(entry.attributes.DEFAULT)
  1270. };
  1271. if (rendition['default']) {
  1272. rendition.autoselect = true;
  1273. } else {
  1274. rendition.autoselect = /yes/i.test(entry.attributes.AUTOSELECT);
  1275. }
  1276. if (entry.attributes.LANGUAGE) {
  1277. rendition.language = entry.attributes.LANGUAGE;
  1278. }
  1279. if (entry.attributes.URI) {
  1280. rendition.uri = entry.attributes.URI;
  1281. }
  1282. // insert the new rendition
  1283. mediaGroup[entry.attributes.NAME] = rendition;
  1284. },
  1285. discontinuity: function discontinuity() {
  1286. currentTimeline += 1;
  1287. currentUri.discontinuity = true;
  1288. this.manifest.discontinuityStarts.push(uris.length);
  1289. },
  1290. targetduration: function targetduration() {
  1291. if (!isFinite(entry.duration) || entry.duration < 0) {
  1292. this.trigger('warn', {
  1293. message: 'ignoring invalid target duration: ' + entry.duration
  1294. });
  1295. return;
  1296. }
  1297. this.manifest.targetDuration = entry.duration;
  1298. },
  1299. totalduration: function totalduration() {
  1300. if (!isFinite(entry.duration) || entry.duration < 0) {
  1301. this.trigger('warn', {
  1302. message: 'ignoring invalid total duration: ' + entry.duration
  1303. });
  1304. return;
  1305. }
  1306. this.manifest.totalDuration = entry.duration;
  1307. }
  1308. })[entry.tagType] || noop).call(self);
  1309. },
  1310. uri: function uri() {
  1311. currentUri.uri = entry.uri;
  1312. uris.push(currentUri);
  1313. // if no explicit duration was declared, use the target duration
  1314. if (this.manifest.targetDuration && !('duration' in currentUri)) {
  1315. this.trigger('warn', {
  1316. message: 'defaulting segment duration to the target duration'
  1317. });
  1318. currentUri.duration = this.manifest.targetDuration;
  1319. }
  1320. // annotate with encryption information, if necessary
  1321. if (_key) {
  1322. currentUri.key = _key;
  1323. }
  1324. currentUri.timeline = currentTimeline;
  1325. // prepare for the next URI
  1326. currentUri = {};
  1327. },
  1328. comment: function comment() {
  1329. // comments are not important for playback
  1330. }
  1331. })[entry.type].call(self);
  1332. });
  1333. }
  1334. /**
  1335. * Parse the input string and update the manifest object.
  1336. *
  1337. * @param {String} chunk a potentially incomplete portion of the manifest
  1338. */
  1339. _createClass(Parser, [{
  1340. key: 'push',
  1341. value: function push(chunk) {
  1342. this.lineStream.push(chunk);
  1343. }
  1344. /**
  1345. * Flush any remaining input. This can be handy if the last line of an M3U8
  1346. * manifest did not contain a trailing newline but the file has been
  1347. * completely received.
  1348. */
  1349. }, {
  1350. key: 'end',
  1351. value: function end() {
  1352. // flush any buffered input
  1353. this.lineStream.push('\n');
  1354. }
  1355. }]);
  1356. return Parser;
  1357. })(_stream2['default']);
  1358. exports['default'] = Parser;
  1359. module.exports = exports['default'];
  1360. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1361. },{"../stream":18,"./line-stream":8,"./parse-stream":9}],11:[function(require,module,exports){
  1362. (function (global){
  1363. /**
  1364. * @file master-playlist-controller.js
  1365. */
  1366. 'use strict';
  1367. Object.defineProperty(exports, '__esModule', {
  1368. value: true
  1369. });
  1370. 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; }; })();
  1371. 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); } } };
  1372. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  1373. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  1374. 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; }
  1375. var _playlistLoader = require('./playlist-loader');
  1376. var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
  1377. var _segmentLoader = require('./segment-loader');
  1378. var _segmentLoader2 = _interopRequireDefault(_segmentLoader);
  1379. var _ranges = require('./ranges');
  1380. var _ranges2 = _interopRequireDefault(_ranges);
  1381. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  1382. var _videoJs2 = _interopRequireDefault(_videoJs);
  1383. var _hlsAudioTrack = require('./hls-audio-track');
  1384. var _hlsAudioTrack2 = _interopRequireDefault(_hlsAudioTrack);
  1385. // 5 minute blacklist
  1386. var BLACKLIST_DURATION = 5 * 60 * 1000;
  1387. var Hls = undefined;
  1388. var parseCodecs = function parseCodecs(codecs) {
  1389. var result = {
  1390. codecCount: 0,
  1391. videoCodec: null,
  1392. audioProfile: null
  1393. };
  1394. result.codecCount = codecs.split(',').length;
  1395. result.codecCount = result.codecCount || 2;
  1396. // parse the video codec but ignore the version
  1397. result.videoCodec = /(^|\s|,)+(avc1)[^ ,]*/i.exec(codecs);
  1398. result.videoCodec = result.videoCodec && result.videoCodec[2];
  1399. // parse the last field of the audio codec
  1400. result.audioProfile = /(^|\s|,)+mp4a.\d+\.(\d+)/i.exec(codecs);
  1401. result.audioProfile = result.audioProfile && result.audioProfile[2];
  1402. return result;
  1403. };
  1404. /**
  1405. * the master playlist controller controller all interactons
  1406. * between playlists and segmentloaders. At this time this mainly
  1407. * involves a master playlist and a series of audio playlists
  1408. * if they are available
  1409. *
  1410. * @class MasterPlaylistController
  1411. * @extends videojs.EventTarget
  1412. */
  1413. var MasterPlaylistController = (function (_videojs$EventTarget) {
  1414. _inherits(MasterPlaylistController, _videojs$EventTarget);
  1415. function MasterPlaylistController(_ref) {
  1416. var _this = this;
  1417. var url = _ref.url;
  1418. var withCredentials = _ref.withCredentials;
  1419. var mode = _ref.mode;
  1420. var tech = _ref.tech;
  1421. var bandwidth = _ref.bandwidth;
  1422. var externHls = _ref.externHls;
  1423. _classCallCheck(this, MasterPlaylistController);
  1424. _get(Object.getPrototypeOf(MasterPlaylistController.prototype), 'constructor', this).call(this);
  1425. Hls = externHls;
  1426. this.withCredentials = withCredentials;
  1427. this.tech_ = tech;
  1428. this.hls_ = tech.hls;
  1429. this.mode_ = mode;
  1430. this.audioTracks_ = [];
  1431. this.mediaSource = new _videoJs2['default'].MediaSource({ mode: mode });
  1432. this.mediaSource.on('audioinfo', function (e) {
  1433. return _this.trigger(e);
  1434. });
  1435. // load the media source into the player
  1436. this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen_.bind(this));
  1437. var segmentLoaderOptions = {
  1438. hls: this.hls_,
  1439. mediaSource: this.mediaSource,
  1440. currentTime: this.tech_.currentTime.bind(this.tech_),
  1441. withCredentials: this.withCredentials,
  1442. seekable: function seekable() {
  1443. return _this.seekable();
  1444. },
  1445. seeking: function seeking() {
  1446. return _this.tech_.seeking();
  1447. },
  1448. setCurrentTime: function setCurrentTime(a) {
  1449. return _this.setCurrentTime(a);
  1450. },
  1451. hasPlayed: function hasPlayed() {
  1452. return _this.tech_.played().length !== 0;
  1453. },
  1454. bandwidth: bandwidth
  1455. };
  1456. // combined audio/video or just video when alternate audio track is selected
  1457. this.mainSegmentLoader_ = new _segmentLoader2['default'](segmentLoaderOptions);
  1458. // alternate audio track
  1459. this.audioSegmentLoader_ = new _segmentLoader2['default'](segmentLoaderOptions);
  1460. if (!url) {
  1461. throw new Error('A non-empty playlist URL is required');
  1462. }
  1463. this.masterPlaylistLoader_ = new _playlistLoader2['default'](url, this.hls_, this.withCredentials);
  1464. this.masterPlaylistLoader_.on('loadedmetadata', function () {
  1465. var media = _this.masterPlaylistLoader_.media();
  1466. // if this isn't a live video and preload permits, start
  1467. // downloading segments
  1468. if (media.endList && _this.tech_.preload() !== 'none') {
  1469. _this.mainSegmentLoader_.playlist(media);
  1470. _this.mainSegmentLoader_.expired(_this.masterPlaylistLoader_.expired_);
  1471. _this.mainSegmentLoader_.load();
  1472. }
  1473. _this.setupSourceBuffer_();
  1474. _this.setupFirstPlay();
  1475. _this.useAudio();
  1476. });
  1477. this.masterPlaylistLoader_.on('loadedplaylist', function () {
  1478. var updatedPlaylist = _this.masterPlaylistLoader_.media();
  1479. var seekable = undefined;
  1480. if (!updatedPlaylist) {
  1481. // select the initial variant
  1482. _this.initialMedia_ = _this.selectPlaylist();
  1483. _this.masterPlaylistLoader_.media(_this.initialMedia_);
  1484. _this.fillAudioTracks_();
  1485. _this.trigger('selectedinitialmedia');
  1486. return;
  1487. }
  1488. _this.mainSegmentLoader_.playlist(updatedPlaylist);
  1489. _this.mainSegmentLoader_.expired(_this.masterPlaylistLoader_.expired_);
  1490. _this.updateDuration();
  1491. // update seekable
  1492. seekable = _this.seekable();
  1493. if (!updatedPlaylist.endList && seekable.length !== 0) {
  1494. _this.mediaSource.addSeekableRange_(seekable.start(0), seekable.end(0));
  1495. }
  1496. });
  1497. this.masterPlaylistLoader_.on('error', function () {
  1498. _this.blacklistCurrentPlaylist(_this.masterPlaylistLoader_.error);
  1499. });
  1500. this.masterPlaylistLoader_.on('mediachanging', function () {
  1501. _this.mainSegmentLoader_.pause();
  1502. });
  1503. this.masterPlaylistLoader_.on('mediachange', function () {
  1504. _this.mainSegmentLoader_.abort();
  1505. _this.mainSegmentLoader_.load();
  1506. _this.tech_.trigger({
  1507. type: 'mediachange',
  1508. bubbles: true
  1509. });
  1510. });
  1511. this.mainSegmentLoader_.on('progress', function () {
  1512. // figure out what stream the next segment should be downloaded from
  1513. // with the updated bandwidth information
  1514. _this.masterPlaylistLoader_.media(_this.selectPlaylist());
  1515. _this.trigger('progress');
  1516. });
  1517. this.mainSegmentLoader_.on('error', function () {
  1518. _this.blacklistCurrentPlaylist(_this.mainSegmentLoader_.error());
  1519. });
  1520. this.audioSegmentLoader_.on('error', function () {
  1521. _videoJs2['default'].log.warn('Problem encountered with the current alternate audio track' + '. Switching back to default.');
  1522. _this.audioSegmentLoader_.abort();
  1523. _this.audioPlaylistLoader_ = null;
  1524. _this.useAudio();
  1525. });
  1526. this.masterPlaylistLoader_.load();
  1527. }
  1528. /**
  1529. * fill our internal list of HlsAudioTracks with data from
  1530. * the master playlist or use a default
  1531. *
  1532. * @private
  1533. */
  1534. _createClass(MasterPlaylistController, [{
  1535. key: 'fillAudioTracks_',
  1536. value: function fillAudioTracks_() {
  1537. var master = this.master();
  1538. var mediaGroups = master.mediaGroups || {};
  1539. // force a default if we have none or we are not
  1540. // in html5 mode (the only mode to support more than one
  1541. // audio track)
  1542. if (!mediaGroups || !mediaGroups.AUDIO || Object.keys(mediaGroups.AUDIO).length === 0 || this.mode_ !== 'html5') {
  1543. // "main" audio group, track name "default"
  1544. mediaGroups.AUDIO = { main: { 'default': { 'default': true } } };
  1545. }
  1546. var tracks = {};
  1547. for (var mediaGroup in mediaGroups.AUDIO) {
  1548. for (var label in mediaGroups.AUDIO[mediaGroup]) {
  1549. var properties = mediaGroups.AUDIO[mediaGroup][label];
  1550. // if the track already exists add a new "location"
  1551. // since tracks in different mediaGroups are actually the same
  1552. // track with different locations to download them from
  1553. if (tracks[label]) {
  1554. tracks[label].addLoader(mediaGroup, properties.resolvedUri);
  1555. continue;
  1556. }
  1557. var track = new _hlsAudioTrack2['default'](_videoJs2['default'].mergeOptions(properties, {
  1558. hls: this.hls_,
  1559. withCredentials: this.withCredential,
  1560. mediaGroup: mediaGroup,
  1561. label: label
  1562. }));
  1563. tracks[label] = track;
  1564. this.audioTracks_.push(track);
  1565. }
  1566. }
  1567. }
  1568. /**
  1569. * Call load on our SegmentLoaders
  1570. */
  1571. }, {
  1572. key: 'load',
  1573. value: function load() {
  1574. this.mainSegmentLoader_.load();
  1575. if (this.audioPlaylistLoader_) {
  1576. this.audioSegmentLoader_.load();
  1577. }
  1578. }
  1579. /**
  1580. * Get the current active Media Group for Audio
  1581. * given the selected playlist and its attributes
  1582. */
  1583. }, {
  1584. key: 'activeAudioGroup',
  1585. value: function activeAudioGroup() {
  1586. var media = this.masterPlaylistLoader_.media();
  1587. var mediaGroup = 'main';
  1588. if (media && media.attributes && media.attributes.AUDIO) {
  1589. mediaGroup = media.attributes.AUDIO;
  1590. }
  1591. return mediaGroup;
  1592. }
  1593. /**
  1594. * Use any audio track that we have, and start to load it
  1595. */
  1596. }, {
  1597. key: 'useAudio',
  1598. value: function useAudio() {
  1599. var _this2 = this;
  1600. var track = undefined;
  1601. this.audioTracks_.forEach(function (t) {
  1602. if (!track && t.enabled) {
  1603. track = t;
  1604. }
  1605. });
  1606. // called too early or no track is enabled
  1607. if (!track) {
  1608. return;
  1609. }
  1610. // Pause any alternative audio
  1611. if (this.audioPlaylistLoader_) {
  1612. this.audioPlaylistLoader_.pause();
  1613. this.audioPlaylistLoader_ = null;
  1614. this.audioSegmentLoader_.pause();
  1615. }
  1616. // If the audio track for the active audio group has
  1617. // a playlist loader than it is an alterative audio track
  1618. // otherwise it is a part of the mainSegmenLoader
  1619. var loader = track.getLoader(this.activeAudioGroup());
  1620. if (!loader) {
  1621. this.mainSegmentLoader_.clearBuffer();
  1622. return;
  1623. }
  1624. // TODO: it may be better to create the playlist loader here
  1625. // when we can change an audioPlaylistLoaders src
  1626. this.audioPlaylistLoader_ = loader;
  1627. if (this.audioPlaylistLoader_.started) {
  1628. this.audioPlaylistLoader_.load();
  1629. this.audioSegmentLoader_.load();
  1630. this.audioSegmentLoader_.clearBuffer();
  1631. return;
  1632. }
  1633. this.audioPlaylistLoader_.on('loadedmetadata', function () {
  1634. /* eslint-disable no-shadow */
  1635. var media = _this2.audioPlaylistLoader_.media();
  1636. /* eslint-enable no-shadow */
  1637. _this2.audioSegmentLoader_.playlist(media);
  1638. _this2.addMimeType_(_this2.audioSegmentLoader_, 'mp4a.40.2', media);
  1639. // if the video is already playing, or if this isn't a live video and preload
  1640. // permits, start downloading segments
  1641. if (!_this2.tech_.paused() || media.endList && _this2.tech_.preload() !== 'none') {
  1642. _this2.audioSegmentLoader_.load();
  1643. }
  1644. if (!media.endList) {
  1645. // trigger the playlist loader to start "expired time"-tracking
  1646. _this2.audioPlaylistLoader_.trigger('firstplay');
  1647. }
  1648. });
  1649. this.audioPlaylistLoader_.on('loadedplaylist', function () {
  1650. var updatedPlaylist = undefined;
  1651. if (_this2.audioPlaylistLoader_) {
  1652. updatedPlaylist = _this2.audioPlaylistLoader_.media();
  1653. }
  1654. if (!updatedPlaylist) {
  1655. // only one playlist to select
  1656. _this2.audioPlaylistLoader_.media(_this2.audioPlaylistLoader_.playlists.master.playlists[0]);
  1657. return;
  1658. }
  1659. _this2.audioSegmentLoader_.playlist(updatedPlaylist);
  1660. });
  1661. this.audioPlaylistLoader_.on('error', function () {
  1662. _videoJs2['default'].log.warn('Problem encountered loading the alternate audio track' + '. Switching back to default.');
  1663. _this2.audioSegmentLoader_.abort();
  1664. _this2.audioPlaylistLoader_ = null;
  1665. _this2.useAudio();
  1666. });
  1667. this.audioSegmentLoader_.clearBuffer();
  1668. this.audioPlaylistLoader_.start();
  1669. }
  1670. /**
  1671. * Re-tune playback quality level for the current player
  1672. * conditions. This method may perform destructive actions, like
  1673. * removing already buffered content, to readjust the currently
  1674. * active playlist quickly.
  1675. *
  1676. * @private
  1677. */
  1678. }, {
  1679. key: 'fastQualityChange_',
  1680. value: function fastQualityChange_() {
  1681. var media = this.selectPlaylist();
  1682. if (media !== this.masterPlaylistLoader_.media()) {
  1683. this.masterPlaylistLoader_.media(media);
  1684. this.mainSegmentLoader_.sourceUpdater_.remove(this.tech_.currentTime() + 5, Infinity);
  1685. }
  1686. }
  1687. /**
  1688. * Begin playback.
  1689. */
  1690. }, {
  1691. key: 'play',
  1692. value: function play() {
  1693. if (this.setupFirstPlay()) {
  1694. return;
  1695. }
  1696. if (this.tech_.ended()) {
  1697. this.tech_.setCurrentTime(0);
  1698. }
  1699. this.load();
  1700. // if the viewer has paused and we fell out of the live window,
  1701. // seek forward to the earliest available position
  1702. if (this.tech_.duration() === Infinity) {
  1703. if (this.tech_.currentTime() < this.tech_.seekable().start(0)) {
  1704. return this.tech_.setCurrentTime(this.tech_.seekable().start(0));
  1705. }
  1706. }
  1707. }
  1708. /**
  1709. * Seek to the latest media position if this is a live video and the
  1710. * player and video are loaded and initialized.
  1711. */
  1712. }, {
  1713. key: 'setupFirstPlay',
  1714. value: function setupFirstPlay() {
  1715. var seekable = undefined;
  1716. var media = this.masterPlaylistLoader_.media();
  1717. // check that everything is ready to begin buffering
  1718. // 1) the active media playlist is available
  1719. if (media &&
  1720. // 2) the video is a live stream
  1721. !media.endList &&
  1722. // 3) the player is not paused
  1723. !this.tech_.paused() &&
  1724. // 4) the player has not started playing
  1725. !this.hasPlayed_) {
  1726. this.load();
  1727. // trigger the playlist loader to start "expired time"-tracking
  1728. this.masterPlaylistLoader_.trigger('firstplay');
  1729. this.hasPlayed_ = true;
  1730. // seek to the latest media position for live videos
  1731. seekable = this.seekable();
  1732. if (seekable.length) {
  1733. this.tech_.setCurrentTime(seekable.end(0));
  1734. }
  1735. return true;
  1736. }
  1737. return false;
  1738. }
  1739. /**
  1740. * handle the sourceopen event on the MediaSource
  1741. *
  1742. * @private
  1743. */
  1744. }, {
  1745. key: 'handleSourceOpen_',
  1746. value: function handleSourceOpen_() {
  1747. // Only attempt to create the source buffer if none already exist.
  1748. // handleSourceOpen is also called when we are "re-opening" a source buffer
  1749. // after `endOfStream` has been called (in response to a seek for instance)
  1750. this.setupSourceBuffer_();
  1751. // if autoplay is enabled, begin playback. This is duplicative of
  1752. // code in video.js but is required because play() must be invoked
  1753. // *after* the media source has opened.
  1754. if (this.tech_.autoplay()) {
  1755. this.tech_.play();
  1756. }
  1757. this.trigger('sourceopen');
  1758. }
  1759. /**
  1760. * Blacklists a playlist when an error occurs for a set amount of time
  1761. * making it unavailable for selection by the rendition selection algorithm
  1762. * and then forces a new playlist (rendition) selection.
  1763. *
  1764. * @param {Object=} error an optional error that may include the playlist
  1765. * to blacklist
  1766. */
  1767. }, {
  1768. key: 'blacklistCurrentPlaylist',
  1769. value: function blacklistCurrentPlaylist() {
  1770. var error = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  1771. var currentPlaylist = undefined;
  1772. var nextPlaylist = undefined;
  1773. // If the `error` was generated by the playlist loader, it will contain
  1774. // the playlist we were trying to load (but failed) and that should be
  1775. // blacklisted instead of the currently selected playlist which is likely
  1776. // out-of-date in this scenario
  1777. currentPlaylist = error.playlist || this.masterPlaylistLoader_.media();
  1778. // If there is no current playlist, then an error occurred while we were
  1779. // trying to load the master OR while we were disposing of the tech
  1780. if (!currentPlaylist) {
  1781. this.error = error;
  1782. return this.mediaSource.endOfStream('network');
  1783. }
  1784. // Blacklist this playlist
  1785. currentPlaylist.excludeUntil = Date.now() + BLACKLIST_DURATION;
  1786. // Select a new playlist
  1787. nextPlaylist = this.selectPlaylist();
  1788. if (nextPlaylist) {
  1789. _videoJs2['default'].log.warn('Problem encountered with the current ' + 'HLS playlist. Switching to another playlist.');
  1790. return this.masterPlaylistLoader_.media(nextPlaylist);
  1791. }
  1792. _videoJs2['default'].log.warn('Problem encountered with the current ' + 'HLS playlist. No suitable alternatives found.');
  1793. // We have no more playlists we can select so we must fail
  1794. this.error = error;
  1795. return this.mediaSource.endOfStream('network');
  1796. }
  1797. /**
  1798. * Pause all segment loaders
  1799. */
  1800. }, {
  1801. key: 'pauseLoading',
  1802. value: function pauseLoading() {
  1803. this.mainSegmentLoader_.pause();
  1804. if (this.audioPlaylistLoader_) {
  1805. this.audioSegmentLoader_.pause();
  1806. }
  1807. }
  1808. /**
  1809. * set the current time on all segment loaders
  1810. *
  1811. * @param {TimeRange} currentTime the current time to set
  1812. * @return {TimeRange} the current time
  1813. */
  1814. }, {
  1815. key: 'setCurrentTime',
  1816. value: function setCurrentTime(currentTime) {
  1817. var buffered = _ranges2['default'].findRange(this.tech_.buffered(), currentTime);
  1818. if (!(this.masterPlaylistLoader_ && this.masterPlaylistLoader_.media())) {
  1819. // return immediately if the metadata is not ready yet
  1820. return 0;
  1821. }
  1822. // it's clearly an edge-case but don't thrown an error if asked to
  1823. // seek within an empty playlist
  1824. if (!this.masterPlaylistLoader_.media().segments) {
  1825. return 0;
  1826. }
  1827. // if the seek location is already buffered, continue buffering as
  1828. // usual
  1829. if (buffered && buffered.length) {
  1830. return currentTime;
  1831. }
  1832. // cancel outstanding requests so we begin buffering at the new
  1833. // location
  1834. this.mainSegmentLoader_.abort();
  1835. if (this.audioPlaylistLoader_) {
  1836. this.audioSegmentLoader_.abort();
  1837. }
  1838. if (!this.tech_.paused()) {
  1839. this.mainSegmentLoader_.load();
  1840. if (this.audioPlaylistLoader_) {
  1841. this.audioSegmentLoader_.load();
  1842. }
  1843. }
  1844. }
  1845. /**
  1846. * get the current duration
  1847. *
  1848. * @return {TimeRange} the duration
  1849. */
  1850. }, {
  1851. key: 'duration',
  1852. value: function duration() {
  1853. if (!this.masterPlaylistLoader_) {
  1854. return 0;
  1855. }
  1856. if (this.mediaSource) {
  1857. return this.mediaSource.duration;
  1858. }
  1859. return Hls.Playlist.duration(this.masterPlaylistLoader_.media());
  1860. }
  1861. /**
  1862. * check the seekable range
  1863. *
  1864. * @return {TimeRange} the seekable range
  1865. */
  1866. }, {
  1867. key: 'seekable',
  1868. value: function seekable() {
  1869. var media = undefined;
  1870. var mainSeekable = undefined;
  1871. var audioSeekable = undefined;
  1872. if (!this.masterPlaylistLoader_) {
  1873. return _videoJs2['default'].createTimeRanges();
  1874. }
  1875. media = this.masterPlaylistLoader_.media();
  1876. if (!media) {
  1877. return _videoJs2['default'].createTimeRanges();
  1878. }
  1879. mainSeekable = Hls.Playlist.seekable(media, this.masterPlaylistLoader_.expired_);
  1880. if (mainSeekable.length === 0) {
  1881. return mainSeekable;
  1882. }
  1883. if (this.audioPlaylistLoader_) {
  1884. audioSeekable = Hls.Playlist.seekable(this.audioPlaylistLoader_.media(), this.audioPlaylistLoader_.expired_);
  1885. if (audioSeekable.length === 0) {
  1886. return audioSeekable;
  1887. }
  1888. }
  1889. if (!audioSeekable) {
  1890. // seekable has been calculated based on buffering video data so it
  1891. // can be returned directly
  1892. return mainSeekable;
  1893. }
  1894. 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)]]);
  1895. }
  1896. /**
  1897. * Update the player duration
  1898. */
  1899. }, {
  1900. key: 'updateDuration',
  1901. value: function updateDuration() {
  1902. var _this3 = this;
  1903. var oldDuration = this.mediaSource.duration;
  1904. var newDuration = Hls.Playlist.duration(this.masterPlaylistLoader_.media());
  1905. var buffered = this.tech_.buffered();
  1906. var setDuration = function setDuration() {
  1907. _this3.mediaSource.duration = newDuration;
  1908. _this3.tech_.trigger('durationchange');
  1909. _this3.mediaSource.removeEventListener('sourceopen', setDuration);
  1910. };
  1911. if (buffered.length > 0) {
  1912. newDuration = Math.max(newDuration, buffered.end(buffered.length - 1));
  1913. }
  1914. // if the duration has changed, invalidate the cached value
  1915. if (oldDuration !== newDuration) {
  1916. // update the duration
  1917. if (this.mediaSource.readyState !== 'open') {
  1918. this.mediaSource.addEventListener('sourceopen', setDuration);
  1919. } else {
  1920. setDuration();
  1921. }
  1922. }
  1923. }
  1924. /**
  1925. * dispose of the MasterPlaylistController and everything
  1926. * that it controls
  1927. */
  1928. }, {
  1929. key: 'dispose',
  1930. value: function dispose() {
  1931. this.masterPlaylistLoader_.dispose();
  1932. this.audioTracks_.forEach(function (track) {
  1933. track.dispose();
  1934. });
  1935. this.audioTracks_.length = 0;
  1936. this.mainSegmentLoader_.dispose();
  1937. this.audioSegmentLoader_.dispose();
  1938. }
  1939. /**
  1940. * return the master playlist object if we have one
  1941. *
  1942. * @return {Object} the master playlist object that we parsed
  1943. */
  1944. }, {
  1945. key: 'master',
  1946. value: function master() {
  1947. return this.masterPlaylistLoader_.master;
  1948. }
  1949. /**
  1950. * return the currently selected playlist
  1951. *
  1952. * @return {Object} the currently selected playlist object that we parsed
  1953. */
  1954. }, {
  1955. key: 'media',
  1956. value: function media() {
  1957. // playlist loader will not return media if it has not been fully loaded
  1958. return this.masterPlaylistLoader_.media() || this.initialMedia_;
  1959. }
  1960. /**
  1961. * setup our internal source buffers on our segment Loaders
  1962. *
  1963. * @private
  1964. */
  1965. }, {
  1966. key: 'setupSourceBuffer_',
  1967. value: function setupSourceBuffer_() {
  1968. var media = this.masterPlaylistLoader_.media();
  1969. // wait until a media playlist is available and the Media Source is
  1970. // attached
  1971. if (!media || this.mediaSource.readyState !== 'open') {
  1972. return;
  1973. }
  1974. this.addMimeType_(this.mainSegmentLoader_, 'avc1.4d400d, mp4a.40.2', media);
  1975. // exclude any incompatible variant streams from future playlist
  1976. // selection
  1977. this.excludeIncompatibleVariants_(media);
  1978. }
  1979. /**
  1980. * add a time type to a segmentLoader
  1981. *
  1982. * @param {SegmentLoader} segmentLoader the segmentloader to work on
  1983. * @param {String} codecs to use by default
  1984. * @param {Object} the parsed media object
  1985. * @private
  1986. */
  1987. }, {
  1988. key: 'addMimeType_',
  1989. value: function addMimeType_(segmentLoader, defaultCodecs, media) {
  1990. var mimeType = 'video/mp2t';
  1991. // if the codecs were explicitly specified, pass them along to the
  1992. // source buffer
  1993. if (media.attributes && media.attributes.CODECS) {
  1994. mimeType += '; codecs="' + media.attributes.CODECS + '"';
  1995. } else {
  1996. mimeType += '; codecs="' + defaultCodecs + '"';
  1997. }
  1998. segmentLoader.mimeType(mimeType);
  1999. }
  2000. /**
  2001. * Blacklist playlists that are known to be codec or
  2002. * stream-incompatible with the SourceBuffer configuration. For
  2003. * instance, Media Source Extensions would cause the video element to
  2004. * stall waiting for video data if you switched from a variant with
  2005. * video and audio to an audio-only one.
  2006. *
  2007. * @param {Object} media a media playlist compatible with the current
  2008. * set of SourceBuffers. Variants in the current master playlist that
  2009. * do not appear to have compatible codec or stream configurations
  2010. * will be excluded from the default playlist selection algorithm
  2011. * indefinitely.
  2012. * @private
  2013. */
  2014. }, {
  2015. key: 'excludeIncompatibleVariants_',
  2016. value: function excludeIncompatibleVariants_(media) {
  2017. var master = this.masterPlaylistLoader_.master;
  2018. var codecCount = 2;
  2019. var videoCodec = null;
  2020. var audioProfile = null;
  2021. var codecs = undefined;
  2022. if (media.attributes && media.attributes.CODECS) {
  2023. codecs = parseCodecs(media.attributes.CODECS);
  2024. videoCodec = codecs.videoCodec;
  2025. audioProfile = codecs.audioProfile;
  2026. codecCount = codecs.codecCount;
  2027. }
  2028. master.playlists.forEach(function (variant) {
  2029. var variantCodecs = {
  2030. codecCount: 2,
  2031. videoCodec: null,
  2032. audioProfile: null
  2033. };
  2034. if (variant.attributes && variant.attributes.CODECS) {
  2035. variantCodecs = parseCodecs(variant.attributes.CODECS);
  2036. }
  2037. // if the streams differ in the presence or absence of audio or
  2038. // video, they are incompatible
  2039. if (variantCodecs.codecCount !== codecCount) {
  2040. variant.excludeUntil = Infinity;
  2041. }
  2042. // if h.264 is specified on the current playlist, some flavor of
  2043. // it must be specified on all compatible variants
  2044. if (variantCodecs.videoCodec !== videoCodec) {
  2045. variant.excludeUntil = Infinity;
  2046. }
  2047. // HE-AAC ("mp4a.40.5") is incompatible with all other versions of
  2048. // AAC audio in Chrome 46. Don't mix the two.
  2049. if (variantCodecs.audioProfile === '5' && audioProfile !== '5' || audioProfile === '5' && variantCodecs.audioProfile !== '5') {
  2050. variant.excludeUntil = Infinity;
  2051. }
  2052. });
  2053. }
  2054. }]);
  2055. return MasterPlaylistController;
  2056. })(_videoJs2['default'].EventTarget);
  2057. exports['default'] = MasterPlaylistController;
  2058. module.exports = exports['default'];
  2059. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2060. },{"./hls-audio-track":6,"./playlist-loader":12,"./ranges":14,"./segment-loader":16}],12:[function(require,module,exports){
  2061. (function (global){
  2062. /**
  2063. * @file playlist-loader.js
  2064. *
  2065. * A state machine that manages the loading, caching, and updating of
  2066. * M3U8 playlists.
  2067. *
  2068. */
  2069. 'use strict';
  2070. Object.defineProperty(exports, '__esModule', {
  2071. value: true
  2072. });
  2073. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  2074. var _resolveUrl = require('./resolve-url');
  2075. var _resolveUrl2 = _interopRequireDefault(_resolveUrl);
  2076. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  2077. var _stream = require('./stream');
  2078. var _stream2 = _interopRequireDefault(_stream);
  2079. var _m3u8 = require('./m3u8');
  2080. var _m3u82 = _interopRequireDefault(_m3u8);
  2081. /**
  2082. * Returns a new array of segments that is the result of merging
  2083. * properties from an older list of segments onto an updated
  2084. * list. No properties on the updated playlist will be overridden.
  2085. *
  2086. * @param {Array} original the outdated list of segments
  2087. * @param {Array} update the updated list of segments
  2088. * @param {Number=} offset the index of the first update
  2089. * segment in the original segment list. For non-live playlists,
  2090. * this should always be zero and does not need to be
  2091. * specified. For live playlists, it should be the difference
  2092. * between the media sequence numbers in the original and updated
  2093. * playlists.
  2094. * @return a list of merged segment objects
  2095. */
  2096. var updateSegments = function updateSegments(original, update, offset) {
  2097. var result = update.slice();
  2098. var length = undefined;
  2099. var i = undefined;
  2100. offset = offset || 0;
  2101. length = Math.min(original.length, update.length + offset);
  2102. for (i = offset; i < length; i++) {
  2103. result[i - offset] = (0, _videoJs.mergeOptions)(original[i], result[i - offset]);
  2104. }
  2105. return result;
  2106. };
  2107. /**
  2108. * Returns a new master playlist that is the result of merging an
  2109. * updated media playlist into the original version. If the
  2110. * updated media playlist does not match any of the playlist
  2111. * entries in the original master playlist, null is returned.
  2112. *
  2113. * @param {Object} master a parsed master M3U8 object
  2114. * @param {Object} media a parsed media M3U8 object
  2115. * @return {Object} a new object that represents the original
  2116. * master playlist with the updated media playlist merged in, or
  2117. * null if the merge produced no change.
  2118. */
  2119. var updateMaster = function updateMaster(master, media) {
  2120. var changed = false;
  2121. var result = (0, _videoJs.mergeOptions)(master, {});
  2122. var i = master.playlists.length;
  2123. var playlist = undefined;
  2124. var segment = undefined;
  2125. var j = undefined;
  2126. while (i--) {
  2127. playlist = result.playlists[i];
  2128. if (playlist.uri === media.uri) {
  2129. // consider the playlist unchanged if the number of segments
  2130. // are equal and the media sequence number is unchanged
  2131. if (playlist.segments && media.segments && playlist.segments.length === media.segments.length && playlist.mediaSequence === media.mediaSequence) {
  2132. continue;
  2133. }
  2134. result.playlists[i] = (0, _videoJs.mergeOptions)(playlist, media);
  2135. result.playlists[media.uri] = result.playlists[i];
  2136. // if the update could overlap existing segment information,
  2137. // merge the two lists
  2138. if (playlist.segments) {
  2139. result.playlists[i].segments = updateSegments(playlist.segments, media.segments, media.mediaSequence - playlist.mediaSequence);
  2140. }
  2141. // resolve any missing segment and key URIs
  2142. j = 0;
  2143. if (result.playlists[i].segments) {
  2144. j = result.playlists[i].segments.length;
  2145. }
  2146. while (j--) {
  2147. segment = result.playlists[i].segments[j];
  2148. if (!segment.resolvedUri) {
  2149. segment.resolvedUri = (0, _resolveUrl2['default'])(playlist.resolvedUri, segment.uri);
  2150. }
  2151. if (segment.key && !segment.key.resolvedUri) {
  2152. segment.key.resolvedUri = (0, _resolveUrl2['default'])(playlist.resolvedUri, segment.key.uri);
  2153. }
  2154. }
  2155. changed = true;
  2156. }
  2157. }
  2158. return changed ? result : null;
  2159. };
  2160. /**
  2161. * Load a playlist from a remote loacation
  2162. *
  2163. * @class PlaylistLoader
  2164. * @extends Stream
  2165. * @param {String} srcUrl the url to start with
  2166. * @param {Boolean} withCredentials the withCredentials xhr option
  2167. * @constructor
  2168. */
  2169. var PlaylistLoader = function PlaylistLoader(srcUrl, hls, withCredentials) {
  2170. var _this = this;
  2171. /* eslint-disable consistent-this */
  2172. var loader = this;
  2173. /* eslint-enable consistent-this */
  2174. var dispose = undefined;
  2175. var mediaUpdateTimeout = undefined;
  2176. var request = undefined;
  2177. var playlistRequestError = undefined;
  2178. var haveMetadata = undefined;
  2179. PlaylistLoader.prototype.constructor.call(this);
  2180. this.hls_ = hls;
  2181. // a flag that disables "expired time"-tracking this setting has
  2182. // no effect when not playing a live stream
  2183. this.trackExpiredTime_ = false;
  2184. if (!srcUrl) {
  2185. throw new Error('A non-empty playlist URL is required');
  2186. }
  2187. playlistRequestError = function (xhr, url, startingState) {
  2188. loader.setBandwidth(request || xhr);
  2189. // any in-flight request is now finished
  2190. request = null;
  2191. if (startingState) {
  2192. loader.state = startingState;
  2193. }
  2194. loader.error = {
  2195. playlist: loader.master.playlists[url],
  2196. status: xhr.status,
  2197. message: 'HLS playlist request error at URL: ' + url,
  2198. responseText: xhr.responseText,
  2199. code: xhr.status >= 500 ? 4 : 2
  2200. };
  2201. loader.trigger('error');
  2202. };
  2203. // update the playlist loader's state in response to a new or
  2204. // updated playlist.
  2205. haveMetadata = function (xhr, url) {
  2206. var parser = undefined;
  2207. var refreshDelay = undefined;
  2208. var update = undefined;
  2209. loader.setBandwidth(request || xhr);
  2210. // any in-flight request is now finished
  2211. request = null;
  2212. loader.state = 'HAVE_METADATA';
  2213. parser = new _m3u82['default'].Parser();
  2214. parser.push(xhr.responseText);
  2215. parser.end();
  2216. parser.manifest.uri = url;
  2217. // merge this playlist into the master
  2218. update = updateMaster(loader.master, parser.manifest);
  2219. refreshDelay = (parser.manifest.targetDuration || 10) * 1000;
  2220. if (update) {
  2221. loader.master = update;
  2222. loader.updateMediaPlaylist_(parser.manifest);
  2223. } else {
  2224. // if the playlist is unchanged since the last reload,
  2225. // try again after half the target duration
  2226. refreshDelay /= 2;
  2227. }
  2228. // refresh live playlists after a target duration passes
  2229. if (!loader.media().endList) {
  2230. window.clearTimeout(mediaUpdateTimeout);
  2231. mediaUpdateTimeout = window.setTimeout(function () {
  2232. loader.trigger('mediaupdatetimeout');
  2233. }, refreshDelay);
  2234. }
  2235. loader.trigger('loadedplaylist');
  2236. };
  2237. // initialize the loader state
  2238. loader.state = 'HAVE_NOTHING';
  2239. // track the time that has expired from the live window
  2240. // this allows the seekable start range to be calculated even if
  2241. // all segments with timing information have expired
  2242. this.expired_ = 0;
  2243. // capture the prototype dispose function
  2244. dispose = this.dispose;
  2245. /**
  2246. * Abort any outstanding work and clean up.
  2247. */
  2248. loader.dispose = function () {
  2249. loader.stopRequest();
  2250. window.clearTimeout(mediaUpdateTimeout);
  2251. dispose.call(this);
  2252. };
  2253. loader.stopRequest = function () {
  2254. if (request) {
  2255. var oldRequest = request;
  2256. request = null;
  2257. oldRequest.onreadystatechange = null;
  2258. oldRequest.abort();
  2259. }
  2260. };
  2261. /**
  2262. * When called without any arguments, returns the currently
  2263. * active media playlist. When called with a single argument,
  2264. * triggers the playlist loader to asynchronously switch to the
  2265. * specified media playlist. Calling this method while the
  2266. * loader is in the HAVE_NOTHING causes an error to be emitted
  2267. * but otherwise has no effect.
  2268. *
  2269. * @param {Object=} playlis tthe parsed media playlist
  2270. * object to switch to
  2271. * @return {Playlist} the current loaded media
  2272. */
  2273. loader.media = function (playlist) {
  2274. var startingState = loader.state;
  2275. var mediaChange = undefined;
  2276. // getter
  2277. if (!playlist) {
  2278. return loader.media_;
  2279. }
  2280. // setter
  2281. if (loader.state === 'HAVE_NOTHING') {
  2282. throw new Error('Cannot switch media playlist from ' + loader.state);
  2283. }
  2284. // find the playlist object if the target playlist has been
  2285. // specified by URI
  2286. if (typeof playlist === 'string') {
  2287. if (!loader.master.playlists[playlist]) {
  2288. throw new Error('Unknown playlist URI: ' + playlist);
  2289. }
  2290. playlist = loader.master.playlists[playlist];
  2291. }
  2292. mediaChange = !loader.media_ || playlist.uri !== loader.media_.uri;
  2293. // switch to fully loaded playlists immediately
  2294. if (loader.master.playlists[playlist.uri].endList) {
  2295. // abort outstanding playlist requests
  2296. if (request) {
  2297. request.onreadystatechange = null;
  2298. request.abort();
  2299. request = null;
  2300. }
  2301. loader.state = 'HAVE_METADATA';
  2302. loader.media_ = playlist;
  2303. // trigger media change if the active media has been updated
  2304. if (mediaChange) {
  2305. loader.trigger('mediachanging');
  2306. loader.trigger('mediachange');
  2307. }
  2308. return;
  2309. }
  2310. // switching to the active playlist is a no-op
  2311. if (!mediaChange) {
  2312. return;
  2313. }
  2314. loader.state = 'SWITCHING_MEDIA';
  2315. // there is already an outstanding playlist request
  2316. if (request) {
  2317. if ((0, _resolveUrl2['default'])(loader.master.uri, playlist.uri) === request.url) {
  2318. // requesting to switch to the same playlist multiple times
  2319. // has no effect after the first
  2320. return;
  2321. }
  2322. request.onreadystatechange = null;
  2323. request.abort();
  2324. request = null;
  2325. }
  2326. // request the new playlist
  2327. if (this.media_) {
  2328. this.trigger('mediachanging');
  2329. }
  2330. request = this.hls_.xhr({
  2331. uri: (0, _resolveUrl2['default'])(loader.master.uri, playlist.uri),
  2332. withCredentials: withCredentials
  2333. }, function (error, req) {
  2334. // disposed
  2335. if (!request) {
  2336. return;
  2337. }
  2338. if (error) {
  2339. return playlistRequestError(request, playlist.uri, startingState);
  2340. }
  2341. haveMetadata(req, playlist.uri);
  2342. // fire loadedmetadata the first time a media playlist is loaded
  2343. if (startingState === 'HAVE_MASTER') {
  2344. loader.trigger('loadedmetadata');
  2345. } else {
  2346. loader.trigger('mediachange');
  2347. }
  2348. });
  2349. };
  2350. /**
  2351. * set the bandwidth on an xhr to the bandwidth on the playlist
  2352. */
  2353. loader.setBandwidth = function (xhr) {
  2354. loader.bandwidth = xhr.bandwidth;
  2355. };
  2356. // In a live playlist, don't keep track of the expired time
  2357. // until HLS tells us that "first play" has commenced
  2358. loader.on('firstplay', function () {
  2359. this.trackExpiredTime_ = true;
  2360. });
  2361. // live playlist staleness timeout
  2362. loader.on('mediaupdatetimeout', function () {
  2363. if (loader.state !== 'HAVE_METADATA') {
  2364. // only refresh the media playlist if no other activity is going on
  2365. return;
  2366. }
  2367. loader.state = 'HAVE_CURRENT_METADATA';
  2368. request = this.hls_.xhr({
  2369. uri: (0, _resolveUrl2['default'])(loader.master.uri, loader.media().uri),
  2370. withCredentials: withCredentials
  2371. }, function (error, req) {
  2372. // disposed
  2373. if (!request) {
  2374. return;
  2375. }
  2376. if (error) {
  2377. return playlistRequestError(request, loader.media().uri);
  2378. }
  2379. haveMetadata(request, loader.media().uri);
  2380. });
  2381. });
  2382. /**
  2383. * pause loading of the playlist
  2384. */
  2385. loader.pause = function () {
  2386. loader.stopRequest();
  2387. window.clearTimeout(mediaUpdateTimeout);
  2388. };
  2389. /**
  2390. * start loading of the playlist
  2391. */
  2392. loader.load = function () {
  2393. if (loader.started) {
  2394. if (!loader.media().endList) {
  2395. loader.trigger('mediaupdatetimeout');
  2396. } else {
  2397. loader.trigger('loadedplaylist');
  2398. }
  2399. } else {
  2400. loader.start();
  2401. }
  2402. };
  2403. /**
  2404. * start loading of the playlist
  2405. */
  2406. loader.start = function () {
  2407. loader.started = true;
  2408. // request the specified URL
  2409. request = _this.hls_.xhr({
  2410. uri: srcUrl,
  2411. withCredentials: withCredentials
  2412. }, function (error, req) {
  2413. var parser = undefined;
  2414. var playlist = undefined;
  2415. var i = undefined;
  2416. // disposed
  2417. if (!request) {
  2418. return;
  2419. }
  2420. // clear the loader's request reference
  2421. request = null;
  2422. if (error) {
  2423. loader.error = {
  2424. status: req.status,
  2425. message: 'HLS playlist request error at URL: ' + srcUrl,
  2426. responseText: req.responseText,
  2427. // MEDIA_ERR_NETWORK
  2428. code: 2
  2429. };
  2430. return loader.trigger('error');
  2431. }
  2432. parser = new _m3u82['default'].Parser();
  2433. parser.push(req.responseText);
  2434. parser.end();
  2435. loader.state = 'HAVE_MASTER';
  2436. parser.manifest.uri = srcUrl;
  2437. // loaded a master playlist
  2438. if (parser.manifest.playlists) {
  2439. loader.master = parser.manifest;
  2440. // setup by-URI lookups and resolve media playlist URIs
  2441. i = loader.master.playlists.length;
  2442. while (i--) {
  2443. playlist = loader.master.playlists[i];
  2444. loader.master.playlists[playlist.uri] = playlist;
  2445. playlist.resolvedUri = (0, _resolveUrl2['default'])(loader.master.uri, playlist.uri);
  2446. }
  2447. // resolve any media group URIs
  2448. for (var groupKey in loader.master.mediaGroups.AUDIO) {
  2449. for (var labelKey in loader.master.mediaGroups.AUDIO[groupKey]) {
  2450. var alternateAudio = loader.master.mediaGroups.AUDIO[groupKey][labelKey];
  2451. if (alternateAudio.uri) {
  2452. alternateAudio.resolvedUri = (0, _resolveUrl2['default'])(loader.master.uri, alternateAudio.uri);
  2453. }
  2454. }
  2455. }
  2456. loader.trigger('loadedplaylist');
  2457. if (!request) {
  2458. // no media playlist was specifically selected so start
  2459. // from the first listed one
  2460. loader.media(parser.manifest.playlists[0]);
  2461. }
  2462. return;
  2463. }
  2464. // loaded a media playlist
  2465. // infer a master playlist if none was previously requested
  2466. loader.master = {
  2467. uri: window.location.href,
  2468. playlists: [{
  2469. uri: srcUrl
  2470. }]
  2471. };
  2472. loader.master.playlists[srcUrl] = loader.master.playlists[0];
  2473. loader.master.playlists[0].resolvedUri = srcUrl;
  2474. haveMetadata(req, srcUrl);
  2475. return loader.trigger('loadedmetadata');
  2476. });
  2477. };
  2478. };
  2479. PlaylistLoader.prototype = new _stream2['default']();
  2480. /**
  2481. * Update the PlaylistLoader state to reflect the changes in an
  2482. * update to the current media playlist.
  2483. *
  2484. * @param {Object} update the updated media playlist object
  2485. */
  2486. PlaylistLoader.prototype.updateMediaPlaylist_ = function (update) {
  2487. var outdated = undefined;
  2488. var i = undefined;
  2489. var segment = undefined;
  2490. outdated = this.media_;
  2491. this.media_ = this.master.playlists[update.uri];
  2492. if (!outdated) {
  2493. return;
  2494. }
  2495. // don't track expired time until this flag is truthy
  2496. if (!this.trackExpiredTime_) {
  2497. return;
  2498. }
  2499. // if the update was the result of a rendition switch do not
  2500. // attempt to calculate expired_ since media-sequences need not
  2501. // correlate between renditions/variants
  2502. if (update.uri !== outdated.uri) {
  2503. return;
  2504. }
  2505. // try using precise timing from first segment of the updated
  2506. // playlist
  2507. if (update.segments.length) {
  2508. if (typeof update.segments[0].start !== 'undefined') {
  2509. this.expired_ = update.segments[0].start;
  2510. return;
  2511. } else if (typeof update.segments[0].end !== 'undefined') {
  2512. this.expired_ = update.segments[0].end - update.segments[0].duration;
  2513. return;
  2514. }
  2515. }
  2516. // calculate expired by walking the outdated playlist
  2517. i = update.mediaSequence - outdated.mediaSequence - 1;
  2518. for (; i >= 0; i--) {
  2519. segment = outdated.segments[i];
  2520. if (!segment) {
  2521. // we missed information on this segment completely between
  2522. // playlist updates so we'll have to take an educated guess
  2523. // once we begin buffering again, any error we introduce can
  2524. // be corrected
  2525. this.expired_ += outdated.targetDuration || 10;
  2526. continue;
  2527. }
  2528. if (typeof segment.end !== 'undefined') {
  2529. this.expired_ = segment.end;
  2530. return;
  2531. }
  2532. if (typeof segment.start !== 'undefined') {
  2533. this.expired_ = segment.start + segment.duration;
  2534. return;
  2535. }
  2536. this.expired_ += segment.duration;
  2537. }
  2538. };
  2539. exports['default'] = PlaylistLoader;
  2540. module.exports = exports['default'];
  2541. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2542. },{"./m3u8":7,"./resolve-url":15,"./stream":18}],13:[function(require,module,exports){
  2543. (function (global){
  2544. /**
  2545. * @file playlist.js
  2546. *
  2547. * Playlist related utilities.
  2548. */
  2549. 'use strict';
  2550. Object.defineProperty(exports, '__esModule', {
  2551. value: true
  2552. });
  2553. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  2554. var Playlist = {
  2555. /**
  2556. * The number of segments that are unsafe to start playback at in
  2557. * a live stream. Changing this value can cause playback stalls.
  2558. * See HTTP Live Streaming, "Playing the Media Playlist File"
  2559. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-18#section-6.3.3
  2560. */
  2561. UNSAFE_LIVE_SEGMENTS: 3
  2562. };
  2563. /**
  2564. * walk backward until we find a duration we can use
  2565. * or return a failure
  2566. *
  2567. * @param {Playlist} playlist the playlist to walk through
  2568. * @param {Number} endSequence the mediaSequence to stop walking on
  2569. */
  2570. var backwardDuration = function backwardDuration(playlist, endSequence) {
  2571. var result = 0;
  2572. var i = endSequence - playlist.mediaSequence;
  2573. // if a start time is available for segment immediately following
  2574. // the interval, use it
  2575. var segment = playlist.segments[i];
  2576. // Walk backward until we find the latest segment with timeline
  2577. // information that is earlier than endSequence
  2578. if (segment) {
  2579. if (typeof segment.start !== 'undefined') {
  2580. return { result: segment.start, precise: true };
  2581. }
  2582. if (typeof segment.end !== 'undefined') {
  2583. return {
  2584. result: segment.end - segment.duration,
  2585. precise: true
  2586. };
  2587. }
  2588. }
  2589. while (i--) {
  2590. segment = playlist.segments[i];
  2591. if (typeof segment.end !== 'undefined') {
  2592. return { result: result + segment.end, precise: true };
  2593. }
  2594. result += segment.duration;
  2595. if (typeof segment.start !== 'undefined') {
  2596. return { result: result + segment.start, precise: true };
  2597. }
  2598. }
  2599. return { result: result, precise: false };
  2600. };
  2601. /**
  2602. * walk forward until we find a duration we can use
  2603. * or return a failure
  2604. *
  2605. * @param {Playlist} playlist the playlist to walk through
  2606. * @param {Number} endSequence the mediaSequence to stop walking on
  2607. */
  2608. var forwardDuration = function forwardDuration(playlist, endSequence) {
  2609. var result = 0;
  2610. var segment = undefined;
  2611. var i = endSequence - playlist.mediaSequence;
  2612. // Walk forward until we find the earliest segment with timeline
  2613. // information
  2614. for (; i < playlist.segments.length; i++) {
  2615. segment = playlist.segments[i];
  2616. if (typeof segment.start !== 'undefined') {
  2617. return {
  2618. result: segment.start - result,
  2619. precise: true
  2620. };
  2621. }
  2622. result += segment.duration;
  2623. if (typeof segment.end !== 'undefined') {
  2624. return {
  2625. result: segment.end - result,
  2626. precise: true
  2627. };
  2628. }
  2629. }
  2630. // indicate we didn't find a useful duration estimate
  2631. return { result: -1, precise: false };
  2632. };
  2633. /**
  2634. * Calculate the media duration from the segments associated with a
  2635. * playlist. The duration of a subinterval of the available segments
  2636. * may be calculated by specifying an end index.
  2637. *
  2638. * @param {Object} playlist a media playlist object
  2639. * @param {Number=} endSequence an exclusive upper boundary
  2640. * for the playlist. Defaults to playlist length.
  2641. * @param {Number} expired the amount of time that has dropped
  2642. * off the front of the playlist in a live scenario
  2643. * @return {Number} the duration between the first available segment
  2644. * and end index.
  2645. */
  2646. var intervalDuration = function intervalDuration(playlist, endSequence, expired) {
  2647. var backward = undefined;
  2648. var forward = undefined;
  2649. if (typeof endSequence === 'undefined') {
  2650. endSequence = playlist.mediaSequence + playlist.segments.length;
  2651. }
  2652. if (endSequence < playlist.mediaSequence) {
  2653. return 0;
  2654. }
  2655. // do a backward walk to estimate the duration
  2656. backward = backwardDuration(playlist, endSequence);
  2657. if (backward.precise) {
  2658. // if we were able to base our duration estimate on timing
  2659. // information provided directly from the Media Source, return
  2660. // it
  2661. return backward.result;
  2662. }
  2663. // walk forward to see if a precise duration estimate can be made
  2664. // that way
  2665. forward = forwardDuration(playlist, endSequence);
  2666. if (forward.precise) {
  2667. // we found a segment that has been buffered and so it's
  2668. // position is known precisely
  2669. return forward.result;
  2670. }
  2671. // return the less-precise, playlist-based duration estimate
  2672. return backward.result + expired;
  2673. };
  2674. /**
  2675. * Calculates the duration of a playlist. If a start and end index
  2676. * are specified, the duration will be for the subset of the media
  2677. * timeline between those two indices. The total duration for live
  2678. * playlists is always Infinity.
  2679. *
  2680. * @param {Object} playlist a media playlist object
  2681. * @param {Number=} endSequence an exclusive upper
  2682. * boundary for the playlist. Defaults to the playlist media
  2683. * sequence number plus its length.
  2684. * @param {Number=} expired the amount of time that has
  2685. * dropped off the front of the playlist in a live scenario
  2686. * @return {Number} the duration between the start index and end
  2687. * index.
  2688. */
  2689. var duration = function duration(playlist, endSequence, expired) {
  2690. if (!playlist) {
  2691. return 0;
  2692. }
  2693. if (typeof expired !== 'number') {
  2694. expired = 0;
  2695. }
  2696. // if a slice of the total duration is not requested, use
  2697. // playlist-level duration indicators when they're present
  2698. if (typeof endSequence === 'undefined') {
  2699. // if present, use the duration specified in the playlist
  2700. if (playlist.totalDuration) {
  2701. return playlist.totalDuration;
  2702. }
  2703. // duration should be Infinity for live playlists
  2704. if (!playlist.endList) {
  2705. return window.Infinity;
  2706. }
  2707. }
  2708. // calculate the total duration based on the segment durations
  2709. return intervalDuration(playlist, endSequence, expired);
  2710. };
  2711. exports.duration = duration;
  2712. /**
  2713. * Calculates the interval of time that is currently seekable in a
  2714. * playlist. The returned time ranges are relative to the earliest
  2715. * moment in the specified playlist that is still available. A full
  2716. * seekable implementation for live streams would need to offset
  2717. * these values by the duration of content that has expired from the
  2718. * stream.
  2719. *
  2720. * @param {Object} playlist a media playlist object
  2721. * @param {Number=} expired the amount of time that has
  2722. * dropped off the front of the playlist in a live scenario
  2723. * @return {TimeRanges} the periods of time that are valid targets
  2724. * for seeking
  2725. */
  2726. var seekable = function seekable(playlist, expired) {
  2727. var start = undefined;
  2728. var end = undefined;
  2729. var endSequence = undefined;
  2730. if (typeof expired !== 'number') {
  2731. expired = 0;
  2732. }
  2733. // without segments, there are no seekable ranges
  2734. if (!playlist || !playlist.segments) {
  2735. return (0, _videoJs.createTimeRange)();
  2736. }
  2737. // when the playlist is complete, the entire duration is seekable
  2738. if (playlist.endList) {
  2739. return (0, _videoJs.createTimeRange)(0, duration(playlist));
  2740. }
  2741. // live playlists should not expose three segment durations worth
  2742. // of content from the end of the playlist
  2743. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-16#section-6.3.3
  2744. start = intervalDuration(playlist, playlist.mediaSequence, expired);
  2745. endSequence = Math.max(0, playlist.segments.length - Playlist.UNSAFE_LIVE_SEGMENTS);
  2746. end = intervalDuration(playlist, playlist.mediaSequence + endSequence, expired);
  2747. return (0, _videoJs.createTimeRange)(start, end);
  2748. };
  2749. exports.seekable = seekable;
  2750. /**
  2751. * Determine the index of the segment that contains a specified
  2752. * playback position in a media playlist.
  2753. *
  2754. * @param {Object} playlist the media playlist to query
  2755. * @param {Number} time The number of seconds since the earliest
  2756. * possible position to determine the containing segment for
  2757. * @param {Number=} expired the duration of content, in
  2758. * seconds, that has been removed from this playlist because it
  2759. * expired
  2760. * @return {Number} The number of the media segment that contains
  2761. * that time position.
  2762. */
  2763. var getMediaIndexForTime_ = function getMediaIndexForTime_(playlist, time, expired) {
  2764. var i = undefined;
  2765. var segment = undefined;
  2766. var originalTime = time;
  2767. var numSegments = playlist.segments.length;
  2768. var lastSegment = numSegments - 1;
  2769. var startIndex = undefined;
  2770. var endIndex = undefined;
  2771. var knownStart = undefined;
  2772. var knownEnd = undefined;
  2773. if (!playlist) {
  2774. return 0;
  2775. }
  2776. // when the requested position is earlier than the current set of
  2777. // segments, return the earliest segment index
  2778. if (time < 0) {
  2779. return 0;
  2780. }
  2781. expired = expired || 0;
  2782. // find segments with known timing information that bound the
  2783. // target time
  2784. for (i = 0; i < numSegments; i++) {
  2785. segment = playlist.segments[i];
  2786. if (segment.end) {
  2787. if (segment.end > time) {
  2788. knownEnd = segment.end;
  2789. endIndex = i;
  2790. break;
  2791. } else {
  2792. knownStart = segment.end;
  2793. startIndex = i + 1;
  2794. }
  2795. }
  2796. }
  2797. // time was equal to or past the end of the last segment in the playlist
  2798. if (startIndex === numSegments) {
  2799. return numSegments;
  2800. }
  2801. // use the bounds we just found and playlist information to
  2802. // estimate the segment that contains the time we are looking for
  2803. if (typeof startIndex !== 'undefined') {
  2804. // We have a known-start point that is before our desired time so
  2805. // walk from that point forwards
  2806. time = time - knownStart;
  2807. for (i = startIndex; i < (endIndex || numSegments); i++) {
  2808. segment = playlist.segments[i];
  2809. time -= segment.duration;
  2810. if (time < 0) {
  2811. return i;
  2812. }
  2813. }
  2814. if (i >= endIndex) {
  2815. // We haven't found a segment but we did hit a known end point
  2816. // so fallback to interpolating between the segment index
  2817. // based on the known span of the timeline we are dealing with
  2818. // and the number of segments inside that span
  2819. return startIndex + Math.floor((originalTime - knownStart) / (knownEnd - knownStart) * (endIndex - startIndex));
  2820. }
  2821. // We _still_ haven't found a segment so load the last one
  2822. return lastSegment;
  2823. } else if (typeof endIndex !== 'undefined') {
  2824. // We _only_ have a known-end point that is after our desired time so
  2825. // walk from that point backwards
  2826. time = knownEnd - time;
  2827. for (i = endIndex; i >= 0; i--) {
  2828. segment = playlist.segments[i];
  2829. time -= segment.duration;
  2830. if (time < 0) {
  2831. return i;
  2832. }
  2833. }
  2834. // We haven't found a segment so load the first one if time is zero
  2835. if (time === 0) {
  2836. return 0;
  2837. }
  2838. return -1;
  2839. }
  2840. // We known nothing so walk from the front of the playlist,
  2841. // subtracting durations until we find a segment that contains
  2842. // time and return it
  2843. time = time - expired;
  2844. if (time < 0) {
  2845. return -1;
  2846. }
  2847. for (i = 0; i < numSegments; i++) {
  2848. segment = playlist.segments[i];
  2849. time -= segment.duration;
  2850. if (time < 0) {
  2851. return i;
  2852. }
  2853. }
  2854. // We are out of possible candidates so load the last one...
  2855. // The last one is the least likely to overlap a buffer and therefore
  2856. // the one most likely to tell us something about the timeline
  2857. return lastSegment;
  2858. };
  2859. exports.getMediaIndexForTime_ = getMediaIndexForTime_;
  2860. Playlist.duration = duration;
  2861. Playlist.seekable = seekable;
  2862. Playlist.getMediaIndexForTime_ = getMediaIndexForTime_;
  2863. // exports
  2864. exports['default'] = Playlist;
  2865. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2866. },{}],14:[function(require,module,exports){
  2867. (function (global){
  2868. /**
  2869. * ranges
  2870. *
  2871. * Utilities for working with TimeRanges.
  2872. *
  2873. */
  2874. 'use strict';
  2875. Object.defineProperty(exports, '__esModule', {
  2876. value: true
  2877. });
  2878. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  2879. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  2880. var _videoJs2 = _interopRequireDefault(_videoJs);
  2881. // Fudge factor to account for TimeRanges rounding
  2882. var TIME_FUDGE_FACTOR = 1 / 30;
  2883. var filterRanges = function filterRanges(timeRanges, predicate) {
  2884. var results = [];
  2885. var i = undefined;
  2886. if (timeRanges && timeRanges.length) {
  2887. // Search for ranges that match the predicate
  2888. for (i = 0; i < timeRanges.length; i++) {
  2889. if (predicate(timeRanges.start(i), timeRanges.end(i))) {
  2890. results.push([timeRanges.start(i), timeRanges.end(i)]);
  2891. }
  2892. }
  2893. }
  2894. return _videoJs2['default'].createTimeRanges(results);
  2895. };
  2896. /**
  2897. * Attempts to find the buffered TimeRange that contains the specified
  2898. * time.
  2899. * @param {TimeRanges} buffered - the TimeRanges object to query
  2900. * @param {number} time - the time to filter on.
  2901. * @returns {TimeRanges} a new TimeRanges object
  2902. */
  2903. var findRange = function findRange(buffered, time) {
  2904. return filterRanges(buffered, function (start, end) {
  2905. return start - TIME_FUDGE_FACTOR <= time && end + TIME_FUDGE_FACTOR >= time;
  2906. });
  2907. };
  2908. /**
  2909. * Returns the TimeRanges that begin at or later than the specified
  2910. * time.
  2911. * @param {TimeRanges} timeRanges - the TimeRanges object to query
  2912. * @param {number} time - the time to filter on.
  2913. * @returns {TimeRanges} a new TimeRanges object.
  2914. */
  2915. var findNextRange = function findNextRange(timeRanges, time) {
  2916. return filterRanges(timeRanges, function (start) {
  2917. return start - TIME_FUDGE_FACTOR >= time;
  2918. });
  2919. };
  2920. /**
  2921. * Search for a likely end time for the segment that was just appened
  2922. * based on the state of the `buffered` property before and after the
  2923. * append. If we fin only one such uncommon end-point return it.
  2924. * @param {TimeRanges} original - the buffered time ranges before the update
  2925. * @param {TimeRanges} update - the buffered time ranges after the update
  2926. * @returns {Number|null} the end time added between `original` and `update`,
  2927. * or null if one cannot be unambiguously determined.
  2928. */
  2929. var findSoleUncommonTimeRangesEnd = function findSoleUncommonTimeRangesEnd(original, update) {
  2930. var i = undefined;
  2931. var start = undefined;
  2932. var end = undefined;
  2933. var result = [];
  2934. var edges = [];
  2935. // In order to qualify as a possible candidate, the end point must:
  2936. // 1) Not have already existed in the `original` ranges
  2937. // 2) Not result from the shrinking of a range that already existed
  2938. // in the `original` ranges
  2939. // 3) Not be contained inside of a range that existed in `original`
  2940. var overlapsCurrentEnd = function overlapsCurrentEnd(span) {
  2941. return span[0] <= end && span[1] >= end;
  2942. };
  2943. if (original) {
  2944. // Save all the edges in the `original` TimeRanges object
  2945. for (i = 0; i < original.length; i++) {
  2946. start = original.start(i);
  2947. end = original.end(i);
  2948. edges.push([start, end]);
  2949. }
  2950. }
  2951. if (update) {
  2952. // Save any end-points in `update` that are not in the `original`
  2953. // TimeRanges object
  2954. for (i = 0; i < update.length; i++) {
  2955. start = update.start(i);
  2956. end = update.end(i);
  2957. if (edges.some(overlapsCurrentEnd)) {
  2958. continue;
  2959. }
  2960. // at this point it must be a unique non-shrinking end edge
  2961. result.push(end);
  2962. }
  2963. }
  2964. // we err on the side of caution and return null if didn't find
  2965. // exactly *one* differing end edge in the search above
  2966. if (result.length !== 1) {
  2967. return null;
  2968. }
  2969. return result[0];
  2970. };
  2971. /**
  2972. * Calculate the intersection of two TimeRanges
  2973. * @param {TimeRanges} bufferA
  2974. * @param {TimeRanges} bufferB
  2975. * @returns {TimeRanges} The interesection of `bufferA` with `bufferB`
  2976. */
  2977. var bufferIntersection = function bufferIntersection(bufferA, bufferB) {
  2978. var start = null;
  2979. var end = null;
  2980. var arity = 0;
  2981. var extents = [];
  2982. var ranges = [];
  2983. if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
  2984. return _videoJs2['default'].createTimeRange();
  2985. }
  2986. // Handle the case where we have both buffers and create an
  2987. // intersection of the two
  2988. var count = bufferA.length;
  2989. // A) Gather up all start and end times
  2990. while (count--) {
  2991. extents.push({ time: bufferA.start(count), type: 'start' });
  2992. extents.push({ time: bufferA.end(count), type: 'end' });
  2993. }
  2994. count = bufferB.length;
  2995. while (count--) {
  2996. extents.push({ time: bufferB.start(count), type: 'start' });
  2997. extents.push({ time: bufferB.end(count), type: 'end' });
  2998. }
  2999. // B) Sort them by time
  3000. extents.sort(function (a, b) {
  3001. return a.time - b.time;
  3002. });
  3003. // C) Go along one by one incrementing arity for start and decrementing
  3004. // arity for ends
  3005. for (count = 0; count < extents.length; count++) {
  3006. if (extents[count].type === 'start') {
  3007. arity++;
  3008. // D) If arity is ever incremented to 2 we are entering an
  3009. // overlapping range
  3010. if (arity === 2) {
  3011. start = extents[count].time;
  3012. }
  3013. } else if (extents[count].type === 'end') {
  3014. arity--;
  3015. // E) If arity is ever decremented to 1 we leaving an
  3016. // overlapping range
  3017. if (arity === 1) {
  3018. end = extents[count].time;
  3019. }
  3020. }
  3021. // F) Record overlapping ranges
  3022. if (start !== null && end !== null) {
  3023. ranges.push([start, end]);
  3024. start = null;
  3025. end = null;
  3026. }
  3027. }
  3028. return _videoJs2['default'].createTimeRanges(ranges);
  3029. };
  3030. /**
  3031. * Calculates the percentage of `segmentRange` that overlaps the
  3032. * `buffered` time ranges.
  3033. * @param {TimeRanges} segmentRange - the time range that the segment covers
  3034. * @param {TimeRanges} buffered - the currently buffered time ranges
  3035. * @returns {Number} percent of the segment currently buffered
  3036. */
  3037. var calculateBufferedPercent = function calculateBufferedPercent(segmentRange, buffered) {
  3038. var segmentDuration = segmentRange.end(0) - segmentRange.start(0);
  3039. var intersection = bufferIntersection(segmentRange, buffered);
  3040. var overlapDuration = 0;
  3041. var count = intersection.length;
  3042. while (count--) {
  3043. overlapDuration += intersection.end(count) - intersection.start(count);
  3044. }
  3045. return overlapDuration / segmentDuration * 100;
  3046. };
  3047. exports['default'] = {
  3048. findRange: findRange,
  3049. findNextRange: findNextRange,
  3050. findSoleUncommonTimeRangesEnd: findSoleUncommonTimeRangesEnd,
  3051. calculateBufferedPercent: calculateBufferedPercent,
  3052. TIME_FUDGE_FACTOR: TIME_FUDGE_FACTOR
  3053. };
  3054. module.exports = exports['default'];
  3055. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3056. },{}],15:[function(require,module,exports){
  3057. /**
  3058. * @file resolve-url.js
  3059. */
  3060. 'use strict';
  3061. Object.defineProperty(exports, '__esModule', {
  3062. value: true
  3063. });
  3064. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  3065. var _globalDocument = require('global/document');
  3066. var _globalDocument2 = _interopRequireDefault(_globalDocument);
  3067. /**
  3068. * Constructs a new URI by interpreting a path relative to another
  3069. * URI.
  3070. *
  3071. * @see http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
  3072. * @param {String} basePath a relative or absolute URI
  3073. * @param {String} path a path part to combine with the base
  3074. * @return {String} a URI that is equivalent to composing `base`
  3075. * with `path`
  3076. */
  3077. var resolveUrl = function resolveUrl(basePath, path) {
  3078. // use the base element to get the browser to handle URI resolution
  3079. var oldBase = _globalDocument2['default'].querySelector('base');
  3080. var docHead = _globalDocument2['default'].querySelector('head');
  3081. var a = _globalDocument2['default'].createElement('a');
  3082. var base = oldBase;
  3083. var oldHref = undefined;
  3084. var result = undefined;
  3085. // prep the document
  3086. if (oldBase) {
  3087. oldHref = oldBase.href;
  3088. } else {
  3089. base = docHead.appendChild(_globalDocument2['default'].createElement('base'));
  3090. }
  3091. base.href = basePath;
  3092. a.href = path;
  3093. result = a.href;
  3094. // clean up
  3095. if (oldBase) {
  3096. oldBase.href = oldHref;
  3097. } else {
  3098. docHead.removeChild(base);
  3099. }
  3100. return result;
  3101. };
  3102. exports['default'] = resolveUrl;
  3103. module.exports = exports['default'];
  3104. },{"global/document":21}],16:[function(require,module,exports){
  3105. (function (global){
  3106. /**
  3107. * @file segment-loader.js
  3108. */
  3109. 'use strict';
  3110. Object.defineProperty(exports, '__esModule', {
  3111. value: true
  3112. });
  3113. 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; }; })();
  3114. 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); } } };
  3115. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  3116. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  3117. 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; }
  3118. var _ranges = require('./ranges');
  3119. var _ranges2 = _interopRequireDefault(_ranges);
  3120. var _playlist = require('./playlist');
  3121. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  3122. var _videoJs2 = _interopRequireDefault(_videoJs);
  3123. var _sourceUpdater = require('./source-updater');
  3124. var _sourceUpdater2 = _interopRequireDefault(_sourceUpdater);
  3125. var _decrypter = require('./decrypter');
  3126. // in ms
  3127. var CHECK_BUFFER_DELAY = 500;
  3128. // the desired length of video to maintain in the buffer, in seconds
  3129. var GOAL_BUFFER_LENGTH = 30;
  3130. exports.GOAL_BUFFER_LENGTH = GOAL_BUFFER_LENGTH;
  3131. /**
  3132. * Updates segment with information about its end-point in time and, optionally,
  3133. * the segment duration if we have enough information to determine a segment duration
  3134. * accurately.
  3135. *
  3136. * @param {Object} playlist a media playlist object
  3137. * @param {Number} segmentIndex the index of segment we last appended
  3138. * @param {Number} segmentEnd the known of the segment referenced by segmentIndex
  3139. */
  3140. var updateSegmentMetadata = function updateSegmentMetadata(playlist, segmentIndex, segmentEnd) {
  3141. if (!playlist) {
  3142. return false;
  3143. }
  3144. var segment = playlist.segments[segmentIndex];
  3145. var previousSegment = playlist.segments[segmentIndex - 1];
  3146. if (segmentEnd && segment) {
  3147. segment.end = segmentEnd;
  3148. // fix up segment durations based on segment end data
  3149. if (!previousSegment) {
  3150. // first segment is always has a start time of 0 making its duration
  3151. // equal to the segment end
  3152. segment.duration = segment.end;
  3153. } else if (previousSegment.end) {
  3154. segment.duration = segment.end - previousSegment.end;
  3155. }
  3156. return true;
  3157. }
  3158. return false;
  3159. };
  3160. /**
  3161. * Determines if we should call endOfStream on the media source based
  3162. * on the state of the buffer or if appened segment was the final
  3163. * segment in the playlist.
  3164. *
  3165. * @param {Object} playlist a media playlist object
  3166. * @param {Object} mediaSource the MediaSource object
  3167. * @param {Number} segmentIndex the index of segment we last appended
  3168. * @param {Object} currentBuffered buffered region that currentTime resides in
  3169. * @returns {Boolean} do we need to call endOfStream on the MediaSource
  3170. */
  3171. var detectEndOfStream = function detectEndOfStream(playlist, mediaSource, segmentIndex, currentBuffered) {
  3172. if (!playlist) {
  3173. return false;
  3174. }
  3175. var segments = playlist.segments;
  3176. // determine a few boolean values to help make the branch below easier
  3177. // to read
  3178. var appendedLastSegment = segmentIndex === segments.length - 1;
  3179. var bufferedToEnd = currentBuffered.length && segments[segments.length - 1].end <= currentBuffered.end(0);
  3180. // if we've buffered to the end of the video, we need to call endOfStream
  3181. // so that MediaSources can trigger the `ended` event when it runs out of
  3182. // buffered data instead of waiting for me
  3183. return playlist.endList && mediaSource.readyState === 'open' && (appendedLastSegment || bufferedToEnd);
  3184. };
  3185. /* Turns segment byterange into a string suitable for use in
  3186. * HTTP Range requests
  3187. */
  3188. var byterangeStr = function byterangeStr(byterange) {
  3189. var byterangeStart = undefined;
  3190. var byterangeEnd = undefined;
  3191. // `byterangeEnd` is one less than `offset + length` because the HTTP range
  3192. // header uses inclusive ranges
  3193. byterangeEnd = byterange.offset + byterange.length - 1;
  3194. byterangeStart = byterange.offset;
  3195. return 'bytes=' + byterangeStart + '-' + byterangeEnd;
  3196. };
  3197. /* Defines headers for use in the xhr request for a particular segment.
  3198. */
  3199. var segmentXhrHeaders = function segmentXhrHeaders(segment) {
  3200. var headers = {};
  3201. if ('byterange' in segment) {
  3202. headers.Range = byterangeStr(segment.byterange);
  3203. }
  3204. return headers;
  3205. };
  3206. /**
  3207. * An object that manages segment loading and appending.
  3208. *
  3209. * @class SegmentLoader
  3210. * @param {Object} options required and optional options
  3211. * @extends videojs.EventTarget
  3212. */
  3213. var SegmentLoader = (function (_videojs$EventTarget) {
  3214. _inherits(SegmentLoader, _videojs$EventTarget);
  3215. function SegmentLoader(options) {
  3216. _classCallCheck(this, SegmentLoader);
  3217. _get(Object.getPrototypeOf(SegmentLoader.prototype), 'constructor', this).call(this);
  3218. var settings = undefined;
  3219. // check pre-conditions
  3220. if (!options) {
  3221. throw new TypeError('Initialization options are required');
  3222. }
  3223. if (typeof options.currentTime !== 'function') {
  3224. throw new TypeError('No currentTime getter specified');
  3225. }
  3226. if (!options.mediaSource) {
  3227. throw new TypeError('No MediaSource specified');
  3228. }
  3229. settings = _videoJs2['default'].mergeOptions(_videoJs2['default'].options.hls, options);
  3230. // public properties
  3231. this.state = 'INIT';
  3232. this.bandwidth = settings.bandwidth;
  3233. this.roundTrip = NaN;
  3234. this.bytesReceived = 0;
  3235. // private properties
  3236. this.hasPlayed_ = settings.hasPlayed;
  3237. this.currentTime_ = settings.currentTime;
  3238. this.seekable_ = settings.seekable;
  3239. this.seeking_ = settings.seeking;
  3240. this.setCurrentTime_ = settings.setCurrentTime;
  3241. this.mediaSource_ = settings.mediaSource;
  3242. this.withCredentials_ = settings.withCredentials;
  3243. this.checkBufferTimeout_ = null;
  3244. this.error_ = void 0;
  3245. this.expired_ = 0;
  3246. this.timeCorrection_ = 0;
  3247. this.currentTimeline_ = -1;
  3248. this.xhr_ = null;
  3249. this.pendingSegment_ = null;
  3250. this.sourceUpdater_ = null;
  3251. this.hls_ = settings.hls;
  3252. }
  3253. /**
  3254. * dispose of the SegmentLoader and reset to the default state
  3255. */
  3256. _createClass(SegmentLoader, [{
  3257. key: 'dispose',
  3258. value: function dispose() {
  3259. this.state = 'DISPOSED';
  3260. this.abort_();
  3261. if (this.sourceUpdater_) {
  3262. this.sourceUpdater_.dispose();
  3263. }
  3264. }
  3265. /**
  3266. * abort anything that is currently doing on with the SegmentLoader
  3267. * and reset to a default state
  3268. */
  3269. }, {
  3270. key: 'abort',
  3271. value: function abort() {
  3272. if (this.state !== 'WAITING') {
  3273. return;
  3274. }
  3275. this.abort_();
  3276. // don't wait for buffer check timeouts to begin fetching the
  3277. // next segment
  3278. if (!this.paused()) {
  3279. this.state = 'READY';
  3280. this.fillBuffer_();
  3281. }
  3282. }
  3283. /**
  3284. * set an error on the segment loader and null out any pending segements
  3285. *
  3286. * @param {Error} error the error to set on the SegmentLoader
  3287. * @return {Error} the error that was set or that is currently set
  3288. */
  3289. }, {
  3290. key: 'error',
  3291. value: function error(_error) {
  3292. if (typeof _error !== 'undefined') {
  3293. this.error_ = _error;
  3294. }
  3295. this.pendingSegment_ = null;
  3296. return this.error_;
  3297. }
  3298. /**
  3299. * load a playlist and start to fill the buffer
  3300. */
  3301. }, {
  3302. key: 'load',
  3303. value: function load() {
  3304. this.monitorBuffer_();
  3305. // if we don't have a playlist yet, keep waiting for one to be
  3306. // specified
  3307. if (!this.playlist_) {
  3308. return;
  3309. }
  3310. // if we're in the middle of processing a segment already, don't
  3311. // kick off an additional segment request
  3312. if (!this.sourceUpdater_ || this.state !== 'READY' && this.state !== 'INIT') {
  3313. return;
  3314. }
  3315. this.state = 'READY';
  3316. this.fillBuffer_();
  3317. }
  3318. /**
  3319. * set a playlist on the segment loader
  3320. *
  3321. * @param {PlaylistLoader} media the playlist to set on the segment loader
  3322. */
  3323. }, {
  3324. key: 'playlist',
  3325. value: function playlist(media) {
  3326. this.playlist_ = media;
  3327. // if we were unpaused but waiting for a playlist, start
  3328. // buffering now
  3329. if (this.sourceUpdater_ && media && this.state === 'INIT' && !this.paused()) {
  3330. this.state = 'READY';
  3331. return this.fillBuffer_();
  3332. }
  3333. }
  3334. /**
  3335. * Prevent the loader from fetching additional segments. If there
  3336. * is a segment request outstanding, it will finish processing
  3337. * before the loader halts. A segment loader can be unpaused by
  3338. * calling load().
  3339. */
  3340. }, {
  3341. key: 'pause',
  3342. value: function pause() {
  3343. if (this.checkBufferTimeout_) {
  3344. window.clearTimeout(this.checkBufferTimeout_);
  3345. this.checkBufferTimeout_ = null;
  3346. }
  3347. }
  3348. /**
  3349. * Returns whether the segment loader is fetching additional
  3350. * segments when given the opportunity. This property can be
  3351. * modified through calls to pause() and load().
  3352. */
  3353. }, {
  3354. key: 'paused',
  3355. value: function paused() {
  3356. return this.checkBufferTimeout_ === null;
  3357. }
  3358. /**
  3359. * setter for expired time on the SegmentLoader
  3360. *
  3361. * @param {Number} expired the exired time to set
  3362. */
  3363. }, {
  3364. key: 'expired',
  3365. value: function expired(_expired) {
  3366. this.expired_ = _expired;
  3367. }
  3368. /**
  3369. * create/set the following mimetype on the SourceBuffer through a
  3370. * SourceUpdater
  3371. *
  3372. * @param {String} mimeType the mime type string to use
  3373. */
  3374. }, {
  3375. key: 'mimeType',
  3376. value: function mimeType(_mimeType) {
  3377. // TODO Allow source buffers to be re-created with different mime-types
  3378. if (!this.sourceUpdater_) {
  3379. this.sourceUpdater_ = new _sourceUpdater2['default'](this.mediaSource_, _mimeType);
  3380. this.clearBuffer();
  3381. // if we were unpaused but waiting for a sourceUpdater, start
  3382. // buffering now
  3383. if (this.playlist_ && this.state === 'INIT' && !this.paused()) {
  3384. this.state = 'READY';
  3385. return this.fillBuffer_();
  3386. }
  3387. }
  3388. }
  3389. /**
  3390. * asynchronously/recursively monitor the buffer
  3391. *
  3392. * @private
  3393. */
  3394. }, {
  3395. key: 'monitorBuffer_',
  3396. value: function monitorBuffer_() {
  3397. if (this.state === 'READY') {
  3398. this.fillBuffer_();
  3399. }
  3400. if (this.checkBufferTimeout_) {
  3401. window.clearTimeout(this.checkBufferTimeout_);
  3402. }
  3403. this.checkBufferTimeout_ = window.setTimeout(this.monitorBuffer_.bind(this), CHECK_BUFFER_DELAY);
  3404. }
  3405. /**
  3406. * Return the amount of a segment specified by the mediaIndex overlaps
  3407. * the current buffered content.
  3408. *
  3409. * @param {Object} playlist the playlist object to fetch segments from
  3410. * @param {Number} mediaIndex the index of the segment in the playlist
  3411. * @param {TimeRanges} buffered the state of the buffer
  3412. * @returns {Number} percentage of the segment's time range that is
  3413. * already in `buffered`
  3414. */
  3415. }, {
  3416. key: 'getSegmentBufferedPercent_',
  3417. value: function getSegmentBufferedPercent_(playlist, mediaIndex, currentTime, buffered) {
  3418. var segment = playlist.segments[mediaIndex];
  3419. var startOfSegment = (0, _playlist.duration)(playlist, playlist.mediaSequence + mediaIndex, this.expired_);
  3420. var segmentRange = _videoJs2['default'].createTimeRanges([[Math.max(currentTime, startOfSegment), startOfSegment + segment.duration]]);
  3421. return _ranges2['default'].calculateBufferedPercent(segmentRange, buffered);
  3422. }
  3423. /**
  3424. * Determines what segment request should be made, given current
  3425. * playback state.
  3426. *
  3427. * @param {TimeRanges} buffered - the state of the buffer
  3428. * @param {Object} playlist - the playlist object to fetch segments from
  3429. * @param {Number} currentTime - the playback position in seconds
  3430. * @returns {Object} a segment info object that describes the
  3431. * request that should be made or null if no request is necessary
  3432. */
  3433. }, {
  3434. key: 'checkBuffer_',
  3435. value: function checkBuffer_(buffered, playlist, currentTime) {
  3436. var currentBuffered = _ranges2['default'].findRange(buffered, currentTime);
  3437. // There are times when MSE reports the first segment as starting a
  3438. // little after 0-time so add a fudge factor to try and fix those cases
  3439. // or we end up fetching the same first segment over and over
  3440. if (currentBuffered.length === 0 && currentTime === 0) {
  3441. currentBuffered = _ranges2['default'].findRange(buffered, currentTime + _ranges2['default'].TIME_FUDGE_FACTOR);
  3442. }
  3443. var bufferedTime = undefined;
  3444. var currentBufferedEnd = undefined;
  3445. var timestampOffset = this.sourceUpdater_.timestampOffset();
  3446. var segment = undefined;
  3447. var mediaIndex = undefined;
  3448. if (!playlist.segments.length) {
  3449. return;
  3450. }
  3451. if (currentBuffered.length === 0) {
  3452. // find the segment containing currentTime
  3453. mediaIndex = (0, _playlist.getMediaIndexForTime_)(playlist, currentTime + this.timeCorrection_, this.expired_);
  3454. } else {
  3455. // find the segment adjacent to the end of the current
  3456. // buffered region
  3457. currentBufferedEnd = currentBuffered.end(0);
  3458. bufferedTime = Math.max(0, currentBufferedEnd - currentTime);
  3459. // if the video has not yet played only, and we already have
  3460. // one segment downloaded do nothing
  3461. if (!this.hasPlayed_() && bufferedTime >= 1) {
  3462. return null;
  3463. }
  3464. // if there is plenty of content buffered, and the video has
  3465. // been played before relax for awhile
  3466. if (this.hasPlayed_() && bufferedTime >= GOAL_BUFFER_LENGTH) {
  3467. return null;
  3468. }
  3469. mediaIndex = (0, _playlist.getMediaIndexForTime_)(playlist, currentBufferedEnd + this.timeCorrection_, this.expired_);
  3470. }
  3471. if (mediaIndex < 0 || mediaIndex === playlist.segments.length) {
  3472. return null;
  3473. }
  3474. segment = playlist.segments[mediaIndex];
  3475. var startOfSegment = (0, _playlist.duration)(playlist, playlist.mediaSequence + mediaIndex, this.expired_);
  3476. // We will need to change timestampOffset of the sourceBuffer if either of
  3477. // the following conditions are true:
  3478. // - The segment.timeline !== this.currentTimeline
  3479. // (we are crossing a discontinuity somehow)
  3480. // - The "timestampOffset" for the start of this segment is less than
  3481. // the currently set timestampOffset
  3482. if (segment.timeline !== this.currentTimeline_ || startOfSegment < this.sourceUpdater_.timestampOffset()) {
  3483. timestampOffset = startOfSegment;
  3484. }
  3485. return {
  3486. // resolve the segment URL relative to the playlist
  3487. uri: segment.resolvedUri,
  3488. // the segment's mediaIndex at the time it was requested
  3489. mediaIndex: mediaIndex,
  3490. // the segment's playlist
  3491. playlist: playlist,
  3492. // unencrypted bytes of the segment
  3493. bytes: null,
  3494. // when a key is defined for this segment, the encrypted bytes
  3495. encryptedBytes: null,
  3496. // the state of the buffer before a segment is appended will be
  3497. // stored here so that the actual segment duration can be
  3498. // determined after it has been appended
  3499. buffered: null,
  3500. // The target timestampOffset for this segment when we append it
  3501. // to the source buffer
  3502. timestampOffset: timestampOffset,
  3503. // The timeline that the segment is in
  3504. timeline: segment.timeline
  3505. };
  3506. }
  3507. /**
  3508. * abort all pending xhr requests and null any pending segements
  3509. *
  3510. * @private
  3511. */
  3512. }, {
  3513. key: 'abort_',
  3514. value: function abort_() {
  3515. if (this.xhr_) {
  3516. this.xhr_.abort();
  3517. }
  3518. // clear out the segment being processed
  3519. this.pendingSegment_ = null;
  3520. }
  3521. /**
  3522. * fill the buffer with segements unless the
  3523. * sourceBuffers are currently updating
  3524. *
  3525. * @private
  3526. */
  3527. }, {
  3528. key: 'fillBuffer_',
  3529. value: function fillBuffer_() {
  3530. if (this.sourceUpdater_.updating()) {
  3531. return;
  3532. }
  3533. // see if we need to begin loading immediately
  3534. var request = this.checkBuffer_(this.sourceUpdater_.buffered(), this.playlist_, this.currentTime_(), this.timestampOffset_);
  3535. if (!request) {
  3536. return;
  3537. }
  3538. // Sanity check the segment-index determining logic by calcuating the
  3539. // percentage of the chosen segment that is buffered. If more than 90%
  3540. // of the segment is buffered then fetching it will likely not help in
  3541. // any way
  3542. var percentBuffered = this.getSegmentBufferedPercent_(this.playlist_, request.mediaIndex, this.currentTime_(), this.sourceUpdater_.buffered());
  3543. if (percentBuffered >= 90) {
  3544. // Increment the timeCorrection_ variable to push the fetcher forward
  3545. // in time and hopefully skip any gaps or flaws in our understanding
  3546. // of the media
  3547. this.incrementTimeCorrection_(this.playlist_.targetDuration);
  3548. if (!this.paused()) {
  3549. this.fillBuffer_();
  3550. }
  3551. return;
  3552. }
  3553. this.loadSegment_(request);
  3554. }
  3555. /**
  3556. * load a specific segment from a request into the buffer
  3557. *
  3558. * @private
  3559. */
  3560. }, {
  3561. key: 'loadSegment_',
  3562. value: function loadSegment_(segmentInfo) {
  3563. var segment = undefined;
  3564. var requestTimeout = undefined;
  3565. var keyXhr = undefined;
  3566. var segmentXhr = undefined;
  3567. var seekable = this.seekable_();
  3568. var currentTime = this.currentTime_();
  3569. var removeToTime = 0;
  3570. // Chrome has a hard limit of 150mb of
  3571. // buffer and a very conservative "garbage collector"
  3572. // We manually clear out the old buffer to ensure
  3573. // we don't trigger the QuotaExceeded error
  3574. // on the source buffer during subsequent appends
  3575. // If we have a seekable range use that as the limit for what can be removed safely
  3576. // otherwise remove anything older than 1 minute before the current play head
  3577. if (seekable.length && seekable.start(0) > 0 && seekable.start(0) < currentTime) {
  3578. removeToTime = seekable.start(0);
  3579. } else {
  3580. removeToTime = currentTime - 60;
  3581. }
  3582. if (removeToTime > 0) {
  3583. this.sourceUpdater_.remove(0, removeToTime);
  3584. }
  3585. segment = segmentInfo.playlist.segments[segmentInfo.mediaIndex];
  3586. // Set xhr timeout to 150% of the segment duration to allow us
  3587. // some time to switch renditions in the event of a catastrophic
  3588. // decrease in network performance or a server issue.
  3589. requestTimeout = segment.duration * 1.5 * 1000;
  3590. if (segment.key) {
  3591. keyXhr = this.hls_.xhr({
  3592. uri: segment.key.resolvedUri,
  3593. responseType: 'arraybuffer',
  3594. withCredentials: this.withCredentials_,
  3595. timeout: requestTimeout
  3596. }, this.handleResponse_.bind(this));
  3597. }
  3598. this.pendingSegment_ = segmentInfo;
  3599. segmentXhr = this.hls_.xhr({
  3600. uri: segmentInfo.uri,
  3601. responseType: 'arraybuffer',
  3602. withCredentials: this.withCredentials_,
  3603. timeout: requestTimeout,
  3604. headers: segmentXhrHeaders(segment)
  3605. }, this.handleResponse_.bind(this));
  3606. this.xhr_ = {
  3607. keyXhr: keyXhr,
  3608. segmentXhr: segmentXhr,
  3609. abort: function abort() {
  3610. if (this.segmentXhr) {
  3611. // Prevent error handler from running.
  3612. this.segmentXhr.onreadystatechange = null;
  3613. this.segmentXhr.abort();
  3614. this.segmentXhr = null;
  3615. }
  3616. if (this.keyXhr) {
  3617. // Prevent error handler from running.
  3618. this.keyXhr.onreadystatechange = null;
  3619. this.keyXhr.abort();
  3620. this.keyXhr = null;
  3621. }
  3622. }
  3623. };
  3624. this.state = 'WAITING';
  3625. }
  3626. /**
  3627. * triggered when a segment response is received
  3628. *
  3629. * @private
  3630. */
  3631. }, {
  3632. key: 'handleResponse_',
  3633. value: function handleResponse_(error, request) {
  3634. var segmentInfo = undefined;
  3635. var segment = undefined;
  3636. var keyXhrRequest = undefined;
  3637. var view = undefined;
  3638. // timeout of previously aborted request
  3639. if (!this.xhr_ || request !== this.xhr_.segmentXhr && request !== this.xhr_.keyXhr) {
  3640. return;
  3641. }
  3642. segmentInfo = this.pendingSegment_;
  3643. segment = segmentInfo.playlist.segments[segmentInfo.mediaIndex];
  3644. // if a request times out, reset bandwidth tracking
  3645. if (request.timedout) {
  3646. this.abort_();
  3647. this.bandwidth = 1;
  3648. this.roundTrip = NaN;
  3649. this.state = 'READY';
  3650. return this.trigger('progress');
  3651. }
  3652. // trigger an event for other errors
  3653. if (!request.aborted && error) {
  3654. // abort will clear xhr_
  3655. keyXhrRequest = this.xhr_.keyXhr;
  3656. this.abort_();
  3657. this.error({
  3658. status: request.status,
  3659. message: request === keyXhrRequest ? 'HLS key request error at URL: ' + segment.key.uri : 'HLS segment request error at URL: ' + segmentInfo.uri,
  3660. code: 2,
  3661. xhr: request
  3662. });
  3663. this.state = 'READY';
  3664. this.pause();
  3665. return this.trigger('error');
  3666. }
  3667. // stop processing if the request was aborted
  3668. if (!request.response) {
  3669. this.abort_();
  3670. return;
  3671. }
  3672. if (request === this.xhr_.segmentXhr) {
  3673. // the segment request is no longer outstanding
  3674. this.xhr_.segmentXhr = null;
  3675. // calculate the download bandwidth based on segment request
  3676. this.roundTrip = request.roundTripTime;
  3677. this.bandwidth = request.bandwidth;
  3678. this.bytesReceived += request.bytesReceived || 0;
  3679. if (segment.key) {
  3680. segmentInfo.encryptedBytes = new Uint8Array(request.response);
  3681. } else {
  3682. segmentInfo.bytes = new Uint8Array(request.response);
  3683. }
  3684. }
  3685. if (request === this.xhr_.keyXhr) {
  3686. keyXhrRequest = this.xhr_.segmentXhr;
  3687. // the key request is no longer outstanding
  3688. this.xhr_.keyXhr = null;
  3689. if (request.response.byteLength !== 16) {
  3690. this.abort_();
  3691. this.error({
  3692. status: request.status,
  3693. message: 'Invalid HLS key at URL: ' + segment.key.uri,
  3694. code: 2,
  3695. xhr: request
  3696. });
  3697. this.state = 'READY';
  3698. this.pause();
  3699. return this.trigger('error');
  3700. }
  3701. view = new DataView(request.response);
  3702. segment.key.bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  3703. // if the media sequence is greater than 2^32, the IV will be incorrect
  3704. // assuming 10s segments, that would be about 1300 years
  3705. segment.key.iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
  3706. }
  3707. if (!this.xhr_.segmentXhr && !this.xhr_.keyXhr) {
  3708. this.xhr_ = null;
  3709. this.processResponse_();
  3710. }
  3711. }
  3712. /**
  3713. * clear anything that is currently in the buffer and throw it away
  3714. */
  3715. }, {
  3716. key: 'clearBuffer',
  3717. value: function clearBuffer() {
  3718. if (this.sourceUpdater_ && this.sourceUpdater_.buffered().length) {
  3719. this.sourceUpdater_.remove(0, Infinity);
  3720. }
  3721. }
  3722. /**
  3723. * Decrypt the segment that is being loaded if necessary
  3724. *
  3725. * @private
  3726. */
  3727. }, {
  3728. key: 'processResponse_',
  3729. value: function processResponse_() {
  3730. var segmentInfo = undefined;
  3731. var segment = undefined;
  3732. this.state = 'DECRYPTING';
  3733. segmentInfo = this.pendingSegment_;
  3734. segment = segmentInfo.playlist.segments[segmentInfo.mediaIndex];
  3735. if (segment.key) {
  3736. // this is an encrypted segment
  3737. // incrementally decrypt the segment
  3738. /* eslint-disable no-new, handle-callback-err */
  3739. new _decrypter.Decrypter(segmentInfo.encryptedBytes, segment.key.bytes, segment.key.iv, (function (err, bytes) {
  3740. // err always null
  3741. segmentInfo.bytes = bytes;
  3742. this.handleSegment_();
  3743. }).bind(this));
  3744. /* eslint-enable */
  3745. } else {
  3746. this.handleSegment_();
  3747. }
  3748. }
  3749. /**
  3750. * append a decrypted segement to the SourceBuffer through a SourceUpdater
  3751. *
  3752. * @private
  3753. */
  3754. }, {
  3755. key: 'handleSegment_',
  3756. value: function handleSegment_() {
  3757. var segmentInfo = undefined;
  3758. this.state = 'APPENDING';
  3759. segmentInfo = this.pendingSegment_;
  3760. segmentInfo.buffered = this.sourceUpdater_.buffered();
  3761. this.currentTimeline_ = segmentInfo.timeline;
  3762. if (segmentInfo.timestampOffset !== this.sourceUpdater_.timestampOffset()) {
  3763. this.sourceUpdater_.timestampOffset(segmentInfo.timestampOffset);
  3764. }
  3765. this.sourceUpdater_.appendBuffer(segmentInfo.bytes, this.handleUpdateEnd_.bind(this));
  3766. }
  3767. /**
  3768. * callback to run when appendBuffer is finished. detects if we are
  3769. * in a good state to do things with the data we got, or if we need
  3770. * to wait for more
  3771. *
  3772. * @private
  3773. */
  3774. }, {
  3775. key: 'handleUpdateEnd_',
  3776. value: function handleUpdateEnd_() {
  3777. var segmentInfo = this.pendingSegment_;
  3778. var currentTime = this.currentTime_();
  3779. this.pendingSegment_ = null;
  3780. // add segment metadata if it we have gained information during the
  3781. // last append
  3782. this.updateTimeline_(segmentInfo);
  3783. this.trigger('progress');
  3784. var currentMediaIndex = segmentInfo.mediaIndex;
  3785. currentMediaIndex += segmentInfo.playlist.mediaSequence - this.playlist_.mediaSequence;
  3786. var currentBuffered = _ranges2['default'].findRange(this.sourceUpdater_.buffered(), currentTime);
  3787. // any time an update finishes and the last segment is in the
  3788. // buffer, end the stream. this ensures the "ended" event will
  3789. // fire if playback reaches that point.
  3790. var isEndOfStream = detectEndOfStream(segmentInfo.playlist, this.mediaSource_, currentMediaIndex, currentBuffered);
  3791. if (isEndOfStream) {
  3792. this.mediaSource_.endOfStream();
  3793. }
  3794. // when seeking to the beginning of the seekable range, it's
  3795. // possible that imprecise timing information may cause the seek to
  3796. // end up earlier than the start of the range
  3797. // in that case, seek again
  3798. var seekable = this.seekable_();
  3799. var next = _ranges2['default'].findNextRange(this.sourceUpdater_.buffered(), currentTime);
  3800. if (this.seeking_() && currentBuffered.length === 0) {
  3801. if (seekable.length && currentTime < seekable.start(0)) {
  3802. if (next.length) {
  3803. _videoJs2['default'].log('tried seeking to', currentTime, 'but that was too early, retrying at', next.start(0));
  3804. this.setCurrentTime_(next.start(0) + _ranges2['default'].TIME_FUDGE_FACTOR);
  3805. }
  3806. }
  3807. }
  3808. this.state = 'READY';
  3809. if (!this.paused()) {
  3810. this.fillBuffer_();
  3811. }
  3812. }
  3813. /**
  3814. * annotate the segment with any start and end time information
  3815. * added by the media processing
  3816. *
  3817. * @private
  3818. * @param {Object} segmentInfo annotate a segment with time info
  3819. */
  3820. }, {
  3821. key: 'updateTimeline_',
  3822. value: function updateTimeline_(segmentInfo) {
  3823. var segment = undefined;
  3824. var segmentEnd = undefined;
  3825. var timelineUpdated = undefined;
  3826. var segmentLength = this.playlist_.targetDuration;
  3827. var playlist = segmentInfo.playlist;
  3828. var currentMediaIndex = segmentInfo.mediaIndex;
  3829. currentMediaIndex += playlist.mediaSequence - this.playlist_.mediaSequence;
  3830. segment = playlist.segments[currentMediaIndex];
  3831. // Update segment meta-data (duration and end-point) based on timeline
  3832. if (segment && segmentInfo && segmentInfo.playlist.uri === this.playlist_.uri) {
  3833. segmentEnd = _ranges2['default'].findSoleUncommonTimeRangesEnd(segmentInfo.buffered, this.sourceUpdater_.buffered());
  3834. timelineUpdated = updateSegmentMetadata(playlist, currentMediaIndex, segmentEnd);
  3835. segmentLength = segment.duration;
  3836. }
  3837. // the last segment append must have been entirely in the
  3838. // already buffered time ranges. adjust the timeCorrection
  3839. // offset to fetch forward until we find a segment that adds
  3840. // to the buffered time ranges and improves subsequent media
  3841. // index calculations.
  3842. if (!timelineUpdated) {
  3843. this.incrementTimeCorrection_(segmentLength);
  3844. } else {
  3845. this.timeCorrection_ = 0;
  3846. }
  3847. }
  3848. /**
  3849. * add a number of seconds to the currentTime when determining which
  3850. * segment to fetch in order to force the fetcher to advance in cases
  3851. * where it may get stuck on the same segment due to buffer gaps or
  3852. * missing segment annotation after a rendition switch (especially
  3853. * during a live stream)
  3854. *
  3855. * @private
  3856. * @param {Number} secondsToIncrement number of seconds to add to the
  3857. * timeCorrection_ variable
  3858. */
  3859. }, {
  3860. key: 'incrementTimeCorrection_',
  3861. value: function incrementTimeCorrection_(secondsToIncrement) {
  3862. // If we have already incremented timeCorrection_ beyond the limit,
  3863. // then stop trying to find a segment, pause fetching, and emit an
  3864. // error event
  3865. if (this.timeCorrection_ >= this.playlist_.targetDuration * 5) {
  3866. this.timeCorrection_ = 0;
  3867. this.pause();
  3868. return this.trigger('error');
  3869. }
  3870. this.timeCorrection_ += secondsToIncrement;
  3871. }
  3872. }]);
  3873. return SegmentLoader;
  3874. })(_videoJs2['default'].EventTarget);
  3875. exports['default'] = SegmentLoader;
  3876. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3877. },{"./decrypter":5,"./playlist":13,"./ranges":14,"./source-updater":17}],17:[function(require,module,exports){
  3878. (function (global){
  3879. /**
  3880. * @file source-updater.js
  3881. */
  3882. 'use strict';
  3883. Object.defineProperty(exports, '__esModule', {
  3884. value: true
  3885. });
  3886. 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; }; })();
  3887. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  3888. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  3889. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  3890. var _videoJs2 = _interopRequireDefault(_videoJs);
  3891. /**
  3892. * A queue of callbacks to be serialized and applied when a
  3893. * MediaSource and its associated SourceBuffers are not in the
  3894. * updating state. It is used by the segment loader to update the
  3895. * underlying SourceBuffers when new data is loaded, for instance.
  3896. *
  3897. * @class SourceUpdater
  3898. * @param {MediaSource} mediaSource the MediaSource to create the
  3899. * SourceBuffer from
  3900. * @param {String} mimeType the desired MIME type of the underlying
  3901. * SourceBuffer
  3902. */
  3903. var SourceUpdater = (function () {
  3904. function SourceUpdater(mediaSource, mimeType) {
  3905. var _this = this;
  3906. _classCallCheck(this, SourceUpdater);
  3907. var createSourceBuffer = function createSourceBuffer() {
  3908. _this.sourceBuffer_ = mediaSource.addSourceBuffer(mimeType);
  3909. // run completion handlers and process callbacks as updateend
  3910. // events fire
  3911. _this.sourceBuffer_.addEventListener('updateend', function () {
  3912. var pendingCallback = _this.pendingCallback_;
  3913. _this.pendingCallback_ = null;
  3914. if (pendingCallback) {
  3915. pendingCallback();
  3916. }
  3917. });
  3918. _this.sourceBuffer_.addEventListener('updateend', _this.runCallback_.bind(_this));
  3919. _this.runCallback_();
  3920. };
  3921. this.callbacks_ = [];
  3922. this.pendingCallback_ = null;
  3923. this.timestampOffset_ = 0;
  3924. this.mediaSource = mediaSource;
  3925. if (mediaSource.readyState === 'closed') {
  3926. mediaSource.addEventListener('sourceopen', createSourceBuffer);
  3927. } else {
  3928. createSourceBuffer();
  3929. }
  3930. }
  3931. /**
  3932. * Aborts the current segment and resets the segment parser.
  3933. *
  3934. * @param {Function} done function to call when done
  3935. * @see http://w3c.github.io/media-source/#widl-SourceBuffer-abort-void
  3936. */
  3937. _createClass(SourceUpdater, [{
  3938. key: 'abort',
  3939. value: function abort(done) {
  3940. var _this2 = this;
  3941. this.queueCallback_(function () {
  3942. _this2.sourceBuffer_.abort();
  3943. }, done);
  3944. }
  3945. /**
  3946. * Queue an update to append an ArrayBuffer.
  3947. *
  3948. * @param {ArrayBuffer} bytes
  3949. * @param {Function} done the function to call when done
  3950. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
  3951. */
  3952. }, {
  3953. key: 'appendBuffer',
  3954. value: function appendBuffer(bytes, done) {
  3955. var _this3 = this;
  3956. this.queueCallback_(function () {
  3957. _this3.sourceBuffer_.appendBuffer(bytes);
  3958. }, done);
  3959. }
  3960. /**
  3961. * Indicates what TimeRanges are buffered in the managed SourceBuffer.
  3962. *
  3963. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-buffered
  3964. */
  3965. }, {
  3966. key: 'buffered',
  3967. value: function buffered() {
  3968. if (!this.sourceBuffer_) {
  3969. return _videoJs2['default'].createTimeRanges();
  3970. }
  3971. return this.sourceBuffer_.buffered;
  3972. }
  3973. /**
  3974. * Queue an update to set the duration.
  3975. *
  3976. * @param {Double} duration what to set the duration to
  3977. * @see http://www.w3.org/TR/media-source/#widl-MediaSource-duration
  3978. */
  3979. }, {
  3980. key: 'duration',
  3981. value: function duration(_duration) {
  3982. var _this4 = this;
  3983. this.queueCallback_(function () {
  3984. _this4.sourceBuffer_.duration = _duration;
  3985. });
  3986. }
  3987. /**
  3988. * Queue an update to remove a time range from the buffer.
  3989. *
  3990. * @param {Number} start where to start the removal
  3991. * @param {Number} end where to end the removal
  3992. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  3993. */
  3994. }, {
  3995. key: 'remove',
  3996. value: function remove(start, end) {
  3997. var _this5 = this;
  3998. this.queueCallback_(function () {
  3999. _this5.sourceBuffer_.remove(start, end);
  4000. });
  4001. }
  4002. /**
  4003. * wether the underlying sourceBuffer is updating or not
  4004. *
  4005. * @return {Boolean} the updating status of the SourceBuffer
  4006. */
  4007. }, {
  4008. key: 'updating',
  4009. value: function updating() {
  4010. return !this.sourceBuffer_ || this.sourceBuffer_.updating;
  4011. }
  4012. /**
  4013. * Set/get the timestampoffset on the SourceBuffer
  4014. *
  4015. * @return {Number} the timestamp offset
  4016. */
  4017. }, {
  4018. key: 'timestampOffset',
  4019. value: function timestampOffset(offset) {
  4020. var _this6 = this;
  4021. if (typeof offset !== 'undefined') {
  4022. this.queueCallback_(function () {
  4023. _this6.sourceBuffer_.timestampOffset = offset;
  4024. });
  4025. this.timestampOffset_ = offset;
  4026. }
  4027. return this.timestampOffset_;
  4028. }
  4029. /**
  4030. * que a callback to run
  4031. */
  4032. }, {
  4033. key: 'queueCallback_',
  4034. value: function queueCallback_(callback, done) {
  4035. this.callbacks_.push([callback.bind(this), done]);
  4036. this.runCallback_();
  4037. }
  4038. /**
  4039. * run a queued callback
  4040. */
  4041. }, {
  4042. key: 'runCallback_',
  4043. value: function runCallback_() {
  4044. var callbacks = undefined;
  4045. if (this.sourceBuffer_ && !this.sourceBuffer_.updating && this.callbacks_.length) {
  4046. callbacks = this.callbacks_.shift();
  4047. this.pendingCallback_ = callbacks[1];
  4048. callbacks[0]();
  4049. }
  4050. }
  4051. /**
  4052. * dispose of the source updater and the underlying sourceBuffer
  4053. */
  4054. }, {
  4055. key: 'dispose',
  4056. value: function dispose() {
  4057. if (this.sourceBuffer_ && this.mediaSource.readyState === 'open') {
  4058. this.sourceBuffer_.abort();
  4059. }
  4060. }
  4061. }]);
  4062. return SourceUpdater;
  4063. })();
  4064. exports['default'] = SourceUpdater;
  4065. module.exports = exports['default'];
  4066. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4067. },{}],18:[function(require,module,exports){
  4068. /**
  4069. * @file stream.js
  4070. */
  4071. /**
  4072. * A lightweight readable stream implemention that handles event dispatching.
  4073. *
  4074. * @class Stream
  4075. */
  4076. 'use strict';
  4077. Object.defineProperty(exports, '__esModule', {
  4078. value: true
  4079. });
  4080. 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; }; })();
  4081. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  4082. var Stream = (function () {
  4083. function Stream() {
  4084. _classCallCheck(this, Stream);
  4085. this.listeners = {};
  4086. }
  4087. /**
  4088. * Add a listener for a specified event type.
  4089. *
  4090. * @param {String} type the event name
  4091. * @param {Function} listener the callback to be invoked when an event of
  4092. * the specified type occurs
  4093. */
  4094. _createClass(Stream, [{
  4095. key: 'on',
  4096. value: function on(type, listener) {
  4097. if (!this.listeners[type]) {
  4098. this.listeners[type] = [];
  4099. }
  4100. this.listeners[type].push(listener);
  4101. }
  4102. /**
  4103. * Remove a listener for a specified event type.
  4104. *
  4105. * @param {String} type the event name
  4106. * @param {Function} listener a function previously registered for this
  4107. * type of event through `on`
  4108. * @return {Boolean} if we could turn it off or not
  4109. */
  4110. }, {
  4111. key: 'off',
  4112. value: function off(type, listener) {
  4113. var index = undefined;
  4114. if (!this.listeners[type]) {
  4115. return false;
  4116. }
  4117. index = this.listeners[type].indexOf(listener);
  4118. this.listeners[type].splice(index, 1);
  4119. return index > -1;
  4120. }
  4121. /**
  4122. * Trigger an event of the specified type on this stream. Any additional
  4123. * arguments to this function are passed as parameters to event listeners.
  4124. *
  4125. * @param {String} type the event name
  4126. */
  4127. }, {
  4128. key: 'trigger',
  4129. value: function trigger(type) {
  4130. var callbacks = undefined;
  4131. var i = undefined;
  4132. var length = undefined;
  4133. var args = undefined;
  4134. callbacks = this.listeners[type];
  4135. if (!callbacks) {
  4136. return;
  4137. }
  4138. // Slicing the arguments on every invocation of this method
  4139. // can add a significant amount of overhead. Avoid the
  4140. // intermediate object creation for the common case of a
  4141. // single callback argument
  4142. if (arguments.length === 2) {
  4143. length = callbacks.length;
  4144. for (i = 0; i < length; ++i) {
  4145. callbacks[i].call(this, arguments[1]);
  4146. }
  4147. } else {
  4148. args = Array.prototype.slice.call(arguments, 1);
  4149. length = callbacks.length;
  4150. for (i = 0; i < length; ++i) {
  4151. callbacks[i].apply(this, args);
  4152. }
  4153. }
  4154. }
  4155. /**
  4156. * Destroys the stream and cleans up.
  4157. */
  4158. }, {
  4159. key: 'dispose',
  4160. value: function dispose() {
  4161. this.listeners = {};
  4162. }
  4163. /**
  4164. * Forwards all `data` events on this stream to the destination stream. The
  4165. * destination stream should provide a method `push` to receive the data
  4166. * events as they arrive.
  4167. *
  4168. * @param {Stream} destination the stream that will receive all `data` events
  4169. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  4170. */
  4171. }, {
  4172. key: 'pipe',
  4173. value: function pipe(destination) {
  4174. this.on('data', function (data) {
  4175. destination.push(data);
  4176. });
  4177. }
  4178. }]);
  4179. return Stream;
  4180. })();
  4181. exports['default'] = Stream;
  4182. module.exports = exports['default'];
  4183. },{}],19:[function(require,module,exports){
  4184. (function (global){
  4185. /**
  4186. * @file xhr.js
  4187. */
  4188. /**
  4189. * A wrapper for videojs.xhr that tracks bandwidth.
  4190. *
  4191. * @param {Object} options options for the XHR
  4192. * @param {Function} callback the callback to call when done
  4193. * @return {Request} the xhr request that is going to be made
  4194. */
  4195. 'use strict';
  4196. Object.defineProperty(exports, '__esModule', {
  4197. value: true
  4198. });
  4199. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  4200. var xhrFactory = function xhrFactory() {
  4201. var xhr = function XhrFunction(options, callback) {
  4202. // Add a default timeout for all hls requests
  4203. options = (0, _videoJs.mergeOptions)({
  4204. timeout: 45e3
  4205. }, options);
  4206. // Allow an optional user-specified function to modify the option
  4207. // object before we construct the xhr request
  4208. if (XhrFunction.beforeRequest && typeof XhrFunction.beforeRequest === 'function') {
  4209. var newOptions = XhrFunction.beforeRequest(options);
  4210. if (newOptions) {
  4211. options = newOptions;
  4212. }
  4213. }
  4214. var request = (0, _videoJs.xhr)(options, function (error, response) {
  4215. if (!error && request.response) {
  4216. request.responseTime = new Date().getTime();
  4217. request.roundTripTime = request.responseTime - request.requestTime;
  4218. request.bytesReceived = request.response.byteLength || request.response.length;
  4219. if (!request.bandwidth) {
  4220. request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
  4221. }
  4222. }
  4223. // videojs.xhr now uses a specific code
  4224. // on the error object to signal that a request has
  4225. // timed out errors of setting a boolean on the request object
  4226. if (error || request.timedout) {
  4227. request.timedout = request.timedout || error.code === 'ETIMEDOUT';
  4228. } else {
  4229. request.timedout = false;
  4230. }
  4231. // videojs.xhr no longer considers status codes outside of 200 and 0
  4232. // (for file uris) to be errors, but the old XHR did, so emulate that
  4233. // behavior. Status 206 may be used in response to byterange requests.
  4234. if (!error && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
  4235. error = new Error('XHR Failed with a response of: ' + (request && (request.response || request.responseText)));
  4236. }
  4237. callback(error, request);
  4238. });
  4239. if(request!=undefined){
  4240. request.requestTime = new Date().getTime();
  4241. return request;
  4242. }
  4243. };
  4244. return xhr;
  4245. };
  4246. exports['default'] = xhrFactory;
  4247. module.exports = exports['default'];
  4248. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4249. },{}],20:[function(require,module,exports){
  4250. },{}],21:[function(require,module,exports){
  4251. (function (global){
  4252. var topLevel = typeof global !== 'undefined' ? global :
  4253. typeof window !== 'undefined' ? window : {}
  4254. var minDoc = require('min-document');
  4255. if (typeof document !== 'undefined') {
  4256. module.exports = document;
  4257. } else {
  4258. var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
  4259. if (!doccy) {
  4260. doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
  4261. }
  4262. module.exports = doccy;
  4263. }
  4264. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4265. },{"min-document":20}],22:[function(require,module,exports){
  4266. /*
  4267. * pkcs7.pad
  4268. * https://github.com/brightcove/pkcs7
  4269. *
  4270. * Copyright (c) 2014 Brightcove
  4271. * Licensed under the apache2 license.
  4272. */
  4273. 'use strict';
  4274. var PADDING;
  4275. /**
  4276. * Returns a new Uint8Array that is padded with PKCS#7 padding.
  4277. * @param plaintext {Uint8Array} the input bytes before encryption
  4278. * @return {Uint8Array} the padded bytes
  4279. * @see http://tools.ietf.org/html/rfc5652
  4280. */
  4281. module.exports = function pad(plaintext) {
  4282. var padding = PADDING[(plaintext.byteLength % 16) || 0],
  4283. result = new Uint8Array(plaintext.byteLength + padding.length);
  4284. result.set(plaintext);
  4285. result.set(padding, plaintext.byteLength);
  4286. return result;
  4287. };
  4288. // pre-define the padding values
  4289. PADDING = [
  4290. [16, 16, 16, 16,
  4291. 16, 16, 16, 16,
  4292. 16, 16, 16, 16,
  4293. 16, 16, 16, 16],
  4294. [15, 15, 15, 15,
  4295. 15, 15, 15, 15,
  4296. 15, 15, 15, 15,
  4297. 15, 15, 15],
  4298. [14, 14, 14, 14,
  4299. 14, 14, 14, 14,
  4300. 14, 14, 14, 14,
  4301. 14, 14],
  4302. [13, 13, 13, 13,
  4303. 13, 13, 13, 13,
  4304. 13, 13, 13, 13,
  4305. 13],
  4306. [12, 12, 12, 12,
  4307. 12, 12, 12, 12,
  4308. 12, 12, 12, 12],
  4309. [11, 11, 11, 11,
  4310. 11, 11, 11, 11,
  4311. 11, 11, 11],
  4312. [10, 10, 10, 10,
  4313. 10, 10, 10, 10,
  4314. 10, 10],
  4315. [9, 9, 9, 9,
  4316. 9, 9, 9, 9,
  4317. 9],
  4318. [8, 8, 8, 8,
  4319. 8, 8, 8, 8],
  4320. [7, 7, 7, 7,
  4321. 7, 7, 7],
  4322. [6, 6, 6, 6,
  4323. 6, 6],
  4324. [5, 5, 5, 5,
  4325. 5],
  4326. [4, 4, 4, 4],
  4327. [3, 3, 3],
  4328. [2, 2],
  4329. [1]
  4330. ];
  4331. },{}],23:[function(require,module,exports){
  4332. /*
  4333. * pkcs7
  4334. * https://github.com/brightcove/pkcs7
  4335. *
  4336. * Copyright (c) 2014 Brightcove
  4337. * Licensed under the apache2 license.
  4338. */
  4339. 'use strict';
  4340. exports.pad = require('./pad.js');
  4341. exports.unpad = require('./unpad.js');
  4342. },{"./pad.js":22,"./unpad.js":24}],24:[function(require,module,exports){
  4343. /*
  4344. * pkcs7.unpad
  4345. * https://github.com/brightcove/pkcs7
  4346. *
  4347. * Copyright (c) 2014 Brightcove
  4348. * Licensed under the apache2 license.
  4349. */
  4350. 'use strict';
  4351. /**
  4352. * Returns the subarray of a Uint8Array without PKCS#7 padding.
  4353. * @param padded {Uint8Array} unencrypted bytes that have been padded
  4354. * @return {Uint8Array} the unpadded bytes
  4355. * @see http://tools.ietf.org/html/rfc5652
  4356. */
  4357. module.exports = function unpad(padded) {
  4358. return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
  4359. };
  4360. },{}],25:[function(require,module,exports){
  4361. (function (global){
  4362. /**
  4363. * @file add-text-track-data.js
  4364. */
  4365. 'use strict';
  4366. Object.defineProperty(exports, '__esModule', {
  4367. value: true
  4368. });
  4369. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  4370. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  4371. var _videoJs2 = _interopRequireDefault(_videoJs);
  4372. /**
  4373. * Define properties on a cue for backwards compatability,
  4374. * but warn the user that the way that they are using it
  4375. * is depricated and will be removed at a later date.
  4376. *
  4377. * @param {Cue} cue the cue to add the properties on
  4378. * @private
  4379. */
  4380. var deprecateOldCue = function deprecateOldCue(cue) {
  4381. Object.defineProperties(cue.frame, {
  4382. id: {
  4383. get: function get() {
  4384. _videoJs2['default'].log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
  4385. return cue.value.key;
  4386. }
  4387. },
  4388. value: {
  4389. get: function get() {
  4390. _videoJs2['default'].log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
  4391. return cue.value.data;
  4392. }
  4393. },
  4394. privateData: {
  4395. get: function get() {
  4396. _videoJs2['default'].log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
  4397. return cue.value.data;
  4398. }
  4399. }
  4400. });
  4401. };
  4402. /**
  4403. * Add text track data to a source handler given the captions and
  4404. * metadata from the buffer.
  4405. *
  4406. * @param {Object} sourceHandler the flash or virtual source buffer
  4407. * @param {Array} captionArray an array of caption data
  4408. * @param {Array} cue an array of meta data
  4409. * @private
  4410. */
  4411. var addTextTrackData = function addTextTrackData(sourceHandler, captionArray, metadataArray) {
  4412. var Cue = window.WebKitDataCue || window.VTTCue;
  4413. if (captionArray) {
  4414. captionArray.forEach(function (caption) {
  4415. this.inbandTextTrack_.addCue(new Cue(caption.startTime + this.timestampOffset, caption.endTime + this.timestampOffset, caption.text));
  4416. }, sourceHandler);
  4417. }
  4418. if (metadataArray) {
  4419. metadataArray.forEach(function (metadata) {
  4420. var time = metadata.cueTime + this.timestampOffset;
  4421. metadata.frames.forEach(function (frame) {
  4422. var cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
  4423. cue.frame = frame;
  4424. cue.value = frame;
  4425. deprecateOldCue(cue);
  4426. this.metadataTrack_.addCue(cue);
  4427. }, this);
  4428. }, sourceHandler);
  4429. }
  4430. };
  4431. exports['default'] = addTextTrackData;
  4432. module.exports = exports['default'];
  4433. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4434. },{}],26:[function(require,module,exports){
  4435. /**
  4436. * @file codec-utils.js
  4437. */
  4438. /**
  4439. * Check if a codec string refers to an audio codec.
  4440. *
  4441. * @param {String} codec codec string to check
  4442. * @return {Boolean} if this is an audio codec
  4443. * @private
  4444. */
  4445. 'use strict';
  4446. Object.defineProperty(exports, '__esModule', {
  4447. value: true
  4448. });
  4449. var isAudioCodec = function isAudioCodec(codec) {
  4450. return (/mp4a\.\d+.\d+/i.test(codec)
  4451. );
  4452. };
  4453. /**
  4454. * Check if a codec string refers to a video codec.
  4455. *
  4456. * @param {String} codec codec string to check
  4457. * @return {Boolean} if this is a video codec
  4458. * @private
  4459. */
  4460. var isVideoCodec = function isVideoCodec(codec) {
  4461. return (/avc1\.[\da-f]+/i.test(codec)
  4462. );
  4463. };
  4464. /**
  4465. * Parse a content type header into a type and parameters
  4466. * object
  4467. *
  4468. * @param {String} type the content type header
  4469. * @return {Object} the parsed content-type
  4470. * @private
  4471. */
  4472. var parseContentType = function parseContentType(type) {
  4473. var object = { type: '', parameters: {} };
  4474. var parameters = type.trim().split(';');
  4475. // first parameter should always be content-type
  4476. object.type = parameters.shift().trim();
  4477. parameters.forEach(function (parameter) {
  4478. var pair = parameter.trim().split('=');
  4479. if (pair.length > 1) {
  4480. var _name = pair[0].replace(/"/g, '').trim();
  4481. var value = pair[1].replace(/"/g, '').trim();
  4482. object.parameters[_name] = value;
  4483. }
  4484. });
  4485. return object;
  4486. };
  4487. exports['default'] = {
  4488. isAudioCodec: isAudioCodec,
  4489. parseContentType: parseContentType,
  4490. isVideoCodec: isVideoCodec
  4491. };
  4492. module.exports = exports['default'];
  4493. },{}],27:[function(require,module,exports){
  4494. /**
  4495. * @file create-text-tracks-if-necessary.js
  4496. */
  4497. /**
  4498. * Create text tracks on video.js if they exist on a segment.
  4499. *
  4500. * @param {Object} sourceBuffer the VSB or FSB
  4501. * @param {Object} mediaSource the HTML or Flash media source
  4502. * @param {Object} segment the segment that may contain the text track
  4503. * @private
  4504. */
  4505. 'use strict';
  4506. Object.defineProperty(exports, '__esModule', {
  4507. value: true
  4508. });
  4509. var createTextTracksIfNecessary = function createTextTracksIfNecessary(sourceBuffer, mediaSource, segment) {
  4510. // create an in-band caption track if one is present in the segment
  4511. if (segment.captions && segment.captions.length && !sourceBuffer.inbandTextTrack_) {
  4512. sourceBuffer.inbandTextTrack_ = mediaSource.player_.addTextTrack('captions', 'cc1');
  4513. }
  4514. if (segment.metadata && segment.metadata.length && !sourceBuffer.metadataTrack_) {
  4515. sourceBuffer.metadataTrack_ = mediaSource.player_.addTextTrack('metadata', 'Timed Metadata');
  4516. sourceBuffer.metadataTrack_.inBandMetadataTrackDispatchType = segment.metadata.dispatchType;
  4517. }
  4518. };
  4519. exports['default'] = createTextTracksIfNecessary;
  4520. module.exports = exports['default'];
  4521. },{}],28:[function(require,module,exports){
  4522. /**
  4523. * @file flash-constants.js
  4524. */
  4525. /**
  4526. * The maximum size in bytes for append operations to the video.js
  4527. * SWF. Calling through to Flash blocks and can be expensive so
  4528. * tuning this parameter may improve playback on slower
  4529. * systems. There are two factors to consider:
  4530. * - Each interaction with the SWF must be quick or you risk dropping
  4531. * video frames. To maintain 60fps for the rest of the page, each append
  4532. * must not take longer than 16ms. Given the likelihood that the page
  4533. * will be executing more javascript than just playback, you probably
  4534. * want to aim for less than 8ms. We aim for just 4ms.
  4535. * - Bigger appends significantly increase throughput. The total number of
  4536. * bytes over time delivered to the SWF must exceed the video bitrate or
  4537. * playback will stall.
  4538. *
  4539. * We adaptively tune the size of appends to give the best throughput
  4540. * possible given the performance of the system. To do that we try to append
  4541. * as much as possible in TIME_PER_TICK and while tuning the size of appends
  4542. * dynamically so that we only append about 4-times in that 4ms span.
  4543. *
  4544. * The reason we try to keep the number of appends around four is due to
  4545. * externalities such as Flash load and garbage collection that are highly
  4546. * variable and having 4 iterations allows us to exit the loop early if
  4547. * an iteration takes longer than expected.
  4548. *
  4549. * @private
  4550. */
  4551. "use strict";
  4552. Object.defineProperty(exports, "__esModule", {
  4553. value: true
  4554. });
  4555. var flashConstants = {
  4556. TIME_BETWEEN_TICKS: Math.floor(1000 / 480),
  4557. TIME_PER_TICK: Math.floor(1000 / 240),
  4558. // 1kb
  4559. BYTES_PER_CHUNK: 1 * 1024,
  4560. MIN_CHUNK: 1024,
  4561. MAX_CHUNK: 1024 * 1024
  4562. };
  4563. exports["default"] = flashConstants;
  4564. module.exports = exports["default"];
  4565. },{}],29:[function(require,module,exports){
  4566. (function (global){
  4567. /**
  4568. * @file flash-media-source.js
  4569. */
  4570. 'use strict';
  4571. Object.defineProperty(exports, '__esModule', {
  4572. value: true
  4573. });
  4574. 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; }; })();
  4575. 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); } } };
  4576. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  4577. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  4578. 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; }
  4579. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  4580. var _videoJs2 = _interopRequireDefault(_videoJs);
  4581. var _flashSourceBuffer = require('./flash-source-buffer');
  4582. var _flashSourceBuffer2 = _interopRequireDefault(_flashSourceBuffer);
  4583. var _flashConstants = require('./flash-constants');
  4584. var _flashConstants2 = _interopRequireDefault(_flashConstants);
  4585. var _codecUtils = require('./codec-utils');
  4586. /**
  4587. * A flash implmentation of HTML MediaSources and a polyfill
  4588. * for browsers that don't support native or HTML MediaSources..
  4589. *
  4590. * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource
  4591. * @class FlashMediaSource
  4592. * @extends videojs.EventTarget
  4593. */
  4594. var FlashMediaSource = (function (_videojs$EventTarget) {
  4595. _inherits(FlashMediaSource, _videojs$EventTarget);
  4596. function FlashMediaSource() {
  4597. var _this = this;
  4598. _classCallCheck(this, FlashMediaSource);
  4599. _get(Object.getPrototypeOf(FlashMediaSource.prototype), 'constructor', this).call(this);
  4600. this.sourceBuffers = [];
  4601. this.readyState = 'closed';
  4602. this.on(['sourceopen', 'webkitsourceopen'], function (event) {
  4603. // find the swf where we will push media data
  4604. _this.swfObj = document.getElementById(event.swfId);
  4605. _this.player_ = (0, _videoJs2['default'])(_this.swfObj.parentNode);
  4606. _this.tech_ = _this.swfObj.tech;
  4607. _this.readyState = 'open';
  4608. _this.tech_.on('seeking', function () {
  4609. var i = _this.sourceBuffers.length;
  4610. while (i--) {
  4611. _this.sourceBuffers[i].abort();
  4612. }
  4613. });
  4614. // trigger load events
  4615. if (_this.swfObj) {
  4616. _this.swfObj.vjs_load();
  4617. }
  4618. });
  4619. }
  4620. /**
  4621. * Set or return the presentation duration.
  4622. *
  4623. * @param {Double} value the duration of the media in seconds
  4624. * @param {Double} the current presentation duration
  4625. * @link http://www.w3.org/TR/media-source/#widl-MediaSource-duration
  4626. */
  4627. /**
  4628. * We have this function so that the html and flash interfaces
  4629. * are the same.
  4630. *
  4631. * @private
  4632. */
  4633. _createClass(FlashMediaSource, [{
  4634. key: 'addSeekableRange_',
  4635. value: function addSeekableRange_() {}
  4636. // intentional no-op
  4637. /**
  4638. * Create a new flash source buffer and add it to our flash media source.
  4639. *
  4640. * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/addSourceBuffer
  4641. * @param {String} type the content-type of the source
  4642. * @return {Object} the flash source buffer
  4643. */
  4644. }, {
  4645. key: 'addSourceBuffer',
  4646. value: function addSourceBuffer(type) {
  4647. var parsedType = (0, _codecUtils.parseContentType)(type);
  4648. var sourceBuffer = undefined;
  4649. // if this is an FLV type, we'll push data to flash
  4650. if (parsedType.type === 'video/mp2t') {
  4651. // Flash source buffers
  4652. sourceBuffer = new _flashSourceBuffer2['default'](this);
  4653. } else {
  4654. throw new Error('NotSupportedError (Video.js)');
  4655. }
  4656. this.sourceBuffers.push(sourceBuffer);
  4657. return sourceBuffer;
  4658. }
  4659. /**
  4660. * Signals the end of the stream.
  4661. *
  4662. * @link https://w3c.github.io/media-source/#widl-MediaSource-endOfStream-void-EndOfStreamError-error
  4663. * @param {String=} error Signals that a playback error
  4664. * has occurred. If specified, it must be either "network" or
  4665. * "decode".
  4666. */
  4667. }, {
  4668. key: 'endOfStream',
  4669. value: function endOfStream(error) {
  4670. if (error === 'network') {
  4671. // MEDIA_ERR_NETWORK
  4672. this.tech_.error(2);
  4673. } else if (error === 'decode') {
  4674. // MEDIA_ERR_DECODE
  4675. this.tech_.error(3);
  4676. }
  4677. if (this.readyState !== 'ended') {
  4678. this.readyState = 'ended';
  4679. this.swfObj.vjs_endOfStream();
  4680. }
  4681. }
  4682. }]);
  4683. return FlashMediaSource;
  4684. })(_videoJs2['default'].EventTarget);
  4685. exports['default'] = FlashMediaSource;
  4686. try {
  4687. Object.defineProperty(FlashMediaSource.prototype, 'duration', {
  4688. /**
  4689. * Return the presentation duration.
  4690. *
  4691. * @return {Double} the duration of the media in seconds
  4692. * @link http://www.w3.org/TR/media-source/#widl-MediaSource-duration
  4693. */
  4694. get: function get() {
  4695. if (!this.swfObj) {
  4696. return NaN;
  4697. }
  4698. // get the current duration from the SWF
  4699. return this.swfObj.vjs_getProperty('duration');
  4700. },
  4701. /**
  4702. * Set the presentation duration.
  4703. *
  4704. * @param {Double} value the duration of the media in seconds
  4705. * @return {Double} the duration of the media in seconds
  4706. * @link http://www.w3.org/TR/media-source/#widl-MediaSource-duration
  4707. */
  4708. set: function set(value) {
  4709. var i = undefined;
  4710. var oldDuration = this.swfObj.vjs_getProperty('duration');
  4711. this.swfObj.vjs_setProperty('duration', value);
  4712. if (value < oldDuration) {
  4713. // In MSE, this triggers the range removal algorithm which causes
  4714. // an update to occur
  4715. for (i = 0; i < this.sourceBuffers.length; i++) {
  4716. this.sourceBuffers[i].remove(value, oldDuration);
  4717. }
  4718. }
  4719. return value;
  4720. }
  4721. });
  4722. } catch (e) {
  4723. // IE8 throws if defineProperty is called on a non-DOM node. We
  4724. // don't support IE8 but we shouldn't throw an error if loaded
  4725. // there.
  4726. FlashMediaSource.prototype.duration = NaN;
  4727. }
  4728. for (var property in _flashConstants2['default']) {
  4729. FlashMediaSource[property] = _flashConstants2['default'][property];
  4730. }
  4731. module.exports = exports['default'];
  4732. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4733. },{"./codec-utils":26,"./flash-constants":28,"./flash-source-buffer":30}],30:[function(require,module,exports){
  4734. (function (global){
  4735. /**
  4736. * @file flash-source-buffer.js
  4737. */
  4738. 'use strict';
  4739. Object.defineProperty(exports, '__esModule', {
  4740. value: true
  4741. });
  4742. 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; }; })();
  4743. 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); } } };
  4744. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  4745. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  4746. 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; }
  4747. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  4748. var _videoJs2 = _interopRequireDefault(_videoJs);
  4749. var _muxJs = require('mux.js');
  4750. var _muxJs2 = _interopRequireDefault(_muxJs);
  4751. var _removeCuesFromTrack = require('./remove-cues-from-track');
  4752. var _removeCuesFromTrack2 = _interopRequireDefault(_removeCuesFromTrack);
  4753. var _createTextTracksIfNecessary = require('./create-text-tracks-if-necessary');
  4754. var _createTextTracksIfNecessary2 = _interopRequireDefault(_createTextTracksIfNecessary);
  4755. var _addTextTrackData = require('./add-text-track-data');
  4756. var _addTextTrackData2 = _interopRequireDefault(_addTextTrackData);
  4757. var _flashConstants = require('./flash-constants');
  4758. var _flashConstants2 = _interopRequireDefault(_flashConstants);
  4759. /**
  4760. * A wrapper around the setTimeout function that uses
  4761. * the flash constant time between ticks value.
  4762. *
  4763. * @param {Function} func the function callback to run
  4764. * @private
  4765. */
  4766. var scheduleTick = function scheduleTick(func) {
  4767. // Chrome doesn't invoke requestAnimationFrame callbacks
  4768. // in background tabs, so use setTimeout.
  4769. window.setTimeout(func, _flashConstants2['default'].TIME_BETWEEN_TICKS);
  4770. };
  4771. /**
  4772. * Round a number to a specified number of places much like
  4773. * toFixed but return a number instead of a string representation.
  4774. *
  4775. * @param {Number} num A number
  4776. * @param {Number} places The number of decimal places which to
  4777. * round
  4778. * @private
  4779. */
  4780. var toDecimalPlaces = function toDecimalPlaces(num, places) {
  4781. if (typeof places !== 'number' || places < 0) {
  4782. places = 0;
  4783. }
  4784. var scale = Math.pow(10, places);
  4785. return Math.round(num * scale) / scale;
  4786. };
  4787. /**
  4788. * A SourceBuffer implementation for Flash rather than HTML.
  4789. *
  4790. * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource
  4791. * @param {Object} mediaSource the flash media source
  4792. * @class FlashSourceBuffer
  4793. * @extends videojs.EventTarget
  4794. */
  4795. var FlashSourceBuffer = (function (_videojs$EventTarget) {
  4796. _inherits(FlashSourceBuffer, _videojs$EventTarget);
  4797. function FlashSourceBuffer(mediaSource) {
  4798. var _this = this;
  4799. _classCallCheck(this, FlashSourceBuffer);
  4800. _get(Object.getPrototypeOf(FlashSourceBuffer.prototype), 'constructor', this).call(this);
  4801. var encodedHeader = undefined;
  4802. // Start off using the globally defined value but refine
  4803. // as we append data into flash
  4804. this.chunkSize_ = _flashConstants2['default'].BYTES_PER_CHUNK;
  4805. // byte arrays queued to be appended
  4806. this.buffer_ = [];
  4807. // the total number of queued bytes
  4808. this.bufferSize_ = 0;
  4809. // to be able to determine the correct position to seek to, we
  4810. // need to retain information about the mapping between the
  4811. // media timeline and PTS values
  4812. this.basePtsOffset_ = NaN;
  4813. this.mediaSource = mediaSource;
  4814. // indicates whether the asynchronous continuation of an operation
  4815. // is still being mulibubf2ulbfvl processed
  4816. // see https://w3c.github.io/media-source/#widl-SourceBuffer-updating
  4817. this.updating = false;
  4818. this.timestampOffset_ = 0;
  4819. // TS to FLV transmuxer
  4820. this.segmentParser_ = new _muxJs2['default'].flv.Transmuxer();
  4821. this.segmentParser_.on('data', this.receiveBuffer_.bind(this));
  4822. encodedHeader = window.btoa(String.fromCharCode.apply(null, Array.prototype.slice.call(this.segmentParser_.getFlvHeader())));
  4823. this.mediaSource.swfObj.vjs_appendBuffer(encodedHeader);
  4824. Object.defineProperty(this, 'timestampOffset', {
  4825. get: function get() {
  4826. return this.timestampOffset_;
  4827. },
  4828. set: function set(val) {
  4829. if (typeof val === 'number' && val >= 0) {
  4830. this.timestampOffset_ = val;
  4831. this.segmentParser_ = new _muxJs2['default'].flv.Transmuxer();
  4832. this.segmentParser_.on('data', this.receiveBuffer_.bind(this));
  4833. // We have to tell flash to expect a discontinuity
  4834. this.mediaSource.swfObj.vjs_discontinuity();
  4835. // the media <-> PTS mapping must be re-established after
  4836. // the discontinuity
  4837. this.basePtsOffset_ = NaN;
  4838. }
  4839. }
  4840. });
  4841. Object.defineProperty(this, 'buffered', {
  4842. get: function get() {
  4843. if (!this.mediaSource || !this.mediaSource.swfObj || !('vjs_getProperty' in this.mediaSource.swfObj)) {
  4844. return _videoJs2['default'].createTimeRange();
  4845. }
  4846. var buffered = this.mediaSource.swfObj.vjs_getProperty('buffered');
  4847. if (buffered && buffered.length) {
  4848. buffered[0][0] = toDecimalPlaces(buffered[0][0], 3);
  4849. buffered[0][1] = toDecimalPlaces(buffered[0][1], 3);
  4850. }
  4851. return _videoJs2['default'].createTimeRanges(buffered);
  4852. }
  4853. });
  4854. // On a seek we remove all text track data since flash has no concept
  4855. // of a buffered-range and everything else is reset on seek
  4856. this.mediaSource.player_.on('seeked', function () {
  4857. (0, _removeCuesFromTrack2['default'])(0, Infinity, _this.metadataTrack_);
  4858. (0, _removeCuesFromTrack2['default'])(0, Infinity, _this.inbandTextTrack_);
  4859. });
  4860. }
  4861. /**
  4862. * Append bytes to the sourcebuffers buffer, in this case we
  4863. * have to append it to swf object.
  4864. *
  4865. * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/appendBuffer
  4866. * @param {Array} bytes
  4867. */
  4868. _createClass(FlashSourceBuffer, [{
  4869. key: 'appendBuffer',
  4870. value: function appendBuffer(bytes) {
  4871. var _this2 = this;
  4872. var error = undefined;
  4873. var chunk = 512 * 1024;
  4874. var i = 0;
  4875. if (this.updating) {
  4876. error = new Error('SourceBuffer.append() cannot be called ' + 'while an update is in progress');
  4877. error.name = 'InvalidStateError';
  4878. error.code = 11;
  4879. throw error;
  4880. }
  4881. this.updating = true;
  4882. this.mediaSource.readyState = 'open';
  4883. this.trigger({ type: 'update' });
  4884. // this is here to use recursion
  4885. var chunkInData = function chunkInData() {
  4886. _this2.segmentParser_.push(bytes.subarray(i, i + chunk));
  4887. i += chunk;
  4888. if (i < bytes.byteLength) {
  4889. scheduleTick(chunkInData);
  4890. } else {
  4891. scheduleTick(_this2.segmentParser_.flush.bind(_this2.segmentParser_));
  4892. }
  4893. };
  4894. chunkInData();
  4895. }
  4896. /**
  4897. * Reset the parser and remove any data queued to be sent to the SWF.
  4898. *
  4899. * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/abort
  4900. */
  4901. }, {
  4902. key: 'abort',
  4903. value: function abort() {
  4904. this.buffer_ = [];
  4905. this.bufferSize_ = 0;
  4906. this.mediaSource.swfObj.vjs_abort();
  4907. // report any outstanding updates have ended
  4908. if (this.updating) {
  4909. this.updating = false;
  4910. this.trigger({ type: 'updateend' });
  4911. }
  4912. }
  4913. /**
  4914. * Flash cannot remove ranges already buffered in the NetStream
  4915. * but seeking clears the buffer entirely. For most purposes,
  4916. * having this operation act as a no-op is acceptable.
  4917. *
  4918. * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/remove
  4919. * @param {Double} start start of the section to remove
  4920. * @param {Double} end end of the section to remove
  4921. */
  4922. }, {
  4923. key: 'remove',
  4924. value: function remove(start, end) {
  4925. (0, _removeCuesFromTrack2['default'])(start, end, this.metadataTrack_);
  4926. (0, _removeCuesFromTrack2['default'])(start, end, this.inbandTextTrack_);
  4927. this.trigger({ type: 'update' });
  4928. this.trigger({ type: 'updateend' });
  4929. }
  4930. /**
  4931. * Receive a buffer from the flv.
  4932. *
  4933. * @param {Object} segment
  4934. * @private
  4935. */
  4936. }, {
  4937. key: 'receiveBuffer_',
  4938. value: function receiveBuffer_(segment) {
  4939. var _this3 = this;
  4940. // create an in-band caption track if one is present in the segment
  4941. (0, _createTextTracksIfNecessary2['default'])(this, this.mediaSource, segment);
  4942. (0, _addTextTrackData2['default'])(this, segment.captions, segment.metadata);
  4943. // Do this asynchronously since convertTagsToData_ can be time consuming
  4944. scheduleTick(function () {
  4945. var flvBytes = _this3.convertTagsToData_(segment);
  4946. if (_this3.buffer_.length === 0) {
  4947. scheduleTick(_this3.processBuffer_.bind(_this3));
  4948. }
  4949. if (flvBytes) {
  4950. _this3.buffer_.push(flvBytes);
  4951. _this3.bufferSize_ += flvBytes.byteLength;
  4952. }
  4953. });
  4954. }
  4955. /**
  4956. * Append a portion of the current buffer to the SWF.
  4957. *
  4958. * @private
  4959. */
  4960. }, {
  4961. key: 'processBuffer_',
  4962. value: function processBuffer_() {
  4963. var chunk = undefined;
  4964. var i = undefined;
  4965. var length = undefined;
  4966. var binary = undefined;
  4967. var b64str = undefined;
  4968. var startByte = 0;
  4969. var appendIterations = 0;
  4970. var startTime = +new Date();
  4971. var appendTime = undefined;
  4972. if (!this.buffer_.length) {
  4973. if (this.updating !== false) {
  4974. this.updating = false;
  4975. this.trigger({ type: 'updateend' });
  4976. }
  4977. // do nothing if the buffer is empty
  4978. return;
  4979. }
  4980. do {
  4981. appendIterations++;
  4982. // concatenate appends up to the max append size
  4983. chunk = this.buffer_[0].subarray(startByte, startByte + this.chunkSize_);
  4984. // requeue any bytes that won't make it this round
  4985. if (chunk.byteLength < this.chunkSize_ || this.buffer_[0].byteLength === startByte + this.chunkSize_) {
  4986. startByte = 0;
  4987. this.buffer_.shift();
  4988. } else {
  4989. startByte += this.chunkSize_;
  4990. }
  4991. this.bufferSize_ -= chunk.byteLength;
  4992. // base64 encode the bytes
  4993. binary = '';
  4994. length = chunk.byteLength;
  4995. for (i = 0; i < length; i++) {
  4996. binary += String.fromCharCode(chunk[i]);
  4997. }
  4998. b64str = window.btoa(binary);
  4999. // bypass normal ExternalInterface calls and pass xml directly
  5000. // IE can be slow by default
  5001. this.mediaSource.swfObj.CallFunction('<invoke name="vjs_appendBuffer"' + 'returntype="javascript"><arguments><string>' + b64str + '</string></arguments></invoke>');
  5002. appendTime = new Date() - startTime;
  5003. } while (this.buffer_.length && appendTime < _flashConstants2['default'].TIME_PER_TICK);
  5004. if (this.buffer_.length && startByte) {
  5005. this.buffer_[0] = this.buffer_[0].subarray(startByte);
  5006. }
  5007. if (appendTime >= _flashConstants2['default'].TIME_PER_TICK) {
  5008. // We want to target 4 iterations per time-slot so that gives us
  5009. // room to adjust to changes in Flash load and other externalities
  5010. // such as garbage collection while still maximizing throughput
  5011. this.chunkSize_ = Math.floor(this.chunkSize_ * (appendIterations / 4));
  5012. }
  5013. // We also make sure that the chunk-size doesn't drop below 1KB or
  5014. // go above 1MB as a sanity check
  5015. this.chunkSize_ = Math.max(_flashConstants2['default'].MIN_CHUNK, Math.min(this.chunkSize_, _flashConstants2['default'].MAX_CHUNK));
  5016. // schedule another append if necessary
  5017. if (this.bufferSize_ !== 0) {
  5018. scheduleTick(this.processBuffer_.bind(this));
  5019. } else {
  5020. this.updating = false;
  5021. this.trigger({ type: 'updateend' });
  5022. }
  5023. }
  5024. /**
  5025. * Turns an array of flv tags into a Uint8Array representing the
  5026. * flv data. Also removes any tags that are before the current
  5027. * time so that playback begins at or slightly after the right
  5028. * place on a seek
  5029. *
  5030. * @private
  5031. * @param {Object} segmentData object of segment data
  5032. */
  5033. }, {
  5034. key: 'convertTagsToData_',
  5035. value: function convertTagsToData_(segmentData) {
  5036. var segmentByteLength = 0;
  5037. var tech = this.mediaSource.tech_;
  5038. var targetPts = 0;
  5039. var i = undefined;
  5040. var j = undefined;
  5041. var segment = undefined;
  5042. var filteredTags = [];
  5043. var tags = this.getOrderedTags_(segmentData);
  5044. // Establish the media timeline to PTS translation if we don't
  5045. // have one already
  5046. if (isNaN(this.basePtsOffset_) && tags.length) {
  5047. this.basePtsOffset_ = tags[0].pts;
  5048. }
  5049. // Trim any tags that are before the end of the end of
  5050. // the current buffer
  5051. if (tech.buffered().length) {
  5052. targetPts = tech.buffered().end(0) - this.timestampOffset;
  5053. }
  5054. // Trim to currentTime if it's ahead of buffered or buffered doesn't exist
  5055. targetPts = Math.max(targetPts, tech.currentTime() - this.timestampOffset);
  5056. // PTS values are represented in milliseconds
  5057. targetPts *= 1e3;
  5058. targetPts += this.basePtsOffset_;
  5059. // skip tags with a presentation time less than the seek target
  5060. for (i = 0; i < tags.length; i++) {
  5061. if (tags[i].pts >= targetPts) {
  5062. filteredTags.push(tags[i]);
  5063. }
  5064. }
  5065. if (filteredTags.length === 0) {
  5066. return;
  5067. }
  5068. // concatenate the bytes into a single segment
  5069. for (i = 0; i < filteredTags.length; i++) {
  5070. segmentByteLength += filteredTags[i].bytes.byteLength;
  5071. }
  5072. segment = new Uint8Array(segmentByteLength);
  5073. for (i = 0, j = 0; i < filteredTags.length; i++) {
  5074. segment.set(filteredTags[i].bytes, j);
  5075. j += filteredTags[i].bytes.byteLength;
  5076. }
  5077. return segment;
  5078. }
  5079. /**
  5080. * Assemble the FLV tags in decoder order.
  5081. *
  5082. * @private
  5083. * @param {Object} segmentData object of segment data
  5084. */
  5085. }, {
  5086. key: 'getOrderedTags_',
  5087. value: function getOrderedTags_(segmentData) {
  5088. var videoTags = segmentData.tags.videoTags;
  5089. var audioTags = segmentData.tags.audioTags;
  5090. var tag = undefined;
  5091. var tags = [];
  5092. while (videoTags.length || audioTags.length) {
  5093. if (!videoTags.length) {
  5094. // only audio tags remain
  5095. tag = audioTags.shift();
  5096. } else if (!audioTags.length) {
  5097. // only video tags remain
  5098. tag = videoTags.shift();
  5099. } else if (audioTags[0].dts < videoTags[0].dts) {
  5100. // audio should be decoded next
  5101. tag = audioTags.shift();
  5102. } else {
  5103. // video should be decoded next
  5104. tag = videoTags.shift();
  5105. }
  5106. tags.push(tag.finalize());
  5107. }
  5108. return tags;
  5109. }
  5110. }]);
  5111. return FlashSourceBuffer;
  5112. })(_videoJs2['default'].EventTarget);
  5113. exports['default'] = FlashSourceBuffer;
  5114. module.exports = exports['default'];
  5115. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  5116. },{"./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){
  5117. (function (global){
  5118. /**
  5119. * @file html-media-source.js
  5120. */
  5121. 'use strict';
  5122. Object.defineProperty(exports, '__esModule', {
  5123. value: true
  5124. });
  5125. 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; }; })();
  5126. 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); } } };
  5127. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  5128. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  5129. 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; }
  5130. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  5131. var _videoJs2 = _interopRequireDefault(_videoJs);
  5132. var _virtualSourceBuffer = require('./virtual-source-buffer');
  5133. var _virtualSourceBuffer2 = _interopRequireDefault(_virtualSourceBuffer);
  5134. var _codecUtils = require('./codec-utils');
  5135. /**
  5136. * Replace the old apple-style `avc1.<dd>.<dd>` codec string with the standard
  5137. * `avc1.<hhhhhh>`
  5138. *
  5139. * @param {Array} codecs an array of codec strings to fix
  5140. * @return {Array} the translated codec array
  5141. * @private
  5142. */
  5143. var translateLegacyCodecs = function translateLegacyCodecs(codecs) {
  5144. return codecs.map(function (codec) {
  5145. return codec.replace(/avc1\.(\d+)\.(\d+)/i, function (orig, profile, avcLevel) {
  5146. var profileHex = ('00' + Number(profile).toString(16)).slice(-2);
  5147. var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);
  5148. return 'avc1.' + profileHex + '00' + avcLevelHex;
  5149. });
  5150. });
  5151. };
  5152. /**
  5153. * Our MediaSource implementation in HTML, mimics native
  5154. * MediaSource where/if possible.
  5155. *
  5156. * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource
  5157. * @class HtmlMediaSource
  5158. * @extends videojs.EventTarget
  5159. */
  5160. var HtmlMediaSource = (function (_videojs$EventTarget) {
  5161. _inherits(HtmlMediaSource, _videojs$EventTarget);
  5162. function HtmlMediaSource() {
  5163. var _this = this;
  5164. _classCallCheck(this, HtmlMediaSource);
  5165. _get(Object.getPrototypeOf(HtmlMediaSource.prototype), 'constructor', this).call(this);
  5166. var property = undefined;
  5167. this.nativeMediaSource_ = new window.MediaSource();
  5168. // delegate to the native MediaSource's methods by default
  5169. for (property in this.nativeMediaSource_) {
  5170. if (!(property in HtmlMediaSource.prototype) && typeof this.nativeMediaSource_[property] === 'function') {
  5171. this[property] = this.nativeMediaSource_[property].bind(this.nativeMediaSource_);
  5172. }
  5173. }
  5174. // emulate `duration` and `seekable` until seeking can be
  5175. // handled uniformly for live streams
  5176. // see https://github.com/w3c/media-source/issues/5
  5177. this.duration_ = NaN;
  5178. Object.defineProperty(this, 'duration', {
  5179. get: function get() {
  5180. if (this.duration_ === Infinity) {
  5181. return this.duration_;
  5182. }
  5183. return this.nativeMediaSource_.duration;
  5184. },
  5185. set: function set(duration) {
  5186. this.duration_ = duration;
  5187. if (duration !== Infinity) {
  5188. this.nativeMediaSource_.duration = duration;
  5189. return;
  5190. }
  5191. }
  5192. });
  5193. Object.defineProperty(this, 'seekable', {
  5194. get: function get() {
  5195. if (this.duration_ === Infinity) {
  5196. return _videoJs2['default'].createTimeRanges([[0, this.nativeMediaSource_.duration]]);
  5197. }
  5198. return this.nativeMediaSource_.seekable;
  5199. }
  5200. });
  5201. Object.defineProperty(this, 'readyState', {
  5202. get: function get() {
  5203. return this.nativeMediaSource_.readyState;
  5204. }
  5205. });
  5206. Object.defineProperty(this, 'activeSourceBuffers', {
  5207. get: function get() {
  5208. return this.activeSourceBuffers_;
  5209. }
  5210. });
  5211. // the list of virtual and native SourceBuffers created by this
  5212. // MediaSource
  5213. this.sourceBuffers = [];
  5214. this.activeSourceBuffers_ = [];
  5215. /**
  5216. * update the list of active source buffers based upon various
  5217. * imformation from HLS and video.js
  5218. *
  5219. * @private
  5220. */
  5221. this.updateActiveSourceBuffers_ = function () {
  5222. // Retain the reference but empty the array
  5223. _this.activeSourceBuffers_.length = 0;
  5224. // By default, the audio in the combined virtual source buffer is enabled
  5225. // and the audio-only source buffer (if it exists) is disabled.
  5226. var combined = false;
  5227. var audioOnly = true;
  5228. // TODO: maybe we can store the sourcebuffers on the track objects?
  5229. // safari may do something like this
  5230. for (var i = 0; i < _this.player_.audioTracks().length; i++) {
  5231. var track = _this.player_.audioTracks()[i];
  5232. if (track.enabled && track.kind !== 'main') {
  5233. // The enabled track is an alternate audio track so disable the audio in
  5234. // the combined source buffer and enable the audio-only source buffer.
  5235. combined = true;
  5236. audioOnly = false;
  5237. break;
  5238. }
  5239. }
  5240. // Since we currently support a max of two source buffers, add all of the source
  5241. // buffers (in order).
  5242. _this.sourceBuffers.forEach(function (sourceBuffer) {
  5243. /* eslinst-disable */
  5244. // TODO once codecs are required, we can switch to using the codecs to determine
  5245. // what stream is the video stream, rather than relying on videoTracks
  5246. /* eslinst-enable */
  5247. if (sourceBuffer.videoCodec_ && sourceBuffer.audioCodec_) {
  5248. // combined
  5249. sourceBuffer.audioDisabled_ = combined;
  5250. } else if (sourceBuffer.videoCodec_ && !sourceBuffer.audioCodec_) {
  5251. // If the "combined" source buffer is video only, then we do not want
  5252. // disable the audio-only source buffer (this is mostly for demuxed
  5253. // audio and video hls)
  5254. sourceBuffer.audioDisabled_ = true;
  5255. audioOnly = false;
  5256. } else if (!sourceBuffer.videoCodec_ && sourceBuffer.audioCodec_) {
  5257. // audio only
  5258. sourceBuffer.audioDisabled_ = audioOnly;
  5259. if (audioOnly) {
  5260. return;
  5261. }
  5262. }
  5263. _this.activeSourceBuffers_.push(sourceBuffer);
  5264. });
  5265. };
  5266. // Re-emit MediaSource events on the polyfill
  5267. ['sourceopen', 'sourceclose', 'sourceended'].forEach(function (eventName) {
  5268. this.nativeMediaSource_.addEventListener(eventName, this.trigger.bind(this));
  5269. }, this);
  5270. // capture the associated player when the MediaSource is
  5271. // successfully attached
  5272. this.on('sourceopen', function (event) {
  5273. // Get the player this MediaSource is attached to
  5274. var video = document.querySelector('[src="' + _this.url_ + '"]');
  5275. if (!video) {
  5276. return;
  5277. }
  5278. _this.player_ = (0, _videoJs2['default'])(video.parentNode);
  5279. if (_this.player_.audioTracks && _this.player_.audioTracks()) {
  5280. _this.player_.audioTracks().on('change', _this.updateActiveSourceBuffers_);
  5281. _this.player_.audioTracks().on('addtrack', _this.updateActiveSourceBuffers_);
  5282. _this.player_.audioTracks().on('removetrack', _this.updateActiveSourceBuffers_);
  5283. }
  5284. });
  5285. // explicitly terminate any WebWorkers that were created
  5286. // by SourceHandlers
  5287. this.on('sourceclose', function (event) {
  5288. this.sourceBuffers.forEach(function (sourceBuffer) {
  5289. if (sourceBuffer.transmuxer_) {
  5290. sourceBuffer.transmuxer_.terminate();
  5291. }
  5292. });
  5293. this.sourceBuffers.length = 0;
  5294. if (!this.player_) {
  5295. return;
  5296. }
  5297. if (this.player_.audioTracks && this.player_.audioTracks()) {
  5298. this.player_.audioTracks().off('change', this.updateActiveSourceBuffers_);
  5299. this.player_.audioTracks().off('addtrack', this.updateActiveSourceBuffers_);
  5300. this.player_.audioTracks().off('removetrack', this.updateActiveSourceBuffers_);
  5301. }
  5302. });
  5303. }
  5304. /**
  5305. * Add a range that that can now be seeked to.
  5306. *
  5307. * @param {Double} start where to start the addition
  5308. * @param {Double} end where to end the addition
  5309. * @private
  5310. */
  5311. _createClass(HtmlMediaSource, [{
  5312. key: 'addSeekableRange_',
  5313. value: function addSeekableRange_(start, end) {
  5314. var error = undefined;
  5315. if (this.duration !== Infinity) {
  5316. error = new Error('MediaSource.addSeekableRange() can only be invoked ' + 'when the duration is Infinity');
  5317. error.name = 'InvalidStateError';
  5318. error.code = 11;
  5319. throw error;
  5320. }
  5321. if (end > this.nativeMediaSource_.duration || isNaN(this.nativeMediaSource_.duration)) {
  5322. this.nativeMediaSource_.duration = end;
  5323. }
  5324. }
  5325. /**
  5326. * Add a source buffer to the media source.
  5327. *
  5328. * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/addSourceBuffer
  5329. * @param {String} type the content-type of the content
  5330. * @return {Object} the created source buffer
  5331. */
  5332. }, {
  5333. key: 'addSourceBuffer',
  5334. value: function addSourceBuffer(type) {
  5335. var buffer = undefined;
  5336. var parsedType = (0, _codecUtils.parseContentType)(type);
  5337. // Create a VirtualSourceBuffer to transmux MPEG-2 transport
  5338. // stream segments into fragmented MP4s
  5339. if (parsedType.type === 'video/mp2t') {
  5340. var codecs = [];
  5341. if (parsedType.parameters && parsedType.parameters.codecs) {
  5342. codecs = parsedType.parameters.codecs.split(',');
  5343. codecs = translateLegacyCodecs(codecs);
  5344. codecs = codecs.filter(function (codec) {
  5345. return (0, _codecUtils.isAudioCodec)(codec) || (0, _codecUtils.isVideoCodec)(codec);
  5346. });
  5347. }
  5348. if (codecs.length === 0) {
  5349. codecs = ['avc1.4d400d', 'mp4a.40.2'];
  5350. }
  5351. buffer = new _virtualSourceBuffer2['default'](this, codecs);
  5352. if (this.sourceBuffers.length !== 0) {
  5353. // If another VirtualSourceBuffer already exists, then we are creating a
  5354. // SourceBuffer for an alternate audio track and therefore we know that
  5355. // the source has both an audio and video track.
  5356. // That means we should trigger the manual creation of the real
  5357. // SourceBuffers instead of waiting for the transmuxer to return data
  5358. this.sourceBuffers[0].createRealSourceBuffers_();
  5359. buffer.createRealSourceBuffers_();
  5360. // Automatically disable the audio on the first source buffer if
  5361. // a second source buffer is ever created
  5362. this.sourceBuffers[0].audioDisabled_ = true;
  5363. }
  5364. } else {
  5365. // delegate to the native implementation
  5366. buffer = this.nativeMediaSource_.addSourceBuffer(type);
  5367. }
  5368. this.sourceBuffers.push(buffer);
  5369. return buffer;
  5370. }
  5371. }]);
  5372. return HtmlMediaSource;
  5373. })(_videoJs2['default'].EventTarget);
  5374. exports['default'] = HtmlMediaSource;
  5375. module.exports = exports['default'];
  5376. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  5377. },{"./codec-utils":26,"./virtual-source-buffer":35}],32:[function(require,module,exports){
  5378. /**
  5379. * @file remove-cues-from-track.js
  5380. */
  5381. /**
  5382. * Remove cues from a track on video.js.
  5383. *
  5384. * @param {Double} start start of where we should remove the cue
  5385. * @param {Double} end end of where the we should remove the cue
  5386. * @param {Object} track the text track to remove the cues from
  5387. * @private
  5388. */
  5389. "use strict";
  5390. Object.defineProperty(exports, "__esModule", {
  5391. value: true
  5392. });
  5393. var removeCuesFromTrack = function removeCuesFromTrack(start, end, track) {
  5394. var i = undefined;
  5395. var cue = undefined;
  5396. if (!track) {
  5397. return;
  5398. }
  5399. i = track.cues.length;
  5400. while (i--) {
  5401. cue = track.cues[i];
  5402. // Remove any overlapping cue
  5403. if (cue.startTime <= end && cue.endTime >= start) {
  5404. track.removeCue(cue);
  5405. }
  5406. }
  5407. };
  5408. exports["default"] = removeCuesFromTrack;
  5409. module.exports = exports["default"];
  5410. },{}],33:[function(require,module,exports){
  5411. /**
  5412. * @file transmuxer-worker.js
  5413. */
  5414. /**
  5415. * videojs-contrib-media-sources
  5416. *
  5417. * Copyright (c) 2015 Brightcove
  5418. * All rights reserved.
  5419. *
  5420. * Handles communication between the browser-world and the mux.js
  5421. * transmuxer running inside of a WebWorker by exposing a simple
  5422. * message-based interface to a Transmuxer object.
  5423. */
  5424. 'use strict';
  5425. Object.defineProperty(exports, '__esModule', {
  5426. value: true
  5427. });
  5428. 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; }; })();
  5429. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  5430. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  5431. var _muxJs = require('mux.js');
  5432. var _muxJs2 = _interopRequireDefault(_muxJs);
  5433. /**
  5434. * Re-emits tranmsuxer events by converting them into messages to the
  5435. * world outside the worker.
  5436. *
  5437. * @param {Object} transmuxer the transmuxer to wire events on
  5438. * @private
  5439. */
  5440. var wireTransmuxerEvents = function wireTransmuxerEvents(transmuxer) {
  5441. transmuxer.on('data', function (segment) {
  5442. // transfer ownership of the underlying ArrayBuffer
  5443. // instead of doing a copy to save memory
  5444. // ArrayBuffers are transferable but generic TypedArrays are not
  5445. // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
  5446. var typedArray = segment.data;
  5447. segment.data = typedArray.buffer;
  5448. postMessage({
  5449. action: 'data',
  5450. segment: segment,
  5451. byteOffset: typedArray.byteOffset,
  5452. byteLength: typedArray.byteLength
  5453. }, [segment.data]);
  5454. });
  5455. if (transmuxer.captionStream) {
  5456. transmuxer.captionStream.on('data', function (caption) {
  5457. postMessage({
  5458. action: 'caption',
  5459. data: caption
  5460. });
  5461. });
  5462. }
  5463. transmuxer.on('done', function (data) {
  5464. postMessage({ action: 'done' });
  5465. });
  5466. };
  5467. /**
  5468. * All incoming messages route through this hash. If no function exists
  5469. * to handle an incoming message, then we ignore the message.
  5470. *
  5471. * @class MessageHandlers
  5472. * @param {Object} options the options to initialize with
  5473. */
  5474. var MessageHandlers = (function () {
  5475. function MessageHandlers(options) {
  5476. _classCallCheck(this, MessageHandlers);
  5477. this.options = options || {};
  5478. this.init();
  5479. }
  5480. /**
  5481. * Our web wroker interface so that things can talk to mux.js
  5482. * that will be running in a web worker. the scope is passed to this by
  5483. * webworkify.
  5484. *
  5485. * @param {Object} self the scope for the web worker
  5486. */
  5487. /**
  5488. * initialize our web worker and wire all the events.
  5489. */
  5490. _createClass(MessageHandlers, [{
  5491. key: 'init',
  5492. value: function init() {
  5493. if (this.transmuxer) {
  5494. this.transmuxer.dispose();
  5495. }
  5496. this.transmuxer = new _muxJs2['default'].mp4.Transmuxer(this.options);
  5497. wireTransmuxerEvents(this.transmuxer);
  5498. }
  5499. /**
  5500. * Adds data (a ts segment) to the start of the transmuxer pipeline for
  5501. * processing.
  5502. *
  5503. * @param {ArrayBuffer} data data to push into the muxer
  5504. */
  5505. }, {
  5506. key: 'push',
  5507. value: function push(data) {
  5508. // Cast array buffer to correct type for transmuxer
  5509. var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  5510. this.transmuxer.push(segment);
  5511. }
  5512. /**
  5513. * Recreate the transmuxer so that the next segment added via `push`
  5514. * start with a fresh transmuxer.
  5515. */
  5516. }, {
  5517. key: 'reset',
  5518. value: function reset() {
  5519. this.init();
  5520. }
  5521. /**
  5522. * Set the value that will be used as the `baseMediaDecodeTime` time for the
  5523. * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
  5524. * set relative to the first based on the PTS values.
  5525. *
  5526. * @param {Object} data used to set the timestamp offset in the muxer
  5527. */
  5528. }, {
  5529. key: 'setTimestampOffset',
  5530. value: function setTimestampOffset(data) {
  5531. var timestampOffset = data.timestampOffset || 0;
  5532. this.transmuxer.setBaseMediaDecodeTime(Math.round(timestampOffset * 90000));
  5533. }
  5534. /**
  5535. * Forces the pipeline to finish processing the last segment and emit it's
  5536. * results.
  5537. *
  5538. * @param {Object} data event data, not really used
  5539. */
  5540. }, {
  5541. key: 'flush',
  5542. value: function flush(data) {
  5543. this.transmuxer.flush();
  5544. }
  5545. }]);
  5546. return MessageHandlers;
  5547. })();
  5548. var Worker = function Worker(self) {
  5549. self.onmessage = function (event) {
  5550. if (event.data.action === 'init' && event.data.options) {
  5551. this.messageHandlers = new MessageHandlers(event.data.options);
  5552. return;
  5553. }
  5554. if (!this.messageHandlers) {
  5555. this.messageHandlers = new MessageHandlers();
  5556. }
  5557. if (event.data && event.data.action && event.data.action !== 'init') {
  5558. if (this.messageHandlers[event.data.action]) {
  5559. this.messageHandlers[event.data.action](event.data);
  5560. }
  5561. }
  5562. };
  5563. };
  5564. exports['default'] = function (self) {
  5565. return new Worker(self);
  5566. };
  5567. module.exports = exports['default'];
  5568. },{"mux.js":43}],34:[function(require,module,exports){
  5569. (function (global){
  5570. /**
  5571. * @file videojs-contrib-media-sources.js
  5572. */
  5573. 'use strict';
  5574. Object.defineProperty(exports, '__esModule', {
  5575. value: true
  5576. });
  5577. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  5578. var _flashMediaSource = require('./flash-media-source');
  5579. var _flashMediaSource2 = _interopRequireDefault(_flashMediaSource);
  5580. var _htmlMediaSource = require('./html-media-source');
  5581. var _htmlMediaSource2 = _interopRequireDefault(_htmlMediaSource);
  5582. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  5583. var _videoJs2 = _interopRequireDefault(_videoJs);
  5584. var urlCount = 0;
  5585. // ------------
  5586. // Media Source
  5587. // ------------
  5588. var defaults = {
  5589. // how to determine the MediaSource implementation to use. There
  5590. // are three available modes:
  5591. // - auto: use native MediaSources where available and Flash
  5592. // everywhere else
  5593. // - html5: always use native MediaSources
  5594. // - flash: always use the Flash MediaSource polyfill
  5595. mode: 'auto'
  5596. };
  5597. // store references to the media sources so they can be connected
  5598. // to a video element (a swf object)
  5599. // TODO: can we store this somewhere local to this module?
  5600. _videoJs2['default'].mediaSources = {};
  5601. /**
  5602. * Provide a method for a swf object to notify JS that a
  5603. * media source is now open.
  5604. *
  5605. * @param {String} msObjectURL string referencing the MSE Object URL
  5606. * @param {String} swfId the swf id
  5607. */
  5608. var open = function open(msObjectURL, swfId) {
  5609. var mediaSource = _videoJs2['default'].mediaSources[msObjectURL];
  5610. if (mediaSource) {
  5611. mediaSource.trigger({ type: 'sourceopen', swfId: swfId });
  5612. } else {
  5613. throw new Error('Media Source not found (Video.js)');
  5614. }
  5615. };
  5616. /**
  5617. * Check to see if the native MediaSource object exists and supports
  5618. * an MP4 container with both H.264 video and AAC-LC audio.
  5619. *
  5620. * @return {Boolean} if native media sources are supported
  5621. */
  5622. var supportsNativeMediaSources = function supportsNativeMediaSources() {
  5623. return !!window.MediaSource && !!window.MediaSource.isTypeSupported && window.MediaSource.isTypeSupported('video/mp4;codecs="avc1.4d400d,mp4a.40.2"');
  5624. };
  5625. /**
  5626. * An emulation of the MediaSource API so that we can support
  5627. * native and non-native functionality such as flash and
  5628. * video/mp2t videos. returns an instance of HtmlMediaSource or
  5629. * FlashMediaSource depending on what is supported and what options
  5630. * are passed in.
  5631. *
  5632. * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/MediaSource
  5633. * @param {Object} options options to use during setup.
  5634. */
  5635. var MediaSource = function MediaSource(options) {
  5636. var settings = _videoJs2['default'].mergeOptions(defaults, options);
  5637. this.MediaSource = {
  5638. open: open,
  5639. supportsNativeMediaSources: supportsNativeMediaSources
  5640. };
  5641. // determine whether HTML MediaSources should be used
  5642. if (settings.mode === 'html5' || settings.mode === 'auto' && supportsNativeMediaSources()) {
  5643. return new _htmlMediaSource2['default']();
  5644. }
  5645. // otherwise, emulate them through the SWF
  5646. return new _flashMediaSource2['default']();
  5647. };
  5648. exports.MediaSource = MediaSource;
  5649. MediaSource.open = open;
  5650. MediaSource.supportsNativeMediaSources = supportsNativeMediaSources;
  5651. /**
  5652. * A wrapper around the native URL for our MSE object
  5653. * implementation, this object is exposed under videojs.URL
  5654. *
  5655. * @link https://developer.mozilla.org/en-US/docs/Web/API/URL/URL
  5656. */
  5657. var URL = {
  5658. /**
  5659. * A wrapper around the native createObjectURL for our objects.
  5660. * This function maps a native or emulated mediaSource to a blob
  5661. * url so that it can be loaded into video.js
  5662. *
  5663. * @link https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
  5664. * @param {MediaSource} object the object to create a blob url to
  5665. */
  5666. createObjectURL: function createObjectURL(object) {
  5667. var objectUrlPrefix = 'blob:vjs-media-source/';
  5668. var url = undefined;
  5669. // use the native MediaSource to generate an object URL
  5670. if (object instanceof _htmlMediaSource2['default']) {
  5671. url = window.URL.createObjectURL(object.nativeMediaSource_);
  5672. object.url_ = url;
  5673. return url;
  5674. }
  5675. // if the object isn't an emulated MediaSource, delegate to the
  5676. // native implementation
  5677. if (!(object instanceof _flashMediaSource2['default'])) {
  5678. url = window.URL.createObjectURL(object);
  5679. object.url_ = url;
  5680. return url;
  5681. }
  5682. // build a URL that can be used to map back to the emulated
  5683. // MediaSource
  5684. url = objectUrlPrefix + urlCount;
  5685. urlCount++;
  5686. // setup the mapping back to object
  5687. _videoJs2['default'].mediaSources[url] = object;
  5688. return url;
  5689. }
  5690. };
  5691. exports.URL = URL;
  5692. _videoJs2['default'].MediaSource = MediaSource;
  5693. _videoJs2['default'].URL = URL;
  5694. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  5695. },{"./flash-media-source":29,"./html-media-source":31}],35:[function(require,module,exports){
  5696. (function (global){
  5697. /**
  5698. * @file virtual-source-buffer.js
  5699. */
  5700. 'use strict';
  5701. Object.defineProperty(exports, '__esModule', {
  5702. value: true
  5703. });
  5704. 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; }; })();
  5705. 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); } } };
  5706. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  5707. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  5708. 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; }
  5709. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  5710. var _videoJs2 = _interopRequireDefault(_videoJs);
  5711. var _createTextTracksIfNecessary = require('./create-text-tracks-if-necessary');
  5712. var _createTextTracksIfNecessary2 = _interopRequireDefault(_createTextTracksIfNecessary);
  5713. var _removeCuesFromTrack = require('./remove-cues-from-track');
  5714. var _removeCuesFromTrack2 = _interopRequireDefault(_removeCuesFromTrack);
  5715. var _addTextTrackData = require('./add-text-track-data');
  5716. var _addTextTrackData2 = _interopRequireDefault(_addTextTrackData);
  5717. var _webworkify = require('webworkify');
  5718. var _webworkify2 = _interopRequireDefault(_webworkify);
  5719. var _transmuxerWorker = require('./transmuxer-worker');
  5720. var _transmuxerWorker2 = _interopRequireDefault(_transmuxerWorker);
  5721. var _codecUtils = require('./codec-utils');
  5722. /**
  5723. * VirtualSourceBuffers exist so that we can transmux non native formats
  5724. * into a native format, but keep the same api as a native source buffer.
  5725. * It creates a transmuxer, that works in its own thread (a web worker) and
  5726. * that transmuxer muxes the data into a native format. VirtualSourceBuffer will
  5727. * then send all of that data to the naive sourcebuffer so that it is
  5728. * indestinguishable from a natively supported format.
  5729. *
  5730. * @param {HtmlMediaSource} mediaSource the parent mediaSource
  5731. * @param {Array} codecs array of codecs that we will be dealing with
  5732. * @class VirtualSourceBuffer
  5733. * @extends video.js.EventTarget
  5734. */
  5735. var VirtualSourceBuffer = (function (_videojs$EventTarget) {
  5736. _inherits(VirtualSourceBuffer, _videojs$EventTarget);
  5737. function VirtualSourceBuffer(mediaSource, codecs) {
  5738. var _this = this;
  5739. _classCallCheck(this, VirtualSourceBuffer);
  5740. _get(Object.getPrototypeOf(VirtualSourceBuffer.prototype), 'constructor', this).call(this, _videoJs2['default'].EventTarget);
  5741. this.timestampOffset_ = 0;
  5742. this.pendingBuffers_ = [];
  5743. this.bufferUpdating_ = false;
  5744. this.mediaSource_ = mediaSource;
  5745. this.codecs_ = codecs;
  5746. this.audioCodec_ = null;
  5747. this.videoCodec_ = null;
  5748. this.audioDisabled_ = false;
  5749. var options = {
  5750. remux: false
  5751. };
  5752. this.codecs_.forEach(function (codec) {
  5753. if ((0, _codecUtils.isAudioCodec)(codec)) {
  5754. _this.audioCodec_ = codec;
  5755. } else if ((0, _codecUtils.isVideoCodec)(codec)) {
  5756. _this.videoCodec_ = codec;
  5757. }
  5758. });
  5759. // append muxed segments to their respective native buffers as
  5760. // soon as they are available
  5761. this.transmuxer_ = (0, _webworkify2['default'])(_transmuxerWorker2['default']);
  5762. this.transmuxer_.postMessage({ action: 'init', options: options });
  5763. this.transmuxer_.onmessage = function (event) {
  5764. if (event.data.action === 'data') {
  5765. return _this.data_(event);
  5766. }
  5767. if (event.data.action === 'done') {
  5768. return _this.done_(event);
  5769. }
  5770. };
  5771. // this timestampOffset is a property with the side-effect of resetting
  5772. // baseMediaDecodeTime in the transmuxer on the setter
  5773. Object.defineProperty(this, 'timestampOffset', {
  5774. get: function get() {
  5775. return this.timestampOffset_;
  5776. },
  5777. set: function set(val) {
  5778. if (typeof val === 'number' && val >= 0) {
  5779. this.timestampOffset_ = val;
  5780. // We have to tell the transmuxer to set the baseMediaDecodeTime to
  5781. // the desired timestampOffset for the next segment
  5782. this.transmuxer_.postMessage({
  5783. action: 'setTimestampOffset',
  5784. timestampOffset: val
  5785. });
  5786. }
  5787. }
  5788. });
  5789. // setting the append window affects both source buffers
  5790. Object.defineProperty(this, 'appendWindowStart', {
  5791. get: function get() {
  5792. return (this.videoBuffer_ || this.audioBuffer_).appendWindowStart;
  5793. },
  5794. set: function set(start) {
  5795. if (this.videoBuffer_) {
  5796. this.videoBuffer_.appendWindowStart = start;
  5797. }
  5798. if (this.audioBuffer_) {
  5799. this.audioBuffer_.appendWindowStart = start;
  5800. }
  5801. }
  5802. });
  5803. // this buffer is "updating" if either of its native buffers are
  5804. Object.defineProperty(this, 'updating', {
  5805. get: function get() {
  5806. return !!(this.bufferUpdating_ || !this.audioDisabled_ && this.audioBuffer_ && this.audioBuffer_.updating || this.videoBuffer_ && this.videoBuffer_.updating);
  5807. }
  5808. });
  5809. // the buffered property is the intersection of the buffered
  5810. // ranges of the native source buffers
  5811. Object.defineProperty(this, 'buffered', {
  5812. get: function get() {
  5813. var start = null;
  5814. var end = null;
  5815. var arity = 0;
  5816. var extents = [];
  5817. var ranges = [];
  5818. if (!this.videoBuffer_ && (this.audioDisabled_ || !this.audioBuffer_)) {
  5819. return _videoJs2['default'].createTimeRange();
  5820. }
  5821. // Handle the case where we only have one buffer
  5822. if (!this.videoBuffer_) {
  5823. return this.audioBuffer_.buffered;
  5824. } else if (this.audioDisabled_ || !this.audioBuffer_) {
  5825. return this.videoBuffer_.buffered;
  5826. }
  5827. // Handle the case where there is no buffer data
  5828. if ((!this.videoBuffer_ || this.videoBuffer_.buffered.length === 0) && (!this.audioBuffer_ || this.audioBuffer_.buffered.length === 0)) {
  5829. return _videoJs2['default'].createTimeRange();
  5830. }
  5831. // Handle the case where we have both buffers and create an
  5832. // intersection of the two
  5833. var videoBuffered = this.videoBuffer_.buffered;
  5834. var audioBuffered = this.audioBuffer_.buffered;
  5835. var count = videoBuffered.length;
  5836. // A) Gather up all start and end times
  5837. while (count--) {
  5838. extents.push({ time: videoBuffered.start(count), type: 'start' });
  5839. extents.push({ time: videoBuffered.end(count), type: 'end' });
  5840. }
  5841. count = audioBuffered.length;
  5842. while (count--) {
  5843. extents.push({ time: audioBuffered.start(count), type: 'start' });
  5844. extents.push({ time: audioBuffered.end(count), type: 'end' });
  5845. }
  5846. // B) Sort them by time
  5847. extents.sort(function (a, b) {
  5848. return a.time - b.time;
  5849. });
  5850. // C) Go along one by one incrementing arity for start and decrementing
  5851. // arity for ends
  5852. for (count = 0; count < extents.length; count++) {
  5853. if (extents[count].type === 'start') {
  5854. arity++;
  5855. // D) If arity is ever incremented to 2 we are entering an
  5856. // overlapping range
  5857. if (arity === 2) {
  5858. start = extents[count].time;
  5859. }
  5860. } else if (extents[count].type === 'end') {
  5861. arity--;
  5862. // E) If arity is ever decremented to 1 we leaving an
  5863. // overlapping range
  5864. if (arity === 1) {
  5865. end = extents[count].time;
  5866. }
  5867. }
  5868. // F) Record overlapping ranges
  5869. if (start !== null && end !== null) {
  5870. ranges.push([start, end]);
  5871. start = null;
  5872. end = null;
  5873. }
  5874. }
  5875. return _videoJs2['default'].createTimeRanges(ranges);
  5876. }
  5877. });
  5878. }
  5879. /**
  5880. * When we get a data event from the transmuxer
  5881. * we call this function and handle the data that
  5882. * was sent to us
  5883. *
  5884. * @private
  5885. * @param {Event} event the data event from the transmuxer
  5886. */
  5887. _createClass(VirtualSourceBuffer, [{
  5888. key: 'data_',
  5889. value: function data_(event) {
  5890. var segment = event.data.segment;
  5891. // Cast ArrayBuffer to TypedArray
  5892. segment.data = new Uint8Array(segment.data, event.data.byteOffset, event.data.byteLength);
  5893. (0, _createTextTracksIfNecessary2['default'])(this, this.mediaSource_, segment);
  5894. // Add the segments to the pendingBuffers array
  5895. this.pendingBuffers_.push(segment);
  5896. return;
  5897. }
  5898. /**
  5899. * When we get a done event from the transmuxer
  5900. * we call this function and we process all
  5901. * of the pending data that we have been saving in the
  5902. * data_ function
  5903. *
  5904. * @private
  5905. * @param {Event} event the done event from the transmuxer
  5906. */
  5907. }, {
  5908. key: 'done_',
  5909. value: function done_(event) {
  5910. // All buffers should have been flushed from the muxer
  5911. // start processing anything we have received
  5912. this.processPendingSegments_();
  5913. return;
  5914. }
  5915. /**
  5916. * Create our internal native audio/video source buffers and add
  5917. * event handlers to them with the following conditions:
  5918. * 1. they do not already exist on the mediaSource
  5919. * 2. this VSB has a codec for them
  5920. *
  5921. * @private
  5922. */
  5923. }, {
  5924. key: 'createRealSourceBuffers_',
  5925. value: function createRealSourceBuffers_() {
  5926. var _this2 = this;
  5927. var types = ['audio', 'video'];
  5928. types.forEach(function (type) {
  5929. // Don't create a SourceBuffer of this type if we don't have a
  5930. // codec for it
  5931. if (!_this2[type + 'Codec_']) {
  5932. return;
  5933. }
  5934. // Do nothing if a SourceBuffer of this type already exists
  5935. if (_this2[type + 'Buffer_']) {
  5936. return;
  5937. }
  5938. var buffer = null;
  5939. // If the mediasource already has a SourceBuffer for the codec
  5940. // use that
  5941. if (_this2.mediaSource_[type + 'Buffer_']) {
  5942. buffer = _this2.mediaSource_[type + 'Buffer_'];
  5943. } else {
  5944. buffer = _this2.mediaSource_.nativeMediaSource_.addSourceBuffer(type + '/mp4;codecs="' + _this2[type + 'Codec_'] + '"');
  5945. _this2.mediaSource_[type + 'Buffer_'] = buffer;
  5946. }
  5947. _this2[type + 'Buffer_'] = buffer;
  5948. // Wire up the events to the SourceBuffer
  5949. ['update', 'updatestart', 'updateend'].forEach(function (event) {
  5950. buffer.addEventListener(event, function () {
  5951. // if audio is disabled
  5952. if (type === 'audio' && _this2.audioDisabled_) {
  5953. return;
  5954. }
  5955. var shouldTrigger = types.every(function (t) {
  5956. // skip checking audio's updating status if audio
  5957. // is not enabled
  5958. if (t === 'audio' && _this2.audioDisabled_) {
  5959. return true;
  5960. }
  5961. // if the other type if updating we don't trigger
  5962. if (type !== t && _this2[t + 'Buffer_'] && _this2[t + 'Buffer_'].updating) {
  5963. return false;
  5964. }
  5965. return true;
  5966. });
  5967. if (shouldTrigger) {
  5968. return _this2.trigger(event);
  5969. }
  5970. });
  5971. });
  5972. });
  5973. }
  5974. /**
  5975. * Emulate the native mediasource function, but our function will
  5976. * send all of the proposed segments to the transmuxer so that we
  5977. * can transmux them before we append them to our internal
  5978. * native source buffers in the correct format.
  5979. *
  5980. * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/appendBuffer
  5981. * @param {Uint8Array} segment the segment to append to the buffer
  5982. */
  5983. }, {
  5984. key: 'appendBuffer',
  5985. value: function appendBuffer(segment) {
  5986. // Start the internal "updating" state
  5987. this.bufferUpdating_ = true;
  5988. this.transmuxer_.postMessage({
  5989. action: 'push',
  5990. // Send the typed-array of data as an ArrayBuffer so that
  5991. // it can be sent as a "Transferable" and avoid the costly
  5992. // memory copy
  5993. data: segment.buffer,
  5994. // To recreate the original typed-array, we need information
  5995. // about what portion of the ArrayBuffer it was a view into
  5996. byteOffset: segment.byteOffset,
  5997. byteLength: segment.byteLength
  5998. }, [segment.buffer]);
  5999. this.transmuxer_.postMessage({ action: 'flush' });
  6000. }
  6001. /**
  6002. * Emulate the native mediasource function and remove parts
  6003. * of the buffer from any of our internal buffers that exist
  6004. *
  6005. * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/remove
  6006. * @param {Double} start position to start the remove at
  6007. * @param {Double} end position to end the remove at
  6008. */
  6009. }, {
  6010. key: 'remove',
  6011. value: function remove(start, end) {
  6012. if (this.videoBuffer_) {
  6013. this.videoBuffer_.remove(start, end);
  6014. }
  6015. if (!this.audioDisabled_ && this.audioBuffer_) {
  6016. this.audioBuffer_.remove(start, end);
  6017. }
  6018. // Remove Metadata Cues (id3)
  6019. (0, _removeCuesFromTrack2['default'])(start, end, this.metadataTrack_);
  6020. // Remove Any Captions
  6021. (0, _removeCuesFromTrack2['default'])(start, end, this.inbandTextTrack_);
  6022. }
  6023. /**
  6024. * Process any segments that the muxer has output
  6025. * Concatenate segments together based on type and append them into
  6026. * their respective sourceBuffers
  6027. *
  6028. * @private
  6029. */
  6030. }, {
  6031. key: 'processPendingSegments_',
  6032. value: function processPendingSegments_() {
  6033. var sortedSegments = {
  6034. video: {
  6035. segments: [],
  6036. bytes: 0
  6037. },
  6038. audio: {
  6039. segments: [],
  6040. bytes: 0
  6041. },
  6042. captions: [],
  6043. metadata: []
  6044. };
  6045. // Sort segments into separate video/audio arrays and
  6046. // keep track of their total byte lengths
  6047. sortedSegments = this.pendingBuffers_.reduce(function (segmentObj, segment) {
  6048. var type = segment.type;
  6049. var data = segment.data;
  6050. segmentObj[type].segments.push(data);
  6051. segmentObj[type].bytes += data.byteLength;
  6052. // Gather any captions into a single array
  6053. if (segment.captions) {
  6054. segmentObj.captions = segmentObj.captions.concat(segment.captions);
  6055. }
  6056. if (segment.info) {
  6057. segmentObj[type].info = segment.info;
  6058. }
  6059. // Gather any metadata into a single array
  6060. if (segment.metadata) {
  6061. segmentObj.metadata = segmentObj.metadata.concat(segment.metadata);
  6062. }
  6063. return segmentObj;
  6064. }, sortedSegments);
  6065. // Create the real source buffers if they don't exist by now since we
  6066. // finally are sure what tracks are contained in the source
  6067. if (!this.videoBuffer_ && !this.audioBuffer_) {
  6068. // Remove any codecs that may have been specified by default but
  6069. // are no longer applicable now
  6070. if (sortedSegments.video.bytes === 0) {
  6071. this.videoCodec_ = null;
  6072. }
  6073. if (sortedSegments.audio.bytes === 0) {
  6074. this.audioCodec_ = null;
  6075. }
  6076. this.createRealSourceBuffers_();
  6077. }
  6078. if (sortedSegments.audio.info) {
  6079. this.mediaSource_.trigger({ type: 'audioinfo', info: sortedSegments.audio.info });
  6080. }
  6081. if (sortedSegments.video.info) {
  6082. this.mediaSource_.trigger({ type: 'videoinfo', info: sortedSegments.video.info });
  6083. }
  6084. // Merge multiple video and audio segments into one and append
  6085. if (this.videoBuffer_) {
  6086. this.concatAndAppendSegments_(sortedSegments.video, this.videoBuffer_);
  6087. // TODO: are video tracks the only ones with text tracks?
  6088. (0, _addTextTrackData2['default'])(this, sortedSegments.captions, sortedSegments.metadata);
  6089. }
  6090. if (!this.audioDisabled_ && this.audioBuffer_) {
  6091. this.concatAndAppendSegments_(sortedSegments.audio, this.audioBuffer_);
  6092. }
  6093. this.pendingBuffers_.length = 0;
  6094. // We are no longer in the internal "updating" state
  6095. this.bufferUpdating_ = false;
  6096. }
  6097. /**
  6098. * Combine all segments into a single Uint8Array and then append them
  6099. * to the destination buffer
  6100. *
  6101. * @param {Object} segmentObj
  6102. * @param {SourceBuffer} destinationBuffer native source buffer to append data to
  6103. * @private
  6104. */
  6105. }, {
  6106. key: 'concatAndAppendSegments_',
  6107. value: function concatAndAppendSegments_(segmentObj, destinationBuffer) {
  6108. var offset = 0;
  6109. var tempBuffer = undefined;
  6110. if (segmentObj.bytes) {
  6111. tempBuffer = new Uint8Array(segmentObj.bytes);
  6112. // Combine the individual segments into one large typed-array
  6113. segmentObj.segments.forEach(function (segment) {
  6114. tempBuffer.set(segment, offset);
  6115. offset += segment.byteLength;
  6116. });
  6117. destinationBuffer.appendBuffer(tempBuffer);
  6118. }
  6119. }
  6120. /**
  6121. * Emulate the native mediasource function. abort any soureBuffer
  6122. * actions and throw out any un-appended data.
  6123. *
  6124. * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/abort
  6125. */
  6126. }, {
  6127. key: 'abort',
  6128. value: function abort() {
  6129. if (this.videoBuffer_) {
  6130. this.videoBuffer_.abort();
  6131. }
  6132. if (this.audioBuffer_) {
  6133. this.audioBuffer_.abort();
  6134. }
  6135. if (this.transmuxer_) {
  6136. this.transmuxer_.postMessage({ action: 'reset' });
  6137. }
  6138. this.pendingBuffers_.length = 0;
  6139. this.bufferUpdating_ = false;
  6140. }
  6141. }]);
  6142. return VirtualSourceBuffer;
  6143. })(_videoJs2['default'].EventTarget);
  6144. exports['default'] = VirtualSourceBuffer;
  6145. module.exports = exports['default'];
  6146. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  6147. },{"./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){
  6148. /**
  6149. * mux.js
  6150. *
  6151. * Copyright (c) 2016 Brightcove
  6152. * All rights reserved.
  6153. *
  6154. * A stream-based aac to mp4 converter. This utility can be used to
  6155. * deliver mp4s to a SourceBuffer on platforms that support native
  6156. * Media Source Extensions.
  6157. */
  6158. 'use strict';
  6159. var Stream = require('../utils/stream.js');
  6160. // Constants
  6161. var AacStream;
  6162. /**
  6163. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  6164. */
  6165. AacStream = function() {
  6166. var
  6167. everything = new Uint8Array(),
  6168. receivedTimeStamp = false,
  6169. timeStamp = 0;
  6170. AacStream.prototype.init.call(this);
  6171. this.setTimestamp = function (timestamp) {
  6172. timeStamp = timestamp;
  6173. };
  6174. this.parseId3TagSize = function(header, byteIndex) {
  6175. var
  6176. returnSize = (header[byteIndex + 6] << 21) |
  6177. (header[byteIndex + 7] << 14) |
  6178. (header[byteIndex + 8] << 7) |
  6179. (header[byteIndex + 9]),
  6180. flags = header[byteIndex + 5],
  6181. footerPresent = (flags & 16) >> 4;
  6182. if (footerPresent) {
  6183. return returnSize + 20;
  6184. }
  6185. return returnSize + 10;
  6186. };
  6187. this.parseAdtsSize = function(header, byteIndex) {
  6188. var
  6189. lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  6190. middle = header[byteIndex + 4] << 3,
  6191. highTwo = header[byteIndex + 3] & 0x3 << 11;
  6192. return (highTwo | middle) | lowThree;
  6193. };
  6194. this.push = function(bytes) {
  6195. var
  6196. frameSize = 0,
  6197. byteIndex = 0,
  6198. bytesLeft,
  6199. chunk,
  6200. packet,
  6201. tempLength;
  6202. // If there are bytes remaining from the last segment, prepend them to the
  6203. // bytes that were pushed in
  6204. if (everything.length) {
  6205. tempLength = everything.length;
  6206. everything = new Uint8Array(bytes.byteLength + tempLength);
  6207. everything.set(everything.subarray(0, tempLength));
  6208. everything.set(bytes, tempLength);
  6209. } else {
  6210. everything = bytes;
  6211. }
  6212. while (everything.length - byteIndex >= 3) {
  6213. if ((everything[byteIndex] === 'I'.charCodeAt(0)) &&
  6214. (everything[byteIndex + 1] === 'D'.charCodeAt(0)) &&
  6215. (everything[byteIndex + 2] === '3'.charCodeAt(0))) {
  6216. // Exit early because we don't have enough to parse
  6217. // the ID3 tag header
  6218. if (everything.length - byteIndex < 10) {
  6219. break;
  6220. }
  6221. // check framesize
  6222. frameSize = this.parseId3TagSize(everything, byteIndex);
  6223. // Exit early if we don't have enough in the buffer
  6224. // to emit a full packet
  6225. if (frameSize > everything.length) {
  6226. break;
  6227. }
  6228. chunk = {
  6229. type: 'timed-metadata',
  6230. data: everything.subarray(byteIndex, byteIndex + frameSize)
  6231. };
  6232. this.trigger('data', chunk);
  6233. byteIndex += frameSize;
  6234. continue;
  6235. } else if ((everything[byteIndex] & 0xff === 0xff) &&
  6236. ((everything[byteIndex + 1] & 0xf0) === 0xf0)) {
  6237. // Exit early because we don't have enough to parse
  6238. // the ADTS frame header
  6239. if (everything.length - byteIndex < 7) {
  6240. break;
  6241. }
  6242. frameSize = this.parseAdtsSize(everything, byteIndex);
  6243. // Exit early if we don't have enough in the buffer
  6244. // to emit a full packet
  6245. if (frameSize > everything.length) {
  6246. break;
  6247. }
  6248. packet = {
  6249. type: 'audio',
  6250. data: everything.subarray(byteIndex, byteIndex + frameSize),
  6251. pts: timeStamp,
  6252. dts: timeStamp,
  6253. };
  6254. this.trigger('data', packet);
  6255. byteIndex += frameSize;
  6256. continue;
  6257. }
  6258. byteIndex++;
  6259. }
  6260. bytesLeft = everything.length - byteIndex;
  6261. if (bytesLeft > 0) {
  6262. everything = everything.subarray(byteIndex);
  6263. } else {
  6264. everything = new Uint8Array();
  6265. }
  6266. };
  6267. };
  6268. AacStream.prototype = new Stream();
  6269. module.exports = AacStream;
  6270. },{"../utils/stream.js":55}],37:[function(require,module,exports){
  6271. 'use strict';
  6272. var Stream = require('../utils/stream.js');
  6273. var AdtsStream;
  6274. var
  6275. ADTS_SAMPLING_FREQUENCIES = [
  6276. 96000,
  6277. 88200,
  6278. 64000,
  6279. 48000,
  6280. 44100,
  6281. 32000,
  6282. 24000,
  6283. 22050,
  6284. 16000,
  6285. 12000,
  6286. 11025,
  6287. 8000,
  6288. 7350
  6289. ];
  6290. /*
  6291. * Accepts a ElementaryStream and emits data events with parsed
  6292. * AAC Audio Frames of the individual packets. Input audio in ADTS
  6293. * format is unpacked and re-emitted as AAC frames.
  6294. *
  6295. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  6296. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  6297. */
  6298. AdtsStream = function() {
  6299. var self, buffer;
  6300. AdtsStream.prototype.init.call(this);
  6301. self = this;
  6302. this.push = function(packet) {
  6303. var
  6304. i = 0,
  6305. frameNum = 0,
  6306. frameLength,
  6307. protectionSkipBytes,
  6308. frameEnd,
  6309. oldBuffer,
  6310. numFrames,
  6311. sampleCount,
  6312. adtsFrameDuration;
  6313. if (packet.type !== 'audio') {
  6314. // ignore non-audio data
  6315. return;
  6316. }
  6317. // Prepend any data in the buffer to the input data so that we can parse
  6318. // aac frames the cross a PES packet boundary
  6319. if (buffer) {
  6320. oldBuffer = buffer;
  6321. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  6322. buffer.set(oldBuffer);
  6323. buffer.set(packet.data, oldBuffer.byteLength);
  6324. } else {
  6325. buffer = packet.data;
  6326. }
  6327. // unpack any ADTS frames which have been fully received
  6328. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  6329. while (i + 5 < buffer.length) {
  6330. // Loook for the start of an ADTS header..
  6331. if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
  6332. // If a valid header was not found, jump one forward and attempt to
  6333. // find a valid ADTS header starting at the next byte
  6334. i++;
  6335. continue;
  6336. }
  6337. // The protection skip bit tells us if we have 2 bytes of CRC data at the
  6338. // end of the ADTS header
  6339. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2;
  6340. // Frame length is a 13 bit integer starting 16 bits from the
  6341. // end of the sync sequence
  6342. frameLength = ((buffer[i + 3] & 0x03) << 11) |
  6343. (buffer[i + 4] << 3) |
  6344. ((buffer[i + 5] & 0xe0) >> 5);
  6345. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  6346. adtsFrameDuration = (sampleCount * 90000) /
  6347. ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2];
  6348. frameEnd = i + frameLength;
  6349. // If we don't have enough data to actually finish this ADTS frame, return
  6350. // and wait for more data
  6351. if (buffer.byteLength < frameEnd) {
  6352. return;
  6353. }
  6354. // Otherwise, deliver the complete AAC frame
  6355. this.trigger('data', {
  6356. pts: packet.pts + (frameNum * adtsFrameDuration),
  6357. dts: packet.dts + (frameNum * adtsFrameDuration),
  6358. sampleCount: sampleCount,
  6359. audioobjecttype: ((buffer[i + 2] >>> 6) & 0x03) + 1,
  6360. channelcount: ((buffer[i + 2] & 1) << 2) |
  6361. ((buffer[i + 3] & 0xc0) >>> 6),
  6362. samplerate: ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2],
  6363. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  6364. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  6365. samplesize: 16,
  6366. data: buffer.subarray(i + 7 + protectionSkipBytes, frameEnd)
  6367. });
  6368. // If the buffer is empty, clear it and return
  6369. if (buffer.byteLength === frameEnd) {
  6370. buffer = undefined;
  6371. return;
  6372. }
  6373. frameNum++;
  6374. // Remove the finished frame from the buffer and start the process again
  6375. buffer = buffer.subarray(frameEnd);
  6376. }
  6377. };
  6378. this.flush = function() {
  6379. this.trigger('done');
  6380. };
  6381. };
  6382. AdtsStream.prototype = new Stream();
  6383. module.exports = AdtsStream;
  6384. },{"../utils/stream.js":55}],38:[function(require,module,exports){
  6385. 'use strict';
  6386. var Stream = require('../utils/stream.js');
  6387. var ExpGolomb = require('../utils/exp-golomb.js');
  6388. var H264Stream, NalByteStream;
  6389. /**
  6390. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  6391. */
  6392. NalByteStream = function() {
  6393. var
  6394. syncPoint = 0,
  6395. i,
  6396. buffer;
  6397. NalByteStream.prototype.init.call(this);
  6398. this.push = function(data) {
  6399. var swapBuffer;
  6400. if (!buffer) {
  6401. buffer = data.data;
  6402. } else {
  6403. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  6404. swapBuffer.set(buffer);
  6405. swapBuffer.set(data.data, buffer.byteLength);
  6406. buffer = swapBuffer;
  6407. }
  6408. // Rec. ITU-T H.264, Annex B
  6409. // scan for NAL unit boundaries
  6410. // a match looks like this:
  6411. // 0 0 1 .. NAL .. 0 0 1
  6412. // ^ sync point ^ i
  6413. // or this:
  6414. // 0 0 1 .. NAL .. 0 0 0
  6415. // ^ sync point ^ i
  6416. // advance the sync point to a NAL start, if necessary
  6417. for (; syncPoint < buffer.byteLength - 3; syncPoint++) {
  6418. if (buffer[syncPoint + 2] === 1) {
  6419. // the sync point is properly aligned
  6420. i = syncPoint + 5;
  6421. break;
  6422. }
  6423. }
  6424. while (i < buffer.byteLength) {
  6425. // look at the current byte to determine if we've hit the end of
  6426. // a NAL unit boundary
  6427. switch (buffer[i]) {
  6428. case 0:
  6429. // skip past non-sync sequences
  6430. if (buffer[i - 1] !== 0) {
  6431. i += 2;
  6432. break;
  6433. } else if (buffer[i - 2] !== 0) {
  6434. i++;
  6435. break;
  6436. }
  6437. // deliver the NAL unit if it isn't empty
  6438. if (syncPoint + 3 !== i - 2) {
  6439. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  6440. }
  6441. // drop trailing zeroes
  6442. do {
  6443. i++;
  6444. } while (buffer[i] !== 1 && i < buffer.length);
  6445. syncPoint = i - 2;
  6446. i += 3;
  6447. break;
  6448. case 1:
  6449. // skip past non-sync sequences
  6450. if (buffer[i - 1] !== 0 ||
  6451. buffer[i - 2] !== 0) {
  6452. i += 3;
  6453. break;
  6454. }
  6455. // deliver the NAL unit
  6456. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  6457. syncPoint = i - 2;
  6458. i += 3;
  6459. break;
  6460. default:
  6461. // the current byte isn't a one or zero, so it cannot be part
  6462. // of a sync sequence
  6463. i += 3;
  6464. break;
  6465. }
  6466. }
  6467. // filter out the NAL units that were delivered
  6468. buffer = buffer.subarray(syncPoint);
  6469. i -= syncPoint;
  6470. syncPoint = 0;
  6471. };
  6472. this.flush = function() {
  6473. // deliver the last buffered NAL unit
  6474. if (buffer && buffer.byteLength > 3) {
  6475. this.trigger('data', buffer.subarray(syncPoint + 3));
  6476. }
  6477. // reset the stream state
  6478. buffer = null;
  6479. syncPoint = 0;
  6480. this.trigger('done');
  6481. };
  6482. };
  6483. NalByteStream.prototype = new Stream();
  6484. /**
  6485. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  6486. * events.
  6487. */
  6488. H264Stream = function() {
  6489. var
  6490. nalByteStream = new NalByteStream(),
  6491. self,
  6492. trackId,
  6493. currentPts,
  6494. currentDts,
  6495. discardEmulationPreventionBytes,
  6496. readSequenceParameterSet,
  6497. skipScalingList;
  6498. H264Stream.prototype.init.call(this);
  6499. self = this;
  6500. this.push = function(packet) {
  6501. if (packet.type !== 'video') {
  6502. return;
  6503. }
  6504. trackId = packet.trackId;
  6505. currentPts = packet.pts;
  6506. currentDts = packet.dts;
  6507. nalByteStream.push(packet);
  6508. };
  6509. nalByteStream.on('data', function(data) {
  6510. var
  6511. event = {
  6512. trackId: trackId,
  6513. pts: currentPts,
  6514. dts: currentDts,
  6515. data: data
  6516. };
  6517. switch (data[0] & 0x1f) {
  6518. case 0x05:
  6519. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  6520. break;
  6521. case 0x06:
  6522. event.nalUnitType = 'sei_rbsp';
  6523. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  6524. break;
  6525. case 0x07:
  6526. event.nalUnitType = 'seq_parameter_set_rbsp';
  6527. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  6528. event.config = readSequenceParameterSet(event.escapedRBSP);
  6529. break;
  6530. case 0x08:
  6531. event.nalUnitType = 'pic_parameter_set_rbsp';
  6532. break;
  6533. case 0x09:
  6534. event.nalUnitType = 'access_unit_delimiter_rbsp';
  6535. break;
  6536. default:
  6537. break;
  6538. }
  6539. self.trigger('data', event);
  6540. });
  6541. nalByteStream.on('done', function() {
  6542. self.trigger('done');
  6543. });
  6544. this.flush = function() {
  6545. nalByteStream.flush();
  6546. };
  6547. /**
  6548. * Advance the ExpGolomb decoder past a scaling list. The scaling
  6549. * list is optionally transmitted as part of a sequence parameter
  6550. * set and is not relevant to transmuxing.
  6551. * @param count {number} the number of entries in this scaling list
  6552. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  6553. * start of a scaling list
  6554. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  6555. */
  6556. skipScalingList = function(count, expGolombDecoder) {
  6557. var
  6558. lastScale = 8,
  6559. nextScale = 8,
  6560. j,
  6561. deltaScale;
  6562. for (j = 0; j < count; j++) {
  6563. if (nextScale !== 0) {
  6564. deltaScale = expGolombDecoder.readExpGolomb();
  6565. nextScale = (lastScale + deltaScale + 256) % 256;
  6566. }
  6567. lastScale = (nextScale === 0) ? lastScale : nextScale;
  6568. }
  6569. };
  6570. /**
  6571. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  6572. * Sequence Payload"
  6573. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  6574. * unit
  6575. * @return {Uint8Array} the RBSP without any Emulation
  6576. * Prevention Bytes
  6577. */
  6578. discardEmulationPreventionBytes = function(data) {
  6579. var
  6580. length = data.byteLength,
  6581. emulationPreventionBytesPositions = [],
  6582. i = 1,
  6583. newLength, newData;
  6584. // Find all `Emulation Prevention Bytes`
  6585. while (i < length - 2) {
  6586. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  6587. emulationPreventionBytesPositions.push(i + 2);
  6588. i += 2;
  6589. } else {
  6590. i++;
  6591. }
  6592. }
  6593. // If no Emulation Prevention Bytes were found just return the original
  6594. // array
  6595. if (emulationPreventionBytesPositions.length === 0) {
  6596. return data;
  6597. }
  6598. // Create a new array to hold the NAL unit data
  6599. newLength = length - emulationPreventionBytesPositions.length;
  6600. newData = new Uint8Array(newLength);
  6601. var sourceIndex = 0;
  6602. for (i = 0; i < newLength; sourceIndex++, i++) {
  6603. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  6604. // Skip this byte
  6605. sourceIndex++;
  6606. // Remove this position index
  6607. emulationPreventionBytesPositions.shift();
  6608. }
  6609. newData[i] = data[sourceIndex];
  6610. }
  6611. return newData;
  6612. };
  6613. /**
  6614. * Read a sequence parameter set and return some interesting video
  6615. * properties. A sequence parameter set is the H264 metadata that
  6616. * describes the properties of upcoming video frames.
  6617. * @param data {Uint8Array} the bytes of a sequence parameter set
  6618. * @return {object} an object with configuration parsed from the
  6619. * sequence parameter set, including the dimensions of the
  6620. * associated video frames.
  6621. */
  6622. readSequenceParameterSet = function(data) {
  6623. var
  6624. frameCropLeftOffset = 0,
  6625. frameCropRightOffset = 0,
  6626. frameCropTopOffset = 0,
  6627. frameCropBottomOffset = 0,
  6628. sarScale = 1,
  6629. expGolombDecoder, profileIdc, levelIdc, profileCompatibility,
  6630. chromaFormatIdc, picOrderCntType,
  6631. numRefFramesInPicOrderCntCycle, picWidthInMbsMinus1,
  6632. picHeightInMapUnitsMinus1,
  6633. frameMbsOnlyFlag,
  6634. scalingListCount,
  6635. sarRatio,
  6636. aspectRatioIdc,
  6637. i;
  6638. expGolombDecoder = new ExpGolomb(data);
  6639. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  6640. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  6641. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  6642. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  6643. // some profiles have more optional data we don't need
  6644. if (profileIdc === 100 ||
  6645. profileIdc === 110 ||
  6646. profileIdc === 122 ||
  6647. profileIdc === 244 ||
  6648. profileIdc === 44 ||
  6649. profileIdc === 83 ||
  6650. profileIdc === 86 ||
  6651. profileIdc === 118 ||
  6652. profileIdc === 128 ||
  6653. profileIdc === 138 ||
  6654. profileIdc === 139 ||
  6655. profileIdc === 134) {
  6656. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  6657. if (chromaFormatIdc === 3) {
  6658. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  6659. }
  6660. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  6661. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  6662. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  6663. if (expGolombDecoder.readBoolean()) { // seq_scaling_matrix_present_flag
  6664. scalingListCount = (chromaFormatIdc !== 3) ? 8 : 12;
  6665. for (i = 0; i < scalingListCount; i++) {
  6666. if (expGolombDecoder.readBoolean()) { // seq_scaling_list_present_flag[ i ]
  6667. if (i < 6) {
  6668. skipScalingList(16, expGolombDecoder);
  6669. } else {
  6670. skipScalingList(64, expGolombDecoder);
  6671. }
  6672. }
  6673. }
  6674. }
  6675. }
  6676. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  6677. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  6678. if (picOrderCntType === 0) {
  6679. expGolombDecoder.readUnsignedExpGolomb(); //log2_max_pic_order_cnt_lsb_minus4
  6680. } else if (picOrderCntType === 1) {
  6681. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  6682. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  6683. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  6684. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  6685. for(i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  6686. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  6687. }
  6688. }
  6689. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  6690. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  6691. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  6692. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  6693. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  6694. if (frameMbsOnlyFlag === 0) {
  6695. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  6696. }
  6697. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  6698. if (expGolombDecoder.readBoolean()) { // frame_cropping_flag
  6699. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  6700. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  6701. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  6702. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  6703. }
  6704. if (expGolombDecoder.readBoolean()) {
  6705. // vui_parameters_present_flag
  6706. if (expGolombDecoder.readBoolean()) {
  6707. // aspect_ratio_info_present_flag
  6708. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  6709. switch (aspectRatioIdc) {
  6710. case 1: sarRatio = [1,1]; break;
  6711. case 2: sarRatio = [12,11]; break;
  6712. case 3: sarRatio = [10,11]; break;
  6713. case 4: sarRatio = [16,11]; break;
  6714. case 5: sarRatio = [40,33]; break;
  6715. case 6: sarRatio = [24,11]; break;
  6716. case 7: sarRatio = [20,11]; break;
  6717. case 8: sarRatio = [32,11]; break;
  6718. case 9: sarRatio = [80,33]; break;
  6719. case 10: sarRatio = [18,11]; break;
  6720. case 11: sarRatio = [15,11]; break;
  6721. case 12: sarRatio = [64,33]; break;
  6722. case 13: sarRatio = [160,99]; break;
  6723. case 14: sarRatio = [4,3]; break;
  6724. case 15: sarRatio = [3,2]; break;
  6725. case 16: sarRatio = [2,1]; break;
  6726. case 255: {
  6727. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 |
  6728. expGolombDecoder.readUnsignedByte(),
  6729. expGolombDecoder.readUnsignedByte() << 8 |
  6730. expGolombDecoder.readUnsignedByte() ];
  6731. break;
  6732. }
  6733. }
  6734. if (sarRatio) {
  6735. sarScale = sarRatio[0] / sarRatio[1];
  6736. }
  6737. }
  6738. }
  6739. return {
  6740. profileIdc: profileIdc,
  6741. levelIdc: levelIdc,
  6742. profileCompatibility: profileCompatibility,
  6743. width: Math.ceil((((picWidthInMbsMinus1 + 1) * 16) - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale),
  6744. height: ((2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16) - (frameCropTopOffset * 2) - (frameCropBottomOffset * 2)
  6745. };
  6746. };
  6747. };
  6748. H264Stream.prototype = new Stream();
  6749. module.exports = {
  6750. H264Stream: H264Stream,
  6751. NalByteStream: NalByteStream,
  6752. };
  6753. },{"../utils/exp-golomb.js":54,"../utils/stream.js":55}],39:[function(require,module,exports){
  6754. module.exports = {
  6755. adts: require('./adts'),
  6756. h264: require('./h264'),
  6757. };
  6758. },{"./adts":37,"./h264":38}],40:[function(require,module,exports){
  6759. /**
  6760. * An object that stores the bytes of an FLV tag and methods for
  6761. * querying and manipulating that data.
  6762. * @see http://download.macromedia.com/f4v/video_file_format_spec_v10_1.pdf
  6763. */
  6764. 'use strict';
  6765. var FlvTag;
  6766. // (type:uint, extraData:Boolean = false) extends ByteArray
  6767. FlvTag = function(type, extraData) {
  6768. var
  6769. // Counter if this is a metadata tag, nal start marker if this is a video
  6770. // tag. unused if this is an audio tag
  6771. adHoc = 0, // :uint
  6772. // The default size is 16kb but this is not enough to hold iframe
  6773. // data and the resizing algorithm costs a bit so we create a larger
  6774. // starting buffer for video tags
  6775. bufferStartSize = 16384,
  6776. // checks whether the FLV tag has enough capacity to accept the proposed
  6777. // write and re-allocates the internal buffers if necessary
  6778. prepareWrite = function(flv, count) {
  6779. var
  6780. bytes,
  6781. minLength = flv.position + count;
  6782. if (minLength < flv.bytes.byteLength) {
  6783. // there's enough capacity so do nothing
  6784. return;
  6785. }
  6786. // allocate a new buffer and copy over the data that will not be modified
  6787. bytes = new Uint8Array(minLength * 2);
  6788. bytes.set(flv.bytes.subarray(0, flv.position), 0);
  6789. flv.bytes = bytes;
  6790. flv.view = new DataView(flv.bytes.buffer);
  6791. },
  6792. // commonly used metadata properties
  6793. widthBytes = FlvTag.widthBytes || new Uint8Array('width'.length),
  6794. heightBytes = FlvTag.heightBytes || new Uint8Array('height'.length),
  6795. videocodecidBytes = FlvTag.videocodecidBytes || new Uint8Array('videocodecid'.length),
  6796. i;
  6797. if (!FlvTag.widthBytes) {
  6798. // calculating the bytes of common metadata names ahead of time makes the
  6799. // corresponding writes faster because we don't have to loop over the
  6800. // characters
  6801. // re-test with test/perf.html if you're planning on changing this
  6802. for (i = 0; i < 'width'.length; i++) {
  6803. widthBytes[i] = 'width'.charCodeAt(i);
  6804. }
  6805. for (i = 0; i < 'height'.length; i++) {
  6806. heightBytes[i] = 'height'.charCodeAt(i);
  6807. }
  6808. for (i = 0; i < 'videocodecid'.length; i++) {
  6809. videocodecidBytes[i] = 'videocodecid'.charCodeAt(i);
  6810. }
  6811. FlvTag.widthBytes = widthBytes;
  6812. FlvTag.heightBytes = heightBytes;
  6813. FlvTag.videocodecidBytes = videocodecidBytes;
  6814. }
  6815. this.keyFrame = false; // :Boolean
  6816. switch(type) {
  6817. case FlvTag.VIDEO_TAG:
  6818. this.length = 16;
  6819. // Start the buffer at 256k
  6820. bufferStartSize *= 6;
  6821. break;
  6822. case FlvTag.AUDIO_TAG:
  6823. this.length = 13;
  6824. this.keyFrame = true;
  6825. break;
  6826. case FlvTag.METADATA_TAG:
  6827. this.length = 29;
  6828. this.keyFrame = true;
  6829. break;
  6830. default:
  6831. throw("Error Unknown TagType");
  6832. }
  6833. this.bytes = new Uint8Array(bufferStartSize);
  6834. this.view = new DataView(this.bytes.buffer);
  6835. this.bytes[0] = type;
  6836. this.position = this.length;
  6837. this.keyFrame = extraData; // Defaults to false
  6838. // presentation timestamp
  6839. this.pts = 0;
  6840. // decoder timestamp
  6841. this.dts = 0;
  6842. // ByteArray#writeBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0)
  6843. this.writeBytes = function(bytes, offset, length) {
  6844. var
  6845. start = offset || 0,
  6846. end;
  6847. length = length || bytes.byteLength;
  6848. end = start + length;
  6849. prepareWrite(this, length);
  6850. this.bytes.set(bytes.subarray(start, end), this.position);
  6851. this.position += length;
  6852. this.length = Math.max(this.length, this.position);
  6853. };
  6854. // ByteArray#writeByte(value:int):void
  6855. this.writeByte = function(byte) {
  6856. prepareWrite(this, 1);
  6857. this.bytes[this.position] = byte;
  6858. this.position++;
  6859. this.length = Math.max(this.length, this.position);
  6860. };
  6861. // ByteArray#writeShort(value:int):void
  6862. this.writeShort = function(short) {
  6863. prepareWrite(this, 2);
  6864. this.view.setUint16(this.position, short);
  6865. this.position += 2;
  6866. this.length = Math.max(this.length, this.position);
  6867. };
  6868. // Negative index into array
  6869. // (pos:uint):int
  6870. this.negIndex = function(pos) {
  6871. return this.bytes[this.length - pos];
  6872. };
  6873. // The functions below ONLY work when this[0] == VIDEO_TAG.
  6874. // We are not going to check for that because we dont want the overhead
  6875. // (nal:ByteArray = null):int
  6876. this.nalUnitSize = function() {
  6877. if (adHoc === 0) {
  6878. return 0;
  6879. }
  6880. return this.length - (adHoc + 4);
  6881. };
  6882. this.startNalUnit = function() {
  6883. // remember position and add 4 bytes
  6884. if (adHoc > 0) {
  6885. throw new Error("Attempted to create new NAL wihout closing the old one");
  6886. }
  6887. // reserve 4 bytes for nal unit size
  6888. adHoc = this.length;
  6889. this.length += 4;
  6890. this.position = this.length;
  6891. };
  6892. // (nal:ByteArray = null):void
  6893. this.endNalUnit = function(nalContainer) {
  6894. var
  6895. nalStart, // :uint
  6896. nalLength; // :uint
  6897. // Rewind to the marker and write the size
  6898. if (this.length === adHoc + 4) {
  6899. // we started a nal unit, but didnt write one, so roll back the 4 byte size value
  6900. this.length -= 4;
  6901. } else if (adHoc > 0) {
  6902. nalStart = adHoc + 4;
  6903. nalLength = this.length - nalStart;
  6904. this.position = adHoc;
  6905. this.view.setUint32(this.position, nalLength);
  6906. this.position = this.length;
  6907. if (nalContainer) {
  6908. // Add the tag to the NAL unit
  6909. nalContainer.push(this.bytes.subarray(nalStart, nalStart + nalLength));
  6910. }
  6911. }
  6912. adHoc = 0;
  6913. };
  6914. /**
  6915. * Write out a 64-bit floating point valued metadata property. This method is
  6916. * called frequently during a typical parse and needs to be fast.
  6917. */
  6918. // (key:String, val:Number):void
  6919. this.writeMetaDataDouble = function(key, val) {
  6920. var i;
  6921. prepareWrite(this, 2 + key.length + 9);
  6922. // write size of property name
  6923. this.view.setUint16(this.position, key.length);
  6924. this.position += 2;
  6925. // this next part looks terrible but it improves parser throughput by
  6926. // 10kB/s in my testing
  6927. // write property name
  6928. if (key === 'width') {
  6929. this.bytes.set(widthBytes, this.position);
  6930. this.position += 5;
  6931. } else if (key === 'height') {
  6932. this.bytes.set(heightBytes, this.position);
  6933. this.position += 6;
  6934. } else if (key === 'videocodecid') {
  6935. this.bytes.set(videocodecidBytes, this.position);
  6936. this.position += 12;
  6937. } else {
  6938. for (i = 0; i < key.length; i++) {
  6939. this.bytes[this.position] = key.charCodeAt(i);
  6940. this.position++;
  6941. }
  6942. }
  6943. // skip null byte
  6944. this.position++;
  6945. // write property value
  6946. this.view.setFloat64(this.position, val);
  6947. this.position += 8;
  6948. // update flv tag length
  6949. this.length = Math.max(this.length, this.position);
  6950. ++adHoc;
  6951. };
  6952. // (key:String, val:Boolean):void
  6953. this.writeMetaDataBoolean = function(key, val) {
  6954. var i;
  6955. prepareWrite(this, 2);
  6956. this.view.setUint16(this.position, key.length);
  6957. this.position += 2;
  6958. for (i = 0; i < key.length; i++) {
  6959. // if key.charCodeAt(i) >= 255, handle error
  6960. prepareWrite(this, 1);
  6961. this.bytes[this.position] = key.charCodeAt(i);
  6962. this.position++;
  6963. }
  6964. prepareWrite(this, 2);
  6965. this.view.setUint8(this.position, 0x01);
  6966. this.position++;
  6967. this.view.setUint8(this.position, val ? 0x01 : 0x00);
  6968. this.position++;
  6969. this.length = Math.max(this.length, this.position);
  6970. ++adHoc;
  6971. };
  6972. // ():ByteArray
  6973. this.finalize = function() {
  6974. var
  6975. dtsDelta, // :int
  6976. len; // :int
  6977. switch(this.bytes[0]) {
  6978. // Video Data
  6979. case FlvTag.VIDEO_TAG:
  6980. 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)
  6981. this.bytes[12] = extraData ? 0x00 : 0x01;
  6982. dtsDelta = this.pts - this.dts;
  6983. this.bytes[13] = (dtsDelta & 0x00FF0000) >>> 16;
  6984. this.bytes[14] = (dtsDelta & 0x0000FF00) >>> 8;
  6985. this.bytes[15] = (dtsDelta & 0x000000FF) >>> 0;
  6986. break;
  6987. case FlvTag.AUDIO_TAG:
  6988. this.bytes[11] = 0xAF; // 44 kHz, 16-bit stereo
  6989. this.bytes[12] = extraData ? 0x00 : 0x01;
  6990. break;
  6991. case FlvTag.METADATA_TAG:
  6992. this.position = 11;
  6993. this.view.setUint8(this.position, 0x02); // String type
  6994. this.position++;
  6995. this.view.setUint16(this.position, 0x0A); // 10 Bytes
  6996. this.position += 2;
  6997. // set "onMetaData"
  6998. this.bytes.set([0x6f, 0x6e, 0x4d, 0x65,
  6999. 0x74, 0x61, 0x44, 0x61,
  7000. 0x74, 0x61], this.position);
  7001. this.position += 10;
  7002. this.bytes[this.position] = 0x08; // Array type
  7003. this.position++;
  7004. this.view.setUint32(this.position, adHoc);
  7005. this.position = this.length;
  7006. this.bytes.set([0, 0, 9], this.position);
  7007. this.position += 3; // End Data Tag
  7008. this.length = this.position;
  7009. break;
  7010. }
  7011. len = this.length - 11;
  7012. // write the DataSize field
  7013. this.bytes[ 1] = (len & 0x00FF0000) >>> 16;
  7014. this.bytes[ 2] = (len & 0x0000FF00) >>> 8;
  7015. this.bytes[ 3] = (len & 0x000000FF) >>> 0;
  7016. // write the Timestamp
  7017. this.bytes[ 4] = (this.dts & 0x00FF0000) >>> 16;
  7018. this.bytes[ 5] = (this.dts & 0x0000FF00) >>> 8;
  7019. this.bytes[ 6] = (this.dts & 0x000000FF) >>> 0;
  7020. this.bytes[ 7] = (this.dts & 0xFF000000) >>> 24;
  7021. // write the StreamID
  7022. this.bytes[ 8] = 0;
  7023. this.bytes[ 9] = 0;
  7024. this.bytes[10] = 0;
  7025. // Sometimes we're at the end of the view and have one slot to write a
  7026. // uint32, so, prepareWrite of count 4, since, view is uint8
  7027. prepareWrite(this, 4);
  7028. this.view.setUint32(this.length, this.length);
  7029. this.length += 4;
  7030. this.position += 4;
  7031. // trim down the byte buffer to what is actually being used
  7032. this.bytes = this.bytes.subarray(0, this.length);
  7033. this.frameTime = FlvTag.frameTime(this.bytes);
  7034. // if bytes.bytelength isn't equal to this.length, handle error
  7035. return this;
  7036. };
  7037. };
  7038. FlvTag.AUDIO_TAG = 0x08; // == 8, :uint
  7039. FlvTag.VIDEO_TAG = 0x09; // == 9, :uint
  7040. FlvTag.METADATA_TAG = 0x12; // == 18, :uint
  7041. // (tag:ByteArray):Boolean {
  7042. FlvTag.isAudioFrame = function(tag) {
  7043. return FlvTag.AUDIO_TAG === tag[0];
  7044. };
  7045. // (tag:ByteArray):Boolean {
  7046. FlvTag.isVideoFrame = function(tag) {
  7047. return FlvTag.VIDEO_TAG === tag[0];
  7048. };
  7049. // (tag:ByteArray):Boolean {
  7050. FlvTag.isMetaData = function(tag) {
  7051. return FlvTag.METADATA_TAG === tag[0];
  7052. };
  7053. // (tag:ByteArray):Boolean {
  7054. FlvTag.isKeyFrame = function(tag) {
  7055. if (FlvTag.isVideoFrame(tag)) {
  7056. return tag[11] === 0x17;
  7057. }
  7058. if (FlvTag.isAudioFrame(tag)) {
  7059. return true;
  7060. }
  7061. if (FlvTag.isMetaData(tag)) {
  7062. return true;
  7063. }
  7064. return false;
  7065. };
  7066. // (tag:ByteArray):uint {
  7067. FlvTag.frameTime = function(tag) {
  7068. var pts = tag[ 4] << 16; // :uint
  7069. pts |= tag[ 5] << 8;
  7070. pts |= tag[ 6] << 0;
  7071. pts |= tag[ 7] << 24;
  7072. return pts;
  7073. };
  7074. module.exports = FlvTag;
  7075. },{}],41:[function(require,module,exports){
  7076. module.exports = {
  7077. tag: require('./flv-tag'),
  7078. Transmuxer: require('./transmuxer'),
  7079. tools: require('../tools/flv-inspector'),
  7080. };
  7081. },{"../tools/flv-inspector":52,"./flv-tag":40,"./transmuxer":42}],42:[function(require,module,exports){
  7082. 'use strict';
  7083. var Stream = require('../utils/stream.js');
  7084. var FlvTag = require('./flv-tag.js');
  7085. var m2ts = require('../m2ts/m2ts.js');
  7086. var AdtsStream = require('../codecs/adts.js');
  7087. var H264Stream = require('../codecs/h264').H264Stream;
  7088. var
  7089. MetadataStream,
  7090. Transmuxer,
  7091. VideoSegmentStream,
  7092. AudioSegmentStream,
  7093. CoalesceStream,
  7094. collectTimelineInfo,
  7095. metaDataTag,
  7096. extraDataTag;
  7097. /**
  7098. * Store information about the start and end of the tracka and the
  7099. * duration for each frame/sample we process in order to calculate
  7100. * the baseMediaDecodeTime
  7101. */
  7102. collectTimelineInfo = function (track, data) {
  7103. if (typeof data.pts === 'number') {
  7104. if (track.timelineStartInfo.pts === undefined) {
  7105. track.timelineStartInfo.pts = data.pts;
  7106. } else {
  7107. track.timelineStartInfo.pts =
  7108. Math.min(track.timelineStartInfo.pts, data.pts);
  7109. }
  7110. }
  7111. if (typeof data.dts === 'number') {
  7112. if (track.timelineStartInfo.dts === undefined) {
  7113. track.timelineStartInfo.dts = data.dts;
  7114. } else {
  7115. track.timelineStartInfo.dts =
  7116. Math.min(track.timelineStartInfo.dts, data.dts);
  7117. }
  7118. }
  7119. };
  7120. metaDataTag = function(track, pts) {
  7121. var
  7122. tag = new FlvTag(FlvTag.METADATA_TAG); // :FlvTag
  7123. tag.dts = pts;
  7124. tag.pts = pts;
  7125. tag.writeMetaDataDouble("videocodecid", 7);
  7126. tag.writeMetaDataDouble("width", track.width);
  7127. tag.writeMetaDataDouble("height", track.height);
  7128. return tag;
  7129. };
  7130. extraDataTag = function(track, pts) {
  7131. var
  7132. i,
  7133. tag = new FlvTag(FlvTag.VIDEO_TAG, true);
  7134. tag.dts = pts;
  7135. tag.pts = pts;
  7136. tag.writeByte(0x01);// version
  7137. tag.writeByte(track.profileIdc);// profile
  7138. tag.writeByte(track.profileCompatibility);// compatibility
  7139. tag.writeByte(track.levelIdc);// level
  7140. tag.writeByte(0xFC | 0x03); // reserved (6 bits), NULA length size - 1 (2 bits)
  7141. tag.writeByte(0xE0 | 0x01 ); // reserved (3 bits), num of SPS (5 bits)
  7142. tag.writeShort( track.sps[0].length ); // data of SPS
  7143. tag.writeBytes( track.sps[0] ); // SPS
  7144. tag.writeByte(track.pps.length); // num of PPS (will there ever be more that 1 PPS?)
  7145. for (i = 0 ; i < track.pps.length ; ++i) {
  7146. tag.writeShort(track.pps[i].length); // 2 bytes for length of PPS
  7147. tag.writeBytes(track.pps[i]); // data of PPS
  7148. }
  7149. return tag;
  7150. };
  7151. /**
  7152. * Constructs a single-track, media segment from AAC data
  7153. * events. The output of this stream can be fed to flash.
  7154. */
  7155. AudioSegmentStream = function(track) {
  7156. var
  7157. adtsFrames = [],
  7158. adtsFramesLength = 0,
  7159. sequenceNumber = 0,
  7160. earliestAllowedDts = 0,
  7161. oldExtraData;
  7162. AudioSegmentStream.prototype.init.call(this);
  7163. this.push = function(data) {
  7164. collectTimelineInfo(track, data);
  7165. if (track && track.channelcount === undefined) {
  7166. track.audioobjecttype = data.audioobjecttype;
  7167. track.channelcount = data.channelcount;
  7168. track.samplerate = data.samplerate;
  7169. track.samplingfrequencyindex = data.samplingfrequencyindex;
  7170. track.samplesize = data.samplesize;
  7171. track.extraData = (track.audioobjecttype << 11) |
  7172. (track.samplingfrequencyindex << 7) |
  7173. (track.channelcount << 3);
  7174. }
  7175. data.pts = Math.round(data.pts / 90);
  7176. data.dts = Math.round(data.dts / 90);
  7177. // buffer audio data until end() is called
  7178. adtsFrames.push(data);
  7179. };
  7180. this.flush = function() {
  7181. var currentFrame, adtsFrame, deltaDts,lastMetaPts, tags = [];
  7182. // return early if no audio data has been observed
  7183. if (adtsFrames.length === 0) {
  7184. this.trigger('done');
  7185. return;
  7186. }
  7187. lastMetaPts = -Infinity;
  7188. while (adtsFrames.length) {
  7189. currentFrame = adtsFrames.shift();
  7190. // write out metadata tags every 1 second so that the decoder
  7191. // is re-initialized quickly after seeking into a different
  7192. // audio configuration
  7193. if (track.extraData !== oldExtraData || currentFrame.pts - lastMetaPts >= 1000) {
  7194. adtsFrame = new FlvTag(FlvTag.METADATA_TAG);
  7195. adtsFrame.pts = currentFrame.pts;
  7196. adtsFrame.dts = currentFrame.dts;
  7197. // AAC is always 10
  7198. adtsFrame.writeMetaDataDouble("audiocodecid", 10);
  7199. adtsFrame.writeMetaDataBoolean("stereo", 2 === track.channelcount);
  7200. adtsFrame.writeMetaDataDouble ("audiosamplerate", track.samplerate);
  7201. // Is AAC always 16 bit?
  7202. adtsFrame.writeMetaDataDouble ("audiosamplesize", 16);
  7203. tags.push(adtsFrame);
  7204. oldExtraData = track.extraData;
  7205. adtsFrame = new FlvTag(FlvTag.AUDIO_TAG, true);
  7206. // For audio, DTS is always the same as PTS. We want to set the DTS
  7207. // however so we can compare with video DTS to determine approximate
  7208. // packet order
  7209. adtsFrame.pts = currentFrame.pts;
  7210. adtsFrame.dts = currentFrame.dts;
  7211. adtsFrame.view.setUint16(adtsFrame.position, track.extraData);
  7212. adtsFrame.position += 2;
  7213. adtsFrame.length = Math.max(adtsFrame.length, adtsFrame.position);
  7214. tags.push(adtsFrame);
  7215. lastMetaPts = currentFrame.pts;
  7216. }
  7217. adtsFrame = new FlvTag(FlvTag.AUDIO_TAG);
  7218. adtsFrame.pts = currentFrame.pts;
  7219. adtsFrame.dts = currentFrame.dts;
  7220. adtsFrame.writeBytes(currentFrame.data);
  7221. tags.push(adtsFrame);
  7222. }
  7223. oldExtraData = null;
  7224. this.trigger('data', {track: track, tags: tags});
  7225. this.trigger('done');
  7226. };
  7227. };
  7228. AudioSegmentStream.prototype = new Stream();
  7229. /**
  7230. * Store FlvTags for the h264 stream
  7231. * @param track {object} track metadata configuration
  7232. */
  7233. VideoSegmentStream = function(track) {
  7234. var
  7235. sequenceNumber = 0,
  7236. nalUnits = [],
  7237. nalUnitsLength = 0,
  7238. config,
  7239. h264Frame;
  7240. VideoSegmentStream.prototype.init.call(this);
  7241. this.finishFrame = function(tags, frame) {
  7242. if (!frame) {
  7243. return;
  7244. }
  7245. // Check if keyframe and the length of tags.
  7246. // This makes sure we write metadata on the first frame of a segment.
  7247. if (config && track && track.newMetadata &&
  7248. (frame.keyFrame || tags.length === 0)) {
  7249. // Push extra data on every IDR frame in case we did a stream change + seek
  7250. tags.push(metaDataTag(config, frame.pts));
  7251. tags.push(extraDataTag(track, frame.pts));
  7252. track.newMetadata = false;
  7253. }
  7254. frame.endNalUnit();
  7255. tags.push(frame);
  7256. };
  7257. this.push = function(data) {
  7258. collectTimelineInfo(track, data);
  7259. data.pts = Math.round(data.pts / 90);
  7260. data.dts = Math.round(data.dts / 90);
  7261. // buffer video until flush() is called
  7262. nalUnits.push(data);
  7263. };
  7264. this.flush = function() {
  7265. var
  7266. currentNal,
  7267. tags = [];
  7268. // Throw away nalUnits at the start of the byte stream until we find
  7269. // the first AUD
  7270. while (nalUnits.length) {
  7271. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  7272. break;
  7273. }
  7274. nalUnits.shift();
  7275. }
  7276. // return early if no video data has been observed
  7277. if (nalUnits.length === 0) {
  7278. this.trigger('done');
  7279. return;
  7280. }
  7281. while (nalUnits.length) {
  7282. currentNal = nalUnits.shift();
  7283. // record the track config
  7284. if (currentNal.nalUnitType === 'seq_parameter_set_rbsp') {
  7285. track.newMetadata = true;
  7286. config = currentNal.config;
  7287. track.width = config.width;
  7288. track.height = config.height;
  7289. track.sps = [currentNal.data];
  7290. track.profileIdc = config.profileIdc;
  7291. track.levelIdc = config.levelIdc;
  7292. track.profileCompatibility = config.profileCompatibility;
  7293. h264Frame.endNalUnit();
  7294. } else if (currentNal.nalUnitType === 'pic_parameter_set_rbsp') {
  7295. track.newMetadata = true;
  7296. track.pps = [currentNal.data];
  7297. h264Frame.endNalUnit();
  7298. } else if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  7299. if (h264Frame) {
  7300. this.finishFrame(tags, h264Frame);
  7301. }
  7302. h264Frame = new FlvTag(FlvTag.VIDEO_TAG);
  7303. h264Frame.pts = currentNal.pts;
  7304. h264Frame.dts = currentNal.dts;
  7305. } else {
  7306. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  7307. // the current sample is a key frame
  7308. h264Frame.keyFrame = true;
  7309. }
  7310. h264Frame.endNalUnit();
  7311. }
  7312. h264Frame.startNalUnit();
  7313. h264Frame.writeBytes(currentNal.data);
  7314. }
  7315. if (h264Frame) {
  7316. this.finishFrame(tags, h264Frame);
  7317. }
  7318. this.trigger('data', {track: track, tags: tags});
  7319. // Continue with the flush process now
  7320. this.trigger('done');
  7321. };
  7322. };
  7323. VideoSegmentStream.prototype = new Stream();
  7324. /**
  7325. * The final stage of the transmuxer that emits the flv tags
  7326. * for audio, video, and metadata. Also tranlates in time and
  7327. * outputs caption data and id3 cues.
  7328. */
  7329. CoalesceStream = function(options) {
  7330. // Number of Tracks per output segment
  7331. // If greater than 1, we combine multiple
  7332. // tracks into a single segment
  7333. this.numberOfTracks = 0;
  7334. this.metadataStream = options.metadataStream;
  7335. this.videoTags = [];
  7336. this.audioTags = [];
  7337. this.videoTrack = null;
  7338. this.audioTrack = null;
  7339. this.pendingCaptions = [];
  7340. this.pendingMetadata = [];
  7341. this.pendingTracks = 0;
  7342. CoalesceStream.prototype.init.call(this);
  7343. // Take output from multiple
  7344. this.push = function(output) {
  7345. // buffer incoming captions until the associated video segment
  7346. // finishes
  7347. if (output.text) {
  7348. return this.pendingCaptions.push(output);
  7349. }
  7350. // buffer incoming id3 tags until the final flush
  7351. if (output.frames) {
  7352. return this.pendingMetadata.push(output);
  7353. }
  7354. if (output.track.type === 'video') {
  7355. this.videoTrack = output.track;
  7356. this.videoTags = output.tags;
  7357. this.pendingTracks++;
  7358. }
  7359. if (output.track.type === 'audio') {
  7360. this.audioTrack = output.track;
  7361. this.audioTags = output.tags;
  7362. this.pendingTracks++;
  7363. }
  7364. };
  7365. };
  7366. CoalesceStream.prototype = new Stream();
  7367. CoalesceStream.prototype.flush = function() {
  7368. var
  7369. id3,
  7370. caption,
  7371. i,
  7372. timelineStartPts,
  7373. event = {
  7374. tags: {},
  7375. captions: [],
  7376. metadata: []
  7377. };
  7378. if (this.pendingTracks < this.numberOfTracks) {
  7379. return;
  7380. }
  7381. if (this.videoTrack) {
  7382. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  7383. } else if (this.audioTrack) {
  7384. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  7385. }
  7386. event.tags.videoTags = this.videoTags;
  7387. event.tags.audioTags = this.audioTags;
  7388. // Translate caption PTS times into second offsets into the
  7389. // video timeline for the segment
  7390. for (i = 0; i < this.pendingCaptions.length; i++) {
  7391. caption = this.pendingCaptions[i];
  7392. caption.startTime = caption.startPts - timelineStartPts;
  7393. caption.startTime /= 90e3;
  7394. caption.endTime = caption.endPts - timelineStartPts;
  7395. caption.endTime /= 90e3;
  7396. event.captions.push(caption);
  7397. }
  7398. // Translate ID3 frame PTS times into second offsets into the
  7399. // video timeline for the segment
  7400. for (i = 0; i < this.pendingMetadata.length; i++) {
  7401. id3 = this.pendingMetadata[i];
  7402. id3.cueTime = id3.pts - timelineStartPts;
  7403. id3.cueTime /= 90e3;
  7404. event.metadata.push(id3);
  7405. }
  7406. // We add this to every single emitted segment even though we only need
  7407. // it for the first
  7408. event.metadata.dispatchType = this.metadataStream.dispatchType;
  7409. // Reset stream state
  7410. this.videoTrack = null;
  7411. this.audioTrack = null;
  7412. this.videoTags = [];
  7413. this.audioTags = [];
  7414. this.pendingCaptions.length = 0;
  7415. this.pendingMetadata.length = 0;
  7416. this.pendingTracks = 0;
  7417. // Emit the final segment
  7418. this.trigger('data', event);
  7419. this.trigger('done');
  7420. };
  7421. /**
  7422. * An object that incrementally transmuxes MPEG2 Trasport Stream
  7423. * chunks into an FLV.
  7424. */
  7425. Transmuxer = function(options) {
  7426. var
  7427. self = this,
  7428. videoTrack,
  7429. audioTrack,
  7430. packetStream, parseStream, elementaryStream,
  7431. adtsStream, h264Stream,
  7432. videoSegmentStream, audioSegmentStream, captionStream,
  7433. coalesceStream;
  7434. Transmuxer.prototype.init.call(this);
  7435. options = options || {};
  7436. // expose the metadata stream
  7437. this.metadataStream = new m2ts.MetadataStream();
  7438. options.metadataStream = this.metadataStream;
  7439. // set up the parsing pipeline
  7440. packetStream = new m2ts.TransportPacketStream();
  7441. parseStream = new m2ts.TransportParseStream();
  7442. elementaryStream = new m2ts.ElementaryStream();
  7443. adtsStream = new AdtsStream();
  7444. h264Stream = new H264Stream();
  7445. coalesceStream = new CoalesceStream(options);
  7446. // disassemble MPEG2-TS packets into elementary streams
  7447. packetStream
  7448. .pipe(parseStream)
  7449. .pipe(elementaryStream);
  7450. // !!THIS ORDER IS IMPORTANT!!
  7451. // demux the streams
  7452. elementaryStream
  7453. .pipe(h264Stream);
  7454. elementaryStream
  7455. .pipe(adtsStream);
  7456. elementaryStream
  7457. .pipe(this.metadataStream)
  7458. .pipe(coalesceStream);
  7459. // if CEA-708 parsing is available, hook up a caption stream
  7460. captionStream = new m2ts.CaptionStream();
  7461. h264Stream.pipe(captionStream)
  7462. .pipe(coalesceStream);
  7463. // hook up the segment streams once track metadata is delivered
  7464. elementaryStream.on('data', function(data) {
  7465. var i, videoTrack, audioTrack;
  7466. if (data.type === 'metadata') {
  7467. i = data.tracks.length;
  7468. // scan the tracks listed in the metadata
  7469. while (i--) {
  7470. if (data.tracks[i].type === 'video') {
  7471. videoTrack = data.tracks[i];
  7472. } else if (data.tracks[i].type === 'audio') {
  7473. audioTrack = data.tracks[i];
  7474. }
  7475. }
  7476. // hook up the video segment stream to the first track with h264 data
  7477. if (videoTrack && !videoSegmentStream) {
  7478. coalesceStream.numberOfTracks++;
  7479. videoSegmentStream = new VideoSegmentStream(videoTrack);
  7480. // Set up the final part of the video pipeline
  7481. h264Stream
  7482. .pipe(videoSegmentStream)
  7483. .pipe(coalesceStream);
  7484. }
  7485. if (audioTrack && !audioSegmentStream) {
  7486. // hook up the audio segment stream to the first track with aac data
  7487. coalesceStream.numberOfTracks++;
  7488. audioSegmentStream = new AudioSegmentStream(audioTrack);
  7489. // Set up the final part of the audio pipeline
  7490. adtsStream
  7491. .pipe(audioSegmentStream)
  7492. .pipe(coalesceStream);
  7493. }
  7494. }
  7495. });
  7496. // feed incoming data to the front of the parsing pipeline
  7497. this.push = function(data) {
  7498. packetStream.push(data);
  7499. };
  7500. // flush any buffered data
  7501. this.flush = function() {
  7502. // Start at the top of the pipeline and flush all pending work
  7503. packetStream.flush();
  7504. };
  7505. // Re-emit any data coming from the coalesce stream to the outside world
  7506. coalesceStream.on('data', function (event) {
  7507. self.trigger('data', event);
  7508. });
  7509. // Let the consumer know we have finished flushing the entire pipeline
  7510. coalesceStream.on('done', function () {
  7511. self.trigger('done');
  7512. });
  7513. // For information on the FLV format, see
  7514. // http://download.macromedia.com/f4v/video_file_format_spec_v10_1.pdf.
  7515. // Technically, this function returns the header and a metadata FLV tag
  7516. // if duration is greater than zero
  7517. // duration in seconds
  7518. // @return {object} the bytes of the FLV header as a Uint8Array
  7519. this.getFlvHeader = function(duration, audio, video) { // :ByteArray {
  7520. var
  7521. headBytes = new Uint8Array(3 + 1 + 1 + 4),
  7522. head = new DataView(headBytes.buffer),
  7523. metadata,
  7524. result,
  7525. metadataLength;
  7526. // default arguments
  7527. duration = duration || 0;
  7528. audio = audio === undefined? true : audio;
  7529. video = video === undefined? true : video;
  7530. // signature
  7531. head.setUint8(0, 0x46); // 'F'
  7532. head.setUint8(1, 0x4c); // 'L'
  7533. head.setUint8(2, 0x56); // 'V'
  7534. // version
  7535. head.setUint8(3, 0x01);
  7536. // flags
  7537. head.setUint8(4, (audio ? 0x04 : 0x00) | (video ? 0x01 : 0x00));
  7538. // data offset, should be 9 for FLV v1
  7539. head.setUint32(5, headBytes.byteLength);
  7540. // init the first FLV tag
  7541. if (duration <= 0) {
  7542. // no duration available so just write the first field of the first
  7543. // FLV tag
  7544. result = new Uint8Array(headBytes.byteLength + 4);
  7545. result.set(headBytes);
  7546. result.set([0, 0, 0, 0], headBytes.byteLength);
  7547. return result;
  7548. }
  7549. // write out the duration metadata tag
  7550. metadata = new FlvTag(FlvTag.METADATA_TAG);
  7551. metadata.pts = metadata.dts = 0;
  7552. metadata.writeMetaDataDouble("duration", duration);
  7553. metadataLength = metadata.finalize().length;
  7554. result = new Uint8Array(headBytes.byteLength + metadataLength);
  7555. result.set(headBytes);
  7556. result.set(head.byteLength, metadataLength);
  7557. return result;
  7558. };
  7559. };
  7560. Transmuxer.prototype = new Stream();
  7561. // forward compatibility
  7562. module.exports = Transmuxer;
  7563. },{"../codecs/adts.js":37,"../codecs/h264":38,"../m2ts/m2ts.js":46,"../utils/stream.js":55,"./flv-tag.js":40}],43:[function(require,module,exports){
  7564. 'use strict';
  7565. var muxjs = {
  7566. codecs: require('./codecs'),
  7567. mp4: require('./mp4'),
  7568. flv: require('./flv'),
  7569. mp2t: require('./m2ts'),
  7570. };
  7571. module.exports = muxjs;
  7572. },{"./codecs":39,"./flv":41,"./m2ts":45,"./mp4":49}],44:[function(require,module,exports){
  7573. /**
  7574. * mux.js
  7575. *
  7576. * Copyright (c) 2015 Brightcove
  7577. * All rights reserved.
  7578. *
  7579. * Reads in-band caption information from a video elementary
  7580. * stream. Captions must follow the CEA-708 standard for injection
  7581. * into an MPEG-2 transport streams.
  7582. * @see https://en.wikipedia.org/wiki/CEA-708
  7583. */
  7584. 'use strict';
  7585. // -----------------
  7586. // Link To Transport
  7587. // -----------------
  7588. // Supplemental enhancement information (SEI) NAL units have a
  7589. // payload type field to indicate how they are to be
  7590. // interpreted. CEAS-708 caption content is always transmitted with
  7591. // payload type 0x04.
  7592. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  7593. RBSP_TRAILING_BITS = 128,
  7594. Stream = require('../utils/stream');
  7595. /**
  7596. * Parse a supplemental enhancement information (SEI) NAL unit.
  7597. * Stops parsing once a message of type ITU T T35 has been found.
  7598. *
  7599. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  7600. * @return {object} the parsed SEI payload
  7601. * @see Rec. ITU-T H.264, 7.3.2.3.1
  7602. */
  7603. var parseSei = function(bytes) {
  7604. var
  7605. i = 0,
  7606. result = {
  7607. payloadType: -1,
  7608. payloadSize: 0,
  7609. },
  7610. payloadType = 0,
  7611. payloadSize = 0;
  7612. // go through the sei_rbsp parsing each each individual sei_message
  7613. while (i < bytes.byteLength) {
  7614. // stop once we have hit the end of the sei_rbsp
  7615. if (bytes[i] === RBSP_TRAILING_BITS) {
  7616. break;
  7617. }
  7618. // Parse payload type
  7619. while (bytes[i] === 0xFF) {
  7620. payloadType += 255;
  7621. i++;
  7622. }
  7623. payloadType += bytes[i++];
  7624. // Parse payload size
  7625. while (bytes[i] === 0xFF) {
  7626. payloadSize += 255;
  7627. i++;
  7628. }
  7629. payloadSize += bytes[i++];
  7630. // this sei_message is a 608/708 caption so save it and break
  7631. // there can only ever be one caption message in a frame's sei
  7632. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  7633. result.payloadType = payloadType;
  7634. result.payloadSize = payloadSize;
  7635. result.payload = bytes.subarray(i, i + payloadSize);
  7636. break;
  7637. }
  7638. // skip the payload and parse the next message
  7639. i += payloadSize;
  7640. payloadType = 0;
  7641. payloadSize = 0;
  7642. }
  7643. return result;
  7644. };
  7645. // see ANSI/SCTE 128-1 (2013), section 8.1
  7646. var parseUserData = function(sei) {
  7647. // itu_t_t35_contry_code must be 181 (United States) for
  7648. // captions
  7649. if (sei.payload[0] !== 181) {
  7650. return null;
  7651. }
  7652. // itu_t_t35_provider_code should be 49 (ATSC) for captions
  7653. if (((sei.payload[1] << 8) | sei.payload[2]) !== 49) {
  7654. return null;
  7655. }
  7656. // the user_identifier should be "GA94" to indicate ATSC1 data
  7657. if (String.fromCharCode(sei.payload[3],
  7658. sei.payload[4],
  7659. sei.payload[5],
  7660. sei.payload[6]) !== 'GA94') {
  7661. return null;
  7662. }
  7663. // finally, user_data_type_code should be 0x03 for caption data
  7664. if (sei.payload[7] !== 0x03) {
  7665. return null;
  7666. }
  7667. // return the user_data_type_structure and strip the trailing
  7668. // marker bits
  7669. return sei.payload.subarray(8, sei.payload.length - 1);
  7670. };
  7671. // see CEA-708-D, section 4.4
  7672. var parseCaptionPackets = function(pts, userData) {
  7673. var results = [], i, count, offset, data;
  7674. // if this is just filler, return immediately
  7675. if (!(userData[0] & 0x40)) {
  7676. return results;
  7677. }
  7678. // parse out the cc_data_1 and cc_data_2 fields
  7679. count = userData[0] & 0x1f;
  7680. for (i = 0; i < count; i++) {
  7681. offset = i * 3;
  7682. data = {
  7683. type: userData[offset + 2] & 0x03,
  7684. pts: pts
  7685. };
  7686. // capture cc data when cc_valid is 1
  7687. if (userData[offset + 2] & 0x04) {
  7688. data.ccData = (userData[offset + 3] << 8) | userData[offset + 4];
  7689. results.push(data);
  7690. }
  7691. }
  7692. return results;
  7693. };
  7694. var CaptionStream = function() {
  7695. var self = this;
  7696. CaptionStream.prototype.init.call(this);
  7697. this.captionPackets_ = [];
  7698. this.field1_ = new Cea608Stream();
  7699. // forward data and done events from field1_ to this CaptionStream
  7700. this.field1_.on('data', this.trigger.bind(this, 'data'));
  7701. this.field1_.on('done', this.trigger.bind(this, 'done'));
  7702. };
  7703. CaptionStream.prototype = new Stream();
  7704. CaptionStream.prototype.push = function(event) {
  7705. var sei, userData, captionPackets;
  7706. // only examine SEI NALs
  7707. if (event.nalUnitType !== 'sei_rbsp') {
  7708. return;
  7709. }
  7710. // parse the sei
  7711. sei = parseSei(event.escapedRBSP);
  7712. // ignore everything but user_data_registered_itu_t_t35
  7713. if (sei.payloadType !== USER_DATA_REGISTERED_ITU_T_T35) {
  7714. return;
  7715. }
  7716. // parse out the user data payload
  7717. userData = parseUserData(sei);
  7718. // ignore unrecognized userData
  7719. if (!userData) {
  7720. return;
  7721. }
  7722. // parse out CC data packets and save them for later
  7723. this.captionPackets_ = this.captionPackets_.concat(parseCaptionPackets(event.pts, userData));
  7724. };
  7725. CaptionStream.prototype.flush = function () {
  7726. // make sure we actually parsed captions before proceeding
  7727. if (!this.captionPackets_.length) {
  7728. this.field1_.flush();
  7729. return;
  7730. }
  7731. // sort caption byte-pairs based on their PTS values
  7732. this.captionPackets_.sort(function(a, b) {
  7733. return a.pts - b.pts;
  7734. });
  7735. // Push each caption into Cea608Stream
  7736. this.captionPackets_.forEach(this.field1_.push, this.field1_);
  7737. this.captionPackets_.length = 0;
  7738. this.field1_.flush();
  7739. return;
  7740. };
  7741. // ----------------------
  7742. // Session to Application
  7743. // ----------------------
  7744. var BASIC_CHARACTER_TRANSLATION = {
  7745. 0x2a: 0xe1,
  7746. 0x5c: 0xe9,
  7747. 0x5e: 0xed,
  7748. 0x5f: 0xf3,
  7749. 0x60: 0xfa,
  7750. 0x7b: 0xe7,
  7751. 0x7c: 0xf7,
  7752. 0x7d: 0xd1,
  7753. 0x7e: 0xf1,
  7754. 0x7f: 0x2588
  7755. };
  7756. var getCharFromCode = function(code) {
  7757. if(code === null) {
  7758. return '';
  7759. }
  7760. code = BASIC_CHARACTER_TRANSLATION[code] || code;
  7761. return String.fromCharCode(code);
  7762. };
  7763. // Constants for the byte codes recognized by Cea608Stream. This
  7764. // list is not exhaustive. For a more comprehensive listing and
  7765. // semantics see
  7766. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  7767. var PADDING = 0x0000,
  7768. // Pop-on Mode
  7769. RESUME_CAPTION_LOADING = 0x1420,
  7770. END_OF_CAPTION = 0x142f,
  7771. // Roll-up Mode
  7772. ROLL_UP_2_ROWS = 0x1425,
  7773. ROLL_UP_3_ROWS = 0x1426,
  7774. ROLL_UP_4_ROWS = 0x1427,
  7775. RESUME_DIRECT_CAPTIONING = 0x1429,
  7776. CARRIAGE_RETURN = 0x142d,
  7777. // Erasure
  7778. BACKSPACE = 0x1421,
  7779. ERASE_DISPLAYED_MEMORY = 0x142c,
  7780. ERASE_NON_DISPLAYED_MEMORY = 0x142e;
  7781. // the index of the last row in a CEA-608 display buffer
  7782. var BOTTOM_ROW = 14;
  7783. // CEA-608 captions are rendered onto a 34x15 matrix of character
  7784. // cells. The "bottom" row is the last element in the outer array.
  7785. var createDisplayBuffer = function() {
  7786. var result = [], i = BOTTOM_ROW + 1;
  7787. while (i--) {
  7788. result.push('');
  7789. }
  7790. return result;
  7791. };
  7792. var Cea608Stream = function() {
  7793. Cea608Stream.prototype.init.call(this);
  7794. this.mode_ = 'popOn';
  7795. // When in roll-up mode, the index of the last row that will
  7796. // actually display captions. If a caption is shifted to a row
  7797. // with a lower index than this, it is cleared from the display
  7798. // buffer
  7799. this.topRow_ = 0;
  7800. this.startPts_ = 0;
  7801. this.displayed_ = createDisplayBuffer();
  7802. this.nonDisplayed_ = createDisplayBuffer();
  7803. this.lastControlCode_ = null;
  7804. this.push = function(packet) {
  7805. // Ignore other channels
  7806. if (packet.type !== 0) {
  7807. return;
  7808. }
  7809. var data, swap, char0, char1;
  7810. // remove the parity bits
  7811. data = packet.ccData & 0x7f7f;
  7812. // ignore duplicate control codes
  7813. if (data === this.lastControlCode_) {
  7814. this.lastControlCode_ = null;
  7815. return;
  7816. }
  7817. // Store control codes
  7818. if ((data & 0xf000) === 0x1000) {
  7819. this.lastControlCode_ = data;
  7820. } else {
  7821. this.lastControlCode_ = null;
  7822. }
  7823. switch (data) {
  7824. case PADDING:
  7825. break;
  7826. case RESUME_CAPTION_LOADING:
  7827. this.mode_ = 'popOn';
  7828. break;
  7829. case END_OF_CAPTION:
  7830. // if a caption was being displayed, it's gone now
  7831. this.flushDisplayed(packet.pts);
  7832. // flip memory
  7833. swap = this.displayed_;
  7834. this.displayed_ = this.nonDisplayed_;
  7835. this.nonDisplayed_ = swap;
  7836. // start measuring the time to display the caption
  7837. this.startPts_ = packet.pts;
  7838. break;
  7839. case ROLL_UP_2_ROWS:
  7840. this.topRow_ = BOTTOM_ROW - 1;
  7841. this.mode_ = 'rollUp';
  7842. break;
  7843. case ROLL_UP_3_ROWS:
  7844. this.topRow_ = BOTTOM_ROW - 2;
  7845. this.mode_ = 'rollUp';
  7846. break;
  7847. case ROLL_UP_4_ROWS:
  7848. this.topRow_ = BOTTOM_ROW - 3;
  7849. this.mode_ = 'rollUp';
  7850. break;
  7851. case CARRIAGE_RETURN:
  7852. this.flushDisplayed(packet.pts);
  7853. this.shiftRowsUp_();
  7854. this.startPts_ = packet.pts;
  7855. break;
  7856. case BACKSPACE:
  7857. if (this.mode_ === 'popOn') {
  7858. this.nonDisplayed_[BOTTOM_ROW] = this.nonDisplayed_[BOTTOM_ROW].slice(0, -1);
  7859. } else {
  7860. this.displayed_[BOTTOM_ROW] = this.displayed_[BOTTOM_ROW].slice(0, -1);
  7861. }
  7862. break;
  7863. case ERASE_DISPLAYED_MEMORY:
  7864. this.flushDisplayed(packet.pts);
  7865. this.displayed_ = createDisplayBuffer();
  7866. break;
  7867. case ERASE_NON_DISPLAYED_MEMORY:
  7868. this.nonDisplayed_ = createDisplayBuffer();
  7869. break;
  7870. default:
  7871. char0 = data >>> 8;
  7872. char1 = data & 0xff;
  7873. // Look for a Channel 1 Preamble Address Code
  7874. if (char0 >= 0x10 && char0 <= 0x17 &&
  7875. char1 >= 0x40 && char1 <= 0x7F &&
  7876. (char0 !== 0x10 || char1 < 0x60)) {
  7877. // Follow Safari's lead and replace the PAC with a space
  7878. char0 = 0x20;
  7879. // we only want one space so make the second character null
  7880. // which will get become '' in getCharFromCode
  7881. char1 = null;
  7882. }
  7883. // Look for special character sets
  7884. if ((char0 === 0x11 || char0 === 0x19) &&
  7885. (char1 >= 0x30 && char1 <= 0x3F)) {
  7886. // Put in eigth note and space
  7887. char0 = 0x266A;
  7888. char1 = '';
  7889. }
  7890. // ignore unsupported control codes
  7891. if ((char0 & 0xf0) === 0x10) {
  7892. return;
  7893. }
  7894. // character handling is dependent on the current mode
  7895. this[this.mode_](packet.pts, char0, char1);
  7896. break;
  7897. }
  7898. };
  7899. };
  7900. Cea608Stream.prototype = new Stream();
  7901. // Trigger a cue point that captures the current state of the
  7902. // display buffer
  7903. Cea608Stream.prototype.flushDisplayed = function(pts) {
  7904. var content = this.displayed_
  7905. // remove spaces from the start and end of the string
  7906. .map(function(row) { return row.trim(); })
  7907. // remove empty rows
  7908. .filter(function(row) { return row.length; })
  7909. // combine all text rows to display in one cue
  7910. .join('\n');
  7911. if (content.length) {
  7912. this.trigger('data', {
  7913. startPts: this.startPts_,
  7914. endPts: pts,
  7915. text: content
  7916. });
  7917. }
  7918. };
  7919. // Mode Implementations
  7920. Cea608Stream.prototype.popOn = function(pts, char0, char1) {
  7921. var baseRow = this.nonDisplayed_[BOTTOM_ROW];
  7922. // buffer characters
  7923. baseRow += getCharFromCode(char0);
  7924. baseRow += getCharFromCode(char1);
  7925. this.nonDisplayed_[BOTTOM_ROW] = baseRow;
  7926. };
  7927. Cea608Stream.prototype.rollUp = function(pts, char0, char1) {
  7928. var baseRow = this.displayed_[BOTTOM_ROW];
  7929. if (baseRow === '') {
  7930. // we're starting to buffer new display input, so flush out the
  7931. // current display
  7932. this.flushDisplayed(pts);
  7933. this.startPts_ = pts;
  7934. }
  7935. baseRow += getCharFromCode(char0);
  7936. baseRow += getCharFromCode(char1);
  7937. this.displayed_[BOTTOM_ROW] = baseRow;
  7938. };
  7939. Cea608Stream.prototype.shiftRowsUp_ = function() {
  7940. var i;
  7941. // clear out inactive rows
  7942. for (i = 0; i < this.topRow_; i++) {
  7943. this.displayed_[i] = '';
  7944. }
  7945. // shift displayed rows up
  7946. for (i = this.topRow_; i < BOTTOM_ROW; i++) {
  7947. this.displayed_[i] = this.displayed_[i + 1];
  7948. }
  7949. // clear out the bottom row
  7950. this.displayed_[BOTTOM_ROW] = '';
  7951. };
  7952. // exports
  7953. module.exports = {
  7954. CaptionStream: CaptionStream,
  7955. Cea608Stream: Cea608Stream,
  7956. };
  7957. },{"../utils/stream":55}],45:[function(require,module,exports){
  7958. module.exports = require('./m2ts');
  7959. },{"./m2ts":46}],46:[function(require,module,exports){
  7960. /**
  7961. * mux.js
  7962. *
  7963. * Copyright (c) 2015 Brightcove
  7964. * All rights reserved.
  7965. *
  7966. * A stream-based mp2t to mp4 converter. This utility can be used to
  7967. * deliver mp4s to a SourceBuffer on platforms that support native
  7968. * Media Source Extensions.
  7969. */
  7970. 'use strict';
  7971. var Stream = require('../utils/stream.js'),
  7972. CaptionStream = require('./caption-stream'),
  7973. StreamTypes = require('./stream-types');
  7974. var Stream = require('../utils/stream.js');
  7975. var m2tsStreamTypes = require('./stream-types.js');
  7976. // object types
  7977. var
  7978. TransportPacketStream, TransportParseStream, ElementaryStream,
  7979. AacStream, H264Stream, NalByteStream;
  7980. // constants
  7981. var
  7982. MP2T_PACKET_LENGTH = 188, // bytes
  7983. SYNC_BYTE = 0x47,
  7984. /**
  7985. * Splits an incoming stream of binary data into MPEG-2 Transport
  7986. * Stream packets.
  7987. */
  7988. TransportPacketStream = function() {
  7989. var
  7990. buffer = new Uint8Array(MP2T_PACKET_LENGTH),
  7991. bytesInBuffer = 0;
  7992. TransportPacketStream.prototype.init.call(this);
  7993. // Deliver new bytes to the stream.
  7994. this.push = function(bytes) {
  7995. var
  7996. i = 0,
  7997. startIndex = 0,
  7998. endIndex = MP2T_PACKET_LENGTH,
  7999. everything;
  8000. // If there are bytes remaining from the last segment, prepend them to the
  8001. // bytes that were pushed in
  8002. if (bytesInBuffer) {
  8003. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  8004. everything.set(buffer.subarray(0, bytesInBuffer));
  8005. everything.set(bytes, bytesInBuffer);
  8006. bytesInBuffer = 0;
  8007. } else {
  8008. everything = bytes;
  8009. }
  8010. // While we have enough data for a packet
  8011. while (endIndex < everything.byteLength) {
  8012. // Look for a pair of start and end sync bytes in the data..
  8013. if (everything[startIndex] === SYNC_BYTE && everything[endIndex] === SYNC_BYTE) {
  8014. // We found a packet so emit it and jump one whole packet forward in
  8015. // the stream
  8016. this.trigger('data', everything.subarray(startIndex, endIndex));
  8017. startIndex += MP2T_PACKET_LENGTH;
  8018. endIndex += MP2T_PACKET_LENGTH;
  8019. continue;
  8020. }
  8021. // If we get here, we have somehow become de-synchronized and we need to step
  8022. // forward one byte at a time until we find a pair of sync bytes that denote
  8023. // a packet
  8024. startIndex++;
  8025. endIndex++;
  8026. }
  8027. // If there was some data left over at the end of the segment that couldn't
  8028. // possibly be a whole packet, keep it because it might be the start of a packet
  8029. // that continues in the next segment
  8030. if (startIndex < everything.byteLength) {
  8031. buffer.set(everything.subarray(startIndex), 0);
  8032. bytesInBuffer = everything.byteLength - startIndex;
  8033. }
  8034. };
  8035. this.flush = function () {
  8036. // If the buffer contains a whole packet when we are being flushed, emit it
  8037. // and empty the buffer. Otherwise hold onto the data because it may be
  8038. // important for decoding the next segment
  8039. if (bytesInBuffer === MP2T_PACKET_LENGTH && buffer[0] === SYNC_BYTE) {
  8040. this.trigger('data', buffer);
  8041. bytesInBuffer = 0;
  8042. }
  8043. this.trigger('done');
  8044. };
  8045. };
  8046. TransportPacketStream.prototype = new Stream();
  8047. /**
  8048. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  8049. * forms of the individual transport stream packets.
  8050. */
  8051. TransportParseStream = function() {
  8052. var parsePsi, parsePat, parsePmt, parsePes, self;
  8053. TransportParseStream.prototype.init.call(this);
  8054. self = this;
  8055. this.packetsWaitingForPmt = [];
  8056. this.programMapTable = undefined;
  8057. parsePsi = function(payload, psi) {
  8058. var offset = 0;
  8059. // PSI packets may be split into multiple sections and those
  8060. // sections may be split into multiple packets. If a PSI
  8061. // section starts in this packet, the payload_unit_start_indicator
  8062. // will be true and the first byte of the payload will indicate
  8063. // the offset from the current position to the start of the
  8064. // section.
  8065. if (psi.payloadUnitStartIndicator) {
  8066. offset += payload[offset] + 1;
  8067. }
  8068. if (psi.type === 'pat') {
  8069. parsePat(payload.subarray(offset), psi);
  8070. } else {
  8071. parsePmt(payload.subarray(offset), psi);
  8072. }
  8073. };
  8074. parsePat = function(payload, pat) {
  8075. pat.section_number = payload[7];
  8076. pat.last_section_number = payload[8];
  8077. // skip the PSI header and parse the first PMT entry
  8078. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  8079. pat.pmtPid = self.pmtPid;
  8080. };
  8081. /**
  8082. * Parse out the relevant fields of a Program Map Table (PMT).
  8083. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  8084. * packet. The first byte in this array should be the table_id
  8085. * field.
  8086. * @param pmt {object} the object that should be decorated with
  8087. * fields parsed from the PMT.
  8088. */
  8089. parsePmt = function(payload, pmt) {
  8090. var sectionLength, tableEnd, programInfoLength, offset;
  8091. // PMTs can be sent ahead of the time when they should actually
  8092. // take effect. We don't believe this should ever be the case
  8093. // for HLS but we'll ignore "forward" PMT declarations if we see
  8094. // them. Future PMT declarations have the current_next_indicator
  8095. // set to zero.
  8096. if (!(payload[5] & 0x01)) {
  8097. return;
  8098. }
  8099. // overwrite any existing program map table
  8100. self.programMapTable = {};
  8101. // the mapping table ends at the end of the current section
  8102. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  8103. tableEnd = 3 + sectionLength - 4;
  8104. // to determine where the table is, we have to figure out how
  8105. // long the program info descriptors are
  8106. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11];
  8107. // advance the offset to the first entry in the mapping table
  8108. offset = 12 + programInfoLength;
  8109. while (offset < tableEnd) {
  8110. // add an entry that maps the elementary_pid to the stream_type
  8111. self.programMapTable[(payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]] = payload[offset];
  8112. // move to the next table entry
  8113. // skip past the elementary stream descriptors, if present
  8114. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  8115. }
  8116. // record the map on the packet as well
  8117. pmt.programMapTable = self.programMapTable;
  8118. // if there are any packets waiting for a PMT to be found, process them now
  8119. while (self.packetsWaitingForPmt.length) {
  8120. self.processPes_.apply(self, self.packetsWaitingForPmt.shift());
  8121. }
  8122. };
  8123. /**
  8124. * Deliver a new MP2T packet to the stream.
  8125. */
  8126. this.push = function(packet) {
  8127. var
  8128. result = {},
  8129. offset = 4;
  8130. result.payloadUnitStartIndicator = !!(packet[1] & 0x40);
  8131. // pid is a 13-bit field starting at the last bit of packet[1]
  8132. result.pid = packet[1] & 0x1f;
  8133. result.pid <<= 8;
  8134. result.pid |= packet[2];
  8135. // if an adaption field is present, its length is specified by the
  8136. // fifth byte of the TS packet header. The adaptation field is
  8137. // used to add stuffing to PES packets that don't fill a complete
  8138. // TS packet, and to specify some forms of timing and control data
  8139. // that we do not currently use.
  8140. if (((packet[3] & 0x30) >>> 4) > 0x01) {
  8141. offset += packet[offset] + 1;
  8142. }
  8143. // parse the rest of the packet based on the type
  8144. if (result.pid === 0) {
  8145. result.type = 'pat';
  8146. parsePsi(packet.subarray(offset), result);
  8147. this.trigger('data', result);
  8148. } else if (result.pid === this.pmtPid) {
  8149. result.type = 'pmt';
  8150. parsePsi(packet.subarray(offset), result);
  8151. this.trigger('data', result);
  8152. } else if (this.programMapTable === undefined) {
  8153. // When we have not seen a PMT yet, defer further processing of
  8154. // PES packets until one has been parsed
  8155. this.packetsWaitingForPmt.push([packet, offset, result]);
  8156. } else {
  8157. this.processPes_(packet, offset, result);
  8158. }
  8159. };
  8160. this.processPes_ = function (packet, offset, result) {
  8161. result.streamType = this.programMapTable[result.pid];
  8162. result.type = 'pes';
  8163. result.data = packet.subarray(offset);
  8164. this.trigger('data', result);
  8165. };
  8166. };
  8167. TransportParseStream.prototype = new Stream();
  8168. TransportParseStream.STREAM_TYPES = {
  8169. h264: 0x1b,
  8170. adts: 0x0f
  8171. };
  8172. /**
  8173. * Reconsistutes program elementary stream (PES) packets from parsed
  8174. * transport stream packets. That is, if you pipe an
  8175. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  8176. * events will be events which capture the bytes for individual PES
  8177. * packets plus relevant metadata that has been extracted from the
  8178. * container.
  8179. */
  8180. ElementaryStream = function() {
  8181. var
  8182. // PES packet fragments
  8183. video = {
  8184. data: [],
  8185. size: 0
  8186. },
  8187. audio = {
  8188. data: [],
  8189. size: 0
  8190. },
  8191. timedMetadata = {
  8192. data: [],
  8193. size: 0
  8194. },
  8195. parsePes = function(payload, pes) {
  8196. var ptsDtsFlags;
  8197. // find out if this packets starts a new keyframe
  8198. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0;
  8199. // PES packets may be annotated with a PTS value, or a PTS value
  8200. // and a DTS value. Determine what combination of values is
  8201. // available to work with.
  8202. ptsDtsFlags = payload[7];
  8203. // PTS and DTS are normally stored as a 33-bit number. Javascript
  8204. // performs all bitwise operations on 32-bit integers but javascript
  8205. // supports a much greater range (52-bits) of integer using standard
  8206. // mathematical operations.
  8207. // We construct a 31-bit value using bitwise operators over the 31
  8208. // most significant bits and then multiply by 4 (equal to a left-shift
  8209. // of 2) before we add the final 2 least significant bits of the
  8210. // timestamp (equal to an OR.)
  8211. if (ptsDtsFlags & 0xC0) {
  8212. // the PTS and DTS are not written out directly. For information
  8213. // on how they are encoded, see
  8214. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  8215. pes.pts = (payload[9] & 0x0E) << 27
  8216. | (payload[10] & 0xFF) << 20
  8217. | (payload[11] & 0xFE) << 12
  8218. | (payload[12] & 0xFF) << 5
  8219. | (payload[13] & 0xFE) >>> 3;
  8220. pes.pts *= 4; // Left shift by 2
  8221. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  8222. pes.dts = pes.pts;
  8223. if (ptsDtsFlags & 0x40) {
  8224. pes.dts = (payload[14] & 0x0E ) << 27
  8225. | (payload[15] & 0xFF ) << 20
  8226. | (payload[16] & 0xFE ) << 12
  8227. | (payload[17] & 0xFF ) << 5
  8228. | (payload[18] & 0xFE ) >>> 3;
  8229. pes.dts *= 4; // Left shift by 2
  8230. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  8231. }
  8232. }
  8233. // the data section starts immediately after the PES header.
  8234. // pes_header_data_length specifies the number of header bytes
  8235. // that follow the last byte of the field.
  8236. pes.data = payload.subarray(9 + payload[8]);
  8237. },
  8238. flushStream = function(stream, type) {
  8239. var
  8240. packetData = new Uint8Array(stream.size),
  8241. event = {
  8242. type: type
  8243. },
  8244. i = 0,
  8245. fragment;
  8246. // do nothing if there is no buffered data
  8247. if (!stream.data.length) {
  8248. return;
  8249. }
  8250. event.trackId = stream.data[0].pid;
  8251. // reassemble the packet
  8252. while (stream.data.length) {
  8253. fragment = stream.data.shift();
  8254. packetData.set(fragment.data, i);
  8255. i += fragment.data.byteLength;
  8256. }
  8257. // parse assembled packet's PES header
  8258. parsePes(packetData, event);
  8259. stream.size = 0;
  8260. self.trigger('data', event);
  8261. },
  8262. self;
  8263. ElementaryStream.prototype.init.call(this);
  8264. self = this;
  8265. this.push = function(data) {
  8266. ({
  8267. pat: function() {
  8268. // we have to wait for the PMT to arrive as well before we
  8269. // have any meaningful metadata
  8270. },
  8271. pes: function() {
  8272. var stream, streamType;
  8273. switch (data.streamType) {
  8274. case StreamTypes.H264_STREAM_TYPE:
  8275. case m2tsStreamTypes.H264_STREAM_TYPE:
  8276. stream = video;
  8277. streamType = 'video';
  8278. break;
  8279. case StreamTypes.ADTS_STREAM_TYPE:
  8280. stream = audio;
  8281. streamType = 'audio';
  8282. break;
  8283. case StreamTypes.METADATA_STREAM_TYPE:
  8284. stream = timedMetadata;
  8285. streamType = 'timed-metadata';
  8286. break;
  8287. default:
  8288. // ignore unknown stream types
  8289. return;
  8290. }
  8291. // if a new packet is starting, we can flush the completed
  8292. // packet
  8293. if (data.payloadUnitStartIndicator) {
  8294. flushStream(stream, streamType);
  8295. }
  8296. // buffer this fragment until we are sure we've received the
  8297. // complete payload
  8298. stream.data.push(data);
  8299. stream.size += data.data.byteLength;
  8300. },
  8301. pmt: function() {
  8302. var
  8303. event = {
  8304. type: 'metadata',
  8305. tracks: []
  8306. },
  8307. programMapTable = data.programMapTable,
  8308. k,
  8309. track;
  8310. // translate streams to tracks
  8311. for (k in programMapTable) {
  8312. if (programMapTable.hasOwnProperty(k)) {
  8313. track = {
  8314. timelineStartInfo: {
  8315. baseMediaDecodeTime: 0
  8316. }
  8317. };
  8318. track.id = +k;
  8319. if (programMapTable[k] === m2tsStreamTypes.H264_STREAM_TYPE) {
  8320. track.codec = 'avc';
  8321. track.type = 'video';
  8322. } else if (programMapTable[k] === m2tsStreamTypes.ADTS_STREAM_TYPE) {
  8323. track.codec = 'adts';
  8324. track.type = 'audio';
  8325. }
  8326. event.tracks.push(track);
  8327. }
  8328. }
  8329. self.trigger('data', event);
  8330. }
  8331. })[data.type]();
  8332. };
  8333. /**
  8334. * Flush any remaining input. Video PES packets may be of variable
  8335. * length. Normally, the start of a new video packet can trigger the
  8336. * finalization of the previous packet. That is not possible if no
  8337. * more video is forthcoming, however. In that case, some other
  8338. * mechanism (like the end of the file) has to be employed. When it is
  8339. * clear that no additional data is forthcoming, calling this method
  8340. * will flush the buffered packets.
  8341. */
  8342. this.flush = function() {
  8343. // !!THIS ORDER IS IMPORTANT!!
  8344. // video first then audio
  8345. flushStream(video, 'video');
  8346. flushStream(audio, 'audio');
  8347. flushStream(timedMetadata, 'timed-metadata');
  8348. this.trigger('done');
  8349. };
  8350. };
  8351. ElementaryStream.prototype = new Stream();
  8352. var m2ts = {
  8353. PAT_PID: 0x0000,
  8354. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH,
  8355. TransportPacketStream: TransportPacketStream,
  8356. TransportParseStream: TransportParseStream,
  8357. ElementaryStream: ElementaryStream,
  8358. CaptionStream: CaptionStream.CaptionStream,
  8359. Cea608Stream: CaptionStream.Cea608Stream,
  8360. MetadataStream: require('./metadata-stream'),
  8361. };
  8362. for (var type in StreamTypes) {
  8363. if (StreamTypes.hasOwnProperty(type)) {
  8364. m2ts[type] = StreamTypes[type];
  8365. }
  8366. }
  8367. module.exports = m2ts;
  8368. },{"../utils/stream.js":55,"./caption-stream":44,"./metadata-stream":47,"./stream-types":48,"./stream-types.js":48}],47:[function(require,module,exports){
  8369. /**
  8370. * Accepts program elementary stream (PES) data events and parses out
  8371. * ID3 metadata from them, if present.
  8372. * @see http://id3.org/id3v2.3.0
  8373. */
  8374. 'use strict';
  8375. var
  8376. Stream = require('../utils/stream'),
  8377. StreamTypes = require('./stream-types'),
  8378. // return a percent-encoded representation of the specified byte range
  8379. // @see http://en.wikipedia.org/wiki/Percent-encoding
  8380. percentEncode = function(bytes, start, end) {
  8381. var i, result = '';
  8382. for (i = start; i < end; i++) {
  8383. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  8384. }
  8385. return result;
  8386. },
  8387. // return the string representation of the specified byte range,
  8388. // interpreted as UTf-8.
  8389. parseUtf8 = function(bytes, start, end) {
  8390. return decodeURIComponent(percentEncode(bytes, start, end));
  8391. },
  8392. // return the string representation of the specified byte range,
  8393. // interpreted as ISO-8859-1.
  8394. parseIso88591 = function(bytes, start, end) {
  8395. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  8396. },
  8397. parseSyncSafeInteger = function (data) {
  8398. return (data[0] << 21) |
  8399. (data[1] << 14) |
  8400. (data[2] << 7) |
  8401. (data[3]);
  8402. },
  8403. tagParsers = {
  8404. 'TXXX': function(tag) {
  8405. var i;
  8406. if (tag.data[0] !== 3) {
  8407. // ignore frames with unrecognized character encodings
  8408. return;
  8409. }
  8410. for (i = 1; i < tag.data.length; i++) {
  8411. if (tag.data[i] === 0) {
  8412. // parse the text fields
  8413. tag.description = parseUtf8(tag.data, 1, i);
  8414. // do not include the null terminator in the tag value
  8415. tag.value = parseUtf8(tag.data, i + 1, tag.data.length - 1);
  8416. break;
  8417. }
  8418. }
  8419. tag.data = tag.value;
  8420. },
  8421. 'WXXX': function(tag) {
  8422. var i;
  8423. if (tag.data[0] !== 3) {
  8424. // ignore frames with unrecognized character encodings
  8425. return;
  8426. }
  8427. for (i = 1; i < tag.data.length; i++) {
  8428. if (tag.data[i] === 0) {
  8429. // parse the description and URL fields
  8430. tag.description = parseUtf8(tag.data, 1, i);
  8431. tag.url = parseUtf8(tag.data, i + 1, tag.data.length);
  8432. break;
  8433. }
  8434. }
  8435. },
  8436. 'PRIV': function(tag) {
  8437. var i;
  8438. for (i = 0; i < tag.data.length; i++) {
  8439. if (tag.data[i] === 0) {
  8440. // parse the description and URL fields
  8441. tag.owner = parseIso88591(tag.data, 0, i);
  8442. break;
  8443. }
  8444. }
  8445. tag.privateData = tag.data.subarray(i + 1);
  8446. tag.data = tag.privateData;
  8447. }
  8448. },
  8449. MetadataStream;
  8450. MetadataStream = function(options) {
  8451. var
  8452. settings = {
  8453. debug: !!(options && options.debug),
  8454. // the bytes of the program-level descriptor field in MP2T
  8455. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  8456. // program element descriptors"
  8457. descriptor: options && options.descriptor
  8458. },
  8459. // the total size in bytes of the ID3 tag being parsed
  8460. tagSize = 0,
  8461. // tag data that is not complete enough to be parsed
  8462. buffer = [],
  8463. // the total number of bytes currently in the buffer
  8464. bufferSize = 0,
  8465. i;
  8466. MetadataStream.prototype.init.call(this);
  8467. // calculate the text track in-band metadata track dispatch type
  8468. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  8469. this.dispatchType = StreamTypes.METADATA_STREAM_TYPE.toString(16);
  8470. if (settings.descriptor) {
  8471. for (i = 0; i < settings.descriptor.length; i++) {
  8472. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  8473. }
  8474. }
  8475. this.push = function(chunk) {
  8476. var tag, frameStart, frameSize, frame, i, frameHeader;
  8477. if (chunk.type !== 'timed-metadata') {
  8478. return;
  8479. }
  8480. // if data_alignment_indicator is set in the PES header,
  8481. // we must have the start of a new ID3 tag. Assume anything
  8482. // remaining in the buffer was malformed and throw it out
  8483. if (chunk.dataAlignmentIndicator) {
  8484. bufferSize = 0;
  8485. buffer.length = 0;
  8486. }
  8487. // ignore events that don't look like ID3 data
  8488. if (buffer.length === 0 &&
  8489. (chunk.data.length < 10 ||
  8490. chunk.data[0] !== 'I'.charCodeAt(0) ||
  8491. chunk.data[1] !== 'D'.charCodeAt(0) ||
  8492. chunk.data[2] !== '3'.charCodeAt(0))) {
  8493. if (settings.debug) {
  8494. console.log('Skipping unrecognized metadata packet');
  8495. }
  8496. return;
  8497. }
  8498. // add this chunk to the data we've collected so far
  8499. buffer.push(chunk);
  8500. bufferSize += chunk.data.byteLength;
  8501. // grab the size of the entire frame from the ID3 header
  8502. if (buffer.length === 1) {
  8503. // the frame size is transmitted as a 28-bit integer in the
  8504. // last four bytes of the ID3 header.
  8505. // The most significant bit of each byte is dropped and the
  8506. // results concatenated to recover the actual value.
  8507. tagSize = parseSyncSafeInteger(chunk.data.subarray(6, 10));
  8508. // ID3 reports the tag size excluding the header but it's more
  8509. // convenient for our comparisons to include it
  8510. tagSize += 10;
  8511. }
  8512. // if the entire frame has not arrived, wait for more data
  8513. if (bufferSize < tagSize) {
  8514. return;
  8515. }
  8516. // collect the entire frame so it can be parsed
  8517. tag = {
  8518. data: new Uint8Array(tagSize),
  8519. frames: [],
  8520. pts: buffer[0].pts,
  8521. dts: buffer[0].dts
  8522. };
  8523. for (i = 0; i < tagSize;) {
  8524. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  8525. i += buffer[0].data.byteLength;
  8526. bufferSize -= buffer[0].data.byteLength;
  8527. buffer.shift();
  8528. }
  8529. // find the start of the first frame and the end of the tag
  8530. frameStart = 10;
  8531. if (tag.data[5] & 0x40) {
  8532. // advance the frame start past the extended header
  8533. frameStart += 4; // header size field
  8534. frameStart += parseSyncSafeInteger(tag.data.subarray(10, 14));
  8535. // clip any padding off the end
  8536. tagSize -= parseSyncSafeInteger(tag.data.subarray(16, 20));
  8537. }
  8538. // parse one or more ID3 frames
  8539. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  8540. do {
  8541. // determine the number of bytes in this frame
  8542. frameSize = parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
  8543. if (frameSize < 1) {
  8544. return console.log('Malformed ID3 frame encountered. Skipping metadata parsing.');
  8545. }
  8546. frameHeader = String.fromCharCode(tag.data[frameStart],
  8547. tag.data[frameStart + 1],
  8548. tag.data[frameStart + 2],
  8549. tag.data[frameStart + 3]);
  8550. frame = {
  8551. id: frameHeader,
  8552. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  8553. };
  8554. frame.key = frame.id;
  8555. if (tagParsers[frame.id]) {
  8556. tagParsers[frame.id](frame);
  8557. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  8558. var
  8559. d = frame.data,
  8560. size = ((d[3] & 0x01) << 30) |
  8561. (d[4] << 22) |
  8562. (d[5] << 14) |
  8563. (d[6] << 6) |
  8564. (d[7] >>> 2);
  8565. size *= 4;
  8566. size += d[7] & 0x03;
  8567. frame.timeStamp = size;
  8568. this.trigger('timestamp', frame);
  8569. }
  8570. }
  8571. tag.frames.push(frame);
  8572. frameStart += 10; // advance past the frame header
  8573. frameStart += frameSize; // advance past the frame body
  8574. } while (frameStart < tagSize);
  8575. this.trigger('data', tag);
  8576. };
  8577. };
  8578. MetadataStream.prototype = new Stream();
  8579. module.exports = MetadataStream;
  8580. },{"../utils/stream":55,"./stream-types":48}],48:[function(require,module,exports){
  8581. 'use strict';
  8582. module.exports = {
  8583. H264_STREAM_TYPE: 0x1B,
  8584. ADTS_STREAM_TYPE: 0x0F,
  8585. METADATA_STREAM_TYPE: 0x15
  8586. };
  8587. },{}],49:[function(require,module,exports){
  8588. module.exports = {
  8589. generator: require('./mp4-generator'),
  8590. Transmuxer: require('./transmuxer').Transmuxer,
  8591. AudioSegmentStream: require('./transmuxer').AudioSegmentStream,
  8592. VideoSegmentStream: require('./transmuxer').VideoSegmentStream,
  8593. tools: require('../tools/mp4-inspector'),
  8594. };
  8595. },{"../tools/mp4-inspector":53,"./mp4-generator":50,"./transmuxer":51}],50:[function(require,module,exports){
  8596. /**
  8597. * mux.js
  8598. *
  8599. * Copyright (c) 2015 Brightcove
  8600. * All rights reserved.
  8601. *
  8602. * Functions that generate fragmented MP4s suitable for use with Media
  8603. * Source Extensions.
  8604. */
  8605. 'use strict';
  8606. var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd, trak,
  8607. tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, styp, traf, trex, trun,
  8608. types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR,
  8609. AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS;
  8610. // pre-calculate constants
  8611. (function() {
  8612. var i;
  8613. types = {
  8614. avc1: [], // codingname
  8615. avcC: [],
  8616. btrt: [],
  8617. dinf: [],
  8618. dref: [],
  8619. esds: [],
  8620. ftyp: [],
  8621. hdlr: [],
  8622. mdat: [],
  8623. mdhd: [],
  8624. mdia: [],
  8625. mfhd: [],
  8626. minf: [],
  8627. moof: [],
  8628. moov: [],
  8629. mp4a: [], // codingname
  8630. mvex: [],
  8631. mvhd: [],
  8632. sdtp: [],
  8633. smhd: [],
  8634. stbl: [],
  8635. stco: [],
  8636. stsc: [],
  8637. stsd: [],
  8638. stsz: [],
  8639. stts: [],
  8640. styp: [],
  8641. tfdt: [],
  8642. tfhd: [],
  8643. traf: [],
  8644. trak: [],
  8645. trun: [],
  8646. trex: [],
  8647. tkhd: [],
  8648. vmhd: []
  8649. };
  8650. // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  8651. // don't throw an error
  8652. if (typeof Uint8Array === 'undefined') {
  8653. return;
  8654. }
  8655. for (i in types) {
  8656. if (types.hasOwnProperty(i)) {
  8657. types[i] = [
  8658. i.charCodeAt(0),
  8659. i.charCodeAt(1),
  8660. i.charCodeAt(2),
  8661. i.charCodeAt(3)
  8662. ];
  8663. }
  8664. }
  8665. MAJOR_BRAND = new Uint8Array([
  8666. 'i'.charCodeAt(0),
  8667. 's'.charCodeAt(0),
  8668. 'o'.charCodeAt(0),
  8669. 'm'.charCodeAt(0)
  8670. ]);
  8671. AVC1_BRAND = new Uint8Array([
  8672. 'a'.charCodeAt(0),
  8673. 'v'.charCodeAt(0),
  8674. 'c'.charCodeAt(0),
  8675. '1'.charCodeAt(0)
  8676. ]);
  8677. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  8678. VIDEO_HDLR = new Uint8Array([
  8679. 0x00, // version 0
  8680. 0x00, 0x00, 0x00, // flags
  8681. 0x00, 0x00, 0x00, 0x00, // pre_defined
  8682. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  8683. 0x00, 0x00, 0x00, 0x00, // reserved
  8684. 0x00, 0x00, 0x00, 0x00, // reserved
  8685. 0x00, 0x00, 0x00, 0x00, // reserved
  8686. 0x56, 0x69, 0x64, 0x65,
  8687. 0x6f, 0x48, 0x61, 0x6e,
  8688. 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  8689. ]);
  8690. AUDIO_HDLR = new Uint8Array([
  8691. 0x00, // version 0
  8692. 0x00, 0x00, 0x00, // flags
  8693. 0x00, 0x00, 0x00, 0x00, // pre_defined
  8694. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  8695. 0x00, 0x00, 0x00, 0x00, // reserved
  8696. 0x00, 0x00, 0x00, 0x00, // reserved
  8697. 0x00, 0x00, 0x00, 0x00, // reserved
  8698. 0x53, 0x6f, 0x75, 0x6e,
  8699. 0x64, 0x48, 0x61, 0x6e,
  8700. 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  8701. ]);
  8702. HDLR_TYPES = {
  8703. "video":VIDEO_HDLR,
  8704. "audio": AUDIO_HDLR
  8705. };
  8706. DREF = new Uint8Array([
  8707. 0x00, // version 0
  8708. 0x00, 0x00, 0x00, // flags
  8709. 0x00, 0x00, 0x00, 0x01, // entry_count
  8710. 0x00, 0x00, 0x00, 0x0c, // entry_size
  8711. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  8712. 0x00, // version 0
  8713. 0x00, 0x00, 0x01 // entry_flags
  8714. ]);
  8715. SMHD = new Uint8Array([
  8716. 0x00, // version
  8717. 0x00, 0x00, 0x00, // flags
  8718. 0x00, 0x00, // balance, 0 means centered
  8719. 0x00, 0x00 // reserved
  8720. ]);
  8721. STCO = new Uint8Array([
  8722. 0x00, // version
  8723. 0x00, 0x00, 0x00, // flags
  8724. 0x00, 0x00, 0x00, 0x00 // entry_count
  8725. ]);
  8726. STSC = STCO;
  8727. STSZ = new Uint8Array([
  8728. 0x00, // version
  8729. 0x00, 0x00, 0x00, // flags
  8730. 0x00, 0x00, 0x00, 0x00, // sample_size
  8731. 0x00, 0x00, 0x00, 0x00, // sample_count
  8732. ]);
  8733. STTS = STCO;
  8734. VMHD = new Uint8Array([
  8735. 0x00, // version
  8736. 0x00, 0x00, 0x01, // flags
  8737. 0x00, 0x00, // graphicsmode
  8738. 0x00, 0x00,
  8739. 0x00, 0x00,
  8740. 0x00, 0x00 // opcolor
  8741. ]);
  8742. })();
  8743. box = function(type) {
  8744. var
  8745. payload = [],
  8746. size = 0,
  8747. i,
  8748. result,
  8749. view;
  8750. for (i = 1; i < arguments.length; i++) {
  8751. payload.push(arguments[i]);
  8752. }
  8753. i = payload.length;
  8754. // calculate the total size we need to allocate
  8755. while (i--) {
  8756. size += payload[i].byteLength;
  8757. }
  8758. result = new Uint8Array(size + 8);
  8759. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  8760. view.setUint32(0, result.byteLength);
  8761. result.set(type, 4);
  8762. // copy the payload into the result
  8763. for (i = 0, size = 8; i < payload.length; i++) {
  8764. result.set(payload[i], size);
  8765. size += payload[i].byteLength;
  8766. }
  8767. return result;
  8768. };
  8769. dinf = function() {
  8770. return box(types.dinf, box(types.dref, DREF));
  8771. };
  8772. esds = function(track) {
  8773. return box(types.esds, new Uint8Array([
  8774. 0x00, // version
  8775. 0x00, 0x00, 0x00, // flags
  8776. // ES_Descriptor
  8777. 0x03, // tag, ES_DescrTag
  8778. 0x19, // length
  8779. 0x00, 0x00, // ES_ID
  8780. 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
  8781. // DecoderConfigDescriptor
  8782. 0x04, // tag, DecoderConfigDescrTag
  8783. 0x11, // length
  8784. 0x40, // object type
  8785. 0x15, // streamType
  8786. 0x00, 0x06, 0x00, // bufferSizeDB
  8787. 0x00, 0x00, 0xda, 0xc0, // maxBitrate
  8788. 0x00, 0x00, 0xda, 0xc0, // avgBitrate
  8789. // DecoderSpecificInfo
  8790. 0x05, // tag, DecoderSpecificInfoTag
  8791. 0x02, // length
  8792. // ISO/IEC 14496-3, AudioSpecificConfig
  8793. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  8794. (track.audioobjecttype << 3) | (track.samplingfrequencyindex >>> 1),
  8795. (track.samplingfrequencyindex << 7) | (track.channelcount << 3),
  8796. 0x06, 0x01, 0x02 // GASpecificConfig
  8797. ]));
  8798. };
  8799. ftyp = function() {
  8800. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  8801. };
  8802. hdlr = function(type) {
  8803. return box(types.hdlr, HDLR_TYPES[type]);
  8804. };
  8805. mdat = function(data) {
  8806. return box(types.mdat, data);
  8807. };
  8808. mdhd = function(track) {
  8809. var result = new Uint8Array([
  8810. 0x00, // version 0
  8811. 0x00, 0x00, 0x00, // flags
  8812. 0x00, 0x00, 0x00, 0x02, // creation_time
  8813. 0x00, 0x00, 0x00, 0x03, // modification_time
  8814. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  8815. (track.duration >>> 24) & 0xFF,
  8816. (track.duration >>> 16) & 0xFF,
  8817. (track.duration >>> 8) & 0xFF,
  8818. track.duration & 0xFF, // duration
  8819. 0x55, 0xc4, // 'und' language (undetermined)
  8820. 0x00, 0x00
  8821. ]);
  8822. // Use the sample rate from the track metadata, when it is
  8823. // defined. The sample rate can be parsed out of an ADTS header, for
  8824. // instance.
  8825. if (track.samplerate) {
  8826. result[12] = (track.samplerate >>> 24) & 0xFF;
  8827. result[13] = (track.samplerate >>> 16) & 0xFF;
  8828. result[14] = (track.samplerate >>> 8) & 0xFF;
  8829. result[15] = (track.samplerate) & 0xFF;
  8830. }
  8831. return box(types.mdhd, result);
  8832. };
  8833. mdia = function(track) {
  8834. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  8835. };
  8836. mfhd = function(sequenceNumber) {
  8837. return box(types.mfhd, new Uint8Array([
  8838. 0x00,
  8839. 0x00, 0x00, 0x00, // flags
  8840. (sequenceNumber & 0xFF000000) >> 24,
  8841. (sequenceNumber & 0xFF0000) >> 16,
  8842. (sequenceNumber & 0xFF00) >> 8,
  8843. sequenceNumber & 0xFF, // sequence_number
  8844. ]));
  8845. };
  8846. minf = function(track) {
  8847. return box(types.minf,
  8848. track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD),
  8849. dinf(),
  8850. stbl(track));
  8851. };
  8852. moof = function(sequenceNumber, tracks) {
  8853. var
  8854. trackFragments = [],
  8855. i = tracks.length;
  8856. // build traf boxes for each track fragment
  8857. while (i--) {
  8858. trackFragments[i] = traf(tracks[i]);
  8859. }
  8860. return box.apply(null, [
  8861. types.moof,
  8862. mfhd(sequenceNumber)
  8863. ].concat(trackFragments));
  8864. };
  8865. /**
  8866. * Returns a movie box.
  8867. * @param tracks {array} the tracks associated with this movie
  8868. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  8869. */
  8870. moov = function(tracks) {
  8871. var
  8872. i = tracks.length,
  8873. boxes = [];
  8874. while (i--) {
  8875. boxes[i] = trak(tracks[i]);
  8876. }
  8877. return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
  8878. };
  8879. mvex = function(tracks) {
  8880. var
  8881. i = tracks.length,
  8882. boxes = [];
  8883. while (i--) {
  8884. boxes[i] = trex(tracks[i]);
  8885. }
  8886. return box.apply(null, [types.mvex].concat(boxes));
  8887. };
  8888. mvhd = function(duration) {
  8889. var
  8890. bytes = new Uint8Array([
  8891. 0x00, // version 0
  8892. 0x00, 0x00, 0x00, // flags
  8893. 0x00, 0x00, 0x00, 0x01, // creation_time
  8894. 0x00, 0x00, 0x00, 0x02, // modification_time
  8895. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  8896. (duration & 0xFF000000) >> 24,
  8897. (duration & 0xFF0000) >> 16,
  8898. (duration & 0xFF00) >> 8,
  8899. duration & 0xFF, // duration
  8900. 0x00, 0x01, 0x00, 0x00, // 1.0 rate
  8901. 0x01, 0x00, // 1.0 volume
  8902. 0x00, 0x00, // reserved
  8903. 0x00, 0x00, 0x00, 0x00, // reserved
  8904. 0x00, 0x00, 0x00, 0x00, // reserved
  8905. 0x00, 0x01, 0x00, 0x00,
  8906. 0x00, 0x00, 0x00, 0x00,
  8907. 0x00, 0x00, 0x00, 0x00,
  8908. 0x00, 0x00, 0x00, 0x00,
  8909. 0x00, 0x01, 0x00, 0x00,
  8910. 0x00, 0x00, 0x00, 0x00,
  8911. 0x00, 0x00, 0x00, 0x00,
  8912. 0x00, 0x00, 0x00, 0x00,
  8913. 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  8914. 0x00, 0x00, 0x00, 0x00,
  8915. 0x00, 0x00, 0x00, 0x00,
  8916. 0x00, 0x00, 0x00, 0x00,
  8917. 0x00, 0x00, 0x00, 0x00,
  8918. 0x00, 0x00, 0x00, 0x00,
  8919. 0x00, 0x00, 0x00, 0x00, // pre_defined
  8920. 0xff, 0xff, 0xff, 0xff // next_track_ID
  8921. ]);
  8922. return box(types.mvhd, bytes);
  8923. };
  8924. sdtp = function(track) {
  8925. var
  8926. samples = track.samples || [],
  8927. bytes = new Uint8Array(4 + samples.length),
  8928. flags,
  8929. i;
  8930. // leave the full box header (4 bytes) all zero
  8931. // write the sample table
  8932. for (i = 0; i < samples.length; i++) {
  8933. flags = samples[i].flags;
  8934. bytes[i + 4] = (flags.dependsOn << 4) |
  8935. (flags.isDependedOn << 2) |
  8936. (flags.hasRedundancy);
  8937. }
  8938. return box(types.sdtp,
  8939. bytes);
  8940. };
  8941. stbl = function(track) {
  8942. return box(types.stbl,
  8943. stsd(track),
  8944. box(types.stts, STTS),
  8945. box(types.stsc, STSC),
  8946. box(types.stsz, STSZ),
  8947. box(types.stco, STCO));
  8948. };
  8949. (function() {
  8950. var videoSample, audioSample;
  8951. stsd = function(track) {
  8952. return box(types.stsd, new Uint8Array([
  8953. 0x00, // version 0
  8954. 0x00, 0x00, 0x00, // flags
  8955. 0x00, 0x00, 0x00, 0x01
  8956. ]), track.type === 'video' ? videoSample(track) : audioSample(track));
  8957. };
  8958. videoSample = function(track) {
  8959. var
  8960. sps = track.sps || [],
  8961. pps = track.pps || [],
  8962. sequenceParameterSets = [],
  8963. pictureParameterSets = [],
  8964. i;
  8965. // assemble the SPSs
  8966. for (i = 0; i < sps.length; i++) {
  8967. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  8968. sequenceParameterSets.push((sps[i].byteLength & 0xFF)); // sequenceParameterSetLength
  8969. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  8970. }
  8971. // assemble the PPSs
  8972. for (i = 0; i < pps.length; i++) {
  8973. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  8974. pictureParameterSets.push((pps[i].byteLength & 0xFF));
  8975. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  8976. }
  8977. return box(types.avc1, new Uint8Array([
  8978. 0x00, 0x00, 0x00,
  8979. 0x00, 0x00, 0x00, // reserved
  8980. 0x00, 0x01, // data_reference_index
  8981. 0x00, 0x00, // pre_defined
  8982. 0x00, 0x00, // reserved
  8983. 0x00, 0x00, 0x00, 0x00,
  8984. 0x00, 0x00, 0x00, 0x00,
  8985. 0x00, 0x00, 0x00, 0x00, // pre_defined
  8986. (track.width & 0xff00) >> 8,
  8987. track.width & 0xff, // width
  8988. (track.height & 0xff00) >> 8,
  8989. track.height & 0xff, // height
  8990. 0x00, 0x48, 0x00, 0x00, // horizresolution
  8991. 0x00, 0x48, 0x00, 0x00, // vertresolution
  8992. 0x00, 0x00, 0x00, 0x00, // reserved
  8993. 0x00, 0x01, // frame_count
  8994. 0x13,
  8995. 0x76, 0x69, 0x64, 0x65,
  8996. 0x6f, 0x6a, 0x73, 0x2d,
  8997. 0x63, 0x6f, 0x6e, 0x74,
  8998. 0x72, 0x69, 0x62, 0x2d,
  8999. 0x68, 0x6c, 0x73, 0x00,
  9000. 0x00, 0x00, 0x00, 0x00,
  9001. 0x00, 0x00, 0x00, 0x00,
  9002. 0x00, 0x00, 0x00, // compressorname
  9003. 0x00, 0x18, // depth = 24
  9004. 0x11, 0x11 // pre_defined = -1
  9005. ]), box(types.avcC, new Uint8Array([
  9006. 0x01, // configurationVersion
  9007. track.profileIdc, // AVCProfileIndication
  9008. track.profileCompatibility, // profile_compatibility
  9009. track.levelIdc, // AVCLevelIndication
  9010. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  9011. ].concat([
  9012. sps.length // numOfSequenceParameterSets
  9013. ]).concat(sequenceParameterSets).concat([
  9014. pps.length // numOfPictureParameterSets
  9015. ]).concat(pictureParameterSets))), // "PPS"
  9016. box(types.btrt, new Uint8Array([
  9017. 0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  9018. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  9019. 0x00, 0x2d, 0xc6, 0xc0
  9020. ])) // avgBitrate
  9021. );
  9022. };
  9023. audioSample = function(track) {
  9024. return box(types.mp4a, new Uint8Array([
  9025. // SampleEntry, ISO/IEC 14496-12
  9026. 0x00, 0x00, 0x00,
  9027. 0x00, 0x00, 0x00, // reserved
  9028. 0x00, 0x01, // data_reference_index
  9029. // AudioSampleEntry, ISO/IEC 14496-12
  9030. 0x00, 0x00, 0x00, 0x00, // reserved
  9031. 0x00, 0x00, 0x00, 0x00, // reserved
  9032. (track.channelcount & 0xff00) >> 8,
  9033. (track.channelcount & 0xff), // channelcount
  9034. (track.samplesize & 0xff00) >> 8,
  9035. (track.samplesize & 0xff), // samplesize
  9036. 0x00, 0x00, // pre_defined
  9037. 0x00, 0x00, // reserved
  9038. (track.samplerate & 0xff00) >> 8,
  9039. (track.samplerate & 0xff),
  9040. 0x00, 0x00 // samplerate, 16.16
  9041. // MP4AudioSampleEntry, ISO/IEC 14496-14
  9042. ]), esds(track));
  9043. };
  9044. })();
  9045. styp = function() {
  9046. return box(types.styp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND);
  9047. };
  9048. tkhd = function(track) {
  9049. var result = new Uint8Array([
  9050. 0x00, // version 0
  9051. 0x00, 0x00, 0x07, // flags
  9052. 0x00, 0x00, 0x00, 0x00, // creation_time
  9053. 0x00, 0x00, 0x00, 0x00, // modification_time
  9054. (track.id & 0xFF000000) >> 24,
  9055. (track.id & 0xFF0000) >> 16,
  9056. (track.id & 0xFF00) >> 8,
  9057. track.id & 0xFF, // track_ID
  9058. 0x00, 0x00, 0x00, 0x00, // reserved
  9059. (track.duration & 0xFF000000) >> 24,
  9060. (track.duration & 0xFF0000) >> 16,
  9061. (track.duration & 0xFF00) >> 8,
  9062. track.duration & 0xFF, // duration
  9063. 0x00, 0x00, 0x00, 0x00,
  9064. 0x00, 0x00, 0x00, 0x00, // reserved
  9065. 0x00, 0x00, // layer
  9066. 0x00, 0x00, // alternate_group
  9067. 0x01, 0x00, // non-audio track volume
  9068. 0x00, 0x00, // reserved
  9069. 0x00, 0x01, 0x00, 0x00,
  9070. 0x00, 0x00, 0x00, 0x00,
  9071. 0x00, 0x00, 0x00, 0x00,
  9072. 0x00, 0x00, 0x00, 0x00,
  9073. 0x00, 0x01, 0x00, 0x00,
  9074. 0x00, 0x00, 0x00, 0x00,
  9075. 0x00, 0x00, 0x00, 0x00,
  9076. 0x00, 0x00, 0x00, 0x00,
  9077. 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  9078. (track.width & 0xFF00) >> 8,
  9079. track.width & 0xFF,
  9080. 0x00, 0x00, // width
  9081. (track.height & 0xFF00) >> 8,
  9082. track.height & 0xFF,
  9083. 0x00, 0x00 // height
  9084. ]);
  9085. return box(types.tkhd, result);
  9086. };
  9087. /**
  9088. * Generate a track fragment (traf) box. A traf box collects metadata
  9089. * about tracks in a movie fragment (moof) box.
  9090. */
  9091. traf = function(track) {
  9092. var trackFragmentHeader, trackFragmentDecodeTime,
  9093. trackFragmentRun, sampleDependencyTable, dataOffset;
  9094. trackFragmentHeader = box(types.tfhd, new Uint8Array([
  9095. 0x00, // version 0
  9096. 0x00, 0x00, 0x3a, // flags
  9097. (track.id & 0xFF000000) >> 24,
  9098. (track.id & 0xFF0000) >> 16,
  9099. (track.id & 0xFF00) >> 8,
  9100. (track.id & 0xFF), // track_ID
  9101. 0x00, 0x00, 0x00, 0x01, // sample_description_index
  9102. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  9103. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  9104. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  9105. ]));
  9106. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([
  9107. 0x00, // version 0
  9108. 0x00, 0x00, 0x00, // flags
  9109. // baseMediaDecodeTime
  9110. (track.baseMediaDecodeTime >>> 24) & 0xFF,
  9111. (track.baseMediaDecodeTime >>> 16) & 0xFF,
  9112. (track.baseMediaDecodeTime >>> 8) & 0xFF,
  9113. track.baseMediaDecodeTime & 0xFF
  9114. ]));
  9115. // the data offset specifies the number of bytes from the start of
  9116. // the containing moof to the first payload byte of the associated
  9117. // mdat
  9118. dataOffset = (32 + // tfhd
  9119. 16 + // tfdt
  9120. 8 + // traf header
  9121. 16 + // mfhd
  9122. 8 + // moof header
  9123. 8); // mdat header
  9124. // audio tracks require less metadata
  9125. if (track.type === 'audio') {
  9126. trackFragmentRun = trun(track, dataOffset);
  9127. return box(types.traf,
  9128. trackFragmentHeader,
  9129. trackFragmentDecodeTime,
  9130. trackFragmentRun);
  9131. }
  9132. // video tracks should contain an independent and disposable samples
  9133. // box (sdtp)
  9134. // generate one and adjust offsets to match
  9135. sampleDependencyTable = sdtp(track);
  9136. trackFragmentRun = trun(track,
  9137. sampleDependencyTable.length + dataOffset);
  9138. return box(types.traf,
  9139. trackFragmentHeader,
  9140. trackFragmentDecodeTime,
  9141. trackFragmentRun,
  9142. sampleDependencyTable);
  9143. };
  9144. /**
  9145. * Generate a track box.
  9146. * @param track {object} a track definition
  9147. * @return {Uint8Array} the track box
  9148. */
  9149. trak = function(track) {
  9150. track.duration = track.duration || 0xffffffff;
  9151. return box(types.trak,
  9152. tkhd(track),
  9153. mdia(track));
  9154. };
  9155. trex = function(track) {
  9156. var result = new Uint8Array([
  9157. 0x00, // version 0
  9158. 0x00, 0x00, 0x00, // flags
  9159. (track.id & 0xFF000000) >> 24,
  9160. (track.id & 0xFF0000) >> 16,
  9161. (track.id & 0xFF00) >> 8,
  9162. (track.id & 0xFF), // track_ID
  9163. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  9164. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  9165. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  9166. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  9167. ]);
  9168. // the last two bytes of default_sample_flags is the sample
  9169. // degradation priority, a hint about the importance of this sample
  9170. // relative to others. Lower the degradation priority for all sample
  9171. // types other than video.
  9172. if (track.type !== 'video') {
  9173. result[result.length - 1] = 0x00;
  9174. }
  9175. return box(types.trex, result);
  9176. };
  9177. (function() {
  9178. var audioTrun, videoTrun, trunHeader;
  9179. // This method assumes all samples are uniform. That is, if a
  9180. // duration is present for the first sample, it will be present for
  9181. // all subsequent samples.
  9182. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  9183. trunHeader = function(samples, offset) {
  9184. var durationPresent = 0, sizePresent = 0,
  9185. flagsPresent = 0, compositionTimeOffset = 0;
  9186. // trun flag constants
  9187. if (samples.length) {
  9188. if (samples[0].duration !== undefined) {
  9189. durationPresent = 0x1;
  9190. }
  9191. if (samples[0].size !== undefined) {
  9192. sizePresent = 0x2;
  9193. }
  9194. if (samples[0].flags !== undefined) {
  9195. flagsPresent = 0x4;
  9196. }
  9197. if (samples[0].compositionTimeOffset !== undefined) {
  9198. compositionTimeOffset = 0x8;
  9199. }
  9200. }
  9201. return [
  9202. 0x00, // version 0
  9203. 0x00,
  9204. durationPresent | sizePresent | flagsPresent | compositionTimeOffset,
  9205. 0x01, // flags
  9206. (samples.length & 0xFF000000) >>> 24,
  9207. (samples.length & 0xFF0000) >>> 16,
  9208. (samples.length & 0xFF00) >>> 8,
  9209. samples.length & 0xFF, // sample_count
  9210. (offset & 0xFF000000) >>> 24,
  9211. (offset & 0xFF0000) >>> 16,
  9212. (offset & 0xFF00) >>> 8,
  9213. offset & 0xFF // data_offset
  9214. ];
  9215. };
  9216. videoTrun = function(track, offset) {
  9217. var bytes, samples, sample, i;
  9218. samples = track.samples || [];
  9219. offset += 8 + 12 + (16 * samples.length);
  9220. bytes = trunHeader(samples, offset);
  9221. for (i = 0; i < samples.length; i++) {
  9222. sample = samples[i];
  9223. bytes = bytes.concat([
  9224. (sample.duration & 0xFF000000) >>> 24,
  9225. (sample.duration & 0xFF0000) >>> 16,
  9226. (sample.duration & 0xFF00) >>> 8,
  9227. sample.duration & 0xFF, // sample_duration
  9228. (sample.size & 0xFF000000) >>> 24,
  9229. (sample.size & 0xFF0000) >>> 16,
  9230. (sample.size & 0xFF00) >>> 8,
  9231. sample.size & 0xFF, // sample_size
  9232. (sample.flags.isLeading << 2) | sample.flags.dependsOn,
  9233. (sample.flags.isDependedOn << 6) |
  9234. (sample.flags.hasRedundancy << 4) |
  9235. (sample.flags.paddingValue << 1) |
  9236. sample.flags.isNonSyncSample,
  9237. sample.flags.degradationPriority & 0xF0 << 8,
  9238. sample.flags.degradationPriority & 0x0F, // sample_flags
  9239. (sample.compositionTimeOffset & 0xFF000000) >>> 24,
  9240. (sample.compositionTimeOffset & 0xFF0000) >>> 16,
  9241. (sample.compositionTimeOffset & 0xFF00) >>> 8,
  9242. sample.compositionTimeOffset & 0xFF // sample_composition_time_offset
  9243. ]);
  9244. }
  9245. return box(types.trun, new Uint8Array(bytes));
  9246. };
  9247. audioTrun = function(track, offset) {
  9248. var bytes, samples, sample, i;
  9249. samples = track.samples || [];
  9250. offset += 8 + 12 + (8 * samples.length);
  9251. bytes = trunHeader(samples, offset);
  9252. for (i = 0; i < samples.length; i++) {
  9253. sample = samples[i];
  9254. bytes = bytes.concat([
  9255. (sample.duration & 0xFF000000) >>> 24,
  9256. (sample.duration & 0xFF0000) >>> 16,
  9257. (sample.duration & 0xFF00) >>> 8,
  9258. sample.duration & 0xFF, // sample_duration
  9259. (sample.size & 0xFF000000) >>> 24,
  9260. (sample.size & 0xFF0000) >>> 16,
  9261. (sample.size & 0xFF00) >>> 8,
  9262. sample.size & 0xFF]); // sample_size
  9263. }
  9264. return box(types.trun, new Uint8Array(bytes));
  9265. };
  9266. trun = function(track, offset) {
  9267. if (track.type === 'audio') {
  9268. return audioTrun(track, offset);
  9269. } else {
  9270. return videoTrun(track, offset);
  9271. }
  9272. };
  9273. })();
  9274. module.exports = {
  9275. ftyp: ftyp,
  9276. mdat: mdat,
  9277. moof: moof,
  9278. moov: moov,
  9279. initSegment: function(tracks) {
  9280. var
  9281. fileType = ftyp(),
  9282. movie = moov(tracks),
  9283. result;
  9284. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  9285. result.set(fileType);
  9286. result.set(movie, fileType.byteLength);
  9287. return result;
  9288. }
  9289. };
  9290. },{}],51:[function(require,module,exports){
  9291. /**
  9292. * mux.js
  9293. *
  9294. * Copyright (c) 2015 Brightcove
  9295. * All rights reserved.
  9296. *
  9297. * A stream-based mp2t to mp4 converter. This utility can be used to
  9298. * deliver mp4s to a SourceBuffer on platforms that support native
  9299. * Media Source Extensions.
  9300. */
  9301. 'use strict';
  9302. var Stream = require('../utils/stream.js');
  9303. var mp4 = require('./mp4-generator.js');
  9304. var m2ts = require('../m2ts/m2ts.js');
  9305. var AdtsStream = require('../codecs/adts.js');
  9306. var H264Stream = require('../codecs/h264').H264Stream;
  9307. var AacStream = require('../aac');
  9308. // constants
  9309. var AUDIO_PROPERTIES = [
  9310. 'audioobjecttype',
  9311. 'channelcount',
  9312. 'samplerate',
  9313. 'samplingfrequencyindex',
  9314. 'samplesize'
  9315. ];
  9316. var VIDEO_PROPERTIES = [
  9317. 'width',
  9318. 'height',
  9319. 'profileIdc',
  9320. 'levelIdc',
  9321. 'profileCompatibility',
  9322. ];
  9323. // object types
  9324. var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;
  9325. // Helper functions
  9326. var
  9327. createDefaultSample,
  9328. isLikelyAacData,
  9329. collectDtsInfo,
  9330. clearDtsInfo,
  9331. calculateTrackBaseMediaDecodeTime,
  9332. arrayEquals,
  9333. sumFrameByteLengths;
  9334. /**
  9335. * Default sample object
  9336. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  9337. */
  9338. createDefaultSample = function () {
  9339. return {
  9340. size: 0,
  9341. flags: {
  9342. isLeading: 0,
  9343. dependsOn: 1,
  9344. isDependedOn: 0,
  9345. hasRedundancy: 0,
  9346. degradationPriority: 0
  9347. }
  9348. };
  9349. };
  9350. isLikelyAacData = function (data) {
  9351. if ((data[0] === 'I'.charCodeAt(0)) &&
  9352. (data[1] === 'D'.charCodeAt(0)) &&
  9353. (data[2] === '3'.charCodeAt(0))) {
  9354. return true;
  9355. }
  9356. return false;
  9357. };
  9358. /**
  9359. * Compare two arrays (even typed) for same-ness
  9360. */
  9361. arrayEquals = function(a, b) {
  9362. var
  9363. i;
  9364. if (a.length !== b.length) {
  9365. return false;
  9366. }
  9367. // compare the value of each element in the array
  9368. for (i = 0; i < a.length; i++) {
  9369. if (a[i] !== b[i]) {
  9370. return false;
  9371. }
  9372. }
  9373. return true;
  9374. };
  9375. /**
  9376. * Sum the `byteLength` properties of the data in each AAC frame
  9377. */
  9378. sumFrameByteLengths = function(array) {
  9379. var
  9380. i,
  9381. currentObj,
  9382. sum = 0;
  9383. // sum the byteLength's all each nal unit in the frame
  9384. for (i = 0; i < array.length; i++) {
  9385. currentObj = array[i];
  9386. sum += currentObj.data.byteLength;
  9387. }
  9388. return sum;
  9389. };
  9390. /**
  9391. * Constructs a single-track, ISO BMFF media segment from AAC data
  9392. * events. The output of this stream can be fed to a SourceBuffer
  9393. * configured with a suitable initialization segment.
  9394. */
  9395. AudioSegmentStream = function(track) {
  9396. var
  9397. adtsFrames = [],
  9398. sequenceNumber = 0,
  9399. earliestAllowedDts = 0;
  9400. AudioSegmentStream.prototype.init.call(this);
  9401. this.push = function(data) {
  9402. collectDtsInfo(track, data);
  9403. if (track) {
  9404. AUDIO_PROPERTIES.forEach(function(prop) {
  9405. track[prop] = data[prop];
  9406. });
  9407. }
  9408. // buffer audio data until end() is called
  9409. adtsFrames.push(data);
  9410. };
  9411. this.setEarliestDts = function(earliestDts) {
  9412. earliestAllowedDts = earliestDts - track.timelineStartInfo.baseMediaDecodeTime;
  9413. };
  9414. this.flush = function() {
  9415. var
  9416. frames,
  9417. moof,
  9418. mdat,
  9419. boxes;
  9420. // return early if no audio data has been observed
  9421. if (adtsFrames.length === 0) {
  9422. this.trigger('done', 'AudioSegmentStream');
  9423. return;
  9424. }
  9425. frames = this.trimAdtsFramesByEarliestDts_(adtsFrames);
  9426. // we have to build the index from byte locations to
  9427. // samples (that is, adts frames) in the audio data
  9428. track.samples = this.generateSampleTable_(frames);
  9429. // concatenate the audio data to constuct the mdat
  9430. mdat = mp4.mdat(this.concatenateFrameData_(frames));
  9431. adtsFrames = [];
  9432. calculateTrackBaseMediaDecodeTime(track);
  9433. moof = mp4.moof(sequenceNumber, [track]);
  9434. boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
  9435. // bump the sequence number for next time
  9436. sequenceNumber++;
  9437. boxes.set(moof);
  9438. boxes.set(mdat, moof.byteLength);
  9439. clearDtsInfo(track);
  9440. this.trigger('data', {track: track, boxes: boxes});
  9441. this.trigger('done', 'AudioSegmentStream');
  9442. };
  9443. // If the audio segment extends before the earliest allowed dts
  9444. // value, remove AAC frames until starts at or after the earliest
  9445. // allowed DTS so that we don't end up with a negative baseMedia-
  9446. // DecodeTime for the audio track
  9447. this.trimAdtsFramesByEarliestDts_ = function(adtsFrames) {
  9448. if (track.minSegmentDts >= earliestAllowedDts) {
  9449. return adtsFrames;
  9450. }
  9451. // We will need to recalculate the earliest segment Dts
  9452. track.minSegmentDts = Infinity;
  9453. return adtsFrames.filter(function(currentFrame) {
  9454. // If this is an allowed frame, keep it and record it's Dts
  9455. if (currentFrame.dts >= earliestAllowedDts) {
  9456. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  9457. track.minSegmentPts = track.minSegmentDts;
  9458. return true;
  9459. }
  9460. // Otherwise, discard it
  9461. return false;
  9462. });
  9463. };
  9464. // generate the track's raw mdat data from an array of frames
  9465. this.generateSampleTable_ = function(frames) {
  9466. var
  9467. i,
  9468. currentFrame,
  9469. samples = [];
  9470. for (i = 0; i < frames.length; i++) {
  9471. currentFrame = frames[i];
  9472. samples.push({
  9473. size: currentFrame.data.byteLength,
  9474. duration: 1024 // For AAC audio, all samples contain 1024 samples
  9475. });
  9476. }
  9477. return samples;
  9478. };
  9479. // generate the track's sample table from an array of frames
  9480. this.concatenateFrameData_ = function(frames) {
  9481. var
  9482. i,
  9483. currentFrame,
  9484. dataOffset = 0,
  9485. data = new Uint8Array(sumFrameByteLengths(frames));
  9486. for (i = 0; i < frames.length; i++) {
  9487. currentFrame = frames[i];
  9488. data.set(currentFrame.data, dataOffset);
  9489. dataOffset += currentFrame.data.byteLength;
  9490. }
  9491. return data;
  9492. };
  9493. };
  9494. AudioSegmentStream.prototype = new Stream();
  9495. /**
  9496. * Constructs a single-track, ISO BMFF media segment from H264 data
  9497. * events. The output of this stream can be fed to a SourceBuffer
  9498. * configured with a suitable initialization segment.
  9499. * @param track {object} track metadata configuration
  9500. */
  9501. VideoSegmentStream = function(track) {
  9502. var
  9503. sequenceNumber = 0,
  9504. nalUnits = [],
  9505. config,
  9506. pps;
  9507. VideoSegmentStream.prototype.init.call(this);
  9508. delete track.minPTS;
  9509. this.gopCache_ = [];
  9510. this.push = function(nalUnit) {
  9511. collectDtsInfo(track, nalUnit);
  9512. // record the track config
  9513. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  9514. config = nalUnit.config;
  9515. track.sps = [nalUnit.data];
  9516. VIDEO_PROPERTIES.forEach(function(prop) {
  9517. track[prop] = config[prop];
  9518. }, this);
  9519. }
  9520. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' &&
  9521. !pps) {
  9522. pps = nalUnit.data;
  9523. track.pps = [nalUnit.data];
  9524. }
  9525. // buffer video until flush() is called
  9526. nalUnits.push(nalUnit);
  9527. };
  9528. this.flush = function() {
  9529. var
  9530. frames,
  9531. gopForFusion,
  9532. gops,
  9533. moof,
  9534. mdat,
  9535. boxes;
  9536. // Throw away nalUnits at the start of the byte stream until
  9537. // we find the first AUD
  9538. while (nalUnits.length) {
  9539. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  9540. break;
  9541. }
  9542. nalUnits.shift();
  9543. }
  9544. // Return early if no video data has been observed
  9545. if (nalUnits.length === 0) {
  9546. this.resetStream_();
  9547. this.trigger('done', 'VideoSegmentStream');
  9548. return;
  9549. }
  9550. // Organize the raw nal-units into arrays that represent
  9551. // higher-level constructs such as frames and gops
  9552. // (group-of-pictures)
  9553. frames = this.groupNalsIntoFrames_(nalUnits);
  9554. gops = this.groupFramesIntoGops_(frames);
  9555. // If the first frame of this fragment is not a keyframe we have
  9556. // a problem since MSE (on Chrome) requires a leading keyframe.
  9557. //
  9558. // We have two approaches to repairing this situation:
  9559. // 1) GOP-FUSION:
  9560. // This is where we keep track of the GOPS (group-of-pictures)
  9561. // from previous fragments and attempt to find one that we can
  9562. // prepend to the current fragment in order to create a valid
  9563. // fragment.
  9564. // 2) KEYFRAME-PULLING:
  9565. // Here we search for the first keyframe in the fragment and
  9566. // throw away all the frames between the start of the fragment
  9567. // and that keyframe. We then extend the duration and pull the
  9568. // PTS of the keyframe forward so that it covers the time range
  9569. // of the frames that were disposed of.
  9570. //
  9571. // #1 is far prefereable over #2 which can cause "stuttering" but
  9572. // requires more things to be just right.
  9573. if (!gops[0][0].keyFrame) {
  9574. // Search for a gop for fusion from our gopCache
  9575. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  9576. if (gopForFusion) {
  9577. gops.unshift(gopForFusion);
  9578. // Adjust Gops' metadata to account for the inclusion of the
  9579. // new gop at the beginning
  9580. gops.byteLength += gopForFusion.byteLength;
  9581. gops.nalCount += gopForFusion.nalCount;
  9582. gops.pts = gopForFusion.pts;
  9583. gops.dts = gopForFusion.dts;
  9584. gops.duration += gopForFusion.duration;
  9585. } else {
  9586. // If we didn't find a candidate gop fall back to keyrame-pulling
  9587. gops = this.extendFirstKeyFrame_(gops);
  9588. }
  9589. }
  9590. collectDtsInfo(track, gops);
  9591. // First, we have to build the index from byte locations to
  9592. // samples (that is, frames) in the video data
  9593. track.samples = this.generateSampleTable_(gops);
  9594. // Concatenate the video data and construct the mdat
  9595. mdat = mp4.mdat(this.concatenateNalData_(gops));
  9596. // save all the nals in the last GOP into the gop cache
  9597. this.gopCache_.unshift({
  9598. gop: gops.pop(),
  9599. pps: track.pps,
  9600. sps: track.sps
  9601. });
  9602. // Keep a maximum of 6 GOPs in the cache
  9603. this.gopCache_.length = Math.min(6, this.gopCache_.length);
  9604. // Clear nalUnits
  9605. nalUnits = [];
  9606. calculateTrackBaseMediaDecodeTime(track);
  9607. this.trigger('timelineStartInfo', track.timelineStartInfo);
  9608. moof = mp4.moof(sequenceNumber, [track]);
  9609. // it would be great to allocate this array up front instead of
  9610. // throwing away hundreds of media segment fragments
  9611. boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
  9612. // Bump the sequence number for next time
  9613. sequenceNumber++;
  9614. boxes.set(moof);
  9615. boxes.set(mdat, moof.byteLength);
  9616. this.trigger('data', {track: track, boxes: boxes});
  9617. this.resetStream_();
  9618. // Continue with the flush process now
  9619. this.trigger('done', 'VideoSegmentStream');
  9620. };
  9621. this.resetStream_ = function() {
  9622. clearDtsInfo(track);
  9623. // reset config and pps because they may differ across segments
  9624. // for instance, when we are rendition switching
  9625. config = undefined;
  9626. pps = undefined;
  9627. };
  9628. // Search for a candidate Gop for gop-fusion from the gop cache and
  9629. // return it or return null if no good candidate was found
  9630. this.getGopForFusion_ = function (nalUnit) {
  9631. var
  9632. halfSecond = 45000, // Half-a-second in a 90khz clock
  9633. allowableOverlap = 10000, // About 3 frames @ 30fps
  9634. nearestDistance = Infinity,
  9635. dtsDistance,
  9636. nearestGopObj,
  9637. currentGop,
  9638. currentGopObj,
  9639. i;
  9640. // Search for the GOP nearest to the beginning of this nal unit
  9641. for (i = 0; i < this.gopCache_.length; i++) {
  9642. currentGopObj = this.gopCache_[i];
  9643. currentGop = currentGopObj.gop;
  9644. // Reject Gops with different SPS or PPS
  9645. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) ||
  9646. !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  9647. continue;
  9648. }
  9649. // Reject Gops that would require a negative baseMediaDecodeTime
  9650. if (currentGop.dts < track.timelineStartInfo.dts) {
  9651. continue;
  9652. }
  9653. // The distance between the end of the gop and the start of the nalUnit
  9654. dtsDistance = (nalUnit.dts - currentGop.dts) - currentGop.duration;
  9655. // Only consider GOPS that start before the nal unit and end within
  9656. // a half-second of the nal unit
  9657. if (dtsDistance >= -allowableOverlap &&
  9658. dtsDistance <= halfSecond) {
  9659. // Always use the closest GOP we found if there is more than
  9660. // one candidate
  9661. if (!nearestGopObj ||
  9662. nearestDistance > dtsDistance) {
  9663. nearestGopObj = currentGopObj;
  9664. nearestDistance = dtsDistance;
  9665. }
  9666. }
  9667. }
  9668. if (nearestGopObj) {
  9669. return nearestGopObj.gop;
  9670. }
  9671. return null;
  9672. };
  9673. this.extendFirstKeyFrame_ = function(gops) {
  9674. var
  9675. h, i,
  9676. currentGop,
  9677. newGops;
  9678. if (!gops[0][0].keyFrame) {
  9679. // Remove the first GOP
  9680. currentGop = gops.shift();
  9681. gops.byteLength -= currentGop.byteLength;
  9682. gops.nalCount -= currentGop.nalCount;
  9683. // Extend the first frame of what is now the
  9684. // first gop to cover the time period of the
  9685. // frames we just removed
  9686. gops[0][0].dts = currentGop.dts;
  9687. gops[0][0].pts = currentGop.pts;
  9688. gops[0][0].duration += currentGop.duration;
  9689. }
  9690. return gops;
  9691. };
  9692. // Convert an array of nal units into an array of frames with each frame being
  9693. // composed of the nal units that make up that frame
  9694. // Also keep track of cummulative data about the frame from the nal units such
  9695. // as the frame duration, starting pts, etc.
  9696. this.groupNalsIntoFrames_ = function(nalUnits) {
  9697. var
  9698. i,
  9699. currentNal,
  9700. startPts,
  9701. startDts,
  9702. currentFrame = [],
  9703. frames = [];
  9704. currentFrame.byteLength = 0;
  9705. for (i = 0; i < nalUnits.length; i++) {
  9706. currentNal = nalUnits[i];
  9707. // Split on 'aud'-type nal units
  9708. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  9709. // Since the very first nal unit is expected to be an AUD
  9710. // only push to the frames array when currentFrame is not empty
  9711. if (currentFrame.length) {
  9712. currentFrame.duration = currentNal.dts - currentFrame.dts;
  9713. frames.push(currentFrame);
  9714. }
  9715. currentFrame = [currentNal];
  9716. currentFrame.byteLength = currentNal.data.byteLength;
  9717. currentFrame.pts = currentNal.pts;
  9718. currentFrame.dts = currentNal.dts;
  9719. } else {
  9720. // Specifically flag key frames for ease of use later
  9721. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  9722. currentFrame.keyFrame = true;
  9723. }
  9724. currentFrame.duration = currentNal.dts - currentFrame.dts;
  9725. currentFrame.byteLength += currentNal.data.byteLength;
  9726. currentFrame.push(currentNal);
  9727. }
  9728. }
  9729. // For the last frame, use the duration of the previous frame if we
  9730. // have nothing better to go on
  9731. if (frames.length &&
  9732. (!currentFrame.duration ||
  9733. currentFrame.duration <= 0)) {
  9734. currentFrame.duration = frames[frames.length - 1].duration;
  9735. }
  9736. // Push the final frame
  9737. frames.push(currentFrame);
  9738. return frames;
  9739. };
  9740. // Convert an array of frames into an array of Gop with each Gop being composed
  9741. // of the frames that make up that Gop
  9742. // Also keep track of cummulative data about the Gop from the frames such as the
  9743. // Gop duration, starting pts, etc.
  9744. this.groupFramesIntoGops_ = function(frames) {
  9745. var
  9746. i,
  9747. currentFrame,
  9748. currentGop = [],
  9749. gops = [];
  9750. // We must pre-set some of the values on the Gop since we
  9751. // keep running totals of these values
  9752. currentGop.byteLength = 0;
  9753. currentGop.nalCount = 0;
  9754. currentGop.duration = 0;
  9755. currentGop.pts = frames[0].pts;
  9756. currentGop.dts = frames[0].dts;
  9757. // store some metadata about all the Gops
  9758. gops.byteLength = 0;
  9759. gops.nalCount = 0;
  9760. gops.duration = 0;
  9761. gops.pts = frames[0].pts;
  9762. gops.dts = frames[0].dts;
  9763. for (i = 0; i < frames.length; i++) {
  9764. currentFrame = frames[i];
  9765. if (currentFrame.keyFrame) {
  9766. // Since the very first frame is expected to be an keyframe
  9767. // only push to the gops array when currentGop is not empty
  9768. if (currentGop.length) {
  9769. gops.push(currentGop);
  9770. gops.byteLength += currentGop.byteLength;
  9771. gops.nalCount += currentGop.nalCount;
  9772. gops.duration += currentGop.duration;
  9773. }
  9774. currentGop = [currentFrame];
  9775. currentGop.nalCount = currentFrame.length;
  9776. currentGop.byteLength = currentFrame.byteLength;
  9777. currentGop.pts = currentFrame.pts;
  9778. currentGop.dts = currentFrame.dts;
  9779. currentGop.duration = currentFrame.duration;
  9780. } else {
  9781. currentGop.duration += currentFrame.duration;
  9782. currentGop.nalCount += currentFrame.length;
  9783. currentGop.byteLength += currentFrame.byteLength;
  9784. currentGop.push(currentFrame);
  9785. }
  9786. }
  9787. if (gops.length && currentGop.duration <= 0) {
  9788. currentGop.duration = gops[gops.length - 1].duration;
  9789. }
  9790. gops.byteLength += currentGop.byteLength;
  9791. gops.nalCount += currentGop.nalCount;
  9792. gops.duration += currentGop.duration;
  9793. // push the final Gop
  9794. gops.push(currentGop);
  9795. return gops;
  9796. };
  9797. // generate the track's sample table from an array of gops
  9798. this.generateSampleTable_ = function(gops, baseDataOffset) {
  9799. var
  9800. h, i,
  9801. sample,
  9802. currentGop,
  9803. currentFrame,
  9804. currentSample,
  9805. dataOffset = baseDataOffset || 0,
  9806. samples = [];
  9807. for (h = 0; h < gops.length; h++) {
  9808. currentGop = gops[h];
  9809. for (i = 0; i < currentGop.length; i++) {
  9810. currentFrame = currentGop[i];
  9811. sample = createDefaultSample();
  9812. sample.dataOffset = dataOffset;
  9813. sample.compositionTimeOffset = currentFrame.pts - currentFrame.dts;
  9814. sample.duration = currentFrame.duration;
  9815. sample.size = 4 * currentFrame.length; // Space for nal unit size
  9816. sample.size += currentFrame.byteLength;
  9817. if (currentFrame.keyFrame) {
  9818. sample.flags.dependsOn = 2;
  9819. }
  9820. dataOffset += sample.size;
  9821. samples.push(sample);
  9822. }
  9823. }
  9824. return samples;
  9825. };
  9826. // generate the track's raw mdat data from an array of gops
  9827. this.concatenateNalData_ = function (gops) {
  9828. var
  9829. h, i, j,
  9830. currentGop,
  9831. currentFrame,
  9832. currentNal,
  9833. dataOffset = 0,
  9834. nalsByteLength = gops.byteLength,
  9835. numberOfNals = gops.nalCount,
  9836. totalByteLength = nalsByteLength + 4 * numberOfNals,
  9837. data = new Uint8Array(totalByteLength),
  9838. view = new DataView(data.buffer);
  9839. // For each Gop..
  9840. for (h = 0; h < gops.length; h++) {
  9841. currentGop = gops[h];
  9842. // For each Frame..
  9843. for (i = 0; i < currentGop.length; i++) {
  9844. currentFrame = currentGop[i];
  9845. // For each NAL..
  9846. for (j = 0; j < currentFrame.length; j++) {
  9847. currentNal = currentFrame[j];
  9848. view.setUint32(dataOffset, currentNal.data.byteLength);
  9849. dataOffset += 4;
  9850. data.set(currentNal.data, dataOffset);
  9851. dataOffset += currentNal.data.byteLength;
  9852. }
  9853. }
  9854. }
  9855. return data;
  9856. };
  9857. };
  9858. VideoSegmentStream.prototype = new Stream();
  9859. /**
  9860. * Store information about the start and end of the track and the
  9861. * duration for each frame/sample we process in order to calculate
  9862. * the baseMediaDecodeTime
  9863. */
  9864. collectDtsInfo = function (track, data) {
  9865. if (typeof data.pts === 'number') {
  9866. if (track.timelineStartInfo.pts === undefined) {
  9867. track.timelineStartInfo.pts = data.pts;
  9868. }
  9869. if (track.minSegmentPts === undefined) {
  9870. track.minSegmentPts = data.pts;
  9871. } else {
  9872. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  9873. }
  9874. if (track.maxSegmentPts === undefined) {
  9875. track.maxSegmentPts = data.pts;
  9876. } else {
  9877. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  9878. }
  9879. }
  9880. if (typeof data.dts === 'number') {
  9881. if (track.timelineStartInfo.dts === undefined) {
  9882. track.timelineStartInfo.dts = data.dts;
  9883. }
  9884. if (track.minSegmentDts === undefined) {
  9885. track.minSegmentDts = data.dts;
  9886. } else {
  9887. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  9888. }
  9889. if (track.maxSegmentDts === undefined) {
  9890. track.maxSegmentDts = data.dts;
  9891. } else {
  9892. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  9893. }
  9894. }
  9895. };
  9896. /**
  9897. * Clear values used to calculate the baseMediaDecodeTime between
  9898. * tracks
  9899. */
  9900. clearDtsInfo = function (track) {
  9901. delete track.minSegmentDts;
  9902. delete track.maxSegmentDts;
  9903. delete track.minSegmentPts;
  9904. delete track.maxSegmentPts;
  9905. };
  9906. /**
  9907. * Calculate the track's baseMediaDecodeTime based on the earliest
  9908. * DTS the transmuxer has ever seen and the minimum DTS for the
  9909. * current track
  9910. */
  9911. calculateTrackBaseMediaDecodeTime = function (track) {
  9912. var
  9913. oneSecondInPTS = 90000, // 90kHz clock
  9914. scale,
  9915. // Calculate the distance, in time, that this segment starts from the start
  9916. // of the timeline (earliest time seen since the transmuxer initialized)
  9917. timeSinceStartOfTimeline = track.minSegmentDts - track.timelineStartInfo.dts,
  9918. // Calculate the first sample's effective compositionTimeOffset
  9919. firstSampleCompositionOffset = track.minSegmentPts - track.minSegmentDts;
  9920. // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  9921. // we want the start of the first segment to be placed
  9922. track.baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime;
  9923. // Add to that the distance this segment is from the very first
  9924. track.baseMediaDecodeTime += timeSinceStartOfTimeline;
  9925. // Subtract this segment's "compositionTimeOffset" so that the first frame of
  9926. // this segment is displayed exactly at the `baseMediaDecodeTime` or at the
  9927. // end of the previous segment
  9928. track.baseMediaDecodeTime -= firstSampleCompositionOffset;
  9929. // baseMediaDecodeTime must not become negative
  9930. track.baseMediaDecodeTime = Math.max(0, track.baseMediaDecodeTime);
  9931. if (track.type === 'audio') {
  9932. // Audio has a different clock equal to the sampling_rate so we need to
  9933. // scale the PTS values into the clock rate of the track
  9934. scale = track.samplerate / oneSecondInPTS;
  9935. track.baseMediaDecodeTime *= scale;
  9936. track.baseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime);
  9937. }
  9938. };
  9939. /**
  9940. * A Stream that can combine multiple streams (ie. audio & video)
  9941. * into a single output segment for MSE. Also supports audio-only
  9942. * and video-only streams.
  9943. */
  9944. CoalesceStream = function(options, metadataStream) {
  9945. // Number of Tracks per output segment
  9946. // If greater than 1, we combine multiple
  9947. // tracks into a single segment
  9948. this.numberOfTracks = 0;
  9949. this.metadataStream = metadataStream;
  9950. if (typeof options.remux !== 'undefined') {
  9951. this.remuxTracks = !!options.remux;
  9952. } else {
  9953. this.remuxTracks = true;
  9954. }
  9955. this.pendingTracks = [];
  9956. this.videoTrack = null;
  9957. this.pendingBoxes = [];
  9958. this.pendingCaptions = [];
  9959. this.pendingMetadata = [];
  9960. this.pendingBytes = 0;
  9961. this.emittedTracks = 0;
  9962. CoalesceStream.prototype.init.call(this);
  9963. // Take output from multiple
  9964. this.push = function(output) {
  9965. // buffer incoming captions until the associated video segment
  9966. // finishes
  9967. if (output.text) {
  9968. return this.pendingCaptions.push(output);
  9969. }
  9970. // buffer incoming id3 tags until the final flush
  9971. if (output.frames) {
  9972. return this.pendingMetadata.push(output);
  9973. }
  9974. // Add this track to the list of pending tracks and store
  9975. // important information required for the construction of
  9976. // the final segment
  9977. this.pendingTracks.push(output.track);
  9978. this.pendingBoxes.push(output.boxes);
  9979. this.pendingBytes += output.boxes.byteLength;
  9980. if (output.track.type === 'video') {
  9981. this.videoTrack = output.track;
  9982. }
  9983. if (output.track.type === 'audio') {
  9984. this.audioTrack = output.track;
  9985. }
  9986. };
  9987. };
  9988. CoalesceStream.prototype = new Stream();
  9989. CoalesceStream.prototype.flush = function(flushSource) {
  9990. var
  9991. offset = 0,
  9992. event = {
  9993. captions: [],
  9994. metadata: [],
  9995. info: {}
  9996. },
  9997. caption,
  9998. id3,
  9999. initSegment,
  10000. timelineStartPts = 0,
  10001. i;
  10002. if (this.pendingTracks.length < this.numberOfTracks) {
  10003. if (flushSource !== 'VideoSegmentStream' &&
  10004. flushSource !== 'AudioSegmentStream') {
  10005. // Return because we haven't received a flush from a data-generating
  10006. // portion of the segment (meaning that we have only recieved meta-data
  10007. // or captions.)
  10008. return;
  10009. } else if (this.remuxTracks) {
  10010. // Return until we have enough tracks from the pipeline to remux (if we
  10011. // are remuxing audio and video into a single MP4)
  10012. return;
  10013. } else if (this.pendingTracks.length === 0) {
  10014. // In the case where we receive a flush without any data having been
  10015. // received we consider it an emitted track for the purposes of coalescing
  10016. // `done` events.
  10017. // We do this for the case where there is an audio and video track in the
  10018. // segment but no audio data. (seen in several playlists with alternate
  10019. // audio tracks and no audio present in the main TS segments.)
  10020. this.emittedTracks++;
  10021. if (this.emittedTracks >= this.numberOfTracks) {
  10022. this.trigger('done');
  10023. this.emittedTracks = 0;
  10024. }
  10025. return;
  10026. }
  10027. }
  10028. if (this.videoTrack) {
  10029. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  10030. VIDEO_PROPERTIES.forEach(function(prop) {
  10031. event.info[prop] = this.videoTrack[prop];
  10032. }, this);
  10033. } else if (this.audioTrack) {
  10034. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  10035. AUDIO_PROPERTIES.forEach(function(prop) {
  10036. event.info[prop] = this.audioTrack[prop];
  10037. }, this);
  10038. }
  10039. if (this.pendingTracks.length === 1) {
  10040. event.type = this.pendingTracks[0].type;
  10041. } else {
  10042. event.type = 'combined';
  10043. }
  10044. this.emittedTracks += this.pendingTracks.length;
  10045. initSegment = mp4.initSegment(this.pendingTracks);
  10046. // Create a new typed array large enough to hold the init
  10047. // segment and all tracks
  10048. event.data = new Uint8Array(initSegment.byteLength +
  10049. this.pendingBytes);
  10050. // Create an init segment containing a moov
  10051. // and track definitions
  10052. event.data.set(initSegment);
  10053. offset += initSegment.byteLength;
  10054. // Append each moof+mdat (one per track) after the init segment
  10055. for (i = 0; i < this.pendingBoxes.length; i++) {
  10056. event.data.set(this.pendingBoxes[i], offset);
  10057. offset += this.pendingBoxes[i].byteLength;
  10058. }
  10059. // Translate caption PTS times into second offsets into the
  10060. // video timeline for the segment
  10061. for (i = 0; i < this.pendingCaptions.length; i++) {
  10062. caption = this.pendingCaptions[i];
  10063. caption.startTime = (caption.startPts - timelineStartPts);
  10064. caption.startTime /= 90e3;
  10065. caption.endTime = (caption.endPts - timelineStartPts);
  10066. caption.endTime /= 90e3;
  10067. event.captions.push(caption);
  10068. }
  10069. // Translate ID3 frame PTS times into second offsets into the
  10070. // video timeline for the segment
  10071. for (i = 0; i < this.pendingMetadata.length; i++) {
  10072. id3 = this.pendingMetadata[i];
  10073. id3.cueTime = (id3.pts - timelineStartPts);
  10074. id3.cueTime /= 90e3;
  10075. event.metadata.push(id3);
  10076. }
  10077. // We add this to every single emitted segment even though we only need
  10078. // it for the first
  10079. event.metadata.dispatchType = this.metadataStream.dispatchType;
  10080. // Reset stream state
  10081. this.pendingTracks.length = 0;
  10082. this.videoTrack = null;
  10083. this.pendingBoxes.length = 0;
  10084. this.pendingCaptions.length = 0;
  10085. this.pendingBytes = 0;
  10086. this.pendingMetadata.length = 0;
  10087. // Emit the built segment
  10088. this.trigger('data', event);
  10089. // Only emit `done` if all tracks have been flushed and emitted
  10090. if (this.emittedTracks >= this.numberOfTracks) {
  10091. this.trigger('done');
  10092. this.emittedTracks = 0;
  10093. }
  10094. };
  10095. /**
  10096. * A Stream that expects MP2T binary data as input and produces
  10097. * corresponding media segments, suitable for use with Media Source
  10098. * Extension (MSE) implementations that support the ISO BMFF byte
  10099. * stream format, like Chrome.
  10100. */
  10101. Transmuxer = function(options) {
  10102. var
  10103. self = this,
  10104. hasFlushed = true,
  10105. videoTrack,
  10106. audioTrack;
  10107. Transmuxer.prototype.init.call(this);
  10108. options = options || {};
  10109. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  10110. this.transmuxPipeline_ = {};
  10111. this.setupAacPipeline = function() {
  10112. var pipeline = {};
  10113. this.transmuxPipeline_ = pipeline;
  10114. pipeline.type = 'aac';
  10115. pipeline.metadataStream = new m2ts.MetadataStream();
  10116. // set up the parsing pipeline
  10117. pipeline.aacStream = new AacStream();
  10118. pipeline.adtsStream = new AdtsStream();
  10119. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  10120. pipeline.headOfPipeline = pipeline.aacStream;
  10121. pipeline.aacStream.pipe(pipeline.adtsStream);
  10122. pipeline.aacStream.pipe(pipeline.metadataStream);
  10123. pipeline.metadataStream.pipe(pipeline.coalesceStream);
  10124. pipeline.metadataStream.on('timestamp', function(frame) {
  10125. pipeline.aacStream.setTimestamp(frame.timeStamp);
  10126. });
  10127. pipeline.aacStream.on('data', function(data) {
  10128. var i;
  10129. if (data.type === 'timed-metadata' && !pipeline.audioSegmentStream) {
  10130. audioTrack = audioTrack || {
  10131. timelineStartInfo: {
  10132. baseMediaDecodeTime: self.baseMediaDecodeTime
  10133. },
  10134. codec: 'adts',
  10135. type: 'audio'
  10136. };
  10137. // hook up the audio segment stream to the first track with aac data
  10138. pipeline.coalesceStream.numberOfTracks++;
  10139. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack);
  10140. // Set up the final part of the audio pipeline
  10141. pipeline.adtsStream
  10142. .pipe(pipeline.audioSegmentStream)
  10143. .pipe(pipeline.coalesceStream);
  10144. }
  10145. });
  10146. // Re-emit any data coming from the coalesce stream to the outside world
  10147. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  10148. // Let the consumer know we have finished flushing the entire pipeline
  10149. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  10150. };
  10151. this.setupTsPipeline = function() {
  10152. var pipeline = {};
  10153. this.transmuxPipeline_ = pipeline;
  10154. pipeline.type = 'ts';
  10155. pipeline.metadataStream = new m2ts.MetadataStream();
  10156. // set up the parsing pipeline
  10157. pipeline.packetStream = new m2ts.TransportPacketStream();
  10158. pipeline.parseStream = new m2ts.TransportParseStream();
  10159. pipeline.elementaryStream = new m2ts.ElementaryStream();
  10160. pipeline.adtsStream = new AdtsStream();
  10161. pipeline.h264Stream = new H264Stream();
  10162. pipeline.captionStream = new m2ts.CaptionStream();
  10163. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  10164. pipeline.headOfPipeline = pipeline.packetStream;
  10165. // disassemble MPEG2-TS packets into elementary streams
  10166. pipeline.packetStream
  10167. .pipe(pipeline.parseStream)
  10168. .pipe(pipeline.elementaryStream);
  10169. // !!THIS ORDER IS IMPORTANT!!
  10170. // demux the streams
  10171. pipeline.elementaryStream
  10172. .pipe(pipeline.h264Stream);
  10173. pipeline.elementaryStream
  10174. .pipe(pipeline.adtsStream);
  10175. pipeline.elementaryStream
  10176. .pipe(pipeline.metadataStream)
  10177. .pipe(pipeline.coalesceStream);
  10178. // Hook up CEA-608/708 caption stream
  10179. pipeline.h264Stream.pipe(pipeline.captionStream)
  10180. .pipe(pipeline.coalesceStream);
  10181. pipeline.elementaryStream.on('data', function(data) {
  10182. var i;
  10183. if (data.type === 'metadata') {
  10184. i = data.tracks.length;
  10185. // scan the tracks listed in the metadata
  10186. while (i--) {
  10187. if (!videoTrack && data.tracks[i].type === 'video') {
  10188. videoTrack = data.tracks[i];
  10189. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  10190. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  10191. audioTrack = data.tracks[i];
  10192. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  10193. }
  10194. }
  10195. // hook up the video segment stream to the first track with h264 data
  10196. if (videoTrack && !pipeline.videoSegmentStream) {
  10197. pipeline.coalesceStream.numberOfTracks++;
  10198. pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack);
  10199. pipeline.videoSegmentStream.on('timelineStartInfo', function(timelineStartInfo){
  10200. // When video emits timelineStartInfo data after a flush, we forward that
  10201. // info to the AudioSegmentStream, if it exists, because video timeline
  10202. // data takes precedence.
  10203. if (audioTrack) {
  10204. audioTrack.timelineStartInfo = timelineStartInfo;
  10205. // On the first segment we trim AAC frames that exist before the
  10206. // very earliest DTS we have seen in video because Chrome will
  10207. // interpret any video track with a baseMediaDecodeTime that is
  10208. // non-zero as a gap.
  10209. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts);
  10210. }
  10211. });
  10212. // Set up the final part of the video pipeline
  10213. pipeline.h264Stream
  10214. .pipe(pipeline.videoSegmentStream)
  10215. .pipe(pipeline.coalesceStream);
  10216. }
  10217. if (audioTrack && !pipeline.audioSegmentStream) {
  10218. // hook up the audio segment stream to the first track with aac data
  10219. pipeline.coalesceStream.numberOfTracks++;
  10220. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack);
  10221. // Set up the final part of the audio pipeline
  10222. pipeline.adtsStream
  10223. .pipe(pipeline.audioSegmentStream)
  10224. .pipe(pipeline.coalesceStream);
  10225. }
  10226. }
  10227. });
  10228. // Re-emit any data coming from the coalesce stream to the outside world
  10229. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  10230. // Let the consumer know we have finished flushing the entire pipeline
  10231. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  10232. };
  10233. // hook up the segment streams once track metadata is delivered
  10234. this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  10235. var pipeline = this.transmuxPipeline_;
  10236. this.baseMediaDecodeTime = baseMediaDecodeTime;
  10237. if (audioTrack) {
  10238. audioTrack.timelineStartInfo.dts = undefined;
  10239. audioTrack.timelineStartInfo.pts = undefined;
  10240. clearDtsInfo(audioTrack);
  10241. audioTrack.timelineStartInfo.baseMediaDecodeTime = baseMediaDecodeTime;
  10242. }
  10243. if (videoTrack) {
  10244. if (pipeline.videoSegmentStream) {
  10245. pipeline.videoSegmentStream.gopCache_ = [];
  10246. }
  10247. videoTrack.timelineStartInfo.dts = undefined;
  10248. videoTrack.timelineStartInfo.pts = undefined;
  10249. clearDtsInfo(videoTrack);
  10250. videoTrack.timelineStartInfo.baseMediaDecodeTime = baseMediaDecodeTime;
  10251. }
  10252. };
  10253. // feed incoming data to the front of the parsing pipeline
  10254. this.push = function(data) {
  10255. if (hasFlushed) {
  10256. var isAac = isLikelyAacData(data);
  10257. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  10258. this.setupAacPipeline();
  10259. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  10260. this.setupTsPipeline();
  10261. }
  10262. hasFlushed = false;
  10263. }
  10264. this.transmuxPipeline_.headOfPipeline.push(data);
  10265. };
  10266. // flush any buffered data
  10267. this.flush = function() {
  10268. hasFlushed = true;
  10269. // Start at the top of the pipeline and flush all pending work
  10270. this.transmuxPipeline_.headOfPipeline.flush();
  10271. };
  10272. };
  10273. Transmuxer.prototype = new Stream();
  10274. module.exports = {
  10275. Transmuxer: Transmuxer,
  10276. VideoSegmentStream: VideoSegmentStream,
  10277. AudioSegmentStream: AudioSegmentStream,
  10278. AUDIO_PROPERTIES: AUDIO_PROPERTIES,
  10279. VIDEO_PROPERTIES: VIDEO_PROPERTIES
  10280. };
  10281. },{"../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){
  10282. 'use strict';
  10283. var
  10284. tagTypes = {
  10285. 0x08: 'audio',
  10286. 0x09: 'video',
  10287. 0x12: 'metadata'
  10288. },
  10289. hex = function (val) {
  10290. return '0x' + ('00' + val.toString(16)).slice(-2).toUpperCase();
  10291. },
  10292. hexStringList = function (data) {
  10293. var arr = [], i;
  10294. /* jshint -W086 */
  10295. while(data.byteLength > 0) {
  10296. i = 0;
  10297. switch(data.byteLength) {
  10298. default:
  10299. arr.push(hex(data[i++]));
  10300. case 7:
  10301. arr.push(hex(data[i++]));
  10302. case 6:
  10303. arr.push(hex(data[i++]));
  10304. case 5:
  10305. arr.push(hex(data[i++]));
  10306. case 4:
  10307. arr.push(hex(data[i++]));
  10308. case 3:
  10309. arr.push(hex(data[i++]));
  10310. case 2:
  10311. arr.push(hex(data[i++]));
  10312. case 1:
  10313. arr.push(hex(data[i++]));
  10314. }
  10315. data = data.subarray(i);
  10316. }
  10317. /* jshint +W086 */
  10318. return arr.join(' ');
  10319. },
  10320. parseAVCTag = function (tag, obj) {
  10321. var
  10322. avcPacketTypes = [
  10323. 'AVC Sequence Header',
  10324. 'AVC NALU',
  10325. 'AVC End-of-Sequence'
  10326. ],
  10327. nalUnitTypes = [
  10328. 'unspecified',
  10329. 'slice_layer_without_partitioning',
  10330. 'slice_data_partition_a_layer',
  10331. 'slice_data_partition_b_layer',
  10332. 'slice_data_partition_c_layer',
  10333. 'slice_layer_without_partitioning_idr',
  10334. 'sei',
  10335. 'seq_parameter_set',
  10336. 'pic_parameter_set',
  10337. 'access_unit_delimiter',
  10338. 'end_of_seq',
  10339. 'end_of_stream',
  10340. 'filler',
  10341. 'seq_parameter_set_ext',
  10342. 'prefix_nal_unit',
  10343. 'subset_seq_parameter_set',
  10344. 'reserved',
  10345. 'reserved',
  10346. 'reserved'
  10347. ],
  10348. compositionTime = (tag[1] & parseInt('01111111', 2) << 16) | (tag[2] << 8) | tag[3];
  10349. obj = obj || {};
  10350. obj.avcPacketType = avcPacketTypes[tag[0]];
  10351. obj.CompositionTime = (tag[1] & parseInt('10000000', 2)) ? -compositionTime : compositionTime;
  10352. if (tag[0] === 1) {
  10353. obj.nalUnitTypeRaw = hexStringList(tag.subarray(4, 100));
  10354. } else {
  10355. obj.data = hexStringList(tag.subarray(4));
  10356. }
  10357. return obj;
  10358. },
  10359. parseVideoTag = function (tag, obj) {
  10360. var
  10361. frameTypes = [
  10362. 'Unknown',
  10363. 'Keyframe (for AVC, a seekable frame)',
  10364. 'Inter frame (for AVC, a nonseekable frame)',
  10365. 'Disposable inter frame (H.263 only)',
  10366. 'Generated keyframe (reserved for server use only)',
  10367. 'Video info/command frame'
  10368. ],
  10369. codecIDs = [
  10370. 'JPEG (currently unused)',
  10371. 'Sorenson H.263',
  10372. 'Screen video',
  10373. 'On2 VP6',
  10374. 'On2 VP6 with alpha channel',
  10375. 'Screen video version 2',
  10376. 'AVC'
  10377. ],
  10378. codecID = tag[0] & parseInt('00001111', 2);
  10379. obj = obj || {};
  10380. obj.frameType = frameTypes[(tag[0] & parseInt('11110000', 2)) >>> 4];
  10381. obj.codecID = codecID;
  10382. if (codecID === 7) {
  10383. return parseAVCTag(tag.subarray(1), obj);
  10384. }
  10385. return obj;
  10386. },
  10387. parseAACTag = function (tag, obj) {
  10388. var packetTypes = [
  10389. 'AAC Sequence Header',
  10390. 'AAC Raw'
  10391. ];
  10392. obj = obj || {};
  10393. obj.aacPacketType = packetTypes[tag[0]];
  10394. obj.data = hexStringList(tag.subarray(1));
  10395. return obj;
  10396. },
  10397. parseAudioTag = function (tag, obj) {
  10398. var
  10399. formatTable = [
  10400. 'Linear PCM, platform endian',
  10401. 'ADPCM',
  10402. 'MP3',
  10403. 'Linear PCM, little endian',
  10404. 'Nellymoser 16-kHz mono',
  10405. 'Nellymoser 8-kHz mono',
  10406. 'Nellymoser',
  10407. 'G.711 A-law logarithmic PCM',
  10408. 'G.711 mu-law logarithmic PCM',
  10409. 'reserved',
  10410. 'AAC',
  10411. 'Speex',
  10412. 'MP3 8-Khz',
  10413. 'Device-specific sound'
  10414. ],
  10415. samplingRateTable = [
  10416. '5.5-kHz',
  10417. '11-kHz',
  10418. '22-kHz',
  10419. '44-kHz'
  10420. ],
  10421. soundFormat = (tag[0] & parseInt('11110000', 2)) >>> 4;
  10422. obj = obj || {};
  10423. obj.soundFormat = formatTable[soundFormat];
  10424. obj.soundRate = samplingRateTable[(tag[0] & parseInt('00001100', 2)) >>> 2];
  10425. obj.soundSize = ((tag[0] & parseInt('00000010', 2)) >>> 1) ? '16-bit' : '8-bit';
  10426. obj.soundType = (tag[0] & parseInt('00000001', 2)) ? 'Stereo' : 'Mono';
  10427. if (soundFormat === 10) {
  10428. return parseAACTag(tag.subarray(1), obj);
  10429. }
  10430. return obj;
  10431. },
  10432. parseGenericTag = function (tag) {
  10433. return {
  10434. tagType: tagTypes[tag[0]],
  10435. dataSize: (tag[1] << 16) | (tag[2] << 8) | tag[3],
  10436. timestamp: (tag[7] << 24) | (tag[4] << 16) | (tag[5] << 8) | tag[6],
  10437. streamID: (tag[8] << 16) | (tag[9] << 8) | tag[10]
  10438. };
  10439. },
  10440. inspectFlvTag = function (tag) {
  10441. var header = parseGenericTag(tag);
  10442. switch (tag[0]) {
  10443. case 0x08:
  10444. parseAudioTag(tag.subarray(11), header);
  10445. break;
  10446. case 0x09:
  10447. parseVideoTag(tag.subarray(11), header);
  10448. break;
  10449. case 0x12:
  10450. }
  10451. return header;
  10452. },
  10453. inspectFlv = function (bytes) {
  10454. var i = 9, // header
  10455. dataSize,
  10456. parsedResults = [],
  10457. tag;
  10458. // traverse the tags
  10459. i += 4; // skip previous tag size
  10460. while (i < bytes.byteLength) {
  10461. dataSize = bytes[i + 1] << 16;
  10462. dataSize |= bytes[i + 2] << 8;
  10463. dataSize |= bytes[i + 3];
  10464. dataSize += 11;
  10465. tag = bytes.subarray(i, i + dataSize);
  10466. parsedResults.push(inspectFlvTag(tag));
  10467. i += dataSize + 4;
  10468. }
  10469. return parsedResults;
  10470. },
  10471. textifyFlv = function (flvTagArray) {
  10472. return JSON.stringify(flvTagArray, null, 2);
  10473. };
  10474. module.exports = {
  10475. inspectTag: inspectFlvTag,
  10476. inspect: inspectFlv,
  10477. textify: textifyFlv
  10478. };
  10479. },{}],53:[function(require,module,exports){
  10480. (function (global){
  10481. 'use strict';
  10482. var
  10483. inspectMp4,
  10484. textifyMp4,
  10485. /**
  10486. * Returns the string representation of an ASCII encoded four byte buffer.
  10487. * @param buffer {Uint8Array} a four-byte buffer to translate
  10488. * @return {string} the corresponding string
  10489. */
  10490. parseType = function(buffer) {
  10491. var result = '';
  10492. result += String.fromCharCode(buffer[0]);
  10493. result += String.fromCharCode(buffer[1]);
  10494. result += String.fromCharCode(buffer[2]);
  10495. result += String.fromCharCode(buffer[3]);
  10496. return result;
  10497. },
  10498. parseMp4Date = function(seconds) {
  10499. return new Date(seconds * 1000 - 2082844800000);
  10500. },
  10501. parseSampleFlags = function(flags) {
  10502. return {
  10503. isLeading: (flags[0] & 0x0c) >>> 2,
  10504. dependsOn: flags[0] & 0x03,
  10505. isDependedOn: (flags[1] & 0xc0) >>> 6,
  10506. hasRedundancy: (flags[1] & 0x30) >>> 4,
  10507. paddingValue: (flags[1] & 0x0e) >>> 1,
  10508. isNonSyncSample: flags[1] & 0x01,
  10509. degradationPriority: (flags[2] << 8) | flags[3]
  10510. };
  10511. },
  10512. nalParse = function(avcStream) {
  10513. var
  10514. avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  10515. result = [],
  10516. i,
  10517. length;
  10518. for (i = 0; i + 4 < avcStream.length; i += length) {
  10519. length = avcView.getUint32(i);
  10520. i += 4;
  10521. // bail if this doesn't appear to be an H264 stream
  10522. if (length <= 0) {
  10523. result.push('<span style=\'color:red;\'>MALFORMED DATA</span>');
  10524. continue;
  10525. }
  10526. switch(avcStream[i] & 0x1F) {
  10527. case 0x01:
  10528. result.push('slice_layer_without_partitioning_rbsp');
  10529. break;
  10530. case 0x05:
  10531. result.push('slice_layer_without_partitioning_rbsp_idr');
  10532. break;
  10533. case 0x06:
  10534. result.push('sei_rbsp');
  10535. break;
  10536. case 0x07:
  10537. result.push('seq_parameter_set_rbsp');
  10538. break;
  10539. case 0x08:
  10540. result.push('pic_parameter_set_rbsp');
  10541. break;
  10542. case 0x09:
  10543. result.push('access_unit_delimiter_rbsp');
  10544. break;
  10545. default:
  10546. result.push('UNKNOWN NAL - ' + avcStream[i] & 0x1F);
  10547. break;
  10548. }
  10549. }
  10550. return result;
  10551. },
  10552. // registry of handlers for individual mp4 box types
  10553. parse = {
  10554. // codingname, not a first-class box type. stsd entries share the
  10555. // same format as real boxes so the parsing infrastructure can be
  10556. // shared
  10557. avc1: function(data) {
  10558. var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  10559. return {
  10560. dataReferenceIndex: view.getUint16(6),
  10561. width: view.getUint16(24),
  10562. height: view.getUint16(26),
  10563. horizresolution: view.getUint16(28) + (view.getUint16(30) / 16),
  10564. vertresolution: view.getUint16(32) + (view.getUint16(34) / 16),
  10565. frameCount: view.getUint16(40),
  10566. depth: view.getUint16(74),
  10567. config: inspectMp4(data.subarray(78, data.byteLength))
  10568. };
  10569. },
  10570. avcC: function(data) {
  10571. var
  10572. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10573. result = {
  10574. configurationVersion: data[0],
  10575. avcProfileIndication: data[1],
  10576. profileCompatibility: data[2],
  10577. avcLevelIndication: data[3],
  10578. lengthSizeMinusOne: data[4] & 0x03,
  10579. sps: [],
  10580. pps: []
  10581. },
  10582. numOfSequenceParameterSets = data[5] & 0x1f,
  10583. numOfPictureParameterSets,
  10584. nalSize,
  10585. offset,
  10586. i;
  10587. // iterate past any SPSs
  10588. offset = 6;
  10589. for (i = 0; i < numOfSequenceParameterSets; i++) {
  10590. nalSize = view.getUint16(offset);
  10591. offset += 2;
  10592. result.sps.push(new Uint8Array(data.subarray(offset, offset + nalSize)));
  10593. offset += nalSize;
  10594. }
  10595. // iterate past any PPSs
  10596. numOfPictureParameterSets = data[offset];
  10597. offset++;
  10598. for (i = 0; i < numOfPictureParameterSets; i++) {
  10599. nalSize = view.getUint16(offset);
  10600. offset += 2;
  10601. result.pps.push(new Uint8Array(data.subarray(offset, offset + nalSize)));
  10602. offset += nalSize;
  10603. }
  10604. return result;
  10605. },
  10606. btrt: function(data) {
  10607. var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  10608. return {
  10609. bufferSizeDB: view.getUint32(0),
  10610. maxBitrate: view.getUint32(4),
  10611. avgBitrate: view.getUint32(8)
  10612. };
  10613. },
  10614. esds: function(data) {
  10615. return {
  10616. version: data[0],
  10617. flags: new Uint8Array(data.subarray(1, 4)),
  10618. esId: (data[6] << 8) | data[7],
  10619. streamPriority: data[8] & 0x1f,
  10620. decoderConfig: {
  10621. objectProfileIndication: data[11],
  10622. streamType: (data[12] >>> 2) & 0x3f,
  10623. bufferSize: (data[13] << 16) | (data[14] << 8) | data[15],
  10624. maxBitrate: (data[16] << 24) |
  10625. (data[17] << 16) |
  10626. (data[18] << 8) |
  10627. data[19],
  10628. avgBitrate: (data[20] << 24) |
  10629. (data[21] << 16) |
  10630. (data[22] << 8) |
  10631. data[23],
  10632. decoderConfigDescriptor: {
  10633. tag: data[24],
  10634. length: data[25],
  10635. audioObjectType: (data[26] >>> 3) & 0x1f,
  10636. samplingFrequencyIndex: ((data[26] & 0x07) << 1) |
  10637. ((data[27] >>> 7) & 0x01),
  10638. channelConfiguration: (data[27] >>> 3) & 0x0f
  10639. }
  10640. }
  10641. };
  10642. },
  10643. ftyp: function(data) {
  10644. var
  10645. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10646. result = {
  10647. majorBrand: parseType(data.subarray(0, 4)),
  10648. minorVersion: view.getUint32(4),
  10649. compatibleBrands: []
  10650. },
  10651. i = 8;
  10652. while (i < data.byteLength) {
  10653. result.compatibleBrands.push(parseType(data.subarray(i, i + 4)));
  10654. i += 4;
  10655. }
  10656. return result;
  10657. },
  10658. dinf: function(data) {
  10659. return {
  10660. boxes: inspectMp4(data)
  10661. };
  10662. },
  10663. dref: function(data) {
  10664. return {
  10665. version: data[0],
  10666. flags: new Uint8Array(data.subarray(1, 4)),
  10667. dataReferences: inspectMp4(data.subarray(8))
  10668. };
  10669. },
  10670. hdlr: function(data) {
  10671. var
  10672. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10673. language,
  10674. result = {
  10675. version: view.getUint8(0),
  10676. flags: new Uint8Array(data.subarray(1, 4)),
  10677. handlerType: parseType(data.subarray(8, 12)),
  10678. name: ''
  10679. },
  10680. i = 8;
  10681. // parse out the name field
  10682. for (i = 24; i < data.byteLength; i++) {
  10683. if (data[i] === 0x00) {
  10684. // the name field is null-terminated
  10685. i++;
  10686. break;
  10687. }
  10688. result.name += String.fromCharCode(data[i]);
  10689. }
  10690. // decode UTF-8 to javascript's internal representation
  10691. // see http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html
  10692. result.name = decodeURIComponent(global.escape(result.name));
  10693. return result;
  10694. },
  10695. mdat: function(data) {
  10696. return {
  10697. byteLength: data.byteLength,
  10698. nals: nalParse(data)
  10699. };
  10700. },
  10701. mdhd: function(data) {
  10702. var
  10703. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10704. i = 4,
  10705. language,
  10706. result = {
  10707. version: view.getUint8(0),
  10708. flags: new Uint8Array(data.subarray(1, 4)),
  10709. language: ''
  10710. };
  10711. if (result.version === 1) {
  10712. i += 4;
  10713. result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  10714. i += 8;
  10715. result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  10716. i += 4;
  10717. result.timescale = view.getUint32(i);
  10718. i += 8;
  10719. result.duration = view.getUint32(i); // truncating top 4 bytes
  10720. } else {
  10721. result.creationTime = parseMp4Date(view.getUint32(i));
  10722. i += 4;
  10723. result.modificationTime = parseMp4Date(view.getUint32(i));
  10724. i += 4;
  10725. result.timescale = view.getUint32(i);
  10726. i += 4;
  10727. result.duration = view.getUint32(i);
  10728. }
  10729. i += 4;
  10730. // language is stored as an ISO-639-2/T code in an array of three 5-bit fields
  10731. // each field is the packed difference between its ASCII value and 0x60
  10732. language = view.getUint16(i);
  10733. result.language += String.fromCharCode((language >> 10) + 0x60);
  10734. result.language += String.fromCharCode(((language & 0x03c0) >> 5) + 0x60);
  10735. result.language += String.fromCharCode((language & 0x1f) + 0x60);
  10736. return result;
  10737. },
  10738. mdia: function(data) {
  10739. return {
  10740. boxes: inspectMp4(data)
  10741. };
  10742. },
  10743. mfhd: function(data) {
  10744. return {
  10745. version: data[0],
  10746. flags: new Uint8Array(data.subarray(1, 4)),
  10747. sequenceNumber: (data[4] << 24) |
  10748. (data[5] << 16) |
  10749. (data[6] << 8) |
  10750. (data[7])
  10751. };
  10752. },
  10753. minf: function(data) {
  10754. return {
  10755. boxes: inspectMp4(data)
  10756. };
  10757. },
  10758. // codingname, not a first-class box type. stsd entries share the
  10759. // same format as real boxes so the parsing infrastructure can be
  10760. // shared
  10761. mp4a: function(data) {
  10762. var
  10763. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10764. result = {
  10765. // 6 bytes reserved
  10766. dataReferenceIndex: view.getUint16(6),
  10767. // 4 + 4 bytes reserved
  10768. channelcount: view.getUint16(16),
  10769. samplesize: view.getUint16(18),
  10770. // 2 bytes pre_defined
  10771. // 2 bytes reserved
  10772. samplerate: view.getUint16(24) + (view.getUint16(26) / 65536)
  10773. };
  10774. // if there are more bytes to process, assume this is an ISO/IEC
  10775. // 14496-14 MP4AudioSampleEntry and parse the ESDBox
  10776. if (data.byteLength > 28) {
  10777. result.streamDescriptor = inspectMp4(data.subarray(28))[0];
  10778. }
  10779. return result;
  10780. },
  10781. moof: function(data) {
  10782. return {
  10783. boxes: inspectMp4(data)
  10784. };
  10785. },
  10786. moov: function(data) {
  10787. return {
  10788. boxes: inspectMp4(data)
  10789. };
  10790. },
  10791. mvex: function(data) {
  10792. return {
  10793. boxes: inspectMp4(data)
  10794. };
  10795. },
  10796. mvhd: function(data) {
  10797. var
  10798. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10799. i = 4,
  10800. result = {
  10801. version: view.getUint8(0),
  10802. flags: new Uint8Array(data.subarray(1, 4))
  10803. };
  10804. if (result.version === 1) {
  10805. i += 4;
  10806. result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  10807. i += 8;
  10808. result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  10809. i += 4;
  10810. result.timescale = view.getUint32(i);
  10811. i += 8;
  10812. result.duration = view.getUint32(i); // truncating top 4 bytes
  10813. } else {
  10814. result.creationTime = parseMp4Date(view.getUint32(i));
  10815. i += 4;
  10816. result.modificationTime = parseMp4Date(view.getUint32(i));
  10817. i += 4;
  10818. result.timescale = view.getUint32(i);
  10819. i += 4;
  10820. result.duration = view.getUint32(i);
  10821. }
  10822. i += 4;
  10823. // convert fixed-point, base 16 back to a number
  10824. result.rate = view.getUint16(i) + (view.getUint16(i + 2) / 16);
  10825. i += 4;
  10826. result.volume = view.getUint8(i) + (view.getUint8(i + 1) / 8);
  10827. i += 2;
  10828. i += 2;
  10829. i += 2 * 4;
  10830. result.matrix = new Uint32Array(data.subarray(i, i + (9 * 4)));
  10831. i += 9 * 4;
  10832. i += 6 * 4;
  10833. result.nextTrackId = view.getUint32(i);
  10834. return result;
  10835. },
  10836. pdin: function(data) {
  10837. var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  10838. return {
  10839. version: view.getUint8(0),
  10840. flags: new Uint8Array(data.subarray(1, 4)),
  10841. rate: view.getUint32(4),
  10842. initialDelay: view.getUint32(8)
  10843. };
  10844. },
  10845. sdtp: function(data) {
  10846. var
  10847. result = {
  10848. version: data[0],
  10849. flags: new Uint8Array(data.subarray(1, 4)),
  10850. samples: []
  10851. }, i;
  10852. for (i = 4; i < data.byteLength; i++) {
  10853. result.samples.push({
  10854. dependsOn: (data[i] & 0x30) >> 4,
  10855. isDependedOn: (data[i] & 0x0c) >> 2,
  10856. hasRedundancy: data[i] & 0x03
  10857. });
  10858. }
  10859. return result;
  10860. },
  10861. sidx: function(data) {
  10862. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10863. result = {
  10864. version: data[0],
  10865. flags: new Uint8Array(data.subarray(1, 4)),
  10866. references: [],
  10867. referenceId: view.getUint32(4),
  10868. timescale: view.getUint32(8),
  10869. earliestPresentationTime: view.getUint32(12),
  10870. firstOffset: view.getUint32(16)
  10871. },
  10872. referenceCount = view.getUint16(22),
  10873. i;
  10874. for (i = 24; referenceCount; i += 12, referenceCount-- ) {
  10875. result.references.push({
  10876. referenceType: (data[i] & 0x80) >>> 7,
  10877. referencedSize: view.getUint32(i) & 0x7FFFFFFF,
  10878. subsegmentDuration: view.getUint32(i + 4),
  10879. startsWithSap: !!(data[i + 8] & 0x80),
  10880. sapType: (data[i + 8] & 0x70) >>> 4,
  10881. sapDeltaTime: view.getUint32(i + 8) & 0x0FFFFFFF
  10882. });
  10883. }
  10884. return result;
  10885. },
  10886. smhd: function(data) {
  10887. return {
  10888. version: data[0],
  10889. flags: new Uint8Array(data.subarray(1, 4)),
  10890. balance: data[4] + (data[5] / 256)
  10891. };
  10892. },
  10893. stbl: function(data) {
  10894. return {
  10895. boxes: inspectMp4(data)
  10896. };
  10897. },
  10898. stco: function(data) {
  10899. var
  10900. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10901. result = {
  10902. version: data[0],
  10903. flags: new Uint8Array(data.subarray(1, 4)),
  10904. chunkOffsets: []
  10905. },
  10906. entryCount = view.getUint32(4),
  10907. i;
  10908. for (i = 8; entryCount; i += 4, entryCount--) {
  10909. result.chunkOffsets.push(view.getUint32(i));
  10910. }
  10911. return result;
  10912. },
  10913. stsc: function(data) {
  10914. var
  10915. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10916. entryCount = view.getUint32(4),
  10917. result = {
  10918. version: data[0],
  10919. flags: new Uint8Array(data.subarray(1, 4)),
  10920. sampleToChunks: []
  10921. },
  10922. i;
  10923. for (i = 8; entryCount; i += 12, entryCount--) {
  10924. result.sampleToChunks.push({
  10925. firstChunk: view.getUint32(i),
  10926. samplesPerChunk: view.getUint32(i + 4),
  10927. sampleDescriptionIndex: view.getUint32(i + 8)
  10928. });
  10929. }
  10930. return result;
  10931. },
  10932. stsd: function(data) {
  10933. return {
  10934. version: data[0],
  10935. flags: new Uint8Array(data.subarray(1, 4)),
  10936. sampleDescriptions: inspectMp4(data.subarray(8))
  10937. };
  10938. },
  10939. stsz: function(data) {
  10940. var
  10941. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10942. result = {
  10943. version: data[0],
  10944. flags: new Uint8Array(data.subarray(1, 4)),
  10945. sampleSize: view.getUint32(4),
  10946. entries: []
  10947. },
  10948. i;
  10949. for (i = 12; i < data.byteLength; i += 4) {
  10950. result.entries.push(view.getUint32(i));
  10951. }
  10952. return result;
  10953. },
  10954. stts: function(data) {
  10955. var
  10956. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10957. result = {
  10958. version: data[0],
  10959. flags: new Uint8Array(data.subarray(1, 4)),
  10960. timeToSamples: []
  10961. },
  10962. entryCount = view.getUint32(4),
  10963. i;
  10964. for (i = 8; entryCount; i += 8, entryCount--) {
  10965. result.timeToSamples.push({
  10966. sampleCount: view.getUint32(i),
  10967. sampleDelta: view.getUint32(i + 4)
  10968. });
  10969. }
  10970. return result;
  10971. },
  10972. styp: function(data) {
  10973. return parse.ftyp(data);
  10974. },
  10975. tfdt: function(data) {
  10976. return {
  10977. version: data[0],
  10978. flags: new Uint8Array(data.subarray(1, 4)),
  10979. baseMediaDecodeTime: data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]
  10980. };
  10981. },
  10982. tfhd: function(data) {
  10983. var
  10984. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10985. result = {
  10986. version: data[0],
  10987. flags: new Uint8Array(data.subarray(1, 4)),
  10988. trackId: view.getUint32(4)
  10989. },
  10990. baseDataOffsetPresent = result.flags[2] & 0x01,
  10991. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  10992. defaultSampleDurationPresent = result.flags[2] & 0x08,
  10993. defaultSampleSizePresent = result.flags[2] & 0x10,
  10994. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  10995. i;
  10996. i = 8;
  10997. if (baseDataOffsetPresent) {
  10998. i += 4; // truncate top 4 bytes
  10999. result.baseDataOffset = view.getUint32(12);
  11000. i += 4;
  11001. }
  11002. if (sampleDescriptionIndexPresent) {
  11003. result.sampleDescriptionIndex = view.getUint32(i);
  11004. i += 4;
  11005. }
  11006. if (defaultSampleDurationPresent) {
  11007. result.defaultSampleDuration = view.getUint32(i);
  11008. i += 4;
  11009. }
  11010. if (defaultSampleSizePresent) {
  11011. result.defaultSampleSize = view.getUint32(i);
  11012. i += 4;
  11013. }
  11014. if (defaultSampleFlagsPresent) {
  11015. result.defaultSampleFlags = view.getUint32(i);
  11016. }
  11017. return result;
  11018. },
  11019. tkhd: function(data) {
  11020. var
  11021. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  11022. i = 4,
  11023. result = {
  11024. version: view.getUint8(0),
  11025. flags: new Uint8Array(data.subarray(1, 4)),
  11026. };
  11027. if (result.version === 1) {
  11028. i += 4;
  11029. result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  11030. i += 8;
  11031. result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  11032. i += 4;
  11033. result.trackId = view.getUint32(i);
  11034. i += 4;
  11035. i += 8;
  11036. result.duration = view.getUint32(i); // truncating top 4 bytes
  11037. } else {
  11038. result.creationTime = parseMp4Date(view.getUint32(i));
  11039. i += 4;
  11040. result.modificationTime = parseMp4Date(view.getUint32(i));
  11041. i += 4;
  11042. result.trackId = view.getUint32(i);
  11043. i += 4;
  11044. i += 4;
  11045. result.duration = view.getUint32(i);
  11046. }
  11047. i += 4;
  11048. i += 2 * 4;
  11049. result.layer = view.getUint16(i);
  11050. i += 2;
  11051. result.alternateGroup = view.getUint16(i);
  11052. i += 2;
  11053. // convert fixed-point, base 16 back to a number
  11054. result.volume = view.getUint8(i) + (view.getUint8(i + 1) / 8);
  11055. i += 2;
  11056. i += 2;
  11057. result.matrix = new Uint32Array(data.subarray(i, i + (9 * 4)));
  11058. i += 9 * 4;
  11059. result.width = view.getUint16(i) + (view.getUint16(i + 2) / 16);
  11060. i += 4;
  11061. result.height = view.getUint16(i) + (view.getUint16(i + 2) / 16);
  11062. return result;
  11063. },
  11064. traf: function(data) {
  11065. return {
  11066. boxes: inspectMp4(data)
  11067. };
  11068. },
  11069. trak: function(data) {
  11070. return {
  11071. boxes: inspectMp4(data)
  11072. };
  11073. },
  11074. trex: function(data) {
  11075. var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  11076. return {
  11077. version: data[0],
  11078. flags: new Uint8Array(data.subarray(1, 4)),
  11079. trackId: view.getUint32(4),
  11080. defaultSampleDescriptionIndex: view.getUint32(8),
  11081. defaultSampleDuration: view.getUint32(12),
  11082. defaultSampleSize: view.getUint32(16),
  11083. sampleDependsOn: data[20] & 0x03,
  11084. sampleIsDependedOn: (data[21] & 0xc0) >> 6,
  11085. sampleHasRedundancy: (data[21] & 0x30) >> 4,
  11086. samplePaddingValue: (data[21] & 0x0e) >> 1,
  11087. sampleIsDifferenceSample: !!(data[21] & 0x01),
  11088. sampleDegradationPriority: view.getUint16(22)
  11089. };
  11090. },
  11091. trun: function(data) {
  11092. var
  11093. result = {
  11094. version: data[0],
  11095. flags: new Uint8Array(data.subarray(1, 4)),
  11096. samples: []
  11097. },
  11098. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  11099. dataOffsetPresent = result.flags[2] & 0x01,
  11100. firstSampleFlagsPresent = result.flags[2] & 0x04,
  11101. sampleDurationPresent = result.flags[1] & 0x01,
  11102. sampleSizePresent = result.flags[1] & 0x02,
  11103. sampleFlagsPresent = result.flags[1] & 0x04,
  11104. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
  11105. sampleCount = view.getUint32(4),
  11106. offset = 8,
  11107. sample;
  11108. if (dataOffsetPresent) {
  11109. result.dataOffset = view.getUint32(offset);
  11110. offset += 4;
  11111. }
  11112. if (firstSampleFlagsPresent && sampleCount) {
  11113. sample = {
  11114. flags: parseSampleFlags(data.subarray(offset, offset + 4))
  11115. };
  11116. offset += 4;
  11117. if (sampleDurationPresent) {
  11118. sample.duration = view.getUint32(offset);
  11119. offset += 4;
  11120. }
  11121. if (sampleSizePresent) {
  11122. sample.size = view.getUint32(offset);
  11123. offset += 4;
  11124. }
  11125. if (sampleCompositionTimeOffsetPresent) {
  11126. sample.compositionTimeOffset = view.getUint32(offset);
  11127. offset += 4;
  11128. }
  11129. result.samples.push(sample);
  11130. sampleCount--;
  11131. }
  11132. while (sampleCount--) {
  11133. sample = {};
  11134. if (sampleDurationPresent) {
  11135. sample.duration = view.getUint32(offset);
  11136. offset += 4;
  11137. }
  11138. if (sampleSizePresent) {
  11139. sample.size = view.getUint32(offset);
  11140. offset += 4;
  11141. }
  11142. if (sampleFlagsPresent) {
  11143. sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
  11144. offset += 4;
  11145. }
  11146. if (sampleCompositionTimeOffsetPresent) {
  11147. sample.compositionTimeOffset = view.getUint32(offset);
  11148. offset += 4;
  11149. }
  11150. result.samples.push(sample);
  11151. }
  11152. return result;
  11153. },
  11154. 'url ': function(data) {
  11155. return {
  11156. version: data[0],
  11157. flags: new Uint8Array(data.subarray(1, 4))
  11158. };
  11159. },
  11160. vmhd: function(data) {
  11161. var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  11162. return {
  11163. version: data[0],
  11164. flags: new Uint8Array(data.subarray(1, 4)),
  11165. graphicsmode: view.getUint16(4),
  11166. opcolor: new Uint16Array([view.getUint16(6),
  11167. view.getUint16(8),
  11168. view.getUint16(10)])
  11169. };
  11170. }
  11171. };
  11172. /**
  11173. * Return a javascript array of box objects parsed from an ISO base
  11174. * media file.
  11175. * @param data {Uint8Array} the binary data of the media to be inspected
  11176. * @return {array} a javascript array of potentially nested box objects
  11177. */
  11178. inspectMp4 = function(data) {
  11179. var
  11180. i = 0,
  11181. result = [],
  11182. view,
  11183. size,
  11184. type,
  11185. end,
  11186. box;
  11187. // Convert data from Uint8Array to ArrayBuffer, to follow Dataview API
  11188. var ab = new ArrayBuffer(data.length);
  11189. var v = new Uint8Array(ab);
  11190. for (var z = 0; z < data.length; ++z) {
  11191. v[z] = data[z];
  11192. }
  11193. view = new DataView(ab);
  11194. while (i < data.byteLength) {
  11195. // parse box data
  11196. size = view.getUint32(i);
  11197. type = parseType(data.subarray(i + 4, i + 8));
  11198. end = size > 1 ? i + size : data.byteLength;
  11199. // parse type-specific data
  11200. box = (parse[type] || function(data) {
  11201. return {
  11202. data: data
  11203. };
  11204. })(data.subarray(i + 8, end));
  11205. box.size = size;
  11206. box.type = type;
  11207. // store this box and move to the next
  11208. result.push(box);
  11209. i = end;
  11210. }
  11211. return result;
  11212. };
  11213. /**
  11214. * Returns a textual representation of the javascript represtentation
  11215. * of an MP4 file. You can use it as an alternative to
  11216. * JSON.stringify() to compare inspected MP4s.
  11217. * @param inspectedMp4 {array} the parsed array of boxes in an MP4
  11218. * file
  11219. * @param depth {number} (optional) the number of ancestor boxes of
  11220. * the elements of inspectedMp4. Assumed to be zero if unspecified.
  11221. * @return {string} a text representation of the parsed MP4
  11222. */
  11223. textifyMp4 = function(inspectedMp4, depth) {
  11224. var indent;
  11225. depth = depth || 0;
  11226. indent = new Array(depth * 2 + 1).join(' ');
  11227. // iterate over all the boxes
  11228. return inspectedMp4.map(function(box, index) {
  11229. // list the box type first at the current indentation level
  11230. return indent + box.type + '\n' +
  11231. // the type is already included and handle child boxes separately
  11232. Object.keys(box).filter(function(key) {
  11233. return key !== 'type' && key !== 'boxes';
  11234. // output all the box properties
  11235. }).map(function(key) {
  11236. var prefix = indent + ' ' + key + ': ',
  11237. value = box[key];
  11238. // print out raw bytes as hexademical
  11239. if (value instanceof Uint8Array || value instanceof Uint32Array) {
  11240. var bytes = Array.prototype.slice.call(new Uint8Array(value.buffer, value.byteOffset, value.byteLength))
  11241. .map(function(byte) {
  11242. return ' ' + ('00' + byte.toString(16)).slice(-2);
  11243. }).join('').match(/.{1,24}/g);
  11244. if (!bytes) {
  11245. return prefix + '<>';
  11246. }
  11247. if (bytes.length === 1) {
  11248. return prefix + '<' + bytes.join('').slice(1) + '>';
  11249. }
  11250. return prefix + '<\n' + bytes.map(function(line) {
  11251. return indent + ' ' + line;
  11252. }).join('\n') + '\n' + indent + ' >';
  11253. }
  11254. // stringify generic objects
  11255. return prefix +
  11256. JSON.stringify(value, null, 2)
  11257. .split('\n').map(function(line, index) {
  11258. if (index === 0) {
  11259. return line;
  11260. }
  11261. return indent + ' ' + line;
  11262. }).join('\n');
  11263. }).join('\n') +
  11264. // recursively textify the child boxes
  11265. (box.boxes ? '\n' + textifyMp4(box.boxes, depth + 1) : '');
  11266. }).join('\n');
  11267. };
  11268. module.exports = {
  11269. inspect: inspectMp4,
  11270. textify: textifyMp4
  11271. };
  11272. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11273. },{}],54:[function(require,module,exports){
  11274. 'use strict';
  11275. var ExpGolomb;
  11276. /**
  11277. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  11278. * scheme used by h264.
  11279. */
  11280. ExpGolomb = function(workingData) {
  11281. var
  11282. // the number of bytes left to examine in workingData
  11283. workingBytesAvailable = workingData.byteLength,
  11284. // the current word being examined
  11285. workingWord = 0, // :uint
  11286. // the number of bits left to examine in the current word
  11287. workingBitsAvailable = 0; // :uint;
  11288. // ():uint
  11289. this.length = function() {
  11290. return (8 * workingBytesAvailable);
  11291. };
  11292. // ():uint
  11293. this.bitsAvailable = function() {
  11294. return (8 * workingBytesAvailable) + workingBitsAvailable;
  11295. };
  11296. // ():void
  11297. this.loadWord = function() {
  11298. var
  11299. position = workingData.byteLength - workingBytesAvailable,
  11300. workingBytes = new Uint8Array(4),
  11301. availableBytes = Math.min(4, workingBytesAvailable);
  11302. if (availableBytes === 0) {
  11303. throw new Error('no bytes available');
  11304. }
  11305. workingBytes.set(workingData.subarray(position,
  11306. position + availableBytes));
  11307. workingWord = new DataView(workingBytes.buffer).getUint32(0);
  11308. // track the amount of workingData that has been processed
  11309. workingBitsAvailable = availableBytes * 8;
  11310. workingBytesAvailable -= availableBytes;
  11311. };
  11312. // (count:int):void
  11313. this.skipBits = function(count) {
  11314. var skipBytes; // :int
  11315. if (workingBitsAvailable > count) {
  11316. workingWord <<= count;
  11317. workingBitsAvailable -= count;
  11318. } else {
  11319. count -= workingBitsAvailable;
  11320. skipBytes = Math.floor(count / 8);
  11321. count -= (skipBytes * 8);
  11322. workingBytesAvailable -= skipBytes;
  11323. this.loadWord();
  11324. workingWord <<= count;
  11325. workingBitsAvailable -= count;
  11326. }
  11327. };
  11328. // (size:int):uint
  11329. this.readBits = function(size) {
  11330. var
  11331. bits = Math.min(workingBitsAvailable, size), // :uint
  11332. valu = workingWord >>> (32 - bits); // :uint
  11333. // if size > 31, handle error
  11334. workingBitsAvailable -= bits;
  11335. if (workingBitsAvailable > 0) {
  11336. workingWord <<= bits;
  11337. } else if (workingBytesAvailable > 0) {
  11338. this.loadWord();
  11339. }
  11340. bits = size - bits;
  11341. if (bits > 0) {
  11342. return valu << bits | this.readBits(bits);
  11343. } else {
  11344. return valu;
  11345. }
  11346. };
  11347. // ():uint
  11348. this.skipLeadingZeros = function() {
  11349. var leadingZeroCount; // :uint
  11350. for (leadingZeroCount = 0 ; leadingZeroCount < workingBitsAvailable ; ++leadingZeroCount) {
  11351. if (0 !== (workingWord & (0x80000000 >>> leadingZeroCount))) {
  11352. // the first bit of working word is 1
  11353. workingWord <<= leadingZeroCount;
  11354. workingBitsAvailable -= leadingZeroCount;
  11355. return leadingZeroCount;
  11356. }
  11357. }
  11358. // we exhausted workingWord and still have not found a 1
  11359. this.loadWord();
  11360. return leadingZeroCount + this.skipLeadingZeros();
  11361. };
  11362. // ():void
  11363. this.skipUnsignedExpGolomb = function() {
  11364. this.skipBits(1 + this.skipLeadingZeros());
  11365. };
  11366. // ():void
  11367. this.skipExpGolomb = function() {
  11368. this.skipBits(1 + this.skipLeadingZeros());
  11369. };
  11370. // ():uint
  11371. this.readUnsignedExpGolomb = function() {
  11372. var clz = this.skipLeadingZeros(); // :uint
  11373. return this.readBits(clz + 1) - 1;
  11374. };
  11375. // ():int
  11376. this.readExpGolomb = function() {
  11377. var valu = this.readUnsignedExpGolomb(); // :int
  11378. if (0x01 & valu) {
  11379. // the number is odd if the low order bit is set
  11380. return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2
  11381. } else {
  11382. return -1 * (valu >>> 1); // divide by two then make it negative
  11383. }
  11384. };
  11385. // Some convenience functions
  11386. // :Boolean
  11387. this.readBoolean = function() {
  11388. return 1 === this.readBits(1);
  11389. };
  11390. // ():int
  11391. this.readUnsignedByte = function() {
  11392. return this.readBits(8);
  11393. };
  11394. this.loadWord();
  11395. };
  11396. module.exports = ExpGolomb;
  11397. },{}],55:[function(require,module,exports){
  11398. /**
  11399. * mux.js
  11400. *
  11401. * Copyright (c) 2014 Brightcove
  11402. * All rights reserved.
  11403. *
  11404. * A lightweight readable stream implemention that handles event dispatching.
  11405. * Objects that inherit from streams should call init in their constructors.
  11406. */
  11407. 'use strict';
  11408. var Stream = function() {
  11409. this.init = function() {
  11410. var listeners = {};
  11411. /**
  11412. * Add a listener for a specified event type.
  11413. * @param type {string} the event name
  11414. * @param listener {function} the callback to be invoked when an event of
  11415. * the specified type occurs
  11416. */
  11417. this.on = function(type, listener) {
  11418. if (!listeners[type]) {
  11419. listeners[type] = [];
  11420. }
  11421. listeners[type].push(listener);
  11422. };
  11423. /**
  11424. * Remove a listener for a specified event type.
  11425. * @param type {string} the event name
  11426. * @param listener {function} a function previously registered for this
  11427. * type of event through `on`
  11428. */
  11429. this.off = function(type, listener) {
  11430. var index;
  11431. if (!listeners[type]) {
  11432. return false;
  11433. }
  11434. index = listeners[type].indexOf(listener);
  11435. listeners[type].splice(index, 1);
  11436. return index > -1;
  11437. };
  11438. /**
  11439. * Trigger an event of the specified type on this stream. Any additional
  11440. * arguments to this function are passed as parameters to event listeners.
  11441. * @param type {string} the event name
  11442. */
  11443. this.trigger = function(type) {
  11444. var callbacks, i, length, args;
  11445. callbacks = listeners[type];
  11446. if (!callbacks) {
  11447. return;
  11448. }
  11449. // Slicing the arguments on every invocation of this method
  11450. // can add a significant amount of overhead. Avoid the
  11451. // intermediate object creation for the common case of a
  11452. // single callback argument
  11453. if (arguments.length === 2) {
  11454. length = callbacks.length;
  11455. for (i = 0; i < length; ++i) {
  11456. callbacks[i].call(this, arguments[1]);
  11457. }
  11458. } else {
  11459. args = [];
  11460. i = arguments.length;
  11461. for (i = 1; i < arguments.length; ++i) {
  11462. args.push(arguments[i]);
  11463. }
  11464. length = callbacks.length;
  11465. for (i = 0; i < length; ++i) {
  11466. callbacks[i].apply(this, args);
  11467. }
  11468. }
  11469. };
  11470. /**
  11471. * Destroys the stream and cleans up.
  11472. */
  11473. this.dispose = function() {
  11474. listeners = {};
  11475. };
  11476. };
  11477. };
  11478. /**
  11479. * Forwards all `data` events on this stream to the destination stream. The
  11480. * destination stream should provide a method `push` to receive the data
  11481. * events as they arrive.
  11482. * @param destination {stream} the stream that will receive all `data` events
  11483. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  11484. * when the current stream emits a 'done' event
  11485. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  11486. */
  11487. Stream.prototype.pipe = function(destination) {
  11488. this.on('data', function(data) {
  11489. destination.push(data);
  11490. });
  11491. this.on('done', function(flushSource) {
  11492. destination.flush(flushSource);
  11493. });
  11494. return destination;
  11495. };
  11496. // Default stream functions that are expected to be overridden to perform
  11497. // actual work. These are provided by the prototype as a sort of no-op
  11498. // implementation so that we don't have to check for their existence in the
  11499. // `pipe` function above.
  11500. Stream.prototype.push = function(data) {
  11501. this.trigger('data', data);
  11502. };
  11503. Stream.prototype.flush = function(flushSource) {
  11504. this.trigger('done', flushSource);
  11505. };
  11506. module.exports = Stream;
  11507. },{}],56:[function(require,module,exports){
  11508. var bundleFn = arguments[3];
  11509. var sources = arguments[4];
  11510. var cache = arguments[5];
  11511. var stringify = JSON.stringify;
  11512. module.exports = function (fn) {
  11513. var keys = [];
  11514. var wkey;
  11515. var cacheKeys = Object.keys(cache);
  11516. for (var i = 0, l = cacheKeys.length; i < l; i++) {
  11517. var key = cacheKeys[i];
  11518. if (cache[key].exports === fn) {
  11519. wkey = key;
  11520. break;
  11521. }
  11522. }
  11523. if (!wkey) {
  11524. wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
  11525. var wcache = {};
  11526. for (var i = 0, l = cacheKeys.length; i < l; i++) {
  11527. var key = cacheKeys[i];
  11528. wcache[key] = key;
  11529. }
  11530. sources[wkey] = [
  11531. Function(['require','module','exports'], '(' + fn + ')(self)'),
  11532. wcache
  11533. ];
  11534. }
  11535. var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
  11536. var scache = {}; scache[wkey] = wkey;
  11537. sources[skey] = [
  11538. Function(['require'],'require(' + stringify(wkey) + ')(self)'),
  11539. scache
  11540. ];
  11541. var src = '(' + bundleFn + ')({'
  11542. + Object.keys(sources).map(function (key) {
  11543. return stringify(key) + ':['
  11544. + sources[key][0]
  11545. + ',' + stringify(sources[key][1]) + ']'
  11546. ;
  11547. }).join(',')
  11548. + '},{},[' + stringify(skey) + '])'
  11549. ;
  11550. var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  11551. return new Worker(URL.createObjectURL(
  11552. new Blob([src], { type: 'text/javascript' })
  11553. ));
  11554. };
  11555. },{}],57:[function(require,module,exports){
  11556. (function (global){
  11557. /**
  11558. * @file videojs-contrib-hls.js
  11559. *
  11560. * The main file for the HLS project.
  11561. * License: https://github.com/videojs/videojs-contrib-hls/blob/master/LICENSE
  11562. */
  11563. 'use strict';
  11564. 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; }; })();
  11565. 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); } } };
  11566. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  11567. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  11568. 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; }
  11569. var _globalDocument = require('global/document');
  11570. var _globalDocument2 = _interopRequireDefault(_globalDocument);
  11571. var _playlistLoader = require('./playlist-loader');
  11572. var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
  11573. var _playlist = require('./playlist');
  11574. var _playlist2 = _interopRequireDefault(_playlist);
  11575. var _xhr = require('./xhr');
  11576. var _xhr2 = _interopRequireDefault(_xhr);
  11577. var _decrypter = require('./decrypter');
  11578. var _binUtils = require('./bin-utils');
  11579. var _binUtils2 = _interopRequireDefault(_binUtils);
  11580. var _videojsContribMediaSources = require('videojs-contrib-media-sources');
  11581. var _m3u8 = require('./m3u8');
  11582. var _m3u82 = _interopRequireDefault(_m3u8);
  11583. var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
  11584. var _videoJs2 = _interopRequireDefault(_videoJs);
  11585. var _masterPlaylistController = require('./master-playlist-controller');
  11586. var _masterPlaylistController2 = _interopRequireDefault(_masterPlaylistController);
  11587. /**
  11588. * determine if an object a is differnt from
  11589. * and object b. both only having one dimensional
  11590. * properties
  11591. *
  11592. * @param {Object} a object one
  11593. * @param {Object} b object two
  11594. * @return {Boolean} if the object has changed or not
  11595. */
  11596. var objectChanged = function objectChanged(a, b) {
  11597. if (typeof a !== typeof b) {
  11598. return true;
  11599. }
  11600. // if we have a different number of elements
  11601. // something has changed
  11602. if (Object.keys(a).length !== Object.keys(b).length) {
  11603. return true;
  11604. }
  11605. for (var prop in a) {
  11606. if (!b[prop] || a[prop] !== b[prop]) {
  11607. return true;
  11608. }
  11609. }
  11610. return false;
  11611. };
  11612. var Hls = {
  11613. PlaylistLoader: _playlistLoader2['default'],
  11614. Playlist: _playlist2['default'],
  11615. Decrypter: _decrypter.Decrypter,
  11616. AsyncStream: _decrypter.AsyncStream,
  11617. decrypt: _decrypter.decrypt,
  11618. utils: _binUtils2['default'],
  11619. xhr: (0, _xhr2['default'])()
  11620. };
  11621. // the desired length of video to maintain in the buffer, in seconds
  11622. Hls.GOAL_BUFFER_LENGTH = 30;
  11623. // A fudge factor to apply to advertised playlist bitrates to account for
  11624. // temporary flucations in client bandwidth
  11625. var BANDWIDTH_VARIANCE = 1.2;
  11626. /**
  11627. * Returns the CSS value for the specified property on an element
  11628. * using `getComputedStyle`. Firefox has a long-standing issue where
  11629. * getComputedStyle() may return null when running in an iframe with
  11630. * `display: none`.
  11631. *
  11632. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  11633. * @param {HTMLElement} el the htmlelement to work on
  11634. * @param {string} the proprety to get the style for
  11635. */
  11636. var safeGetComputedStyle = function safeGetComputedStyle(el, property) {
  11637. var result = undefined;
  11638. if (!el) {
  11639. return '';
  11640. }
  11641. result = getComputedStyle(el);
  11642. if (!result) {
  11643. return '';
  11644. }
  11645. return result[property];
  11646. };
  11647. /**
  11648. * Chooses the appropriate media playlist based on the current
  11649. * bandwidth estimate and the player size.
  11650. *
  11651. * @return {Playlist} the highest bitrate playlist less than the currently detected
  11652. * bandwidth, accounting for some amount of bandwidth variance
  11653. */
  11654. Hls.STANDARD_PLAYLIST_SELECTOR = function () {
  11655. var effectiveBitrate = undefined;
  11656. var sortedPlaylists = this.playlists.master.playlists.slice();
  11657. var bandwidthPlaylists = [];
  11658. var now = +new Date();
  11659. var i = undefined;
  11660. var variant = undefined;
  11661. var bandwidthBestVariant = undefined;
  11662. var resolutionPlusOne = undefined;
  11663. var resolutionPlusOneAttribute = undefined;
  11664. var resolutionBestVariant = undefined;
  11665. var width = undefined;
  11666. var height = undefined;
  11667. sortedPlaylists.sort(Hls.comparePlaylistBandwidth);
  11668. // filter out any playlists that have been excluded due to
  11669. // incompatible configurations or playback errors
  11670. sortedPlaylists = sortedPlaylists.filter(function (localVariant) {
  11671. if (typeof localVariant.excludeUntil !== 'undefined') {
  11672. return now >= localVariant.excludeUntil;
  11673. }
  11674. return true;
  11675. });
  11676. // filter out any variant that has greater effective bitrate
  11677. // than the current estimated bandwidth
  11678. i = sortedPlaylists.length;
  11679. while (i--) {
  11680. variant = sortedPlaylists[i];
  11681. // ignore playlists without bandwidth information
  11682. if (!variant.attributes || !variant.attributes.BANDWIDTH) {
  11683. continue;
  11684. }
  11685. effectiveBitrate = variant.attributes.BANDWIDTH * BANDWIDTH_VARIANCE;
  11686. if (effectiveBitrate < this.bandwidth) {
  11687. bandwidthPlaylists.push(variant);
  11688. // since the playlists are sorted in ascending order by
  11689. // bandwidth, the first viable variant is the best
  11690. if (!bandwidthBestVariant) {
  11691. bandwidthBestVariant = variant;
  11692. }
  11693. }
  11694. }
  11695. i = bandwidthPlaylists.length;
  11696. // sort variants by resolution
  11697. bandwidthPlaylists.sort(Hls.comparePlaylistResolution);
  11698. // forget our old variant from above,
  11699. // or we might choose that in high-bandwidth scenarios
  11700. // (this could be the lowest bitrate rendition as we go through all of them above)
  11701. variant = null;
  11702. width = parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10);
  11703. height = parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10);
  11704. // iterate through the bandwidth-filtered playlists and find
  11705. // best rendition by player dimension
  11706. while (i--) {
  11707. variant = bandwidthPlaylists[i];
  11708. // ignore playlists without resolution information
  11709. if (!variant.attributes || !variant.attributes.RESOLUTION || !variant.attributes.RESOLUTION.width || !variant.attributes.RESOLUTION.height) {
  11710. continue;
  11711. }
  11712. // since the playlists are sorted, the first variant that has
  11713. // dimensions less than or equal to the player size is the best
  11714. var variantResolution = variant.attributes.RESOLUTION;
  11715. if (variantResolution.width === width && variantResolution.height === height) {
  11716. // if we have the exact resolution as the player use it
  11717. resolutionPlusOne = null;
  11718. resolutionBestVariant = variant;
  11719. break;
  11720. } else if (variantResolution.width < width && variantResolution.height < height) {
  11721. // if both dimensions are less than the player use the
  11722. // previous (next-largest) variant
  11723. break;
  11724. } else if (!resolutionPlusOne || variantResolution.width < resolutionPlusOneAttribute.width && variantResolution.height < resolutionPlusOneAttribute.height) {
  11725. // If we still haven't found a good match keep a
  11726. // reference to the previous variant for the next loop
  11727. // iteration
  11728. // By only saving variants if they are smaller than the
  11729. // previously saved variant, we ensure that we also pick
  11730. // the highest bandwidth variant that is just-larger-than
  11731. // the video player
  11732. resolutionPlusOne = variant;
  11733. resolutionPlusOneAttribute = resolutionPlusOne.attributes.RESOLUTION;
  11734. }
  11735. }
  11736. // fallback chain of variants
  11737. return resolutionPlusOne || resolutionBestVariant || bandwidthBestVariant || sortedPlaylists[0];
  11738. };
  11739. // HLS is a source handler, not a tech. Make sure attempts to use it
  11740. // as one do not cause exceptions.
  11741. Hls.canPlaySource = function () {
  11742. return _videoJs2['default'].log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  11743. };
  11744. /**
  11745. * Whether the browser has built-in HLS support.
  11746. */
  11747. Hls.supportsNativeHls = (function () {
  11748. var video = _globalDocument2['default'].createElement('video');
  11749. // native HLS is definitely not supported if HTML5 video isn't
  11750. if (!_videoJs2['default'].getComponent('Html5').isSupported()) {
  11751. return false;
  11752. }
  11753. // HLS manifests can go by many mime-types
  11754. var canPlay = [
  11755. // Apple santioned
  11756. 'application/vnd.apple.mpegurl',
  11757. // Apple sanctioned for backwards compatibility
  11758. 'audio/mpegurl',
  11759. // Very common
  11760. 'audio/x-mpegurl',
  11761. // Very common
  11762. 'application/x-mpegurl',
  11763. // Included for completeness
  11764. 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
  11765. return canPlay.some(function (canItPlay) {
  11766. return (/maybe|probably/i.test(video.canPlayType(canItPlay))
  11767. );
  11768. });
  11769. })();
  11770. /**
  11771. * HLS is a source handler, not a tech. Make sure attempts to use it
  11772. * as one do not cause exceptions.
  11773. */
  11774. Hls.isSupported = function () {
  11775. return _videoJs2['default'].log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  11776. };
  11777. var Component = _videoJs2['default'].getComponent('Component');
  11778. /**
  11779. * The Hls Handler object, where we orchestrate all of the parts
  11780. * of HLS to interact with video.js
  11781. *
  11782. * @class HlsHandler
  11783. * @extends videojs.Component
  11784. * @param {Object} source the soruce object
  11785. * @param {Tech} tech the parent tech object
  11786. * @param {Object} options optional and required options
  11787. */
  11788. var HlsHandler = (function (_Component) {
  11789. _inherits(HlsHandler, _Component);
  11790. function HlsHandler(source, tech, options) {
  11791. var _this = this;
  11792. _classCallCheck(this, HlsHandler);
  11793. _get(Object.getPrototypeOf(HlsHandler.prototype), 'constructor', this).call(this, tech);
  11794. // tech.player() is deprecated but setup a reference to HLS for
  11795. // backwards-compatibility
  11796. if (tech.options_ && tech.options_.playerId) {
  11797. var _player = (0, _videoJs2['default'])(tech.options_.playerId);
  11798. if (!_player.hasOwnProperty('hls')) {
  11799. Object.defineProperty(_player, 'hls', {
  11800. get: function get() {
  11801. _videoJs2['default'].log.warn('player.hls is deprecated. Use player.tech.hls instead.');
  11802. return _this;
  11803. }
  11804. });
  11805. }
  11806. }
  11807. this.options_ = _videoJs2['default'].mergeOptions(_videoJs2['default'].options.hls || {}, options.hls);
  11808. this.tech_ = tech;
  11809. this.source_ = source;
  11810. // start playlist selection at a reasonable bandwidth for
  11811. // broadband internet
  11812. // 0.5 Mbps
  11813. this.bandwidth = this.options_.bandwidth || 4194304;
  11814. this.bytesReceived = 0;
  11815. // listen for fullscreenchange events for this player so that we
  11816. // can adjust our quality selection quickly
  11817. this.on(_globalDocument2['default'], ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], function (event) {
  11818. var fullscreenElement = _globalDocument2['default'].fullscreenElement || _globalDocument2['default'].webkitFullscreenElement || _globalDocument2['default'].mozFullScreenElement || _globalDocument2['default'].msFullscreenElement;
  11819. if (fullscreenElement && fullscreenElement.contains(_this.tech_.el())) {
  11820. _this.masterPlaylistController_.fastQualityChange_();
  11821. }
  11822. });
  11823. this.on(this.tech_, 'seeking', function () {
  11824. this.setCurrentTime(this.tech_.currentTime());
  11825. });
  11826. this.on(this.tech_, 'error', function () {
  11827. if (this.masterPlaylistController_) {
  11828. this.masterPlaylistController_.pauseLoading();
  11829. }
  11830. });
  11831. this.audioTrackChange_ = function () {
  11832. _this.masterPlaylistController_.useAudio();
  11833. };
  11834. this.on(this.tech_, 'play', this.play);
  11835. }
  11836. /**
  11837. * The Source Handler object, which informs video.js what additional
  11838. * MIME types are supported and sets up playback. It is registered
  11839. * automatically to the appropriate tech based on the capabilities of
  11840. * the browser it is running in. It is not necessary to use or modify
  11841. * this object in normal usage.
  11842. */
  11843. /**
  11844. * called when player.src gets called, handle a new source
  11845. *
  11846. * @param {Object} src the source object to handle
  11847. */
  11848. _createClass(HlsHandler, [{
  11849. key: 'src',
  11850. value: function src(_src) {
  11851. var _this2 = this;
  11852. // do nothing if the src is falsey
  11853. if (!_src) {
  11854. return;
  11855. }
  11856. ['withCredentials', 'bandwidth'].forEach(function (option) {
  11857. if (typeof _this2.source_[option] !== 'undefined') {
  11858. _this2.options_[option] = _this2.source_[option];
  11859. }
  11860. });
  11861. this.options_.url = this.source_.src;
  11862. this.options_.tech = this.tech_;
  11863. this.options_.externHls = Hls;
  11864. this.options_.bandwidth = this.bandwidth;
  11865. this.masterPlaylistController_ = new _masterPlaylistController2['default'](this.options_);
  11866. // `this` in selectPlaylist should be the HlsHandler for backwards
  11867. // compatibility with < v2
  11868. this.masterPlaylistController_.selectPlaylist = Hls.STANDARD_PLAYLIST_SELECTOR.bind(this);
  11869. // re-expose some internal objects for backwards compatibility with < v2
  11870. this.playlists = this.masterPlaylistController_.masterPlaylistLoader_;
  11871. this.mediaSource = this.masterPlaylistController_.mediaSource;
  11872. // Proxy assignment of some properties to the master playlist
  11873. // controller. Using a custom property for backwards compatibility
  11874. // with < v2
  11875. Object.defineProperties(this, {
  11876. selectPlaylist: {
  11877. get: function get() {
  11878. return this.masterPlaylistController_.selectPlaylist;
  11879. },
  11880. set: function set(selectPlaylist) {
  11881. this.masterPlaylistController_.selectPlaylist = selectPlaylist.bind(this);
  11882. }
  11883. },
  11884. bandwidth: {
  11885. get: function get() {
  11886. return this.masterPlaylistController_.mainSegmentLoader_.bandwidth;
  11887. },
  11888. set: function set(bandwidth) {
  11889. this.masterPlaylistController_.mainSegmentLoader_.bandwidth = bandwidth;
  11890. }
  11891. }
  11892. });
  11893. this.tech_.one('canplay', this.masterPlaylistController_.setupFirstPlay.bind(this.masterPlaylistController_));
  11894. this.masterPlaylistController_.on('sourceopen', function () {
  11895. _this2.tech_.audioTracks().addEventListener('change', _this2.audioTrackChange_);
  11896. });
  11897. this.masterPlaylistController_.on('audioinfo', function (e) {
  11898. if (!_videoJs2['default'].browser.IS_FIREFOX || !_this2.audioInfo_ || !objectChanged(_this2.audioInfo_, e.info)) {
  11899. _this2.audioInfo_ = e.info;
  11900. return;
  11901. }
  11902. 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';
  11903. var enabledTrack = undefined;
  11904. var defaultTrack = undefined;
  11905. _this2.masterPlaylistController_.audioTracks_.forEach(function (t) {
  11906. if (!defaultTrack && t['default']) {
  11907. defaultTrack = t;
  11908. }
  11909. if (!enabledTrack && t.enabled) {
  11910. enabledTrack = t;
  11911. }
  11912. });
  11913. // they did not switch audiotracks
  11914. // blacklist the current playlist
  11915. if (!enabledTrack.getLoader(_this2.activeAudioGroup_())) {
  11916. 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!';
  11917. _this2.masterPlaylistController_.blacklistCurrentPlaylist();
  11918. } else {
  11919. 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!');
  11920. defaultTrack.enabled = true;
  11921. _this2.tech_.audioTracks().removeTrack(enabledTrack);
  11922. }
  11923. _videoJs2['default'].log.warn(error);
  11924. _this2.masterPlaylistController_.useAudio();
  11925. });
  11926. this.masterPlaylistController_.on('selectedinitialmedia', function () {
  11927. // clear current audioTracks
  11928. _this2.tech_.clearTracks('audio');
  11929. _this2.masterPlaylistController_.audioTracks_.forEach(function (track) {
  11930. _this2.tech_.audioTracks().addTrack(track);
  11931. });
  11932. });
  11933. // the bandwidth of the primary segment loader is our best
  11934. // estimate of overall bandwidth
  11935. this.on(this.masterPlaylistController_, 'progress', function () {
  11936. this.bandwidth = this.masterPlaylistController_.mainSegmentLoader_.bandwidth;
  11937. this.tech_.trigger('progress');
  11938. });
  11939. // do nothing if the tech has been disposed already
  11940. // this can occur if someone sets the src in player.ready(), for instance
  11941. if (!this.tech_.el()) {
  11942. return;
  11943. }
  11944. this.tech_.src(_videoJs2['default'].URL.createObjectURL(this.masterPlaylistController_.mediaSource));
  11945. }
  11946. /**
  11947. * a helper for grabbing the active audio group from MasterPlaylistController
  11948. *
  11949. * @private
  11950. */
  11951. }, {
  11952. key: 'activeAudioGroup_',
  11953. value: function activeAudioGroup_() {
  11954. return this.masterPlaylistController_.activeAudioGroup();
  11955. }
  11956. /**
  11957. * Begin playing the video.
  11958. */
  11959. }, {
  11960. key: 'play',
  11961. value: function play() {
  11962. this.masterPlaylistController_.play();
  11963. }
  11964. /**
  11965. * a wrapper around the function in MasterPlaylistController
  11966. */
  11967. }, {
  11968. key: 'setCurrentTime',
  11969. value: function setCurrentTime(currentTime) {
  11970. this.masterPlaylistController_.setCurrentTime(currentTime);
  11971. }
  11972. /**
  11973. * a wrapper around the function in MasterPlaylistController
  11974. */
  11975. }, {
  11976. key: 'duration',
  11977. value: function duration() {
  11978. return this.masterPlaylistController_.duration();
  11979. }
  11980. /**
  11981. * a wrapper around the function in MasterPlaylistController
  11982. */
  11983. }, {
  11984. key: 'seekable',
  11985. value: function seekable() {
  11986. return this.masterPlaylistController_.seekable();
  11987. }
  11988. /**
  11989. * Abort all outstanding work and cleanup.
  11990. */
  11991. }, {
  11992. key: 'dispose',
  11993. value: function dispose() {
  11994. if (this.masterPlaylistController_) {
  11995. this.masterPlaylistController_.dispose();
  11996. }
  11997. this.tech_.audioTracks().removeEventListener('change', this.audioTrackChange_);
  11998. _get(Object.getPrototypeOf(HlsHandler.prototype), 'dispose', this).call(this);
  11999. }
  12000. }]);
  12001. return HlsHandler;
  12002. })(Component);
  12003. var HlsSourceHandler = function HlsSourceHandler(mode) {
  12004. return {
  12005. canHandleSource: function canHandleSource(srcObj) {
  12006. // this forces video.js to skip this tech/mode if its not the one we have been
  12007. // overriden to use, by returing that we cannot handle the source.
  12008. if (_videoJs2['default'].options.hls && _videoJs2['default'].options.hls.mode && _videoJs2['default'].options.hls.mode !== mode) {
  12009. return false;
  12010. }
  12011. return HlsSourceHandler.canPlayType(srcObj.type);
  12012. },
  12013. handleSource: function handleSource(source, tech, options) {
  12014. if (mode === 'flash') {
  12015. // We need to trigger this asynchronously to give others the chance
  12016. // to bind to the event when a source is set at player creation
  12017. tech.setTimeout(function () {
  12018. tech.trigger('loadstart');
  12019. }, 1);
  12020. }
  12021. var settings = _videoJs2['default'].mergeOptions(options, { hls: { mode: mode } });
  12022. tech.hls = new HlsHandler(source, tech, settings);
  12023. tech.hls.xhr = (0, _xhr2['default'])();
  12024. // Use a global `before` function if specified on videojs.Hls.xhr
  12025. // but still allow for a per-player override
  12026. if (_videoJs2['default'].Hls.xhr.beforeRequest) {
  12027. tech.hls.xhr.beforeRequest = _videoJs2['default'].Hls.xhr.beforeRequest;
  12028. }
  12029. tech.hls.src(source.src);
  12030. return tech.hls;
  12031. },
  12032. canPlayType: function canPlayType(type) {
  12033. if (HlsSourceHandler.canPlayType(type)) {
  12034. return 'maybe';
  12035. }
  12036. return '';
  12037. }
  12038. };
  12039. };
  12040. /**
  12041. * A comparator function to sort two playlist object by bandwidth.
  12042. *
  12043. * @param {Object} left a media playlist object
  12044. * @param {Object} right a media playlist object
  12045. * @return {Number} Greater than zero if the bandwidth attribute of
  12046. * left is greater than the corresponding attribute of right. Less
  12047. * than zero if the bandwidth of right is greater than left and
  12048. * exactly zero if the two are equal.
  12049. */
  12050. Hls.comparePlaylistBandwidth = function (left, right) {
  12051. var leftBandwidth = undefined;
  12052. var rightBandwidth = undefined;
  12053. if (left.attributes && left.attributes.BANDWIDTH) {
  12054. leftBandwidth = left.attributes.BANDWIDTH;
  12055. }
  12056. leftBandwidth = leftBandwidth || window.Number.MAX_VALUE;
  12057. if (right.attributes && right.attributes.BANDWIDTH) {
  12058. rightBandwidth = right.attributes.BANDWIDTH;
  12059. }
  12060. rightBandwidth = rightBandwidth || window.Number.MAX_VALUE;
  12061. return leftBandwidth - rightBandwidth;
  12062. };
  12063. /**
  12064. * A comparator function to sort two playlist object by resolution (width).
  12065. * @param {Object} left a media playlist object
  12066. * @param {Object} right a media playlist object
  12067. * @return {Number} Greater than zero if the resolution.width attribute of
  12068. * left is greater than the corresponding attribute of right. Less
  12069. * than zero if the resolution.width of right is greater than left and
  12070. * exactly zero if the two are equal.
  12071. */
  12072. Hls.comparePlaylistResolution = function (left, right) {
  12073. var leftWidth = undefined;
  12074. var rightWidth = undefined;
  12075. if (left.attributes && left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
  12076. leftWidth = left.attributes.RESOLUTION.width;
  12077. }
  12078. leftWidth = leftWidth || window.Number.MAX_VALUE;
  12079. if (right.attributes && right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
  12080. rightWidth = right.attributes.RESOLUTION.width;
  12081. }
  12082. rightWidth = rightWidth || window.Number.MAX_VALUE;
  12083. // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
  12084. // have the same media dimensions/ resolution
  12085. if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
  12086. return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
  12087. }
  12088. return leftWidth - rightWidth;
  12089. };
  12090. HlsSourceHandler.canPlayType = function (type) {
  12091. var mpegurlRE = /^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i;
  12092. // favor native HLS support if it's available
  12093. if (Hls.supportsNativeHls) {
  12094. return false;
  12095. }
  12096. return mpegurlRE.test(type);
  12097. };
  12098. if (typeof _videoJs2['default'].MediaSource === 'undefined' || typeof _videoJs2['default'].URL === 'undefined') {
  12099. _videoJs2['default'].MediaSource = _videojsContribMediaSources.MediaSource;
  12100. _videoJs2['default'].URL = _videojsContribMediaSources.URL;
  12101. }
  12102. // register source handlers with the appropriate techs
  12103. if (_videojsContribMediaSources.MediaSource.supportsNativeMediaSources()) {
  12104. _videoJs2['default'].getComponent('Html5').registerSourceHandler(HlsSourceHandler('html5'));
  12105. }
  12106. if (window.Uint8Array) {
  12107. _videoJs2['default'].getComponent('Flash').registerSourceHandler(HlsSourceHandler('flash'));
  12108. }
  12109. _videoJs2['default'].HlsHandler = HlsHandler;
  12110. _videoJs2['default'].HlsSourceHandler = HlsSourceHandler;
  12111. _videoJs2['default'].Hls = Hls;
  12112. _videoJs2['default'].m3u8 = _m3u82['default'];
  12113. _videoJs2['default'].registerComponent('Hls', Hls);
  12114. _videoJs2['default'].options.hls = _videoJs2['default'].options.hls || {};
  12115. module.exports = {
  12116. Hls: Hls,
  12117. HlsHandler: HlsHandler,
  12118. HlsSourceHandler: HlsSourceHandler
  12119. };
  12120. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12121. },{"./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)
  12122. });