mux-mp4.js 209 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052
  1. (function(f){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.muxjs = f()})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. /**
  3. * mux.js
  4. *
  5. * Copyright (c) Brightcove
  6. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  7. *
  8. * A stream-based aac to mp4 converter. This utility can be used to
  9. * deliver mp4s to a SourceBuffer on platforms that support native
  10. * Media Source Extensions.
  11. */
  12. 'use strict';
  13. var Stream = require(31);
  14. var aacUtils = require(2);
  15. // Constants
  16. var AacStream;
  17. /**
  18. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  19. */
  20. AacStream = function() {
  21. var
  22. everything = new Uint8Array(),
  23. timeStamp = 0;
  24. AacStream.prototype.init.call(this);
  25. this.setTimestamp = function(timestamp) {
  26. timeStamp = timestamp;
  27. };
  28. this.push = function(bytes) {
  29. var
  30. frameSize = 0,
  31. byteIndex = 0,
  32. bytesLeft,
  33. chunk,
  34. packet,
  35. tempLength;
  36. // If there are bytes remaining from the last segment, prepend them to the
  37. // bytes that were pushed in
  38. if (everything.length) {
  39. tempLength = everything.length;
  40. everything = new Uint8Array(bytes.byteLength + tempLength);
  41. everything.set(everything.subarray(0, tempLength));
  42. everything.set(bytes, tempLength);
  43. } else {
  44. everything = bytes;
  45. }
  46. while (everything.length - byteIndex >= 3) {
  47. if ((everything[byteIndex] === 'I'.charCodeAt(0)) &&
  48. (everything[byteIndex + 1] === 'D'.charCodeAt(0)) &&
  49. (everything[byteIndex + 2] === '3'.charCodeAt(0))) {
  50. // Exit early because we don't have enough to parse
  51. // the ID3 tag header
  52. if (everything.length - byteIndex < 10) {
  53. break;
  54. }
  55. // check framesize
  56. frameSize = aacUtils.parseId3TagSize(everything, byteIndex);
  57. // Exit early if we don't have enough in the buffer
  58. // to emit a full packet
  59. // Add to byteIndex to support multiple ID3 tags in sequence
  60. if (byteIndex + frameSize > everything.length) {
  61. break;
  62. }
  63. chunk = {
  64. type: 'timed-metadata',
  65. data: everything.subarray(byteIndex, byteIndex + frameSize)
  66. };
  67. this.trigger('data', chunk);
  68. byteIndex += frameSize;
  69. continue;
  70. } else if (((everything[byteIndex] & 0xff) === 0xff) &&
  71. ((everything[byteIndex + 1] & 0xf0) === 0xf0)) {
  72. // Exit early because we don't have enough to parse
  73. // the ADTS frame header
  74. if (everything.length - byteIndex < 7) {
  75. break;
  76. }
  77. frameSize = aacUtils.parseAdtsSize(everything, byteIndex);
  78. // Exit early if we don't have enough in the buffer
  79. // to emit a full packet
  80. if (byteIndex + frameSize > everything.length) {
  81. break;
  82. }
  83. packet = {
  84. type: 'audio',
  85. data: everything.subarray(byteIndex, byteIndex + frameSize),
  86. pts: timeStamp,
  87. dts: timeStamp
  88. };
  89. this.trigger('data', packet);
  90. byteIndex += frameSize;
  91. continue;
  92. }
  93. byteIndex++;
  94. }
  95. bytesLeft = everything.length - byteIndex;
  96. if (bytesLeft > 0) {
  97. everything = everything.subarray(byteIndex);
  98. } else {
  99. everything = new Uint8Array();
  100. }
  101. };
  102. this.reset = function() {
  103. everything = new Uint8Array();
  104. this.trigger('reset');
  105. };
  106. this.endTimeline = function() {
  107. everything = new Uint8Array();
  108. this.trigger('endedtimeline');
  109. };
  110. };
  111. AacStream.prototype = new Stream();
  112. module.exports = AacStream;
  113. },{"2":2,"31":31}],2:[function(require,module,exports){
  114. /**
  115. * mux.js
  116. *
  117. * Copyright (c) Brightcove
  118. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  119. *
  120. * Utilities to detect basic properties and metadata about Aac data.
  121. */
  122. 'use strict';
  123. var ADTS_SAMPLING_FREQUENCIES = [
  124. 96000,
  125. 88200,
  126. 64000,
  127. 48000,
  128. 44100,
  129. 32000,
  130. 24000,
  131. 22050,
  132. 16000,
  133. 12000,
  134. 11025,
  135. 8000,
  136. 7350
  137. ];
  138. var parseId3TagSize = function(header, byteIndex) {
  139. var
  140. returnSize = (header[byteIndex + 6] << 21) |
  141. (header[byteIndex + 7] << 14) |
  142. (header[byteIndex + 8] << 7) |
  143. (header[byteIndex + 9]),
  144. flags = header[byteIndex + 5],
  145. footerPresent = (flags & 16) >> 4;
  146. // if we get a negative returnSize clamp it to 0
  147. returnSize = returnSize >= 0 ? returnSize : 0;
  148. if (footerPresent) {
  149. return returnSize + 20;
  150. }
  151. return returnSize + 10;
  152. };
  153. var getId3Offset = function(data, offset) {
  154. if (data.length - offset < 10 ||
  155. data[offset] !== 'I'.charCodeAt(0) ||
  156. data[offset + 1] !== 'D'.charCodeAt(0) ||
  157. data[offset + 2] !== '3'.charCodeAt(0)) {
  158. return offset;
  159. }
  160. offset += parseId3TagSize(data, offset);
  161. return getId3Offset(data, offset);
  162. };
  163. // TODO: use vhs-utils
  164. var isLikelyAacData = function(data) {
  165. var offset = getId3Offset(data, 0);
  166. return data.length >= offset + 2 &&
  167. (data[offset] & 0xFF) === 0xFF &&
  168. (data[offset + 1] & 0xF0) === 0xF0 &&
  169. // verify that the 2 layer bits are 0, aka this
  170. // is not mp3 data but aac data.
  171. (data[offset + 1] & 0x16) === 0x10;
  172. };
  173. var parseSyncSafeInteger = function(data) {
  174. return (data[0] << 21) |
  175. (data[1] << 14) |
  176. (data[2] << 7) |
  177. (data[3]);
  178. };
  179. // return a percent-encoded representation of the specified byte range
  180. // @see http://en.wikipedia.org/wiki/Percent-encoding
  181. var percentEncode = function(bytes, start, end) {
  182. var i, result = '';
  183. for (i = start; i < end; i++) {
  184. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  185. }
  186. return result;
  187. };
  188. // return the string representation of the specified byte range,
  189. // interpreted as ISO-8859-1.
  190. var parseIso88591 = function(bytes, start, end) {
  191. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  192. };
  193. var parseAdtsSize = function(header, byteIndex) {
  194. var
  195. lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  196. middle = header[byteIndex + 4] << 3,
  197. highTwo = header[byteIndex + 3] & 0x3 << 11;
  198. return (highTwo | middle) | lowThree;
  199. };
  200. var parseType = function(header, byteIndex) {
  201. if ((header[byteIndex] === 'I'.charCodeAt(0)) &&
  202. (header[byteIndex + 1] === 'D'.charCodeAt(0)) &&
  203. (header[byteIndex + 2] === '3'.charCodeAt(0))) {
  204. return 'timed-metadata';
  205. } else if ((header[byteIndex] & 0xff === 0xff) &&
  206. ((header[byteIndex + 1] & 0xf0) === 0xf0)) {
  207. return 'audio';
  208. }
  209. return null;
  210. };
  211. var parseSampleRate = function(packet) {
  212. var i = 0;
  213. while (i + 5 < packet.length) {
  214. if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
  215. // If a valid header was not found, jump one forward and attempt to
  216. // find a valid ADTS header starting at the next byte
  217. i++;
  218. continue;
  219. }
  220. return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
  221. }
  222. return null;
  223. };
  224. var parseAacTimestamp = function(packet) {
  225. var frameStart, frameSize, frame, frameHeader;
  226. // find the start of the first frame and the end of the tag
  227. frameStart = 10;
  228. if (packet[5] & 0x40) {
  229. // advance the frame start past the extended header
  230. frameStart += 4; // header size field
  231. frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
  232. }
  233. // parse one or more ID3 frames
  234. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  235. do {
  236. // determine the number of bytes in this frame
  237. frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
  238. if (frameSize < 1) {
  239. return null;
  240. }
  241. frameHeader = String.fromCharCode(packet[frameStart],
  242. packet[frameStart + 1],
  243. packet[frameStart + 2],
  244. packet[frameStart + 3]);
  245. if (frameHeader === 'PRIV') {
  246. frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
  247. for (var i = 0; i < frame.byteLength; i++) {
  248. if (frame[i] === 0) {
  249. var owner = parseIso88591(frame, 0, i);
  250. if (owner === 'com.apple.streaming.transportStreamTimestamp') {
  251. var d = frame.subarray(i + 1);
  252. var size = ((d[3] & 0x01) << 30) |
  253. (d[4] << 22) |
  254. (d[5] << 14) |
  255. (d[6] << 6) |
  256. (d[7] >>> 2);
  257. size *= 4;
  258. size += d[7] & 0x03;
  259. return size;
  260. }
  261. break;
  262. }
  263. }
  264. }
  265. frameStart += 10; // advance past the frame header
  266. frameStart += frameSize; // advance past the frame body
  267. } while (frameStart < packet.byteLength);
  268. return null;
  269. };
  270. module.exports = {
  271. isLikelyAacData: isLikelyAacData,
  272. parseId3TagSize: parseId3TagSize,
  273. parseAdtsSize: parseAdtsSize,
  274. parseType: parseType,
  275. parseSampleRate: parseSampleRate,
  276. parseAacTimestamp: parseAacTimestamp
  277. };
  278. },{}],3:[function(require,module,exports){
  279. /**
  280. * mux.js
  281. *
  282. * Copyright (c) Brightcove
  283. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  284. */
  285. 'use strict';
  286. var Stream = require(31);
  287. var ONE_SECOND_IN_TS = require(29).ONE_SECOND_IN_TS;
  288. var AdtsStream;
  289. var
  290. ADTS_SAMPLING_FREQUENCIES = [
  291. 96000,
  292. 88200,
  293. 64000,
  294. 48000,
  295. 44100,
  296. 32000,
  297. 24000,
  298. 22050,
  299. 16000,
  300. 12000,
  301. 11025,
  302. 8000,
  303. 7350
  304. ];
  305. /*
  306. * Accepts a ElementaryStream and emits data events with parsed
  307. * AAC Audio Frames of the individual packets. Input audio in ADTS
  308. * format is unpacked and re-emitted as AAC frames.
  309. *
  310. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  311. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  312. */
  313. AdtsStream = function(handlePartialSegments) {
  314. var
  315. buffer,
  316. frameNum = 0;
  317. AdtsStream.prototype.init.call(this);
  318. this.push = function(packet) {
  319. var
  320. i = 0,
  321. frameLength,
  322. protectionSkipBytes,
  323. frameEnd,
  324. oldBuffer,
  325. sampleCount,
  326. adtsFrameDuration;
  327. if (!handlePartialSegments) {
  328. frameNum = 0;
  329. }
  330. if (packet.type !== 'audio') {
  331. // ignore non-audio data
  332. return;
  333. }
  334. // Prepend any data in the buffer to the input data so that we can parse
  335. // aac frames the cross a PES packet boundary
  336. if (buffer) {
  337. oldBuffer = buffer;
  338. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  339. buffer.set(oldBuffer);
  340. buffer.set(packet.data, oldBuffer.byteLength);
  341. } else {
  342. buffer = packet.data;
  343. }
  344. // unpack any ADTS frames which have been fully received
  345. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  346. while (i + 5 < buffer.length) {
  347. // Look for the start of an ADTS header..
  348. if ((buffer[i] !== 0xFF) || (buffer[i + 1] & 0xF6) !== 0xF0) {
  349. // If a valid header was not found, jump one forward and attempt to
  350. // find a valid ADTS header starting at the next byte
  351. i++;
  352. continue;
  353. }
  354. // The protection skip bit tells us if we have 2 bytes of CRC data at the
  355. // end of the ADTS header
  356. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2;
  357. // Frame length is a 13 bit integer starting 16 bits from the
  358. // end of the sync sequence
  359. frameLength = ((buffer[i + 3] & 0x03) << 11) |
  360. (buffer[i + 4] << 3) |
  361. ((buffer[i + 5] & 0xe0) >> 5);
  362. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  363. adtsFrameDuration = (sampleCount * ONE_SECOND_IN_TS) /
  364. ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2];
  365. frameEnd = i + frameLength;
  366. // If we don't have enough data to actually finish this ADTS frame, return
  367. // and wait for more data
  368. if (buffer.byteLength < frameEnd) {
  369. return;
  370. }
  371. // Otherwise, deliver the complete AAC frame
  372. this.trigger('data', {
  373. pts: packet.pts + (frameNum * adtsFrameDuration),
  374. dts: packet.dts + (frameNum * adtsFrameDuration),
  375. sampleCount: sampleCount,
  376. audioobjecttype: ((buffer[i + 2] >>> 6) & 0x03) + 1,
  377. channelcount: ((buffer[i + 2] & 1) << 2) |
  378. ((buffer[i + 3] & 0xc0) >>> 6),
  379. samplerate: ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2],
  380. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  381. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  382. samplesize: 16,
  383. data: buffer.subarray(i + 7 + protectionSkipBytes, frameEnd)
  384. });
  385. frameNum++;
  386. // If the buffer is empty, clear it and return
  387. if (buffer.byteLength === frameEnd) {
  388. buffer = undefined;
  389. return;
  390. }
  391. // Remove the finished frame from the buffer and start the process again
  392. buffer = buffer.subarray(frameEnd);
  393. }
  394. };
  395. this.flush = function() {
  396. frameNum = 0;
  397. this.trigger('done');
  398. };
  399. this.reset = function() {
  400. buffer = void 0;
  401. this.trigger('reset');
  402. };
  403. this.endTimeline = function() {
  404. buffer = void 0;
  405. this.trigger('endedtimeline');
  406. };
  407. };
  408. AdtsStream.prototype = new Stream();
  409. module.exports = AdtsStream;
  410. },{"29":29,"31":31}],4:[function(require,module,exports){
  411. /**
  412. * mux.js
  413. *
  414. * Copyright (c) Brightcove
  415. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  416. */
  417. 'use strict';
  418. var Stream = require(31);
  419. var ExpGolomb = require(30);
  420. var H264Stream, NalByteStream;
  421. var PROFILES_WITH_OPTIONAL_SPS_DATA;
  422. /**
  423. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  424. */
  425. NalByteStream = function() {
  426. var
  427. syncPoint = 0,
  428. i,
  429. buffer;
  430. NalByteStream.prototype.init.call(this);
  431. /*
  432. * Scans a byte stream and triggers a data event with the NAL units found.
  433. * @param {Object} data Event received from H264Stream
  434. * @param {Uint8Array} data.data The h264 byte stream to be scanned
  435. *
  436. * @see H264Stream.push
  437. */
  438. this.push = function(data) {
  439. var swapBuffer;
  440. if (!buffer) {
  441. buffer = data.data;
  442. } else {
  443. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  444. swapBuffer.set(buffer);
  445. swapBuffer.set(data.data, buffer.byteLength);
  446. buffer = swapBuffer;
  447. }
  448. var len = buffer.byteLength;
  449. // Rec. ITU-T H.264, Annex B
  450. // scan for NAL unit boundaries
  451. // a match looks like this:
  452. // 0 0 1 .. NAL .. 0 0 1
  453. // ^ sync point ^ i
  454. // or this:
  455. // 0 0 1 .. NAL .. 0 0 0
  456. // ^ sync point ^ i
  457. // advance the sync point to a NAL start, if necessary
  458. for (; syncPoint < len - 3; syncPoint++) {
  459. if (buffer[syncPoint + 2] === 1) {
  460. // the sync point is properly aligned
  461. i = syncPoint + 5;
  462. break;
  463. }
  464. }
  465. while (i < len) {
  466. // look at the current byte to determine if we've hit the end of
  467. // a NAL unit boundary
  468. switch (buffer[i]) {
  469. case 0:
  470. // skip past non-sync sequences
  471. if (buffer[i - 1] !== 0) {
  472. i += 2;
  473. break;
  474. } else if (buffer[i - 2] !== 0) {
  475. i++;
  476. break;
  477. }
  478. // deliver the NAL unit if it isn't empty
  479. if (syncPoint + 3 !== i - 2) {
  480. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  481. }
  482. // drop trailing zeroes
  483. do {
  484. i++;
  485. } while (buffer[i] !== 1 && i < len);
  486. syncPoint = i - 2;
  487. i += 3;
  488. break;
  489. case 1:
  490. // skip past non-sync sequences
  491. if (buffer[i - 1] !== 0 ||
  492. buffer[i - 2] !== 0) {
  493. i += 3;
  494. break;
  495. }
  496. // deliver the NAL unit
  497. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  498. syncPoint = i - 2;
  499. i += 3;
  500. break;
  501. default:
  502. // the current byte isn't a one or zero, so it cannot be part
  503. // of a sync sequence
  504. i += 3;
  505. break;
  506. }
  507. }
  508. // filter out the NAL units that were delivered
  509. buffer = buffer.subarray(syncPoint);
  510. i -= syncPoint;
  511. syncPoint = 0;
  512. };
  513. this.reset = function() {
  514. buffer = null;
  515. syncPoint = 0;
  516. this.trigger('reset');
  517. };
  518. this.flush = function() {
  519. // deliver the last buffered NAL unit
  520. if (buffer && buffer.byteLength > 3) {
  521. this.trigger('data', buffer.subarray(syncPoint + 3));
  522. }
  523. // reset the stream state
  524. buffer = null;
  525. syncPoint = 0;
  526. this.trigger('done');
  527. };
  528. this.endTimeline = function() {
  529. this.flush();
  530. this.trigger('endedtimeline');
  531. };
  532. };
  533. NalByteStream.prototype = new Stream();
  534. // values of profile_idc that indicate additional fields are included in the SPS
  535. // see Recommendation ITU-T H.264 (4/2013),
  536. // 7.3.2.1.1 Sequence parameter set data syntax
  537. PROFILES_WITH_OPTIONAL_SPS_DATA = {
  538. 100: true,
  539. 110: true,
  540. 122: true,
  541. 244: true,
  542. 44: true,
  543. 83: true,
  544. 86: true,
  545. 118: true,
  546. 128: true,
  547. 138: true,
  548. 139: true,
  549. 134: true
  550. };
  551. /**
  552. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  553. * events.
  554. */
  555. H264Stream = function() {
  556. var
  557. nalByteStream = new NalByteStream(),
  558. self,
  559. trackId,
  560. currentPts,
  561. currentDts,
  562. discardEmulationPreventionBytes,
  563. readSequenceParameterSet,
  564. skipScalingList;
  565. H264Stream.prototype.init.call(this);
  566. self = this;
  567. /*
  568. * Pushes a packet from a stream onto the NalByteStream
  569. *
  570. * @param {Object} packet - A packet received from a stream
  571. * @param {Uint8Array} packet.data - The raw bytes of the packet
  572. * @param {Number} packet.dts - Decode timestamp of the packet
  573. * @param {Number} packet.pts - Presentation timestamp of the packet
  574. * @param {Number} packet.trackId - The id of the h264 track this packet came from
  575. * @param {('video'|'audio')} packet.type - The type of packet
  576. *
  577. */
  578. this.push = function(packet) {
  579. if (packet.type !== 'video') {
  580. return;
  581. }
  582. trackId = packet.trackId;
  583. currentPts = packet.pts;
  584. currentDts = packet.dts;
  585. nalByteStream.push(packet);
  586. };
  587. /*
  588. * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
  589. * for the NALUs to the next stream component.
  590. * Also, preprocess caption and sequence parameter NALUs.
  591. *
  592. * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
  593. * @see NalByteStream.push
  594. */
  595. nalByteStream.on('data', function(data) {
  596. var
  597. event = {
  598. trackId: trackId,
  599. pts: currentPts,
  600. dts: currentDts,
  601. data: data
  602. };
  603. switch (data[0] & 0x1f) {
  604. case 0x05:
  605. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  606. break;
  607. case 0x06:
  608. event.nalUnitType = 'sei_rbsp';
  609. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  610. break;
  611. case 0x07:
  612. event.nalUnitType = 'seq_parameter_set_rbsp';
  613. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  614. event.config = readSequenceParameterSet(event.escapedRBSP);
  615. break;
  616. case 0x08:
  617. event.nalUnitType = 'pic_parameter_set_rbsp';
  618. break;
  619. case 0x09:
  620. event.nalUnitType = 'access_unit_delimiter_rbsp';
  621. break;
  622. default:
  623. break;
  624. }
  625. // This triggers data on the H264Stream
  626. self.trigger('data', event);
  627. });
  628. nalByteStream.on('done', function() {
  629. self.trigger('done');
  630. });
  631. nalByteStream.on('partialdone', function() {
  632. self.trigger('partialdone');
  633. });
  634. nalByteStream.on('reset', function() {
  635. self.trigger('reset');
  636. });
  637. nalByteStream.on('endedtimeline', function() {
  638. self.trigger('endedtimeline');
  639. });
  640. this.flush = function() {
  641. nalByteStream.flush();
  642. };
  643. this.partialFlush = function() {
  644. nalByteStream.partialFlush();
  645. };
  646. this.reset = function() {
  647. nalByteStream.reset();
  648. };
  649. this.endTimeline = function() {
  650. nalByteStream.endTimeline();
  651. };
  652. /**
  653. * Advance the ExpGolomb decoder past a scaling list. The scaling
  654. * list is optionally transmitted as part of a sequence parameter
  655. * set and is not relevant to transmuxing.
  656. * @param count {number} the number of entries in this scaling list
  657. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  658. * start of a scaling list
  659. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  660. */
  661. skipScalingList = function(count, expGolombDecoder) {
  662. var
  663. lastScale = 8,
  664. nextScale = 8,
  665. j,
  666. deltaScale;
  667. for (j = 0; j < count; j++) {
  668. if (nextScale !== 0) {
  669. deltaScale = expGolombDecoder.readExpGolomb();
  670. nextScale = (lastScale + deltaScale + 256) % 256;
  671. }
  672. lastScale = (nextScale === 0) ? lastScale : nextScale;
  673. }
  674. };
  675. /**
  676. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  677. * Sequence Payload"
  678. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  679. * unit
  680. * @return {Uint8Array} the RBSP without any Emulation
  681. * Prevention Bytes
  682. */
  683. discardEmulationPreventionBytes = function(data) {
  684. var
  685. length = data.byteLength,
  686. emulationPreventionBytesPositions = [],
  687. i = 1,
  688. newLength, newData;
  689. // Find all `Emulation Prevention Bytes`
  690. while (i < length - 2) {
  691. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  692. emulationPreventionBytesPositions.push(i + 2);
  693. i += 2;
  694. } else {
  695. i++;
  696. }
  697. }
  698. // If no Emulation Prevention Bytes were found just return the original
  699. // array
  700. if (emulationPreventionBytesPositions.length === 0) {
  701. return data;
  702. }
  703. // Create a new array to hold the NAL unit data
  704. newLength = length - emulationPreventionBytesPositions.length;
  705. newData = new Uint8Array(newLength);
  706. var sourceIndex = 0;
  707. for (i = 0; i < newLength; sourceIndex++, i++) {
  708. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  709. // Skip this byte
  710. sourceIndex++;
  711. // Remove this position index
  712. emulationPreventionBytesPositions.shift();
  713. }
  714. newData[i] = data[sourceIndex];
  715. }
  716. return newData;
  717. };
  718. /**
  719. * Read a sequence parameter set and return some interesting video
  720. * properties. A sequence parameter set is the H264 metadata that
  721. * describes the properties of upcoming video frames.
  722. * @param data {Uint8Array} the bytes of a sequence parameter set
  723. * @return {object} an object with configuration parsed from the
  724. * sequence parameter set, including the dimensions of the
  725. * associated video frames.
  726. */
  727. readSequenceParameterSet = function(data) {
  728. var
  729. frameCropLeftOffset = 0,
  730. frameCropRightOffset = 0,
  731. frameCropTopOffset = 0,
  732. frameCropBottomOffset = 0,
  733. sarScale = 1,
  734. expGolombDecoder, profileIdc, levelIdc, profileCompatibility,
  735. chromaFormatIdc, picOrderCntType,
  736. numRefFramesInPicOrderCntCycle, picWidthInMbsMinus1,
  737. picHeightInMapUnitsMinus1,
  738. frameMbsOnlyFlag,
  739. scalingListCount,
  740. sarRatio,
  741. aspectRatioIdc,
  742. i;
  743. expGolombDecoder = new ExpGolomb(data);
  744. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  745. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  746. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  747. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  748. // some profiles have more optional data we don't need
  749. if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
  750. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  751. if (chromaFormatIdc === 3) {
  752. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  753. }
  754. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  755. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  756. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  757. if (expGolombDecoder.readBoolean()) { // seq_scaling_matrix_present_flag
  758. scalingListCount = (chromaFormatIdc !== 3) ? 8 : 12;
  759. for (i = 0; i < scalingListCount; i++) {
  760. if (expGolombDecoder.readBoolean()) { // seq_scaling_list_present_flag[ i ]
  761. if (i < 6) {
  762. skipScalingList(16, expGolombDecoder);
  763. } else {
  764. skipScalingList(64, expGolombDecoder);
  765. }
  766. }
  767. }
  768. }
  769. }
  770. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  771. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  772. if (picOrderCntType === 0) {
  773. expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
  774. } else if (picOrderCntType === 1) {
  775. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  776. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  777. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  778. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  779. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  780. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  781. }
  782. }
  783. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  784. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  785. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  786. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  787. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  788. if (frameMbsOnlyFlag === 0) {
  789. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  790. }
  791. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  792. if (expGolombDecoder.readBoolean()) { // frame_cropping_flag
  793. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  794. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  795. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  796. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  797. }
  798. if (expGolombDecoder.readBoolean()) {
  799. // vui_parameters_present_flag
  800. if (expGolombDecoder.readBoolean()) {
  801. // aspect_ratio_info_present_flag
  802. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  803. switch (aspectRatioIdc) {
  804. case 1: sarRatio = [1, 1]; break;
  805. case 2: sarRatio = [12, 11]; break;
  806. case 3: sarRatio = [10, 11]; break;
  807. case 4: sarRatio = [16, 11]; break;
  808. case 5: sarRatio = [40, 33]; break;
  809. case 6: sarRatio = [24, 11]; break;
  810. case 7: sarRatio = [20, 11]; break;
  811. case 8: sarRatio = [32, 11]; break;
  812. case 9: sarRatio = [80, 33]; break;
  813. case 10: sarRatio = [18, 11]; break;
  814. case 11: sarRatio = [15, 11]; break;
  815. case 12: sarRatio = [64, 33]; break;
  816. case 13: sarRatio = [160, 99]; break;
  817. case 14: sarRatio = [4, 3]; break;
  818. case 15: sarRatio = [3, 2]; break;
  819. case 16: sarRatio = [2, 1]; break;
  820. case 255: {
  821. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 |
  822. expGolombDecoder.readUnsignedByte(),
  823. expGolombDecoder.readUnsignedByte() << 8 |
  824. expGolombDecoder.readUnsignedByte() ];
  825. break;
  826. }
  827. }
  828. if (sarRatio) {
  829. sarScale = sarRatio[0] / sarRatio[1];
  830. }
  831. }
  832. }
  833. return {
  834. profileIdc: profileIdc,
  835. levelIdc: levelIdc,
  836. profileCompatibility: profileCompatibility,
  837. width: Math.ceil((((picWidthInMbsMinus1 + 1) * 16) - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale),
  838. height: ((2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16) - (frameCropTopOffset * 2) - (frameCropBottomOffset * 2),
  839. sarRatio: sarRatio
  840. };
  841. };
  842. };
  843. H264Stream.prototype = new Stream();
  844. module.exports = {
  845. H264Stream: H264Stream,
  846. NalByteStream: NalByteStream
  847. };
  848. },{"30":30,"31":31}],5:[function(require,module,exports){
  849. // constants
  850. var AUDIO_PROPERTIES = [
  851. 'audioobjecttype',
  852. 'channelcount',
  853. 'samplerate',
  854. 'samplingfrequencyindex',
  855. 'samplesize'
  856. ];
  857. module.exports = AUDIO_PROPERTIES;
  858. },{}],6:[function(require,module,exports){
  859. var VIDEO_PROPERTIES = [
  860. 'width',
  861. 'height',
  862. 'profileIdc',
  863. 'levelIdc',
  864. 'profileCompatibility',
  865. 'sarRatio'
  866. ];
  867. module.exports = VIDEO_PROPERTIES;
  868. },{}],7:[function(require,module,exports){
  869. /**
  870. * mux.js
  871. *
  872. * Copyright (c) Brightcove
  873. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  874. */
  875. var highPrefix = [33, 16, 5, 32, 164, 27];
  876. var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  877. var zeroFill = function(count) {
  878. var a = [];
  879. while (count--) {
  880. a.push(0);
  881. }
  882. return a;
  883. };
  884. var makeTable = function(metaTable) {
  885. return Object.keys(metaTable).reduce(function(obj, key) {
  886. obj[key] = new Uint8Array(metaTable[key].reduce(function(arr, part) {
  887. return arr.concat(part);
  888. }, []));
  889. return obj;
  890. }, {});
  891. };
  892. var silence;
  893. module.exports = function() {
  894. if (!silence) {
  895. // Frames-of-silence to use for filling in missing AAC frames
  896. var coneOfSilence = {
  897. 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
  898. 88200: [highPrefix, [231], zeroFill(170), [56]],
  899. 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
  900. 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
  901. 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
  902. 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
  903. 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
  904. 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
  905. 12000: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 253, 128], zeroFill(259), [56]],
  906. 11025: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 255, 192], zeroFill(268), [55, 175, 128], zeroFill(108), [112]],
  907. 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
  908. };
  909. silence = makeTable(coneOfSilence);
  910. }
  911. return silence;
  912. };
  913. },{}],8:[function(require,module,exports){
  914. /**
  915. * mux.js
  916. *
  917. * Copyright (c) Brightcove
  918. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  919. *
  920. * Reads in-band caption information from a video elementary
  921. * stream. Captions must follow the CEA-708 standard for injection
  922. * into an MPEG-2 transport streams.
  923. * @see https://en.wikipedia.org/wiki/CEA-708
  924. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  925. */
  926. 'use strict';
  927. // -----------------
  928. // Link To Transport
  929. // -----------------
  930. var Stream = require(31);
  931. var cea708Parser = require(23);
  932. var CaptionStream = function() {
  933. CaptionStream.prototype.init.call(this);
  934. this.captionPackets_ = [];
  935. this.ccStreams_ = [
  936. new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
  937. new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
  938. new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
  939. new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  940. ];
  941. this.reset();
  942. // forward data and done events from CCs to this CaptionStream
  943. this.ccStreams_.forEach(function(cc) {
  944. cc.on('data', this.trigger.bind(this, 'data'));
  945. cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
  946. cc.on('done', this.trigger.bind(this, 'done'));
  947. }, this);
  948. };
  949. CaptionStream.prototype = new Stream();
  950. CaptionStream.prototype.push = function(event) {
  951. var sei, userData, newCaptionPackets;
  952. // only examine SEI NALs
  953. if (event.nalUnitType !== 'sei_rbsp') {
  954. return;
  955. }
  956. // parse the sei
  957. sei = cea708Parser.parseSei(event.escapedRBSP);
  958. // ignore everything but user_data_registered_itu_t_t35
  959. if (sei.payloadType !== cea708Parser.USER_DATA_REGISTERED_ITU_T_T35) {
  960. return;
  961. }
  962. // parse out the user data payload
  963. userData = cea708Parser.parseUserData(sei);
  964. // ignore unrecognized userData
  965. if (!userData) {
  966. return;
  967. }
  968. // Sometimes, the same segment # will be downloaded twice. To stop the
  969. // caption data from being processed twice, we track the latest dts we've
  970. // received and ignore everything with a dts before that. However, since
  971. // data for a specific dts can be split across packets on either side of
  972. // a segment boundary, we need to make sure we *don't* ignore the packets
  973. // from the *next* segment that have dts === this.latestDts_. By constantly
  974. // tracking the number of packets received with dts === this.latestDts_, we
  975. // know how many should be ignored once we start receiving duplicates.
  976. if (event.dts < this.latestDts_) {
  977. // We've started getting older data, so set the flag.
  978. this.ignoreNextEqualDts_ = true;
  979. return;
  980. } else if ((event.dts === this.latestDts_) && (this.ignoreNextEqualDts_)) {
  981. this.numSameDts_--;
  982. if (!this.numSameDts_) {
  983. // We've received the last duplicate packet, time to start processing again
  984. this.ignoreNextEqualDts_ = false;
  985. }
  986. return;
  987. }
  988. // parse out CC data packets and save them for later
  989. newCaptionPackets = cea708Parser.parseCaptionPackets(event.pts, userData);
  990. this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  991. if (this.latestDts_ !== event.dts) {
  992. this.numSameDts_ = 0;
  993. }
  994. this.numSameDts_++;
  995. this.latestDts_ = event.dts;
  996. };
  997. CaptionStream.prototype.flushCCStreams = function(flushType) {
  998. this.ccStreams_.forEach(function(cc) {
  999. return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  1000. }, this);
  1001. };
  1002. CaptionStream.prototype.flushStream = function(flushType) {
  1003. // make sure we actually parsed captions before proceeding
  1004. if (!this.captionPackets_.length) {
  1005. this.flushCCStreams(flushType);
  1006. return;
  1007. }
  1008. // In Chrome, the Array#sort function is not stable so add a
  1009. // presortIndex that we can use to ensure we get a stable-sort
  1010. this.captionPackets_.forEach(function(elem, idx) {
  1011. elem.presortIndex = idx;
  1012. });
  1013. // sort caption byte-pairs based on their PTS values
  1014. this.captionPackets_.sort(function(a, b) {
  1015. if (a.pts === b.pts) {
  1016. return a.presortIndex - b.presortIndex;
  1017. }
  1018. return a.pts - b.pts;
  1019. });
  1020. this.captionPackets_.forEach(function(packet) {
  1021. if (packet.type < 2) {
  1022. // Dispatch packet to the right Cea608Stream
  1023. this.dispatchCea608Packet(packet);
  1024. }
  1025. // this is where an 'else' would go for a dispatching packets
  1026. // to a theoretical Cea708Stream that handles SERVICEn data
  1027. }, this);
  1028. this.captionPackets_.length = 0;
  1029. this.flushCCStreams(flushType);
  1030. };
  1031. CaptionStream.prototype.flush = function() {
  1032. return this.flushStream('flush');
  1033. };
  1034. // Only called if handling partial data
  1035. CaptionStream.prototype.partialFlush = function() {
  1036. return this.flushStream('partialFlush');
  1037. };
  1038. CaptionStream.prototype.reset = function() {
  1039. this.latestDts_ = null;
  1040. this.ignoreNextEqualDts_ = false;
  1041. this.numSameDts_ = 0;
  1042. this.activeCea608Channel_ = [null, null];
  1043. this.ccStreams_.forEach(function(ccStream) {
  1044. ccStream.reset();
  1045. });
  1046. };
  1047. // From the CEA-608 spec:
  1048. /*
  1049. * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
  1050. * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
  1051. * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
  1052. * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
  1053. * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
  1054. * to switch to captioning or Text.
  1055. */
  1056. // With that in mind, we ignore any data between an XDS control code and a
  1057. // subsequent closed-captioning control code.
  1058. CaptionStream.prototype.dispatchCea608Packet = function(packet) {
  1059. // NOTE: packet.type is the CEA608 field
  1060. if (this.setsTextOrXDSActive(packet)) {
  1061. this.activeCea608Channel_[packet.type] = null;
  1062. } else if (this.setsChannel1Active(packet)) {
  1063. this.activeCea608Channel_[packet.type] = 0;
  1064. } else if (this.setsChannel2Active(packet)) {
  1065. this.activeCea608Channel_[packet.type] = 1;
  1066. }
  1067. if (this.activeCea608Channel_[packet.type] === null) {
  1068. // If we haven't received anything to set the active channel, or the
  1069. // packets are Text/XDS data, discard the data; we don't want jumbled
  1070. // captions
  1071. return;
  1072. }
  1073. this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  1074. };
  1075. CaptionStream.prototype.setsChannel1Active = function(packet) {
  1076. return ((packet.ccData & 0x7800) === 0x1000);
  1077. };
  1078. CaptionStream.prototype.setsChannel2Active = function(packet) {
  1079. return ((packet.ccData & 0x7800) === 0x1800);
  1080. };
  1081. CaptionStream.prototype.setsTextOrXDSActive = function(packet) {
  1082. return ((packet.ccData & 0x7100) === 0x0100) ||
  1083. ((packet.ccData & 0x78fe) === 0x102a) ||
  1084. ((packet.ccData & 0x78fe) === 0x182a);
  1085. };
  1086. // ----------------------
  1087. // Session to Application
  1088. // ----------------------
  1089. // This hash maps non-ASCII, special, and extended character codes to their
  1090. // proper Unicode equivalent. The first keys that are only a single byte
  1091. // are the non-standard ASCII characters, which simply map the CEA608 byte
  1092. // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
  1093. // character codes, but have their MSB bitmasked with 0x03 so that a lookup
  1094. // can be performed regardless of the field and data channel on which the
  1095. // character code was received.
  1096. var CHARACTER_TRANSLATION = {
  1097. 0x2a: 0xe1, // á
  1098. 0x5c: 0xe9, // é
  1099. 0x5e: 0xed, // í
  1100. 0x5f: 0xf3, // ó
  1101. 0x60: 0xfa, // ú
  1102. 0x7b: 0xe7, // ç
  1103. 0x7c: 0xf7, // ÷
  1104. 0x7d: 0xd1, // Ñ
  1105. 0x7e: 0xf1, // ñ
  1106. 0x7f: 0x2588, // █
  1107. 0x0130: 0xae, // ®
  1108. 0x0131: 0xb0, // °
  1109. 0x0132: 0xbd, // ½
  1110. 0x0133: 0xbf, // ¿
  1111. 0x0134: 0x2122, // ™
  1112. 0x0135: 0xa2, // ¢
  1113. 0x0136: 0xa3, // £
  1114. 0x0137: 0x266a, // ♪
  1115. 0x0138: 0xe0, // à
  1116. 0x0139: 0xa0, //
  1117. 0x013a: 0xe8, // è
  1118. 0x013b: 0xe2, // â
  1119. 0x013c: 0xea, // ê
  1120. 0x013d: 0xee, // î
  1121. 0x013e: 0xf4, // ô
  1122. 0x013f: 0xfb, // û
  1123. 0x0220: 0xc1, // Á
  1124. 0x0221: 0xc9, // É
  1125. 0x0222: 0xd3, // Ó
  1126. 0x0223: 0xda, // Ú
  1127. 0x0224: 0xdc, // Ü
  1128. 0x0225: 0xfc, // ü
  1129. 0x0226: 0x2018, // ‘
  1130. 0x0227: 0xa1, // ¡
  1131. 0x0228: 0x2a, // *
  1132. 0x0229: 0x27, // '
  1133. 0x022a: 0x2014, // —
  1134. 0x022b: 0xa9, // ©
  1135. 0x022c: 0x2120, // ℠
  1136. 0x022d: 0x2022, // •
  1137. 0x022e: 0x201c, // “
  1138. 0x022f: 0x201d, // ”
  1139. 0x0230: 0xc0, // À
  1140. 0x0231: 0xc2, // Â
  1141. 0x0232: 0xc7, // Ç
  1142. 0x0233: 0xc8, // È
  1143. 0x0234: 0xca, // Ê
  1144. 0x0235: 0xcb, // Ë
  1145. 0x0236: 0xeb, // ë
  1146. 0x0237: 0xce, // Î
  1147. 0x0238: 0xcf, // Ï
  1148. 0x0239: 0xef, // ï
  1149. 0x023a: 0xd4, // Ô
  1150. 0x023b: 0xd9, // Ù
  1151. 0x023c: 0xf9, // ù
  1152. 0x023d: 0xdb, // Û
  1153. 0x023e: 0xab, // «
  1154. 0x023f: 0xbb, // »
  1155. 0x0320: 0xc3, // Ã
  1156. 0x0321: 0xe3, // ã
  1157. 0x0322: 0xcd, // Í
  1158. 0x0323: 0xcc, // Ì
  1159. 0x0324: 0xec, // ì
  1160. 0x0325: 0xd2, // Ò
  1161. 0x0326: 0xf2, // ò
  1162. 0x0327: 0xd5, // Õ
  1163. 0x0328: 0xf5, // õ
  1164. 0x0329: 0x7b, // {
  1165. 0x032a: 0x7d, // }
  1166. 0x032b: 0x5c, // \
  1167. 0x032c: 0x5e, // ^
  1168. 0x032d: 0x5f, // _
  1169. 0x032e: 0x7c, // |
  1170. 0x032f: 0x7e, // ~
  1171. 0x0330: 0xc4, // Ä
  1172. 0x0331: 0xe4, // ä
  1173. 0x0332: 0xd6, // Ö
  1174. 0x0333: 0xf6, // ö
  1175. 0x0334: 0xdf, // ß
  1176. 0x0335: 0xa5, // ¥
  1177. 0x0336: 0xa4, // ¤
  1178. 0x0337: 0x2502, // │
  1179. 0x0338: 0xc5, // Å
  1180. 0x0339: 0xe5, // å
  1181. 0x033a: 0xd8, // Ø
  1182. 0x033b: 0xf8, // ø
  1183. 0x033c: 0x250c, // ┌
  1184. 0x033d: 0x2510, // ┐
  1185. 0x033e: 0x2514, // └
  1186. 0x033f: 0x2518 // ┘
  1187. };
  1188. var getCharFromCode = function(code) {
  1189. if (code === null) {
  1190. return '';
  1191. }
  1192. code = CHARACTER_TRANSLATION[code] || code;
  1193. return String.fromCharCode(code);
  1194. };
  1195. // the index of the last row in a CEA-608 display buffer
  1196. var BOTTOM_ROW = 14;
  1197. // This array is used for mapping PACs -> row #, since there's no way of
  1198. // getting it through bit logic.
  1199. var ROWS = [0x1100, 0x1120, 0x1200, 0x1220, 0x1500, 0x1520, 0x1600, 0x1620,
  1200. 0x1700, 0x1720, 0x1000, 0x1300, 0x1320, 0x1400, 0x1420];
  1201. // CEA-608 captions are rendered onto a 34x15 matrix of character
  1202. // cells. The "bottom" row is the last element in the outer array.
  1203. var createDisplayBuffer = function() {
  1204. var result = [], i = BOTTOM_ROW + 1;
  1205. while (i--) {
  1206. result.push('');
  1207. }
  1208. return result;
  1209. };
  1210. var Cea608Stream = function(field, dataChannel) {
  1211. Cea608Stream.prototype.init.call(this);
  1212. this.field_ = field || 0;
  1213. this.dataChannel_ = dataChannel || 0;
  1214. this.name_ = 'CC' + (((this.field_ << 1) | this.dataChannel_) + 1);
  1215. this.setConstants();
  1216. this.reset();
  1217. this.push = function(packet) {
  1218. var data, swap, char0, char1, text;
  1219. // remove the parity bits
  1220. data = packet.ccData & 0x7f7f;
  1221. // ignore duplicate control codes; the spec demands they're sent twice
  1222. if (data === this.lastControlCode_) {
  1223. this.lastControlCode_ = null;
  1224. return;
  1225. }
  1226. // Store control codes
  1227. if ((data & 0xf000) === 0x1000) {
  1228. this.lastControlCode_ = data;
  1229. } else if (data !== this.PADDING_) {
  1230. this.lastControlCode_ = null;
  1231. }
  1232. char0 = data >>> 8;
  1233. char1 = data & 0xff;
  1234. if (data === this.PADDING_) {
  1235. return;
  1236. } else if (data === this.RESUME_CAPTION_LOADING_) {
  1237. this.mode_ = 'popOn';
  1238. } else if (data === this.END_OF_CAPTION_) {
  1239. // If an EOC is received while in paint-on mode, the displayed caption
  1240. // text should be swapped to non-displayed memory as if it was a pop-on
  1241. // caption. Because of that, we should explicitly switch back to pop-on
  1242. // mode
  1243. this.mode_ = 'popOn';
  1244. this.clearFormatting(packet.pts);
  1245. // if a caption was being displayed, it's gone now
  1246. this.flushDisplayed(packet.pts);
  1247. // flip memory
  1248. swap = this.displayed_;
  1249. this.displayed_ = this.nonDisplayed_;
  1250. this.nonDisplayed_ = swap;
  1251. // start measuring the time to display the caption
  1252. this.startPts_ = packet.pts;
  1253. } else if (data === this.ROLL_UP_2_ROWS_) {
  1254. this.rollUpRows_ = 2;
  1255. this.setRollUp(packet.pts);
  1256. } else if (data === this.ROLL_UP_3_ROWS_) {
  1257. this.rollUpRows_ = 3;
  1258. this.setRollUp(packet.pts);
  1259. } else if (data === this.ROLL_UP_4_ROWS_) {
  1260. this.rollUpRows_ = 4;
  1261. this.setRollUp(packet.pts);
  1262. } else if (data === this.CARRIAGE_RETURN_) {
  1263. this.clearFormatting(packet.pts);
  1264. this.flushDisplayed(packet.pts);
  1265. this.shiftRowsUp_();
  1266. this.startPts_ = packet.pts;
  1267. } else if (data === this.BACKSPACE_) {
  1268. if (this.mode_ === 'popOn') {
  1269. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  1270. } else {
  1271. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  1272. }
  1273. } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
  1274. this.flushDisplayed(packet.pts);
  1275. this.displayed_ = createDisplayBuffer();
  1276. } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
  1277. this.nonDisplayed_ = createDisplayBuffer();
  1278. } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
  1279. if (this.mode_ !== 'paintOn') {
  1280. // NOTE: This should be removed when proper caption positioning is
  1281. // implemented
  1282. this.flushDisplayed(packet.pts);
  1283. this.displayed_ = createDisplayBuffer();
  1284. }
  1285. this.mode_ = 'paintOn';
  1286. this.startPts_ = packet.pts;
  1287. // Append special characters to caption text
  1288. } else if (this.isSpecialCharacter(char0, char1)) {
  1289. // Bitmask char0 so that we can apply character transformations
  1290. // regardless of field and data channel.
  1291. // Then byte-shift to the left and OR with char1 so we can pass the
  1292. // entire character code to `getCharFromCode`.
  1293. char0 = (char0 & 0x03) << 8;
  1294. text = getCharFromCode(char0 | char1);
  1295. this[this.mode_](packet.pts, text);
  1296. this.column_++;
  1297. // Append extended characters to caption text
  1298. } else if (this.isExtCharacter(char0, char1)) {
  1299. // Extended characters always follow their "non-extended" equivalents.
  1300. // IE if a "è" is desired, you'll always receive "eè"; non-compliant
  1301. // decoders are supposed to drop the "è", while compliant decoders
  1302. // backspace the "e" and insert "è".
  1303. // Delete the previous character
  1304. if (this.mode_ === 'popOn') {
  1305. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  1306. } else {
  1307. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  1308. }
  1309. // Bitmask char0 so that we can apply character transformations
  1310. // regardless of field and data channel.
  1311. // Then byte-shift to the left and OR with char1 so we can pass the
  1312. // entire character code to `getCharFromCode`.
  1313. char0 = (char0 & 0x03) << 8;
  1314. text = getCharFromCode(char0 | char1);
  1315. this[this.mode_](packet.pts, text);
  1316. this.column_++;
  1317. // Process mid-row codes
  1318. } else if (this.isMidRowCode(char0, char1)) {
  1319. // Attributes are not additive, so clear all formatting
  1320. this.clearFormatting(packet.pts);
  1321. // According to the standard, mid-row codes
  1322. // should be replaced with spaces, so add one now
  1323. this[this.mode_](packet.pts, ' ');
  1324. this.column_++;
  1325. if ((char1 & 0xe) === 0xe) {
  1326. this.addFormatting(packet.pts, ['i']);
  1327. }
  1328. if ((char1 & 0x1) === 0x1) {
  1329. this.addFormatting(packet.pts, ['u']);
  1330. }
  1331. // Detect offset control codes and adjust cursor
  1332. } else if (this.isOffsetControlCode(char0, char1)) {
  1333. // Cursor position is set by indent PAC (see below) in 4-column
  1334. // increments, with an additional offset code of 1-3 to reach any
  1335. // of the 32 columns specified by CEA-608. So all we need to do
  1336. // here is increment the column cursor by the given offset.
  1337. this.column_ += (char1 & 0x03);
  1338. // Detect PACs (Preamble Address Codes)
  1339. } else if (this.isPAC(char0, char1)) {
  1340. // There's no logic for PAC -> row mapping, so we have to just
  1341. // find the row code in an array and use its index :(
  1342. var row = ROWS.indexOf(data & 0x1f20);
  1343. // Configure the caption window if we're in roll-up mode
  1344. if (this.mode_ === 'rollUp') {
  1345. // This implies that the base row is incorrectly set.
  1346. // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
  1347. // of roll-up rows set.
  1348. if (row - this.rollUpRows_ + 1 < 0) {
  1349. row = this.rollUpRows_ - 1;
  1350. }
  1351. this.setRollUp(packet.pts, row);
  1352. }
  1353. if (row !== this.row_) {
  1354. // formatting is only persistent for current row
  1355. this.clearFormatting(packet.pts);
  1356. this.row_ = row;
  1357. }
  1358. // All PACs can apply underline, so detect and apply
  1359. // (All odd-numbered second bytes set underline)
  1360. if ((char1 & 0x1) && (this.formatting_.indexOf('u') === -1)) {
  1361. this.addFormatting(packet.pts, ['u']);
  1362. }
  1363. if ((data & 0x10) === 0x10) {
  1364. // We've got an indent level code. Each successive even number
  1365. // increments the column cursor by 4, so we can get the desired
  1366. // column position by bit-shifting to the right (to get n/2)
  1367. // and multiplying by 4.
  1368. this.column_ = ((data & 0xe) >> 1) * 4;
  1369. }
  1370. if (this.isColorPAC(char1)) {
  1371. // it's a color code, though we only support white, which
  1372. // can be either normal or italicized. white italics can be
  1373. // either 0x4e or 0x6e depending on the row, so we just
  1374. // bitwise-and with 0xe to see if italics should be turned on
  1375. if ((char1 & 0xe) === 0xe) {
  1376. this.addFormatting(packet.pts, ['i']);
  1377. }
  1378. }
  1379. // We have a normal character in char0, and possibly one in char1
  1380. } else if (this.isNormalChar(char0)) {
  1381. if (char1 === 0x00) {
  1382. char1 = null;
  1383. }
  1384. text = getCharFromCode(char0);
  1385. text += getCharFromCode(char1);
  1386. this[this.mode_](packet.pts, text);
  1387. this.column_ += text.length;
  1388. } // finish data processing
  1389. };
  1390. };
  1391. Cea608Stream.prototype = new Stream();
  1392. // Trigger a cue point that captures the current state of the
  1393. // display buffer
  1394. Cea608Stream.prototype.flushDisplayed = function(pts) {
  1395. var content = this.displayed_
  1396. // remove spaces from the start and end of the string
  1397. .map(function(row) {
  1398. try {
  1399. return row.trim();
  1400. } catch (e) {
  1401. // Ordinarily, this shouldn't happen. However, caption
  1402. // parsing errors should not throw exceptions and
  1403. // break playback.
  1404. // eslint-disable-next-line no-console
  1405. console.error('Skipping malformed caption.');
  1406. return '';
  1407. }
  1408. })
  1409. // combine all text rows to display in one cue
  1410. .join('\n')
  1411. // and remove blank rows from the start and end, but not the middle
  1412. .replace(/^\n+|\n+$/g, '');
  1413. if (content.length) {
  1414. this.trigger('data', {
  1415. startPts: this.startPts_,
  1416. endPts: pts,
  1417. text: content,
  1418. stream: this.name_
  1419. });
  1420. }
  1421. };
  1422. /**
  1423. * Zero out the data, used for startup and on seek
  1424. */
  1425. Cea608Stream.prototype.reset = function() {
  1426. this.mode_ = 'popOn';
  1427. // When in roll-up mode, the index of the last row that will
  1428. // actually display captions. If a caption is shifted to a row
  1429. // with a lower index than this, it is cleared from the display
  1430. // buffer
  1431. this.topRow_ = 0;
  1432. this.startPts_ = 0;
  1433. this.displayed_ = createDisplayBuffer();
  1434. this.nonDisplayed_ = createDisplayBuffer();
  1435. this.lastControlCode_ = null;
  1436. // Track row and column for proper line-breaking and spacing
  1437. this.column_ = 0;
  1438. this.row_ = BOTTOM_ROW;
  1439. this.rollUpRows_ = 2;
  1440. // This variable holds currently-applied formatting
  1441. this.formatting_ = [];
  1442. };
  1443. /**
  1444. * Sets up control code and related constants for this instance
  1445. */
  1446. Cea608Stream.prototype.setConstants = function() {
  1447. // The following attributes have these uses:
  1448. // ext_ : char0 for mid-row codes, and the base for extended
  1449. // chars (ext_+0, ext_+1, and ext_+2 are char0s for
  1450. // extended codes)
  1451. // control_: char0 for control codes, except byte-shifted to the
  1452. // left so that we can do this.control_ | CONTROL_CODE
  1453. // offset_: char0 for tab offset codes
  1454. //
  1455. // It's also worth noting that control codes, and _only_ control codes,
  1456. // differ between field 1 and field2. Field 2 control codes are always
  1457. // their field 1 value plus 1. That's why there's the "| field" on the
  1458. // control value.
  1459. if (this.dataChannel_ === 0) {
  1460. this.BASE_ = 0x10;
  1461. this.EXT_ = 0x11;
  1462. this.CONTROL_ = (0x14 | this.field_) << 8;
  1463. this.OFFSET_ = 0x17;
  1464. } else if (this.dataChannel_ === 1) {
  1465. this.BASE_ = 0x18;
  1466. this.EXT_ = 0x19;
  1467. this.CONTROL_ = (0x1c | this.field_) << 8;
  1468. this.OFFSET_ = 0x1f;
  1469. }
  1470. // Constants for the LSByte command codes recognized by Cea608Stream. This
  1471. // list is not exhaustive. For a more comprehensive listing and semantics see
  1472. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  1473. // Padding
  1474. this.PADDING_ = 0x0000;
  1475. // Pop-on Mode
  1476. this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
  1477. this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f;
  1478. // Roll-up Mode
  1479. this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
  1480. this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
  1481. this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
  1482. this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d;
  1483. // paint-on mode
  1484. this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29;
  1485. // Erasure
  1486. this.BACKSPACE_ = this.CONTROL_ | 0x21;
  1487. this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
  1488. this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
  1489. };
  1490. /**
  1491. * Detects if the 2-byte packet data is a special character
  1492. *
  1493. * Special characters have a second byte in the range 0x30 to 0x3f,
  1494. * with the first byte being 0x11 (for data channel 1) or 0x19 (for
  1495. * data channel 2).
  1496. *
  1497. * @param {Integer} char0 The first byte
  1498. * @param {Integer} char1 The second byte
  1499. * @return {Boolean} Whether the 2 bytes are an special character
  1500. */
  1501. Cea608Stream.prototype.isSpecialCharacter = function(char0, char1) {
  1502. return (char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f);
  1503. };
  1504. /**
  1505. * Detects if the 2-byte packet data is an extended character
  1506. *
  1507. * Extended characters have a second byte in the range 0x20 to 0x3f,
  1508. * with the first byte being 0x12 or 0x13 (for data channel 1) or
  1509. * 0x1a or 0x1b (for data channel 2).
  1510. *
  1511. * @param {Integer} char0 The first byte
  1512. * @param {Integer} char1 The second byte
  1513. * @return {Boolean} Whether the 2 bytes are an extended character
  1514. */
  1515. Cea608Stream.prototype.isExtCharacter = function(char0, char1) {
  1516. return ((char0 === (this.EXT_ + 1) || char0 === (this.EXT_ + 2)) &&
  1517. (char1 >= 0x20 && char1 <= 0x3f));
  1518. };
  1519. /**
  1520. * Detects if the 2-byte packet is a mid-row code
  1521. *
  1522. * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
  1523. * the first byte being 0x11 (for data channel 1) or 0x19 (for data
  1524. * channel 2).
  1525. *
  1526. * @param {Integer} char0 The first byte
  1527. * @param {Integer} char1 The second byte
  1528. * @return {Boolean} Whether the 2 bytes are a mid-row code
  1529. */
  1530. Cea608Stream.prototype.isMidRowCode = function(char0, char1) {
  1531. return (char0 === this.EXT_ && (char1 >= 0x20 && char1 <= 0x2f));
  1532. };
  1533. /**
  1534. * Detects if the 2-byte packet is an offset control code
  1535. *
  1536. * Offset control codes have a second byte in the range 0x21 to 0x23,
  1537. * with the first byte being 0x17 (for data channel 1) or 0x1f (for
  1538. * data channel 2).
  1539. *
  1540. * @param {Integer} char0 The first byte
  1541. * @param {Integer} char1 The second byte
  1542. * @return {Boolean} Whether the 2 bytes are an offset control code
  1543. */
  1544. Cea608Stream.prototype.isOffsetControlCode = function(char0, char1) {
  1545. return (char0 === this.OFFSET_ && (char1 >= 0x21 && char1 <= 0x23));
  1546. };
  1547. /**
  1548. * Detects if the 2-byte packet is a Preamble Address Code
  1549. *
  1550. * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
  1551. * or 0x18 to 0x1f (for data channel 2), with the second byte in the
  1552. * range 0x40 to 0x7f.
  1553. *
  1554. * @param {Integer} char0 The first byte
  1555. * @param {Integer} char1 The second byte
  1556. * @return {Boolean} Whether the 2 bytes are a PAC
  1557. */
  1558. Cea608Stream.prototype.isPAC = function(char0, char1) {
  1559. return (char0 >= this.BASE_ && char0 < (this.BASE_ + 8) &&
  1560. (char1 >= 0x40 && char1 <= 0x7f));
  1561. };
  1562. /**
  1563. * Detects if a packet's second byte is in the range of a PAC color code
  1564. *
  1565. * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
  1566. * 0x60 to 0x6f.
  1567. *
  1568. * @param {Integer} char1 The second byte
  1569. * @return {Boolean} Whether the byte is a color PAC
  1570. */
  1571. Cea608Stream.prototype.isColorPAC = function(char1) {
  1572. return ((char1 >= 0x40 && char1 <= 0x4f) || (char1 >= 0x60 && char1 <= 0x7f));
  1573. };
  1574. /**
  1575. * Detects if a single byte is in the range of a normal character
  1576. *
  1577. * Normal text bytes are in the range 0x20 to 0x7f.
  1578. *
  1579. * @param {Integer} char The byte
  1580. * @return {Boolean} Whether the byte is a normal character
  1581. */
  1582. Cea608Stream.prototype.isNormalChar = function(char) {
  1583. return (char >= 0x20 && char <= 0x7f);
  1584. };
  1585. /**
  1586. * Configures roll-up
  1587. *
  1588. * @param {Integer} pts Current PTS
  1589. * @param {Integer} newBaseRow Used by PACs to slide the current window to
  1590. * a new position
  1591. */
  1592. Cea608Stream.prototype.setRollUp = function(pts, newBaseRow) {
  1593. // Reset the base row to the bottom row when switching modes
  1594. if (this.mode_ !== 'rollUp') {
  1595. this.row_ = BOTTOM_ROW;
  1596. this.mode_ = 'rollUp';
  1597. // Spec says to wipe memories when switching to roll-up
  1598. this.flushDisplayed(pts);
  1599. this.nonDisplayed_ = createDisplayBuffer();
  1600. this.displayed_ = createDisplayBuffer();
  1601. }
  1602. if (newBaseRow !== undefined && newBaseRow !== this.row_) {
  1603. // move currently displayed captions (up or down) to the new base row
  1604. for (var i = 0; i < this.rollUpRows_; i++) {
  1605. this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
  1606. this.displayed_[this.row_ - i] = '';
  1607. }
  1608. }
  1609. if (newBaseRow === undefined) {
  1610. newBaseRow = this.row_;
  1611. }
  1612. this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  1613. };
  1614. // Adds the opening HTML tag for the passed character to the caption text,
  1615. // and keeps track of it for later closing
  1616. Cea608Stream.prototype.addFormatting = function(pts, format) {
  1617. this.formatting_ = this.formatting_.concat(format);
  1618. var text = format.reduce(function(text, format) {
  1619. return text + '<' + format + '>';
  1620. }, '');
  1621. this[this.mode_](pts, text);
  1622. };
  1623. // Adds HTML closing tags for current formatting to caption text and
  1624. // clears remembered formatting
  1625. Cea608Stream.prototype.clearFormatting = function(pts) {
  1626. if (!this.formatting_.length) {
  1627. return;
  1628. }
  1629. var text = this.formatting_.reverse().reduce(function(text, format) {
  1630. return text + '</' + format + '>';
  1631. }, '');
  1632. this.formatting_ = [];
  1633. this[this.mode_](pts, text);
  1634. };
  1635. // Mode Implementations
  1636. Cea608Stream.prototype.popOn = function(pts, text) {
  1637. var baseRow = this.nonDisplayed_[this.row_];
  1638. // buffer characters
  1639. baseRow += text;
  1640. this.nonDisplayed_[this.row_] = baseRow;
  1641. };
  1642. Cea608Stream.prototype.rollUp = function(pts, text) {
  1643. var baseRow = this.displayed_[this.row_];
  1644. baseRow += text;
  1645. this.displayed_[this.row_] = baseRow;
  1646. };
  1647. Cea608Stream.prototype.shiftRowsUp_ = function() {
  1648. var i;
  1649. // clear out inactive rows
  1650. for (i = 0; i < this.topRow_; i++) {
  1651. this.displayed_[i] = '';
  1652. }
  1653. for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
  1654. this.displayed_[i] = '';
  1655. }
  1656. // shift displayed rows up
  1657. for (i = this.topRow_; i < this.row_; i++) {
  1658. this.displayed_[i] = this.displayed_[i + 1];
  1659. }
  1660. // clear out the bottom row
  1661. this.displayed_[this.row_] = '';
  1662. };
  1663. Cea608Stream.prototype.paintOn = function(pts, text) {
  1664. var baseRow = this.displayed_[this.row_];
  1665. baseRow += text;
  1666. this.displayed_[this.row_] = baseRow;
  1667. };
  1668. // exports
  1669. module.exports = {
  1670. CaptionStream: CaptionStream,
  1671. Cea608Stream: Cea608Stream
  1672. };
  1673. },{"23":23,"31":31}],9:[function(require,module,exports){
  1674. /**
  1675. * mux.js
  1676. *
  1677. * Copyright (c) Brightcove
  1678. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  1679. *
  1680. * A stream-based mp2t to mp4 converter. This utility can be used to
  1681. * deliver mp4s to a SourceBuffer on platforms that support native
  1682. * Media Source Extensions.
  1683. */
  1684. 'use strict';
  1685. var Stream = require(31),
  1686. CaptionStream = require(8),
  1687. StreamTypes = require(11),
  1688. TimestampRolloverStream = require(12).TimestampRolloverStream;
  1689. // object types
  1690. var TransportPacketStream, TransportParseStream, ElementaryStream;
  1691. // constants
  1692. var
  1693. MP2T_PACKET_LENGTH = 188, // bytes
  1694. SYNC_BYTE = 0x47;
  1695. /**
  1696. * Splits an incoming stream of binary data into MPEG-2 Transport
  1697. * Stream packets.
  1698. */
  1699. TransportPacketStream = function() {
  1700. var
  1701. buffer = new Uint8Array(MP2T_PACKET_LENGTH),
  1702. bytesInBuffer = 0;
  1703. TransportPacketStream.prototype.init.call(this);
  1704. // Deliver new bytes to the stream.
  1705. /**
  1706. * Split a stream of data into M2TS packets
  1707. **/
  1708. this.push = function(bytes) {
  1709. var
  1710. startIndex = 0,
  1711. endIndex = MP2T_PACKET_LENGTH,
  1712. everything;
  1713. // If there are bytes remaining from the last segment, prepend them to the
  1714. // bytes that were pushed in
  1715. if (bytesInBuffer) {
  1716. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  1717. everything.set(buffer.subarray(0, bytesInBuffer));
  1718. everything.set(bytes, bytesInBuffer);
  1719. bytesInBuffer = 0;
  1720. } else {
  1721. everything = bytes;
  1722. }
  1723. // While we have enough data for a packet
  1724. while (endIndex < everything.byteLength) {
  1725. // Look for a pair of start and end sync bytes in the data..
  1726. if (everything[startIndex] === SYNC_BYTE && everything[endIndex] === SYNC_BYTE) {
  1727. // We found a packet so emit it and jump one whole packet forward in
  1728. // the stream
  1729. this.trigger('data', everything.subarray(startIndex, endIndex));
  1730. startIndex += MP2T_PACKET_LENGTH;
  1731. endIndex += MP2T_PACKET_LENGTH;
  1732. continue;
  1733. }
  1734. // If we get here, we have somehow become de-synchronized and we need to step
  1735. // forward one byte at a time until we find a pair of sync bytes that denote
  1736. // a packet
  1737. startIndex++;
  1738. endIndex++;
  1739. }
  1740. // If there was some data left over at the end of the segment that couldn't
  1741. // possibly be a whole packet, keep it because it might be the start of a packet
  1742. // that continues in the next segment
  1743. if (startIndex < everything.byteLength) {
  1744. buffer.set(everything.subarray(startIndex), 0);
  1745. bytesInBuffer = everything.byteLength - startIndex;
  1746. }
  1747. };
  1748. /**
  1749. * Passes identified M2TS packets to the TransportParseStream to be parsed
  1750. **/
  1751. this.flush = function() {
  1752. // If the buffer contains a whole packet when we are being flushed, emit it
  1753. // and empty the buffer. Otherwise hold onto the data because it may be
  1754. // important for decoding the next segment
  1755. if (bytesInBuffer === MP2T_PACKET_LENGTH && buffer[0] === SYNC_BYTE) {
  1756. this.trigger('data', buffer);
  1757. bytesInBuffer = 0;
  1758. }
  1759. this.trigger('done');
  1760. };
  1761. this.endTimeline = function() {
  1762. this.flush();
  1763. this.trigger('endedtimeline');
  1764. };
  1765. this.reset = function() {
  1766. bytesInBuffer = 0;
  1767. this.trigger('reset');
  1768. };
  1769. };
  1770. TransportPacketStream.prototype = new Stream();
  1771. /**
  1772. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  1773. * forms of the individual transport stream packets.
  1774. */
  1775. TransportParseStream = function() {
  1776. var parsePsi, parsePat, parsePmt, self;
  1777. TransportParseStream.prototype.init.call(this);
  1778. self = this;
  1779. this.packetsWaitingForPmt = [];
  1780. this.programMapTable = undefined;
  1781. parsePsi = function(payload, psi) {
  1782. var offset = 0;
  1783. // PSI packets may be split into multiple sections and those
  1784. // sections may be split into multiple packets. If a PSI
  1785. // section starts in this packet, the payload_unit_start_indicator
  1786. // will be true and the first byte of the payload will indicate
  1787. // the offset from the current position to the start of the
  1788. // section.
  1789. if (psi.payloadUnitStartIndicator) {
  1790. offset += payload[offset] + 1;
  1791. }
  1792. if (psi.type === 'pat') {
  1793. parsePat(payload.subarray(offset), psi);
  1794. } else {
  1795. parsePmt(payload.subarray(offset), psi);
  1796. }
  1797. };
  1798. parsePat = function(payload, pat) {
  1799. pat.section_number = payload[7]; // eslint-disable-line camelcase
  1800. pat.last_section_number = payload[8]; // eslint-disable-line camelcase
  1801. // skip the PSI header and parse the first PMT entry
  1802. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  1803. pat.pmtPid = self.pmtPid;
  1804. };
  1805. /**
  1806. * Parse out the relevant fields of a Program Map Table (PMT).
  1807. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  1808. * packet. The first byte in this array should be the table_id
  1809. * field.
  1810. * @param pmt {object} the object that should be decorated with
  1811. * fields parsed from the PMT.
  1812. */
  1813. parsePmt = function(payload, pmt) {
  1814. var sectionLength, tableEnd, programInfoLength, offset;
  1815. // PMTs can be sent ahead of the time when they should actually
  1816. // take effect. We don't believe this should ever be the case
  1817. // for HLS but we'll ignore "forward" PMT declarations if we see
  1818. // them. Future PMT declarations have the current_next_indicator
  1819. // set to zero.
  1820. if (!(payload[5] & 0x01)) {
  1821. return;
  1822. }
  1823. // overwrite any existing program map table
  1824. self.programMapTable = {
  1825. video: null,
  1826. audio: null,
  1827. 'timed-metadata': {}
  1828. };
  1829. // the mapping table ends at the end of the current section
  1830. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  1831. tableEnd = 3 + sectionLength - 4;
  1832. // to determine where the table is, we have to figure out how
  1833. // long the program info descriptors are
  1834. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11];
  1835. // advance the offset to the first entry in the mapping table
  1836. offset = 12 + programInfoLength;
  1837. while (offset < tableEnd) {
  1838. var streamType = payload[offset];
  1839. var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2];
  1840. // only map a single elementary_pid for audio and video stream types
  1841. // TODO: should this be done for metadata too? for now maintain behavior of
  1842. // multiple metadata streams
  1843. if (streamType === StreamTypes.H264_STREAM_TYPE &&
  1844. self.programMapTable.video === null) {
  1845. self.programMapTable.video = pid;
  1846. } else if (streamType === StreamTypes.ADTS_STREAM_TYPE &&
  1847. self.programMapTable.audio === null) {
  1848. self.programMapTable.audio = pid;
  1849. } else if (streamType === StreamTypes.METADATA_STREAM_TYPE) {
  1850. // map pid to stream type for metadata streams
  1851. self.programMapTable['timed-metadata'][pid] = streamType;
  1852. }
  1853. // move to the next table entry
  1854. // skip past the elementary stream descriptors, if present
  1855. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  1856. }
  1857. // record the map on the packet as well
  1858. pmt.programMapTable = self.programMapTable;
  1859. };
  1860. /**
  1861. * Deliver a new MP2T packet to the next stream in the pipeline.
  1862. */
  1863. this.push = function(packet) {
  1864. var
  1865. result = {},
  1866. offset = 4;
  1867. result.payloadUnitStartIndicator = !!(packet[1] & 0x40);
  1868. // pid is a 13-bit field starting at the last bit of packet[1]
  1869. result.pid = packet[1] & 0x1f;
  1870. result.pid <<= 8;
  1871. result.pid |= packet[2];
  1872. // if an adaption field is present, its length is specified by the
  1873. // fifth byte of the TS packet header. The adaptation field is
  1874. // used to add stuffing to PES packets that don't fill a complete
  1875. // TS packet, and to specify some forms of timing and control data
  1876. // that we do not currently use.
  1877. if (((packet[3] & 0x30) >>> 4) > 0x01) {
  1878. offset += packet[offset] + 1;
  1879. }
  1880. // parse the rest of the packet based on the type
  1881. if (result.pid === 0) {
  1882. result.type = 'pat';
  1883. parsePsi(packet.subarray(offset), result);
  1884. this.trigger('data', result);
  1885. } else if (result.pid === this.pmtPid) {
  1886. result.type = 'pmt';
  1887. parsePsi(packet.subarray(offset), result);
  1888. this.trigger('data', result);
  1889. // if there are any packets waiting for a PMT to be found, process them now
  1890. while (this.packetsWaitingForPmt.length) {
  1891. this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
  1892. }
  1893. } else if (this.programMapTable === undefined) {
  1894. // When we have not seen a PMT yet, defer further processing of
  1895. // PES packets until one has been parsed
  1896. this.packetsWaitingForPmt.push([packet, offset, result]);
  1897. } else {
  1898. this.processPes_(packet, offset, result);
  1899. }
  1900. };
  1901. this.processPes_ = function(packet, offset, result) {
  1902. // set the appropriate stream type
  1903. if (result.pid === this.programMapTable.video) {
  1904. result.streamType = StreamTypes.H264_STREAM_TYPE;
  1905. } else if (result.pid === this.programMapTable.audio) {
  1906. result.streamType = StreamTypes.ADTS_STREAM_TYPE;
  1907. } else {
  1908. // if not video or audio, it is timed-metadata or unknown
  1909. // if unknown, streamType will be undefined
  1910. result.streamType = this.programMapTable['timed-metadata'][result.pid];
  1911. }
  1912. result.type = 'pes';
  1913. result.data = packet.subarray(offset);
  1914. this.trigger('data', result);
  1915. };
  1916. };
  1917. TransportParseStream.prototype = new Stream();
  1918. TransportParseStream.STREAM_TYPES = {
  1919. h264: 0x1b,
  1920. adts: 0x0f
  1921. };
  1922. /**
  1923. * Reconsistutes program elementary stream (PES) packets from parsed
  1924. * transport stream packets. That is, if you pipe an
  1925. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  1926. * events will be events which capture the bytes for individual PES
  1927. * packets plus relevant metadata that has been extracted from the
  1928. * container.
  1929. */
  1930. ElementaryStream = function() {
  1931. var
  1932. self = this,
  1933. // PES packet fragments
  1934. video = {
  1935. data: [],
  1936. size: 0
  1937. },
  1938. audio = {
  1939. data: [],
  1940. size: 0
  1941. },
  1942. timedMetadata = {
  1943. data: [],
  1944. size: 0
  1945. },
  1946. programMapTable,
  1947. parsePes = function(payload, pes) {
  1948. var ptsDtsFlags;
  1949. // get the packet length, this will be 0 for video
  1950. pes.packetLength = 6 + ((payload[4] << 8) | payload[5]);
  1951. // find out if this packets starts a new keyframe
  1952. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0;
  1953. // PES packets may be annotated with a PTS value, or a PTS value
  1954. // and a DTS value. Determine what combination of values is
  1955. // available to work with.
  1956. ptsDtsFlags = payload[7];
  1957. // PTS and DTS are normally stored as a 33-bit number. Javascript
  1958. // performs all bitwise operations on 32-bit integers but javascript
  1959. // supports a much greater range (52-bits) of integer using standard
  1960. // mathematical operations.
  1961. // We construct a 31-bit value using bitwise operators over the 31
  1962. // most significant bits and then multiply by 4 (equal to a left-shift
  1963. // of 2) before we add the final 2 least significant bits of the
  1964. // timestamp (equal to an OR.)
  1965. if (ptsDtsFlags & 0xC0) {
  1966. // the PTS and DTS are not written out directly. For information
  1967. // on how they are encoded, see
  1968. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  1969. pes.pts = (payload[9] & 0x0E) << 27 |
  1970. (payload[10] & 0xFF) << 20 |
  1971. (payload[11] & 0xFE) << 12 |
  1972. (payload[12] & 0xFF) << 5 |
  1973. (payload[13] & 0xFE) >>> 3;
  1974. pes.pts *= 4; // Left shift by 2
  1975. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  1976. pes.dts = pes.pts;
  1977. if (ptsDtsFlags & 0x40) {
  1978. pes.dts = (payload[14] & 0x0E) << 27 |
  1979. (payload[15] & 0xFF) << 20 |
  1980. (payload[16] & 0xFE) << 12 |
  1981. (payload[17] & 0xFF) << 5 |
  1982. (payload[18] & 0xFE) >>> 3;
  1983. pes.dts *= 4; // Left shift by 2
  1984. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  1985. }
  1986. }
  1987. // the data section starts immediately after the PES header.
  1988. // pes_header_data_length specifies the number of header bytes
  1989. // that follow the last byte of the field.
  1990. pes.data = payload.subarray(9 + payload[8]);
  1991. },
  1992. /**
  1993. * Pass completely parsed PES packets to the next stream in the pipeline
  1994. **/
  1995. flushStream = function(stream, type, forceFlush) {
  1996. var
  1997. packetData = new Uint8Array(stream.size),
  1998. event = {
  1999. type: type
  2000. },
  2001. i = 0,
  2002. offset = 0,
  2003. packetFlushable = false,
  2004. fragment;
  2005. // do nothing if there is not enough buffered data for a complete
  2006. // PES header
  2007. if (!stream.data.length || stream.size < 9) {
  2008. return;
  2009. }
  2010. event.trackId = stream.data[0].pid;
  2011. // reassemble the packet
  2012. for (i = 0; i < stream.data.length; i++) {
  2013. fragment = stream.data[i];
  2014. packetData.set(fragment.data, offset);
  2015. offset += fragment.data.byteLength;
  2016. }
  2017. // parse assembled packet's PES header
  2018. parsePes(packetData, event);
  2019. // non-video PES packets MUST have a non-zero PES_packet_length
  2020. // check that there is enough stream data to fill the packet
  2021. packetFlushable = type === 'video' || event.packetLength <= stream.size;
  2022. // flush pending packets if the conditions are right
  2023. if (forceFlush || packetFlushable) {
  2024. stream.size = 0;
  2025. stream.data.length = 0;
  2026. }
  2027. // only emit packets that are complete. this is to avoid assembling
  2028. // incomplete PES packets due to poor segmentation
  2029. if (packetFlushable) {
  2030. self.trigger('data', event);
  2031. }
  2032. };
  2033. ElementaryStream.prototype.init.call(this);
  2034. /**
  2035. * Identifies M2TS packet types and parses PES packets using metadata
  2036. * parsed from the PMT
  2037. **/
  2038. this.push = function(data) {
  2039. ({
  2040. pat: function() {
  2041. // we have to wait for the PMT to arrive as well before we
  2042. // have any meaningful metadata
  2043. },
  2044. pes: function() {
  2045. var stream, streamType;
  2046. switch (data.streamType) {
  2047. case StreamTypes.H264_STREAM_TYPE:
  2048. stream = video;
  2049. streamType = 'video';
  2050. break;
  2051. case StreamTypes.ADTS_STREAM_TYPE:
  2052. stream = audio;
  2053. streamType = 'audio';
  2054. break;
  2055. case StreamTypes.METADATA_STREAM_TYPE:
  2056. stream = timedMetadata;
  2057. streamType = 'timed-metadata';
  2058. break;
  2059. default:
  2060. // ignore unknown stream types
  2061. return;
  2062. }
  2063. // if a new packet is starting, we can flush the completed
  2064. // packet
  2065. if (data.payloadUnitStartIndicator) {
  2066. flushStream(stream, streamType, true);
  2067. }
  2068. // buffer this fragment until we are sure we've received the
  2069. // complete payload
  2070. stream.data.push(data);
  2071. stream.size += data.data.byteLength;
  2072. },
  2073. pmt: function() {
  2074. var
  2075. event = {
  2076. type: 'metadata',
  2077. tracks: []
  2078. };
  2079. programMapTable = data.programMapTable;
  2080. // translate audio and video streams to tracks
  2081. if (programMapTable.video !== null) {
  2082. event.tracks.push({
  2083. timelineStartInfo: {
  2084. baseMediaDecodeTime: 0
  2085. },
  2086. id: +programMapTable.video,
  2087. codec: 'avc',
  2088. type: 'video'
  2089. });
  2090. }
  2091. if (programMapTable.audio !== null) {
  2092. event.tracks.push({
  2093. timelineStartInfo: {
  2094. baseMediaDecodeTime: 0
  2095. },
  2096. id: +programMapTable.audio,
  2097. codec: 'adts',
  2098. type: 'audio'
  2099. });
  2100. }
  2101. self.trigger('data', event);
  2102. }
  2103. })[data.type]();
  2104. };
  2105. this.reset = function() {
  2106. video.size = 0;
  2107. video.data.length = 0;
  2108. audio.size = 0;
  2109. audio.data.length = 0;
  2110. this.trigger('reset');
  2111. };
  2112. /**
  2113. * Flush any remaining input. Video PES packets may be of variable
  2114. * length. Normally, the start of a new video packet can trigger the
  2115. * finalization of the previous packet. That is not possible if no
  2116. * more video is forthcoming, however. In that case, some other
  2117. * mechanism (like the end of the file) has to be employed. When it is
  2118. * clear that no additional data is forthcoming, calling this method
  2119. * will flush the buffered packets.
  2120. */
  2121. this.flushStreams_ = function() {
  2122. // !!THIS ORDER IS IMPORTANT!!
  2123. // video first then audio
  2124. flushStream(video, 'video');
  2125. flushStream(audio, 'audio');
  2126. flushStream(timedMetadata, 'timed-metadata');
  2127. };
  2128. this.flush = function() {
  2129. this.flushStreams_();
  2130. this.trigger('done');
  2131. };
  2132. };
  2133. ElementaryStream.prototype = new Stream();
  2134. var m2ts = {
  2135. PAT_PID: 0x0000,
  2136. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH,
  2137. TransportPacketStream: TransportPacketStream,
  2138. TransportParseStream: TransportParseStream,
  2139. ElementaryStream: ElementaryStream,
  2140. TimestampRolloverStream: TimestampRolloverStream,
  2141. CaptionStream: CaptionStream.CaptionStream,
  2142. Cea608Stream: CaptionStream.Cea608Stream,
  2143. MetadataStream: require(10)
  2144. };
  2145. for (var type in StreamTypes) {
  2146. if (StreamTypes.hasOwnProperty(type)) {
  2147. m2ts[type] = StreamTypes[type];
  2148. }
  2149. }
  2150. module.exports = m2ts;
  2151. },{"10":10,"11":11,"12":12,"31":31,"8":8}],10:[function(require,module,exports){
  2152. /**
  2153. * mux.js
  2154. *
  2155. * Copyright (c) Brightcove
  2156. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  2157. *
  2158. * Accepts program elementary stream (PES) data events and parses out
  2159. * ID3 metadata from them, if present.
  2160. * @see http://id3.org/id3v2.3.0
  2161. */
  2162. 'use strict';
  2163. var
  2164. Stream = require(31),
  2165. StreamTypes = require(11),
  2166. // return a percent-encoded representation of the specified byte range
  2167. // @see http://en.wikipedia.org/wiki/Percent-encoding
  2168. percentEncode = function(bytes, start, end) {
  2169. var i, result = '';
  2170. for (i = start; i < end; i++) {
  2171. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  2172. }
  2173. return result;
  2174. },
  2175. // return the string representation of the specified byte range,
  2176. // interpreted as UTf-8.
  2177. parseUtf8 = function(bytes, start, end) {
  2178. return decodeURIComponent(percentEncode(bytes, start, end));
  2179. },
  2180. // return the string representation of the specified byte range,
  2181. // interpreted as ISO-8859-1.
  2182. parseIso88591 = function(bytes, start, end) {
  2183. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  2184. },
  2185. parseSyncSafeInteger = function(data) {
  2186. return (data[0] << 21) |
  2187. (data[1] << 14) |
  2188. (data[2] << 7) |
  2189. (data[3]);
  2190. },
  2191. tagParsers = {
  2192. TXXX: function(tag) {
  2193. var i;
  2194. if (tag.data[0] !== 3) {
  2195. // ignore frames with unrecognized character encodings
  2196. return;
  2197. }
  2198. for (i = 1; i < tag.data.length; i++) {
  2199. if (tag.data[i] === 0) {
  2200. // parse the text fields
  2201. tag.description = parseUtf8(tag.data, 1, i);
  2202. // do not include the null terminator in the tag value
  2203. tag.value = parseUtf8(tag.data, i + 1, tag.data.length).replace(/\0*$/, '');
  2204. break;
  2205. }
  2206. }
  2207. tag.data = tag.value;
  2208. },
  2209. WXXX: function(tag) {
  2210. var i;
  2211. if (tag.data[0] !== 3) {
  2212. // ignore frames with unrecognized character encodings
  2213. return;
  2214. }
  2215. for (i = 1; i < tag.data.length; i++) {
  2216. if (tag.data[i] === 0) {
  2217. // parse the description and URL fields
  2218. tag.description = parseUtf8(tag.data, 1, i);
  2219. tag.url = parseUtf8(tag.data, i + 1, tag.data.length);
  2220. break;
  2221. }
  2222. }
  2223. },
  2224. PRIV: function(tag) {
  2225. var i;
  2226. for (i = 0; i < tag.data.length; i++) {
  2227. if (tag.data[i] === 0) {
  2228. // parse the description and URL fields
  2229. tag.owner = parseIso88591(tag.data, 0, i);
  2230. break;
  2231. }
  2232. }
  2233. tag.privateData = tag.data.subarray(i + 1);
  2234. tag.data = tag.privateData;
  2235. }
  2236. },
  2237. MetadataStream;
  2238. MetadataStream = function(options) {
  2239. var
  2240. settings = {
  2241. debug: !!(options && options.debug),
  2242. // the bytes of the program-level descriptor field in MP2T
  2243. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  2244. // program element descriptors"
  2245. descriptor: options && options.descriptor
  2246. },
  2247. // the total size in bytes of the ID3 tag being parsed
  2248. tagSize = 0,
  2249. // tag data that is not complete enough to be parsed
  2250. buffer = [],
  2251. // the total number of bytes currently in the buffer
  2252. bufferSize = 0,
  2253. i;
  2254. MetadataStream.prototype.init.call(this);
  2255. // calculate the text track in-band metadata track dispatch type
  2256. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  2257. this.dispatchType = StreamTypes.METADATA_STREAM_TYPE.toString(16);
  2258. if (settings.descriptor) {
  2259. for (i = 0; i < settings.descriptor.length; i++) {
  2260. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  2261. }
  2262. }
  2263. this.push = function(chunk) {
  2264. var tag, frameStart, frameSize, frame, i, frameHeader;
  2265. if (chunk.type !== 'timed-metadata') {
  2266. return;
  2267. }
  2268. // if data_alignment_indicator is set in the PES header,
  2269. // we must have the start of a new ID3 tag. Assume anything
  2270. // remaining in the buffer was malformed and throw it out
  2271. if (chunk.dataAlignmentIndicator) {
  2272. bufferSize = 0;
  2273. buffer.length = 0;
  2274. }
  2275. // ignore events that don't look like ID3 data
  2276. if (buffer.length === 0 &&
  2277. (chunk.data.length < 10 ||
  2278. chunk.data[0] !== 'I'.charCodeAt(0) ||
  2279. chunk.data[1] !== 'D'.charCodeAt(0) ||
  2280. chunk.data[2] !== '3'.charCodeAt(0))) {
  2281. if (settings.debug) {
  2282. // eslint-disable-next-line no-console
  2283. console.log('Skipping unrecognized metadata packet');
  2284. }
  2285. return;
  2286. }
  2287. // add this chunk to the data we've collected so far
  2288. buffer.push(chunk);
  2289. bufferSize += chunk.data.byteLength;
  2290. // grab the size of the entire frame from the ID3 header
  2291. if (buffer.length === 1) {
  2292. // the frame size is transmitted as a 28-bit integer in the
  2293. // last four bytes of the ID3 header.
  2294. // The most significant bit of each byte is dropped and the
  2295. // results concatenated to recover the actual value.
  2296. tagSize = parseSyncSafeInteger(chunk.data.subarray(6, 10));
  2297. // ID3 reports the tag size excluding the header but it's more
  2298. // convenient for our comparisons to include it
  2299. tagSize += 10;
  2300. }
  2301. // if the entire frame has not arrived, wait for more data
  2302. if (bufferSize < tagSize) {
  2303. return;
  2304. }
  2305. // collect the entire frame so it can be parsed
  2306. tag = {
  2307. data: new Uint8Array(tagSize),
  2308. frames: [],
  2309. pts: buffer[0].pts,
  2310. dts: buffer[0].dts
  2311. };
  2312. for (i = 0; i < tagSize;) {
  2313. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  2314. i += buffer[0].data.byteLength;
  2315. bufferSize -= buffer[0].data.byteLength;
  2316. buffer.shift();
  2317. }
  2318. // find the start of the first frame and the end of the tag
  2319. frameStart = 10;
  2320. if (tag.data[5] & 0x40) {
  2321. // advance the frame start past the extended header
  2322. frameStart += 4; // header size field
  2323. frameStart += parseSyncSafeInteger(tag.data.subarray(10, 14));
  2324. // clip any padding off the end
  2325. tagSize -= parseSyncSafeInteger(tag.data.subarray(16, 20));
  2326. }
  2327. // parse one or more ID3 frames
  2328. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  2329. do {
  2330. // determine the number of bytes in this frame
  2331. frameSize = parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
  2332. if (frameSize < 1) {
  2333. // eslint-disable-next-line no-console
  2334. return console.log('Malformed ID3 frame encountered. Skipping metadata parsing.');
  2335. }
  2336. frameHeader = String.fromCharCode(tag.data[frameStart],
  2337. tag.data[frameStart + 1],
  2338. tag.data[frameStart + 2],
  2339. tag.data[frameStart + 3]);
  2340. frame = {
  2341. id: frameHeader,
  2342. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  2343. };
  2344. frame.key = frame.id;
  2345. if (tagParsers[frame.id]) {
  2346. tagParsers[frame.id](frame);
  2347. // handle the special PRIV frame used to indicate the start
  2348. // time for raw AAC data
  2349. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  2350. var
  2351. d = frame.data,
  2352. size = ((d[3] & 0x01) << 30) |
  2353. (d[4] << 22) |
  2354. (d[5] << 14) |
  2355. (d[6] << 6) |
  2356. (d[7] >>> 2);
  2357. size *= 4;
  2358. size += d[7] & 0x03;
  2359. frame.timeStamp = size;
  2360. // in raw AAC, all subsequent data will be timestamped based
  2361. // on the value of this frame
  2362. // we couldn't have known the appropriate pts and dts before
  2363. // parsing this ID3 tag so set those values now
  2364. if (tag.pts === undefined && tag.dts === undefined) {
  2365. tag.pts = frame.timeStamp;
  2366. tag.dts = frame.timeStamp;
  2367. }
  2368. this.trigger('timestamp', frame);
  2369. }
  2370. }
  2371. tag.frames.push(frame);
  2372. frameStart += 10; // advance past the frame header
  2373. frameStart += frameSize; // advance past the frame body
  2374. } while (frameStart < tagSize);
  2375. this.trigger('data', tag);
  2376. };
  2377. };
  2378. MetadataStream.prototype = new Stream();
  2379. module.exports = MetadataStream;
  2380. },{"11":11,"31":31}],11:[function(require,module,exports){
  2381. /**
  2382. * mux.js
  2383. *
  2384. * Copyright (c) Brightcove
  2385. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  2386. */
  2387. 'use strict';
  2388. module.exports = {
  2389. H264_STREAM_TYPE: 0x1B,
  2390. ADTS_STREAM_TYPE: 0x0F,
  2391. METADATA_STREAM_TYPE: 0x15
  2392. };
  2393. },{}],12:[function(require,module,exports){
  2394. /**
  2395. * mux.js
  2396. *
  2397. * Copyright (c) Brightcove
  2398. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  2399. *
  2400. * Accepts program elementary stream (PES) data events and corrects
  2401. * decode and presentation time stamps to account for a rollover
  2402. * of the 33 bit value.
  2403. */
  2404. 'use strict';
  2405. var Stream = require(31);
  2406. var MAX_TS = 8589934592;
  2407. var RO_THRESH = 4294967296;
  2408. var TYPE_SHARED = 'shared';
  2409. var handleRollover = function(value, reference) {
  2410. var direction = 1;
  2411. if (value > reference) {
  2412. // If the current timestamp value is greater than our reference timestamp and we detect a
  2413. // timestamp rollover, this means the roll over is happening in the opposite direction.
  2414. // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
  2415. // point will be set to a small number, e.g. 1. The user then seeks backwards over the
  2416. // rollover point. In loading this segment, the timestamp values will be very large,
  2417. // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
  2418. // the time stamp to be `value - 2^33`.
  2419. direction = -1;
  2420. }
  2421. // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  2422. // cause an incorrect adjustment.
  2423. while (Math.abs(reference - value) > RO_THRESH) {
  2424. value += (direction * MAX_TS);
  2425. }
  2426. return value;
  2427. };
  2428. var TimestampRolloverStream = function(type) {
  2429. var lastDTS, referenceDTS;
  2430. TimestampRolloverStream.prototype.init.call(this);
  2431. // The "shared" type is used in cases where a stream will contain muxed
  2432. // video and audio. We could use `undefined` here, but having a string
  2433. // makes debugging a little clearer.
  2434. this.type_ = type || TYPE_SHARED;
  2435. this.push = function(data) {
  2436. // Any "shared" rollover streams will accept _all_ data. Otherwise,
  2437. // streams will only accept data that matches their type.
  2438. if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
  2439. return;
  2440. }
  2441. if (referenceDTS === undefined) {
  2442. referenceDTS = data.dts;
  2443. }
  2444. data.dts = handleRollover(data.dts, referenceDTS);
  2445. data.pts = handleRollover(data.pts, referenceDTS);
  2446. lastDTS = data.dts;
  2447. this.trigger('data', data);
  2448. };
  2449. this.flush = function() {
  2450. referenceDTS = lastDTS;
  2451. this.trigger('done');
  2452. };
  2453. this.endTimeline = function() {
  2454. this.flush();
  2455. this.trigger('endedtimeline');
  2456. };
  2457. this.discontinuity = function() {
  2458. referenceDTS = void 0;
  2459. lastDTS = void 0;
  2460. };
  2461. this.reset = function() {
  2462. this.discontinuity();
  2463. this.trigger('reset');
  2464. };
  2465. };
  2466. TimestampRolloverStream.prototype = new Stream();
  2467. module.exports = {
  2468. TimestampRolloverStream: TimestampRolloverStream,
  2469. handleRollover: handleRollover
  2470. };
  2471. },{"31":31}],13:[function(require,module,exports){
  2472. /**
  2473. * mux.js
  2474. *
  2475. * Copyright (c) Brightcove
  2476. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  2477. */
  2478. var coneOfSilence = require(7);
  2479. var clock = require(29);
  2480. /**
  2481. * Sum the `byteLength` properties of the data in each AAC frame
  2482. */
  2483. var sumFrameByteLengths = function(array) {
  2484. var
  2485. i,
  2486. currentObj,
  2487. sum = 0;
  2488. // sum the byteLength's all each nal unit in the frame
  2489. for (i = 0; i < array.length; i++) {
  2490. currentObj = array[i];
  2491. sum += currentObj.data.byteLength;
  2492. }
  2493. return sum;
  2494. };
  2495. // Possibly pad (prefix) the audio track with silence if appending this track
  2496. // would lead to the introduction of a gap in the audio buffer
  2497. var prefixWithSilence = function(
  2498. track,
  2499. frames,
  2500. audioAppendStartTs,
  2501. videoBaseMediaDecodeTime
  2502. ) {
  2503. var
  2504. baseMediaDecodeTimeTs,
  2505. frameDuration = 0,
  2506. audioGapDuration = 0,
  2507. audioFillFrameCount = 0,
  2508. audioFillDuration = 0,
  2509. silentFrame,
  2510. i,
  2511. firstFrame;
  2512. if (!frames.length) {
  2513. return;
  2514. }
  2515. baseMediaDecodeTimeTs =
  2516. clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate);
  2517. // determine frame clock duration based on sample rate, round up to avoid overfills
  2518. frameDuration = Math.ceil(clock.ONE_SECOND_IN_TS / (track.samplerate / 1024));
  2519. if (audioAppendStartTs && videoBaseMediaDecodeTime) {
  2520. // insert the shortest possible amount (audio gap or audio to video gap)
  2521. audioGapDuration =
  2522. baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime);
  2523. // number of full frames in the audio gap
  2524. audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
  2525. audioFillDuration = audioFillFrameCount * frameDuration;
  2526. }
  2527. // don't attempt to fill gaps smaller than a single frame or larger
  2528. // than a half second
  2529. if (audioFillFrameCount < 1 || audioFillDuration > clock.ONE_SECOND_IN_TS / 2) {
  2530. return;
  2531. }
  2532. silentFrame = coneOfSilence()[track.samplerate];
  2533. if (!silentFrame) {
  2534. // we don't have a silent frame pregenerated for the sample rate, so use a frame
  2535. // from the content instead
  2536. silentFrame = frames[0].data;
  2537. }
  2538. for (i = 0; i < audioFillFrameCount; i++) {
  2539. firstFrame = frames[0];
  2540. frames.splice(0, 0, {
  2541. data: silentFrame,
  2542. dts: firstFrame.dts - frameDuration,
  2543. pts: firstFrame.pts - frameDuration
  2544. });
  2545. }
  2546. track.baseMediaDecodeTime -=
  2547. Math.floor(clock.videoTsToAudioTs(audioFillDuration, track.samplerate));
  2548. };
  2549. // If the audio segment extends before the earliest allowed dts
  2550. // value, remove AAC frames until starts at or after the earliest
  2551. // allowed DTS so that we don't end up with a negative baseMedia-
  2552. // DecodeTime for the audio track
  2553. var trimAdtsFramesByEarliestDts = function(adtsFrames, track, earliestAllowedDts) {
  2554. if (track.minSegmentDts >= earliestAllowedDts) {
  2555. return adtsFrames;
  2556. }
  2557. // We will need to recalculate the earliest segment Dts
  2558. track.minSegmentDts = Infinity;
  2559. return adtsFrames.filter(function(currentFrame) {
  2560. // If this is an allowed frame, keep it and record it's Dts
  2561. if (currentFrame.dts >= earliestAllowedDts) {
  2562. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  2563. track.minSegmentPts = track.minSegmentDts;
  2564. return true;
  2565. }
  2566. // Otherwise, discard it
  2567. return false;
  2568. });
  2569. };
  2570. // generate the track's raw mdat data from an array of frames
  2571. var generateSampleTable = function(frames) {
  2572. var
  2573. i,
  2574. currentFrame,
  2575. samples = [];
  2576. for (i = 0; i < frames.length; i++) {
  2577. currentFrame = frames[i];
  2578. samples.push({
  2579. size: currentFrame.data.byteLength,
  2580. duration: 1024 // For AAC audio, all samples contain 1024 samples
  2581. });
  2582. }
  2583. return samples;
  2584. };
  2585. // generate the track's sample table from an array of frames
  2586. var concatenateFrameData = function(frames) {
  2587. var
  2588. i,
  2589. currentFrame,
  2590. dataOffset = 0,
  2591. data = new Uint8Array(sumFrameByteLengths(frames));
  2592. for (i = 0; i < frames.length; i++) {
  2593. currentFrame = frames[i];
  2594. data.set(currentFrame.data, dataOffset);
  2595. dataOffset += currentFrame.data.byteLength;
  2596. }
  2597. return data;
  2598. };
  2599. module.exports = {
  2600. prefixWithSilence: prefixWithSilence,
  2601. trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  2602. generateSampleTable: generateSampleTable,
  2603. concatenateFrameData: concatenateFrameData
  2604. };
  2605. },{"29":29,"7":7}],14:[function(require,module,exports){
  2606. /**
  2607. * mux.js
  2608. *
  2609. * Copyright (c) Brightcove
  2610. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  2611. *
  2612. * Reads in-band CEA-708 captions out of FMP4 segments.
  2613. * @see https://en.wikipedia.org/wiki/CEA-708
  2614. */
  2615. 'use strict';
  2616. var discardEmulationPreventionBytes = require(23).discardEmulationPreventionBytes;
  2617. var CaptionStream = require(8).CaptionStream;
  2618. var findBox = require(15);
  2619. var parseTfdt = require(25);
  2620. var parseTrun = require(27);
  2621. var parseTfhd = require(26);
  2622. /**
  2623. * Maps an offset in the mdat to a sample based on the the size of the samples.
  2624. * Assumes that `parseSamples` has been called first.
  2625. *
  2626. * @param {Number} offset - The offset into the mdat
  2627. * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  2628. * @return {?Object} The matching sample, or null if no match was found.
  2629. *
  2630. * @see ISO-BMFF-12/2015, Section 8.8.8
  2631. **/
  2632. var mapToSample = function(offset, samples) {
  2633. var approximateOffset = offset;
  2634. for (var i = 0; i < samples.length; i++) {
  2635. var sample = samples[i];
  2636. if (approximateOffset < sample.size) {
  2637. return sample;
  2638. }
  2639. approximateOffset -= sample.size;
  2640. }
  2641. return null;
  2642. };
  2643. /**
  2644. * Finds SEI nal units contained in a Media Data Box.
  2645. * Assumes that `parseSamples` has been called first.
  2646. *
  2647. * @param {Uint8Array} avcStream - The bytes of the mdat
  2648. * @param {Object[]} samples - The samples parsed out by `parseSamples`
  2649. * @param {Number} trackId - The trackId of this video track
  2650. * @return {Object[]} seiNals - the parsed SEI NALUs found.
  2651. * The contents of the seiNal should match what is expected by
  2652. * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  2653. *
  2654. * @see ISO-BMFF-12/2015, Section 8.1.1
  2655. * @see Rec. ITU-T H.264, 7.3.2.3.1
  2656. **/
  2657. var findSeiNals = function(avcStream, samples, trackId) {
  2658. var
  2659. avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  2660. result = [],
  2661. seiNal,
  2662. i,
  2663. length,
  2664. lastMatchedSample;
  2665. for (i = 0; i + 4 < avcStream.length; i += length) {
  2666. length = avcView.getUint32(i);
  2667. i += 4;
  2668. // Bail if this doesn't appear to be an H264 stream
  2669. if (length <= 0) {
  2670. continue;
  2671. }
  2672. switch (avcStream[i] & 0x1F) {
  2673. case 0x06:
  2674. var data = avcStream.subarray(i + 1, i + 1 + length);
  2675. var matchingSample = mapToSample(i, samples);
  2676. seiNal = {
  2677. nalUnitType: 'sei_rbsp',
  2678. size: length,
  2679. data: data,
  2680. escapedRBSP: discardEmulationPreventionBytes(data),
  2681. trackId: trackId
  2682. };
  2683. if (matchingSample) {
  2684. seiNal.pts = matchingSample.pts;
  2685. seiNal.dts = matchingSample.dts;
  2686. lastMatchedSample = matchingSample;
  2687. } else if (lastMatchedSample) {
  2688. // If a matching sample cannot be found, use the last
  2689. // sample's values as they should be as close as possible
  2690. seiNal.pts = lastMatchedSample.pts;
  2691. seiNal.dts = lastMatchedSample.dts;
  2692. } else {
  2693. // eslint-disable-next-line no-console
  2694. console.log("We've encountered a nal unit without data. See mux.js#233.");
  2695. break;
  2696. }
  2697. result.push(seiNal);
  2698. break;
  2699. default:
  2700. break;
  2701. }
  2702. }
  2703. return result;
  2704. };
  2705. /**
  2706. * Parses sample information out of Track Run Boxes and calculates
  2707. * the absolute presentation and decode timestamps of each sample.
  2708. *
  2709. * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  2710. * @param {Number} baseMediaDecodeTime - base media decode time from tfdt
  2711. @see ISO-BMFF-12/2015, Section 8.8.12
  2712. * @param {Object} tfhd - The parsed Track Fragment Header
  2713. * @see inspect.parseTfhd
  2714. * @return {Object[]} the parsed samples
  2715. *
  2716. * @see ISO-BMFF-12/2015, Section 8.8.8
  2717. **/
  2718. var parseSamples = function(truns, baseMediaDecodeTime, tfhd) {
  2719. var currentDts = baseMediaDecodeTime;
  2720. var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  2721. var defaultSampleSize = tfhd.defaultSampleSize || 0;
  2722. var trackId = tfhd.trackId;
  2723. var allSamples = [];
  2724. truns.forEach(function(trun) {
  2725. // Note: We currently do not parse the sample table as well
  2726. // as the trun. It's possible some sources will require this.
  2727. // moov > trak > mdia > minf > stbl
  2728. var trackRun = parseTrun(trun);
  2729. var samples = trackRun.samples;
  2730. samples.forEach(function(sample) {
  2731. if (sample.duration === undefined) {
  2732. sample.duration = defaultSampleDuration;
  2733. }
  2734. if (sample.size === undefined) {
  2735. sample.size = defaultSampleSize;
  2736. }
  2737. sample.trackId = trackId;
  2738. sample.dts = currentDts;
  2739. if (sample.compositionTimeOffset === undefined) {
  2740. sample.compositionTimeOffset = 0;
  2741. }
  2742. sample.pts = currentDts + sample.compositionTimeOffset;
  2743. currentDts += sample.duration;
  2744. });
  2745. allSamples = allSamples.concat(samples);
  2746. });
  2747. return allSamples;
  2748. };
  2749. /**
  2750. * Parses out caption nals from an FMP4 segment's video tracks.
  2751. *
  2752. * @param {Uint8Array} segment - The bytes of a single segment
  2753. * @param {Number} videoTrackId - The trackId of a video track in the segment
  2754. * @return {Object.<Number, Object[]>} A mapping of video trackId to
  2755. * a list of seiNals found in that track
  2756. **/
  2757. var parseCaptionNals = function(segment, videoTrackId) {
  2758. // To get the samples
  2759. var trafs = findBox(segment, ['moof', 'traf']);
  2760. // To get SEI NAL units
  2761. var mdats = findBox(segment, ['mdat']);
  2762. var captionNals = {};
  2763. var mdatTrafPairs = [];
  2764. // Pair up each traf with a mdat as moofs and mdats are in pairs
  2765. mdats.forEach(function(mdat, index) {
  2766. var matchingTraf = trafs[index];
  2767. mdatTrafPairs.push({
  2768. mdat: mdat,
  2769. traf: matchingTraf
  2770. });
  2771. });
  2772. mdatTrafPairs.forEach(function(pair) {
  2773. var mdat = pair.mdat;
  2774. var traf = pair.traf;
  2775. var tfhd = findBox(traf, ['tfhd']);
  2776. // Exactly 1 tfhd per traf
  2777. var headerInfo = parseTfhd(tfhd[0]);
  2778. var trackId = headerInfo.trackId;
  2779. var tfdt = findBox(traf, ['tfdt']);
  2780. // Either 0 or 1 tfdt per traf
  2781. var baseMediaDecodeTime = (tfdt.length > 0) ? parseTfdt(tfdt[0]).baseMediaDecodeTime : 0;
  2782. var truns = findBox(traf, ['trun']);
  2783. var samples;
  2784. var seiNals;
  2785. // Only parse video data for the chosen video track
  2786. if (videoTrackId === trackId && truns.length > 0) {
  2787. samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
  2788. seiNals = findSeiNals(mdat, samples, trackId);
  2789. if (!captionNals[trackId]) {
  2790. captionNals[trackId] = [];
  2791. }
  2792. captionNals[trackId] = captionNals[trackId].concat(seiNals);
  2793. }
  2794. });
  2795. return captionNals;
  2796. };
  2797. /**
  2798. * Parses out inband captions from an MP4 container and returns
  2799. * caption objects that can be used by WebVTT and the TextTrack API.
  2800. * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  2801. * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  2802. * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  2803. *
  2804. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  2805. * @param {Number} trackId - The id of the video track to parse
  2806. * @param {Number} timescale - The timescale for the video track from the init segment
  2807. *
  2808. * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  2809. * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  2810. * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  2811. * @return {String} parsedCaptions[].text - The visible content of the caption
  2812. **/
  2813. var parseEmbeddedCaptions = function(segment, trackId, timescale) {
  2814. var seiNals;
  2815. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  2816. if (trackId === null) {
  2817. return null;
  2818. }
  2819. seiNals = parseCaptionNals(segment, trackId);
  2820. return {
  2821. seiNals: seiNals[trackId],
  2822. timescale: timescale
  2823. };
  2824. };
  2825. /**
  2826. * Converts SEI NALUs into captions that can be used by video.js
  2827. **/
  2828. var CaptionParser = function() {
  2829. var isInitialized = false;
  2830. var captionStream;
  2831. // Stores segments seen before trackId and timescale are set
  2832. var segmentCache;
  2833. // Stores video track ID of the track being parsed
  2834. var trackId;
  2835. // Stores the timescale of the track being parsed
  2836. var timescale;
  2837. // Stores captions parsed so far
  2838. var parsedCaptions;
  2839. // Stores whether we are receiving partial data or not
  2840. var parsingPartial;
  2841. /**
  2842. * A method to indicate whether a CaptionParser has been initalized
  2843. * @returns {Boolean}
  2844. **/
  2845. this.isInitialized = function() {
  2846. return isInitialized;
  2847. };
  2848. /**
  2849. * Initializes the underlying CaptionStream, SEI NAL parsing
  2850. * and management, and caption collection
  2851. **/
  2852. this.init = function(options) {
  2853. captionStream = new CaptionStream();
  2854. isInitialized = true;
  2855. parsingPartial = options ? options.isPartial : false;
  2856. // Collect dispatched captions
  2857. captionStream.on('data', function(event) {
  2858. // Convert to seconds in the source's timescale
  2859. event.startTime = event.startPts / timescale;
  2860. event.endTime = event.endPts / timescale;
  2861. parsedCaptions.captions.push(event);
  2862. parsedCaptions.captionStreams[event.stream] = true;
  2863. });
  2864. };
  2865. /**
  2866. * Determines if a new video track will be selected
  2867. * or if the timescale changed
  2868. * @return {Boolean}
  2869. **/
  2870. this.isNewInit = function(videoTrackIds, timescales) {
  2871. if ((videoTrackIds && videoTrackIds.length === 0) ||
  2872. (timescales && typeof timescales === 'object' &&
  2873. Object.keys(timescales).length === 0)) {
  2874. return false;
  2875. }
  2876. return trackId !== videoTrackIds[0] ||
  2877. timescale !== timescales[trackId];
  2878. };
  2879. /**
  2880. * Parses out SEI captions and interacts with underlying
  2881. * CaptionStream to return dispatched captions
  2882. *
  2883. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  2884. * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
  2885. * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
  2886. * @see parseEmbeddedCaptions
  2887. * @see m2ts/caption-stream.js
  2888. **/
  2889. this.parse = function(segment, videoTrackIds, timescales) {
  2890. var parsedData;
  2891. if (!this.isInitialized()) {
  2892. return null;
  2893. // This is not likely to be a video segment
  2894. } else if (!videoTrackIds || !timescales) {
  2895. return null;
  2896. } else if (this.isNewInit(videoTrackIds, timescales)) {
  2897. // Use the first video track only as there is no
  2898. // mechanism to switch to other video tracks
  2899. trackId = videoTrackIds[0];
  2900. timescale = timescales[trackId];
  2901. // If an init segment has not been seen yet, hold onto segment
  2902. // data until we have one.
  2903. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  2904. } else if (trackId === null || !timescale) {
  2905. segmentCache.push(segment);
  2906. return null;
  2907. }
  2908. // Now that a timescale and trackId is set, parse cached segments
  2909. while (segmentCache.length > 0) {
  2910. var cachedSegment = segmentCache.shift();
  2911. this.parse(cachedSegment, videoTrackIds, timescales);
  2912. }
  2913. parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
  2914. if (parsedData === null || !parsedData.seiNals) {
  2915. return null;
  2916. }
  2917. this.pushNals(parsedData.seiNals);
  2918. // Force the parsed captions to be dispatched
  2919. this.flushStream();
  2920. return parsedCaptions;
  2921. };
  2922. /**
  2923. * Pushes SEI NALUs onto CaptionStream
  2924. * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
  2925. * Assumes that `parseCaptionNals` has been called first
  2926. * @see m2ts/caption-stream.js
  2927. **/
  2928. this.pushNals = function(nals) {
  2929. if (!this.isInitialized() || !nals || nals.length === 0) {
  2930. return null;
  2931. }
  2932. nals.forEach(function(nal) {
  2933. captionStream.push(nal);
  2934. });
  2935. };
  2936. /**
  2937. * Flushes underlying CaptionStream to dispatch processed, displayable captions
  2938. * @see m2ts/caption-stream.js
  2939. **/
  2940. this.flushStream = function() {
  2941. if (!this.isInitialized()) {
  2942. return null;
  2943. }
  2944. if (!parsingPartial) {
  2945. captionStream.flush();
  2946. } else {
  2947. captionStream.partialFlush();
  2948. }
  2949. };
  2950. /**
  2951. * Reset caption buckets for new data
  2952. **/
  2953. this.clearParsedCaptions = function() {
  2954. parsedCaptions.captions = [];
  2955. parsedCaptions.captionStreams = {};
  2956. };
  2957. /**
  2958. * Resets underlying CaptionStream
  2959. * @see m2ts/caption-stream.js
  2960. **/
  2961. this.resetCaptionStream = function() {
  2962. if (!this.isInitialized()) {
  2963. return null;
  2964. }
  2965. captionStream.reset();
  2966. };
  2967. /**
  2968. * Convenience method to clear all captions flushed from the
  2969. * CaptionStream and still being parsed
  2970. * @see m2ts/caption-stream.js
  2971. **/
  2972. this.clearAllCaptions = function() {
  2973. this.clearParsedCaptions();
  2974. this.resetCaptionStream();
  2975. };
  2976. /**
  2977. * Reset caption parser
  2978. **/
  2979. this.reset = function() {
  2980. segmentCache = [];
  2981. trackId = null;
  2982. timescale = null;
  2983. if (!parsedCaptions) {
  2984. parsedCaptions = {
  2985. captions: [],
  2986. // CC1, CC2, CC3, CC4
  2987. captionStreams: {}
  2988. };
  2989. } else {
  2990. this.clearParsedCaptions();
  2991. }
  2992. this.resetCaptionStream();
  2993. };
  2994. this.reset();
  2995. };
  2996. module.exports = CaptionParser;
  2997. },{"15":15,"23":23,"25":25,"26":26,"27":27,"8":8}],15:[function(require,module,exports){
  2998. var toUnsigned = require(28).toUnsigned;
  2999. var parseType = require(19);
  3000. var findBox = function(data, path) {
  3001. var results = [],
  3002. i, size, type, end, subresults;
  3003. if (!path.length) {
  3004. // short-circuit the search for empty paths
  3005. return null;
  3006. }
  3007. for (i = 0; i < data.byteLength;) {
  3008. size = toUnsigned(data[i] << 24 |
  3009. data[i + 1] << 16 |
  3010. data[i + 2] << 8 |
  3011. data[i + 3]);
  3012. type = parseType(data.subarray(i + 4, i + 8));
  3013. end = size > 1 ? i + size : data.byteLength;
  3014. if (type === path[0]) {
  3015. if (path.length === 1) {
  3016. // this is the end of the path and we've found the box we were
  3017. // looking for
  3018. results.push(data.subarray(i + 8, end));
  3019. } else {
  3020. // recursively search for the next box along the path
  3021. subresults = findBox(data.subarray(i + 8, end), path.slice(1));
  3022. if (subresults.length) {
  3023. results = results.concat(subresults);
  3024. }
  3025. }
  3026. }
  3027. i = end;
  3028. }
  3029. // we've finished searching all of data
  3030. return results;
  3031. };
  3032. module.exports = findBox;
  3033. },{"19":19,"28":28}],16:[function(require,module,exports){
  3034. /**
  3035. * mux.js
  3036. *
  3037. * Copyright (c) Brightcove
  3038. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  3039. */
  3040. // Convert an array of nal units into an array of frames with each frame being
  3041. // composed of the nal units that make up that frame
  3042. // Also keep track of cummulative data about the frame from the nal units such
  3043. // as the frame duration, starting pts, etc.
  3044. var groupNalsIntoFrames = function(nalUnits) {
  3045. var
  3046. i,
  3047. currentNal,
  3048. currentFrame = [],
  3049. frames = [];
  3050. // TODO added for LHLS, make sure this is OK
  3051. frames.byteLength = 0;
  3052. frames.nalCount = 0;
  3053. frames.duration = 0;
  3054. currentFrame.byteLength = 0;
  3055. for (i = 0; i < nalUnits.length; i++) {
  3056. currentNal = nalUnits[i];
  3057. // Split on 'aud'-type nal units
  3058. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  3059. // Since the very first nal unit is expected to be an AUD
  3060. // only push to the frames array when currentFrame is not empty
  3061. if (currentFrame.length) {
  3062. currentFrame.duration = currentNal.dts - currentFrame.dts;
  3063. // TODO added for LHLS, make sure this is OK
  3064. frames.byteLength += currentFrame.byteLength;
  3065. frames.nalCount += currentFrame.length;
  3066. frames.duration += currentFrame.duration;
  3067. frames.push(currentFrame);
  3068. }
  3069. currentFrame = [currentNal];
  3070. currentFrame.byteLength = currentNal.data.byteLength;
  3071. currentFrame.pts = currentNal.pts;
  3072. currentFrame.dts = currentNal.dts;
  3073. } else {
  3074. // Specifically flag key frames for ease of use later
  3075. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  3076. currentFrame.keyFrame = true;
  3077. }
  3078. currentFrame.duration = currentNal.dts - currentFrame.dts;
  3079. currentFrame.byteLength += currentNal.data.byteLength;
  3080. currentFrame.push(currentNal);
  3081. }
  3082. }
  3083. // For the last frame, use the duration of the previous frame if we
  3084. // have nothing better to go on
  3085. if (frames.length &&
  3086. (!currentFrame.duration ||
  3087. currentFrame.duration <= 0)) {
  3088. currentFrame.duration = frames[frames.length - 1].duration;
  3089. }
  3090. // Push the final frame
  3091. // TODO added for LHLS, make sure this is OK
  3092. frames.byteLength += currentFrame.byteLength;
  3093. frames.nalCount += currentFrame.length;
  3094. frames.duration += currentFrame.duration;
  3095. frames.push(currentFrame);
  3096. return frames;
  3097. };
  3098. // Convert an array of frames into an array of Gop with each Gop being composed
  3099. // of the frames that make up that Gop
  3100. // Also keep track of cummulative data about the Gop from the frames such as the
  3101. // Gop duration, starting pts, etc.
  3102. var groupFramesIntoGops = function(frames) {
  3103. var
  3104. i,
  3105. currentFrame,
  3106. currentGop = [],
  3107. gops = [];
  3108. // We must pre-set some of the values on the Gop since we
  3109. // keep running totals of these values
  3110. currentGop.byteLength = 0;
  3111. currentGop.nalCount = 0;
  3112. currentGop.duration = 0;
  3113. currentGop.pts = frames[0].pts;
  3114. currentGop.dts = frames[0].dts;
  3115. // store some metadata about all the Gops
  3116. gops.byteLength = 0;
  3117. gops.nalCount = 0;
  3118. gops.duration = 0;
  3119. gops.pts = frames[0].pts;
  3120. gops.dts = frames[0].dts;
  3121. for (i = 0; i < frames.length; i++) {
  3122. currentFrame = frames[i];
  3123. if (currentFrame.keyFrame) {
  3124. // Since the very first frame is expected to be an keyframe
  3125. // only push to the gops array when currentGop is not empty
  3126. if (currentGop.length) {
  3127. gops.push(currentGop);
  3128. gops.byteLength += currentGop.byteLength;
  3129. gops.nalCount += currentGop.nalCount;
  3130. gops.duration += currentGop.duration;
  3131. }
  3132. currentGop = [currentFrame];
  3133. currentGop.nalCount = currentFrame.length;
  3134. currentGop.byteLength = currentFrame.byteLength;
  3135. currentGop.pts = currentFrame.pts;
  3136. currentGop.dts = currentFrame.dts;
  3137. currentGop.duration = currentFrame.duration;
  3138. } else {
  3139. currentGop.duration += currentFrame.duration;
  3140. currentGop.nalCount += currentFrame.length;
  3141. currentGop.byteLength += currentFrame.byteLength;
  3142. currentGop.push(currentFrame);
  3143. }
  3144. }
  3145. if (gops.length && currentGop.duration <= 0) {
  3146. currentGop.duration = gops[gops.length - 1].duration;
  3147. }
  3148. gops.byteLength += currentGop.byteLength;
  3149. gops.nalCount += currentGop.nalCount;
  3150. gops.duration += currentGop.duration;
  3151. // push the final Gop
  3152. gops.push(currentGop);
  3153. return gops;
  3154. };
  3155. /*
  3156. * Search for the first keyframe in the GOPs and throw away all frames
  3157. * until that keyframe. Then extend the duration of the pulled keyframe
  3158. * and pull the PTS and DTS of the keyframe so that it covers the time
  3159. * range of the frames that were disposed.
  3160. *
  3161. * @param {Array} gops video GOPs
  3162. * @returns {Array} modified video GOPs
  3163. */
  3164. var extendFirstKeyFrame = function(gops) {
  3165. var currentGop;
  3166. if (!gops[0][0].keyFrame && gops.length > 1) {
  3167. // Remove the first GOP
  3168. currentGop = gops.shift();
  3169. gops.byteLength -= currentGop.byteLength;
  3170. gops.nalCount -= currentGop.nalCount;
  3171. // Extend the first frame of what is now the
  3172. // first gop to cover the time period of the
  3173. // frames we just removed
  3174. gops[0][0].dts = currentGop.dts;
  3175. gops[0][0].pts = currentGop.pts;
  3176. gops[0][0].duration += currentGop.duration;
  3177. }
  3178. return gops;
  3179. };
  3180. /**
  3181. * Default sample object
  3182. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  3183. */
  3184. var createDefaultSample = function() {
  3185. return {
  3186. size: 0,
  3187. flags: {
  3188. isLeading: 0,
  3189. dependsOn: 1,
  3190. isDependedOn: 0,
  3191. hasRedundancy: 0,
  3192. degradationPriority: 0,
  3193. isNonSyncSample: 1
  3194. }
  3195. };
  3196. };
  3197. /*
  3198. * Collates information from a video frame into an object for eventual
  3199. * entry into an MP4 sample table.
  3200. *
  3201. * @param {Object} frame the video frame
  3202. * @param {Number} dataOffset the byte offset to position the sample
  3203. * @return {Object} object containing sample table info for a frame
  3204. */
  3205. var sampleForFrame = function(frame, dataOffset) {
  3206. var sample = createDefaultSample();
  3207. sample.dataOffset = dataOffset;
  3208. sample.compositionTimeOffset = frame.pts - frame.dts;
  3209. sample.duration = frame.duration;
  3210. sample.size = 4 * frame.length; // Space for nal unit size
  3211. sample.size += frame.byteLength;
  3212. if (frame.keyFrame) {
  3213. sample.flags.dependsOn = 2;
  3214. sample.flags.isNonSyncSample = 0;
  3215. }
  3216. return sample;
  3217. };
  3218. // generate the track's sample table from an array of gops
  3219. var generateSampleTable = function(gops, baseDataOffset) {
  3220. var
  3221. h, i,
  3222. sample,
  3223. currentGop,
  3224. currentFrame,
  3225. dataOffset = baseDataOffset || 0,
  3226. samples = [];
  3227. for (h = 0; h < gops.length; h++) {
  3228. currentGop = gops[h];
  3229. for (i = 0; i < currentGop.length; i++) {
  3230. currentFrame = currentGop[i];
  3231. sample = sampleForFrame(currentFrame, dataOffset);
  3232. dataOffset += sample.size;
  3233. samples.push(sample);
  3234. }
  3235. }
  3236. return samples;
  3237. };
  3238. // generate the track's raw mdat data from an array of gops
  3239. var concatenateNalData = function(gops) {
  3240. var
  3241. h, i, j,
  3242. currentGop,
  3243. currentFrame,
  3244. currentNal,
  3245. dataOffset = 0,
  3246. nalsByteLength = gops.byteLength,
  3247. numberOfNals = gops.nalCount,
  3248. totalByteLength = nalsByteLength + 4 * numberOfNals,
  3249. data = new Uint8Array(totalByteLength),
  3250. view = new DataView(data.buffer);
  3251. // For each Gop..
  3252. for (h = 0; h < gops.length; h++) {
  3253. currentGop = gops[h];
  3254. // For each Frame..
  3255. for (i = 0; i < currentGop.length; i++) {
  3256. currentFrame = currentGop[i];
  3257. // For each NAL..
  3258. for (j = 0; j < currentFrame.length; j++) {
  3259. currentNal = currentFrame[j];
  3260. view.setUint32(dataOffset, currentNal.data.byteLength);
  3261. dataOffset += 4;
  3262. data.set(currentNal.data, dataOffset);
  3263. dataOffset += currentNal.data.byteLength;
  3264. }
  3265. }
  3266. }
  3267. return data;
  3268. };
  3269. // generate the track's sample table from a frame
  3270. var generateSampleTableForFrame = function(frame, baseDataOffset) {
  3271. var
  3272. sample,
  3273. dataOffset = baseDataOffset || 0,
  3274. samples = [];
  3275. sample = sampleForFrame(frame, dataOffset);
  3276. samples.push(sample);
  3277. return samples;
  3278. };
  3279. // generate the track's raw mdat data from a frame
  3280. var concatenateNalDataForFrame = function(frame) {
  3281. var
  3282. i,
  3283. currentNal,
  3284. dataOffset = 0,
  3285. nalsByteLength = frame.byteLength,
  3286. numberOfNals = frame.length,
  3287. totalByteLength = nalsByteLength + 4 * numberOfNals,
  3288. data = new Uint8Array(totalByteLength),
  3289. view = new DataView(data.buffer);
  3290. // For each NAL..
  3291. for (i = 0; i < frame.length; i++) {
  3292. currentNal = frame[i];
  3293. view.setUint32(dataOffset, currentNal.data.byteLength);
  3294. dataOffset += 4;
  3295. data.set(currentNal.data, dataOffset);
  3296. dataOffset += currentNal.data.byteLength;
  3297. }
  3298. return data;
  3299. };
  3300. module.exports = {
  3301. groupNalsIntoFrames: groupNalsIntoFrames,
  3302. groupFramesIntoGops: groupFramesIntoGops,
  3303. extendFirstKeyFrame: extendFirstKeyFrame,
  3304. generateSampleTable: generateSampleTable,
  3305. concatenateNalData: concatenateNalData,
  3306. generateSampleTableForFrame: generateSampleTableForFrame,
  3307. concatenateNalDataForFrame: concatenateNalDataForFrame
  3308. };
  3309. },{}],17:[function(require,module,exports){
  3310. /**
  3311. * mux.js
  3312. *
  3313. * Copyright (c) Brightcove
  3314. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  3315. */
  3316. module.exports = {
  3317. generator: require(18),
  3318. probe: require(20),
  3319. Transmuxer: require(22).Transmuxer,
  3320. AudioSegmentStream: require(22).AudioSegmentStream,
  3321. VideoSegmentStream: require(22).VideoSegmentStream,
  3322. CaptionParser: require(14)
  3323. };
  3324. },{"14":14,"18":18,"20":20,"22":22}],18:[function(require,module,exports){
  3325. /**
  3326. * mux.js
  3327. *
  3328. * Copyright (c) Brightcove
  3329. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  3330. *
  3331. * Functions that generate fragmented MP4s suitable for use with Media
  3332. * Source Extensions.
  3333. */
  3334. 'use strict';
  3335. var UINT32_MAX = Math.pow(2, 32) - 1;
  3336. var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd,
  3337. trak, tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, traf, trex,
  3338. trun, types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR,
  3339. AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS;
  3340. var customDuration = 0xffffffff;
  3341. // pre-calculate constants
  3342. (function() {
  3343. var i;
  3344. types = {
  3345. avc1: [], // codingname
  3346. avcC: [],
  3347. btrt: [],
  3348. dinf: [],
  3349. dref: [],
  3350. esds: [],
  3351. ftyp: [],
  3352. hdlr: [],
  3353. mdat: [],
  3354. mdhd: [],
  3355. mdia: [],
  3356. mfhd: [],
  3357. minf: [],
  3358. moof: [],
  3359. moov: [],
  3360. mp4a: [], // codingname
  3361. mvex: [],
  3362. mvhd: [],
  3363. pasp: [],
  3364. sdtp: [],
  3365. smhd: [],
  3366. stbl: [],
  3367. stco: [],
  3368. stsc: [],
  3369. stsd: [],
  3370. stsz: [],
  3371. stts: [],
  3372. styp: [],
  3373. tfdt: [],
  3374. tfhd: [],
  3375. traf: [],
  3376. trak: [],
  3377. trun: [],
  3378. trex: [],
  3379. tkhd: [],
  3380. vmhd: []
  3381. };
  3382. // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  3383. // don't throw an error
  3384. if (typeof Uint8Array === 'undefined') {
  3385. return;
  3386. }
  3387. for (i in types) {
  3388. if (types.hasOwnProperty(i)) {
  3389. types[i] = [
  3390. i.charCodeAt(0),
  3391. i.charCodeAt(1),
  3392. i.charCodeAt(2),
  3393. i.charCodeAt(3)
  3394. ];
  3395. }
  3396. }
  3397. MAJOR_BRAND = new Uint8Array([
  3398. 'i'.charCodeAt(0),
  3399. 's'.charCodeAt(0),
  3400. 'o'.charCodeAt(0),
  3401. 'm'.charCodeAt(0)
  3402. ]);
  3403. AVC1_BRAND = new Uint8Array([
  3404. 'a'.charCodeAt(0),
  3405. 'v'.charCodeAt(0),
  3406. 'c'.charCodeAt(0),
  3407. '1'.charCodeAt(0)
  3408. ]);
  3409. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  3410. VIDEO_HDLR = new Uint8Array([
  3411. 0x00, // version 0
  3412. 0x00, 0x00, 0x00, // flags
  3413. 0x00, 0x00, 0x00, 0x00, // pre_defined
  3414. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  3415. 0x00, 0x00, 0x00, 0x00, // reserved
  3416. 0x00, 0x00, 0x00, 0x00, // reserved
  3417. 0x00, 0x00, 0x00, 0x00, // reserved
  3418. 0x56, 0x69, 0x64, 0x65,
  3419. 0x6f, 0x48, 0x61, 0x6e,
  3420. 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  3421. ]);
  3422. AUDIO_HDLR = new Uint8Array([
  3423. 0x00, // version 0
  3424. 0x00, 0x00, 0x00, // flags
  3425. 0x00, 0x00, 0x00, 0x00, // pre_defined
  3426. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  3427. 0x00, 0x00, 0x00, 0x00, // reserved
  3428. 0x00, 0x00, 0x00, 0x00, // reserved
  3429. 0x00, 0x00, 0x00, 0x00, // reserved
  3430. 0x53, 0x6f, 0x75, 0x6e,
  3431. 0x64, 0x48, 0x61, 0x6e,
  3432. 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  3433. ]);
  3434. HDLR_TYPES = {
  3435. video: VIDEO_HDLR,
  3436. audio: AUDIO_HDLR
  3437. };
  3438. DREF = new Uint8Array([
  3439. 0x00, // version 0
  3440. 0x00, 0x00, 0x00, // flags
  3441. 0x00, 0x00, 0x00, 0x01, // entry_count
  3442. 0x00, 0x00, 0x00, 0x0c, // entry_size
  3443. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  3444. 0x00, // version 0
  3445. 0x00, 0x00, 0x01 // entry_flags
  3446. ]);
  3447. SMHD = new Uint8Array([
  3448. 0x00, // version
  3449. 0x00, 0x00, 0x00, // flags
  3450. 0x00, 0x00, // balance, 0 means centered
  3451. 0x00, 0x00 // reserved
  3452. ]);
  3453. STCO = new Uint8Array([
  3454. 0x00, // version
  3455. 0x00, 0x00, 0x00, // flags
  3456. 0x00, 0x00, 0x00, 0x00 // entry_count
  3457. ]);
  3458. STSC = STCO;
  3459. STSZ = new Uint8Array([
  3460. 0x00, // version
  3461. 0x00, 0x00, 0x00, // flags
  3462. 0x00, 0x00, 0x00, 0x00, // sample_size
  3463. 0x00, 0x00, 0x00, 0x00 // sample_count
  3464. ]);
  3465. STTS = STCO;
  3466. VMHD = new Uint8Array([
  3467. 0x00, // version
  3468. 0x00, 0x00, 0x01, // flags
  3469. 0x00, 0x00, // graphicsmode
  3470. 0x00, 0x00,
  3471. 0x00, 0x00,
  3472. 0x00, 0x00 // opcolor
  3473. ]);
  3474. }());
  3475. box = function(type) {
  3476. var
  3477. payload = [],
  3478. size = 0,
  3479. i,
  3480. result,
  3481. view;
  3482. for (i = 1; i < arguments.length; i++) {
  3483. payload.push(arguments[i]);
  3484. }
  3485. i = payload.length;
  3486. // calculate the total size we need to allocate
  3487. while (i--) {
  3488. size += payload[i].byteLength;
  3489. }
  3490. result = new Uint8Array(size + 8);
  3491. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  3492. view.setUint32(0, result.byteLength);
  3493. result.set(type, 4);
  3494. // copy the payload into the result
  3495. for (i = 0, size = 8; i < payload.length; i++) {
  3496. result.set(payload[i], size);
  3497. size += payload[i].byteLength;
  3498. }
  3499. return result;
  3500. };
  3501. dinf = function() {
  3502. return box(types.dinf, box(types.dref, DREF));
  3503. };
  3504. esds = function(track) {
  3505. return box(types.esds, new Uint8Array([
  3506. 0x00, // version
  3507. 0x00, 0x00, 0x00, // flags
  3508. // ES_Descriptor
  3509. 0x03, // tag, ES_DescrTag
  3510. 0x19, // length
  3511. 0x00, 0x00, // ES_ID
  3512. 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
  3513. // DecoderConfigDescriptor
  3514. 0x04, // tag, DecoderConfigDescrTag
  3515. 0x11, // length
  3516. 0x40, // object type
  3517. 0x15, // streamType
  3518. 0x00, 0x06, 0x00, // bufferSizeDB
  3519. 0x00, 0x00, 0xda, 0xc0, // maxBitrate
  3520. 0x00, 0x00, 0xda, 0xc0, // avgBitrate
  3521. // DecoderSpecificInfo
  3522. 0x05, // tag, DecoderSpecificInfoTag
  3523. 0x02, // length
  3524. // ISO/IEC 14496-3, AudioSpecificConfig
  3525. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  3526. (track.audioobjecttype << 3) | (track.samplingfrequencyindex >>> 1),
  3527. (track.samplingfrequencyindex << 7) | (track.channelcount << 3),
  3528. 0x06, 0x01, 0x02 // GASpecificConfig
  3529. ]));
  3530. };
  3531. ftyp = function() {
  3532. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  3533. };
  3534. hdlr = function(type) {
  3535. return box(types.hdlr, HDLR_TYPES[type]);
  3536. };
  3537. mdat = function(data) {
  3538. return box(types.mdat, data);
  3539. };
  3540. mdhd = function(track) {
  3541. var result = new Uint8Array([
  3542. 0x00, // version 0
  3543. 0x00, 0x00, 0x00, // flags
  3544. 0x00, 0x00, 0x00, 0x02, // creation_time
  3545. 0x00, 0x00, 0x00, 0x03, // modification_time
  3546. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  3547. (track.duration >>> 24) & 0xFF,
  3548. (track.duration >>> 16) & 0xFF,
  3549. (track.duration >>> 8) & 0xFF,
  3550. track.duration & 0xFF, // duration
  3551. 0x55, 0xc4, // 'und' language (undetermined)
  3552. 0x00, 0x00
  3553. ]);
  3554. // Use the sample rate from the track metadata, when it is
  3555. // defined. The sample rate can be parsed out of an ADTS header, for
  3556. // instance.
  3557. if (track.samplerate) {
  3558. result[12] = (track.samplerate >>> 24) & 0xFF;
  3559. result[13] = (track.samplerate >>> 16) & 0xFF;
  3560. result[14] = (track.samplerate >>> 8) & 0xFF;
  3561. result[15] = (track.samplerate) & 0xFF;
  3562. // 重置该轨道长度
  3563. track.duration = track.duration / 90000 * track.samplerate;
  3564. result[16] = (track.duration >>> 24) & 0xFF;
  3565. result[17] = (track.duration >>> 16) & 0xFF;
  3566. result[18] = (track.duration >>> 8) & 0xFF;
  3567. result[19] = (track.duration) & 0xFF;
  3568. }
  3569. return box(types.mdhd, result);
  3570. };
  3571. mdia = function(track) {
  3572. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  3573. };
  3574. mfhd = function(sequenceNumber) {
  3575. return box(types.mfhd, new Uint8Array([
  3576. 0x00,
  3577. 0x00, 0x00, 0x00, // flags
  3578. (sequenceNumber & 0xFF000000) >> 24,
  3579. (sequenceNumber & 0xFF0000) >> 16,
  3580. (sequenceNumber & 0xFF00) >> 8,
  3581. sequenceNumber & 0xFF // sequence_number
  3582. ]));
  3583. };
  3584. minf = function(track) {
  3585. return box(types.minf,
  3586. track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD),
  3587. dinf(),
  3588. stbl(track));
  3589. };
  3590. moof = function(sequenceNumber, tracks) {
  3591. var
  3592. trackFragments = [],
  3593. i = tracks.length;
  3594. // build traf boxes for each track fragment
  3595. while (i--) {
  3596. trackFragments[i] = traf(tracks[i]);
  3597. }
  3598. return box.apply(null, [
  3599. types.moof,
  3600. mfhd(sequenceNumber)
  3601. ].concat(trackFragments));
  3602. };
  3603. /**
  3604. * Returns a movie box.
  3605. * @param tracks {array} the tracks associated with this movie
  3606. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  3607. */
  3608. moov = function(tracks) {
  3609. var
  3610. i = tracks.length,
  3611. boxes = [];
  3612. while (i--) {
  3613. boxes[i] = trak(tracks[i]);
  3614. }
  3615. return box.apply(null, [types.moov, mvhd(customDuration)].concat(boxes).concat(mvex(tracks)));
  3616. };
  3617. mvex = function(tracks) {
  3618. var
  3619. i = tracks.length,
  3620. boxes = [];
  3621. while (i--) {
  3622. boxes[i] = trex(tracks[i]);
  3623. }
  3624. return box.apply(null, [types.mvex].concat(boxes));
  3625. };
  3626. mvhd = function(duration) {
  3627. var
  3628. bytes = new Uint8Array([
  3629. 0x00, // version 0
  3630. 0x00, 0x00, 0x00, // flags
  3631. 0x00, 0x00, 0x00, 0x01, // creation_time
  3632. 0x00, 0x00, 0x00, 0x02, // modification_time
  3633. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  3634. (duration & 0xFF000000) >> 24,
  3635. (duration & 0xFF0000) >> 16,
  3636. (duration & 0xFF00) >> 8,
  3637. duration & 0xFF, // duration
  3638. 0x00, 0x01, 0x00, 0x00, // 1.0 rate
  3639. 0x01, 0x00, // 1.0 volume
  3640. 0x00, 0x00, // reserved
  3641. 0x00, 0x00, 0x00, 0x00, // reserved
  3642. 0x00, 0x00, 0x00, 0x00, // reserved
  3643. 0x00, 0x01, 0x00, 0x00,
  3644. 0x00, 0x00, 0x00, 0x00,
  3645. 0x00, 0x00, 0x00, 0x00,
  3646. 0x00, 0x00, 0x00, 0x00,
  3647. 0x00, 0x01, 0x00, 0x00,
  3648. 0x00, 0x00, 0x00, 0x00,
  3649. 0x00, 0x00, 0x00, 0x00,
  3650. 0x00, 0x00, 0x00, 0x00,
  3651. 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  3652. 0x00, 0x00, 0x00, 0x00,
  3653. 0x00, 0x00, 0x00, 0x00,
  3654. 0x00, 0x00, 0x00, 0x00,
  3655. 0x00, 0x00, 0x00, 0x00,
  3656. 0x00, 0x00, 0x00, 0x00,
  3657. 0x00, 0x00, 0x00, 0x00, // pre_defined
  3658. 0xff, 0xff, 0xff, 0xff // next_track_ID
  3659. ]);
  3660. return box(types.mvhd, bytes);
  3661. };
  3662. sdtp = function(track) {
  3663. var
  3664. samples = track.samples || [],
  3665. bytes = new Uint8Array(4 + samples.length),
  3666. flags,
  3667. i;
  3668. // leave the full box header (4 bytes) all zero
  3669. // write the sample table
  3670. for (i = 0; i < samples.length; i++) {
  3671. flags = samples[i].flags;
  3672. bytes[i + 4] = (flags.dependsOn << 4) |
  3673. (flags.isDependedOn << 2) |
  3674. (flags.hasRedundancy);
  3675. }
  3676. return box(types.sdtp,
  3677. bytes);
  3678. };
  3679. stbl = function(track) {
  3680. return box(types.stbl,
  3681. stsd(track),
  3682. box(types.stts, STTS),
  3683. box(types.stsc, STSC),
  3684. box(types.stsz, STSZ),
  3685. box(types.stco, STCO));
  3686. };
  3687. (function() {
  3688. var videoSample, audioSample;
  3689. stsd = function(track) {
  3690. return box(types.stsd, new Uint8Array([
  3691. 0x00, // version 0
  3692. 0x00, 0x00, 0x00, // flags
  3693. 0x00, 0x00, 0x00, 0x01
  3694. ]), track.type === 'video' ? videoSample(track) : audioSample(track));
  3695. };
  3696. videoSample = function(track) {
  3697. var
  3698. sps = track.sps || [],
  3699. pps = track.pps || [],
  3700. sequenceParameterSets = [],
  3701. pictureParameterSets = [],
  3702. i,
  3703. avc1Box;
  3704. // assemble the SPSs
  3705. for (i = 0; i < sps.length; i++) {
  3706. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  3707. sequenceParameterSets.push((sps[i].byteLength & 0xFF)); // sequenceParameterSetLength
  3708. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  3709. }
  3710. // assemble the PPSs
  3711. for (i = 0; i < pps.length; i++) {
  3712. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  3713. pictureParameterSets.push((pps[i].byteLength & 0xFF));
  3714. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  3715. }
  3716. avc1Box = [
  3717. types.avc1, new Uint8Array([
  3718. 0x00, 0x00, 0x00,
  3719. 0x00, 0x00, 0x00, // reserved
  3720. 0x00, 0x01, // data_reference_index
  3721. 0x00, 0x00, // pre_defined
  3722. 0x00, 0x00, // reserved
  3723. 0x00, 0x00, 0x00, 0x00,
  3724. 0x00, 0x00, 0x00, 0x00,
  3725. 0x00, 0x00, 0x00, 0x00, // pre_defined
  3726. (track.width & 0xff00) >> 8,
  3727. track.width & 0xff, // width
  3728. (track.height & 0xff00) >> 8,
  3729. track.height & 0xff, // height
  3730. 0x00, 0x48, 0x00, 0x00, // horizresolution
  3731. 0x00, 0x48, 0x00, 0x00, // vertresolution
  3732. 0x00, 0x00, 0x00, 0x00, // reserved
  3733. 0x00, 0x01, // frame_count
  3734. 0x13,
  3735. 0x76, 0x69, 0x64, 0x65,
  3736. 0x6f, 0x6a, 0x73, 0x2d,
  3737. 0x63, 0x6f, 0x6e, 0x74,
  3738. 0x72, 0x69, 0x62, 0x2d,
  3739. 0x68, 0x6c, 0x73, 0x00,
  3740. 0x00, 0x00, 0x00, 0x00,
  3741. 0x00, 0x00, 0x00, 0x00,
  3742. 0x00, 0x00, 0x00, // compressorname
  3743. 0x00, 0x18, // depth = 24
  3744. 0x11, 0x11 // pre_defined = -1
  3745. ]),
  3746. box(types.avcC, new Uint8Array([
  3747. 0x01, // configurationVersion
  3748. track.profileIdc, // AVCProfileIndication
  3749. track.profileCompatibility, // profile_compatibility
  3750. track.levelIdc, // AVCLevelIndication
  3751. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  3752. ].concat(
  3753. [sps.length], // numOfSequenceParameterSets
  3754. sequenceParameterSets, // "SPS"
  3755. [pps.length], // numOfPictureParameterSets
  3756. pictureParameterSets // "PPS"
  3757. ))),
  3758. box(types.btrt, new Uint8Array([
  3759. 0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  3760. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  3761. 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
  3762. ]))
  3763. ];
  3764. if (track.sarRatio) {
  3765. var
  3766. hSpacing = track.sarRatio[0],
  3767. vSpacing = track.sarRatio[1];
  3768. avc1Box.push(
  3769. box(types.pasp, new Uint8Array([
  3770. (hSpacing & 0xFF000000) >> 24,
  3771. (hSpacing & 0xFF0000) >> 16,
  3772. (hSpacing & 0xFF00) >> 8,
  3773. hSpacing & 0xFF,
  3774. (vSpacing & 0xFF000000) >> 24,
  3775. (vSpacing & 0xFF0000) >> 16,
  3776. (vSpacing & 0xFF00) >> 8,
  3777. vSpacing & 0xFF
  3778. ]))
  3779. );
  3780. }
  3781. return box.apply(null, avc1Box);
  3782. };
  3783. audioSample = function(track) {
  3784. return box(types.mp4a, new Uint8Array([
  3785. // SampleEntry, ISO/IEC 14496-12
  3786. 0x00, 0x00, 0x00,
  3787. 0x00, 0x00, 0x00, // reserved
  3788. 0x00, 0x01, // data_reference_index
  3789. // AudioSampleEntry, ISO/IEC 14496-12
  3790. 0x00, 0x00, 0x00, 0x00, // reserved
  3791. 0x00, 0x00, 0x00, 0x00, // reserved
  3792. (track.channelcount & 0xff00) >> 8,
  3793. (track.channelcount & 0xff), // channelcount
  3794. (track.samplesize & 0xff00) >> 8,
  3795. (track.samplesize & 0xff), // samplesize
  3796. 0x00, 0x00, // pre_defined
  3797. 0x00, 0x00, // reserved
  3798. (track.samplerate & 0xff00) >> 8,
  3799. (track.samplerate & 0xff),
  3800. 0x00, 0x00 // samplerate, 16.16
  3801. // MP4AudioSampleEntry, ISO/IEC 14496-14
  3802. ]), esds(track));
  3803. };
  3804. }());
  3805. tkhd = function(track) {
  3806. var result = new Uint8Array([
  3807. 0x00, // version 0
  3808. 0x00, 0x00, 0x07, // flags
  3809. 0x00, 0x00, 0x00, 0x00, // creation_time
  3810. 0x00, 0x00, 0x00, 0x00, // modification_time
  3811. (track.id & 0xFF000000) >> 24,
  3812. (track.id & 0xFF0000) >> 16,
  3813. (track.id & 0xFF00) >> 8,
  3814. track.id & 0xFF, // track_ID
  3815. 0x00, 0x00, 0x00, 0x00, // reserved
  3816. (track.duration & 0xFF000000) >> 24,
  3817. (track.duration & 0xFF0000) >> 16,
  3818. (track.duration & 0xFF00) >> 8,
  3819. track.duration & 0xFF, // duration
  3820. 0x00, 0x00, 0x00, 0x00,
  3821. 0x00, 0x00, 0x00, 0x00, // reserved
  3822. 0x00, 0x00, // layer
  3823. 0x00, 0x00, // alternate_group
  3824. 0x01, 0x00, // non-audio track volume
  3825. 0x00, 0x00, // reserved
  3826. 0x00, 0x01, 0x00, 0x00,
  3827. 0x00, 0x00, 0x00, 0x00,
  3828. 0x00, 0x00, 0x00, 0x00,
  3829. 0x00, 0x00, 0x00, 0x00,
  3830. 0x00, 0x01, 0x00, 0x00,
  3831. 0x00, 0x00, 0x00, 0x00,
  3832. 0x00, 0x00, 0x00, 0x00,
  3833. 0x00, 0x00, 0x00, 0x00,
  3834. 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  3835. (track.width & 0xFF00) >> 8,
  3836. track.width & 0xFF,
  3837. 0x00, 0x00, // width
  3838. (track.height & 0xFF00) >> 8,
  3839. track.height & 0xFF,
  3840. 0x00, 0x00 // height
  3841. ]);
  3842. return box(types.tkhd, result);
  3843. };
  3844. /**
  3845. * Generate a track fragment (traf) box. A traf box collects metadata
  3846. * about tracks in a movie fragment (moof) box.
  3847. */
  3848. traf = function(track) {
  3849. var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun,
  3850. sampleDependencyTable, dataOffset,
  3851. upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
  3852. trackFragmentHeader = box(types.tfhd, new Uint8Array([
  3853. 0x00, // version 0
  3854. 0x00, 0x00, 0x3a, // flags
  3855. (track.id & 0xFF000000) >> 24,
  3856. (track.id & 0xFF0000) >> 16,
  3857. (track.id & 0xFF00) >> 8,
  3858. (track.id & 0xFF), // track_ID
  3859. 0x00, 0x00, 0x00, 0x01, // sample_description_index
  3860. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  3861. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  3862. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  3863. ]));
  3864. upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / (UINT32_MAX + 1));
  3865. lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % (UINT32_MAX + 1));
  3866. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([
  3867. 0x01, // version 1
  3868. 0x00, 0x00, 0x00, // flags
  3869. // baseMediaDecodeTime
  3870. (upperWordBaseMediaDecodeTime >>> 24) & 0xFF,
  3871. (upperWordBaseMediaDecodeTime >>> 16) & 0xFF,
  3872. (upperWordBaseMediaDecodeTime >>> 8) & 0xFF,
  3873. upperWordBaseMediaDecodeTime & 0xFF,
  3874. (lowerWordBaseMediaDecodeTime >>> 24) & 0xFF,
  3875. (lowerWordBaseMediaDecodeTime >>> 16) & 0xFF,
  3876. (lowerWordBaseMediaDecodeTime >>> 8) & 0xFF,
  3877. lowerWordBaseMediaDecodeTime & 0xFF
  3878. ]));
  3879. // the data offset specifies the number of bytes from the start of
  3880. // the containing moof to the first payload byte of the associated
  3881. // mdat
  3882. dataOffset = (32 + // tfhd
  3883. 20 + // tfdt
  3884. 8 + // traf header
  3885. 16 + // mfhd
  3886. 8 + // moof header
  3887. 8); // mdat header
  3888. // audio tracks require less metadata
  3889. if (track.type === 'audio') {
  3890. trackFragmentRun = trun(track, dataOffset);
  3891. return box(types.traf,
  3892. trackFragmentHeader,
  3893. trackFragmentDecodeTime,
  3894. trackFragmentRun);
  3895. }
  3896. // video tracks should contain an independent and disposable samples
  3897. // box (sdtp)
  3898. // generate one and adjust offsets to match
  3899. sampleDependencyTable = sdtp(track);
  3900. trackFragmentRun = trun(track,
  3901. sampleDependencyTable.length + dataOffset);
  3902. return box(types.traf,
  3903. trackFragmentHeader,
  3904. trackFragmentDecodeTime,
  3905. trackFragmentRun,
  3906. sampleDependencyTable);
  3907. };
  3908. /**
  3909. * Generate a track box.
  3910. * @param track {object} a track definition
  3911. * @return {Uint8Array} the track box
  3912. */
  3913. trak = function(track) {
  3914. track.duration = track.duration || customDuration;
  3915. return box(types.trak,
  3916. tkhd(track),
  3917. mdia(track));
  3918. };
  3919. trex = function(track) {
  3920. var result = new Uint8Array([
  3921. 0x00, // version 0
  3922. 0x00, 0x00, 0x00, // flags
  3923. (track.id & 0xFF000000) >> 24,
  3924. (track.id & 0xFF0000) >> 16,
  3925. (track.id & 0xFF00) >> 8,
  3926. (track.id & 0xFF), // track_ID
  3927. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  3928. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  3929. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  3930. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  3931. ]);
  3932. // the last two bytes of default_sample_flags is the sample
  3933. // degradation priority, a hint about the importance of this sample
  3934. // relative to others. Lower the degradation priority for all sample
  3935. // types other than video.
  3936. if (track.type !== 'video') {
  3937. result[result.length - 1] = 0x00;
  3938. }
  3939. return box(types.trex, result);
  3940. };
  3941. (function() {
  3942. var audioTrun, videoTrun, trunHeader;
  3943. // This method assumes all samples are uniform. That is, if a
  3944. // duration is present for the first sample, it will be present for
  3945. // all subsequent samples.
  3946. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  3947. trunHeader = function(samples, offset) {
  3948. var durationPresent = 0, sizePresent = 0,
  3949. flagsPresent = 0, compositionTimeOffset = 0;
  3950. // trun flag constants
  3951. if (samples.length) {
  3952. if (samples[0].duration !== undefined) {
  3953. durationPresent = 0x1;
  3954. }
  3955. if (samples[0].size !== undefined) {
  3956. sizePresent = 0x2;
  3957. }
  3958. if (samples[0].flags !== undefined) {
  3959. flagsPresent = 0x4;
  3960. }
  3961. if (samples[0].compositionTimeOffset !== undefined) {
  3962. compositionTimeOffset = 0x8;
  3963. }
  3964. }
  3965. return [
  3966. 0x00, // version 0
  3967. 0x00,
  3968. durationPresent | sizePresent | flagsPresent | compositionTimeOffset,
  3969. 0x01, // flags
  3970. (samples.length & 0xFF000000) >>> 24,
  3971. (samples.length & 0xFF0000) >>> 16,
  3972. (samples.length & 0xFF00) >>> 8,
  3973. samples.length & 0xFF, // sample_count
  3974. (offset & 0xFF000000) >>> 24,
  3975. (offset & 0xFF0000) >>> 16,
  3976. (offset & 0xFF00) >>> 8,
  3977. offset & 0xFF // data_offset
  3978. ];
  3979. };
  3980. videoTrun = function(track, offset) {
  3981. var bytesOffest, bytes, header, samples, sample, i;
  3982. samples = track.samples || [];
  3983. offset += 8 + 12 + (16 * samples.length);
  3984. header = trunHeader(samples, offset);
  3985. bytes = new Uint8Array(header.length + samples.length * 16);
  3986. bytes.set(header);
  3987. bytesOffest = header.length;
  3988. for (i = 0; i < samples.length; i++) {
  3989. sample = samples[i];
  3990. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  3991. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  3992. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  3993. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  3994. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  3995. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  3996. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  3997. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  3998. bytes[bytesOffest++] = (sample.flags.isLeading << 2) | sample.flags.dependsOn;
  3999. bytes[bytesOffest++] = (sample.flags.isDependedOn << 6) |
  4000. (sample.flags.hasRedundancy << 4) |
  4001. (sample.flags.paddingValue << 1) |
  4002. sample.flags.isNonSyncSample;
  4003. bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
  4004. bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
  4005. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
  4006. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
  4007. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
  4008. bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
  4009. }
  4010. return box(types.trun, bytes);
  4011. };
  4012. audioTrun = function(track, offset) {
  4013. var bytes, bytesOffest, header, samples, sample, i;
  4014. samples = track.samples || [];
  4015. offset += 8 + 12 + (8 * samples.length);
  4016. header = trunHeader(samples, offset);
  4017. bytes = new Uint8Array(header.length + samples.length * 8);
  4018. bytes.set(header);
  4019. bytesOffest = header.length;
  4020. for (i = 0; i < samples.length; i++) {
  4021. sample = samples[i];
  4022. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  4023. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  4024. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  4025. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  4026. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  4027. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  4028. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  4029. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  4030. }
  4031. return box(types.trun, bytes);
  4032. };
  4033. trun = function(track, offset) {
  4034. if (track.type === 'audio') {
  4035. return audioTrun(track, offset);
  4036. }
  4037. return videoTrun(track, offset);
  4038. };
  4039. }());
  4040. module.exports = {
  4041. ftyp: ftyp,
  4042. mdat: mdat,
  4043. moof: moof,
  4044. moov: moov,
  4045. setDuration: function(duration) {
  4046. if (duration) {
  4047. customDuration = duration * 90000; // 乘以 timescale
  4048. }
  4049. },
  4050. initSegment: function(tracks) {
  4051. var
  4052. fileType = ftyp(),
  4053. movie = moov(tracks),
  4054. result;
  4055. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  4056. result.set(fileType);
  4057. result.set(movie, fileType.byteLength);
  4058. return result;
  4059. }
  4060. };
  4061. },{}],19:[function(require,module,exports){
  4062. var parseType = function(buffer) {
  4063. var result = '';
  4064. result += String.fromCharCode(buffer[0]);
  4065. result += String.fromCharCode(buffer[1]);
  4066. result += String.fromCharCode(buffer[2]);
  4067. result += String.fromCharCode(buffer[3]);
  4068. return result;
  4069. };
  4070. module.exports = parseType;
  4071. },{}],20:[function(require,module,exports){
  4072. /**
  4073. * mux.js
  4074. *
  4075. * Copyright (c) Brightcove
  4076. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4077. *
  4078. * Utilities to detect basic properties and metadata about MP4s.
  4079. */
  4080. 'use strict';
  4081. var toUnsigned = require(28).toUnsigned;
  4082. var toHexString = require(28).toHexString;
  4083. var findBox = require(15);
  4084. var parseType = require(19);
  4085. var parseTfhd = require(26);
  4086. var parseTrun = require(27);
  4087. var parseTfdt = require(25);
  4088. var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks,
  4089. getTimescaleFromMediaHeader;
  4090. /**
  4091. * Parses an MP4 initialization segment and extracts the timescale
  4092. * values for any declared tracks. Timescale values indicate the
  4093. * number of clock ticks per second to assume for time-based values
  4094. * elsewhere in the MP4.
  4095. *
  4096. * To determine the start time of an MP4, you need two pieces of
  4097. * information: the timescale unit and the earliest base media decode
  4098. * time. Multiple timescales can be specified within an MP4 but the
  4099. * base media decode time is always expressed in the timescale from
  4100. * the media header box for the track:
  4101. * ```
  4102. * moov > trak > mdia > mdhd.timescale
  4103. * ```
  4104. * @param init {Uint8Array} the bytes of the init segment
  4105. * @return {object} a hash of track ids to timescale values or null if
  4106. * the init segment is malformed.
  4107. */
  4108. timescale = function(init) {
  4109. var
  4110. result = {},
  4111. traks = findBox(init, ['moov', 'trak']);
  4112. // mdhd timescale
  4113. return traks.reduce(function(result, trak) {
  4114. var tkhd, version, index, id, mdhd;
  4115. tkhd = findBox(trak, ['tkhd'])[0];
  4116. if (!tkhd) {
  4117. return null;
  4118. }
  4119. version = tkhd[0];
  4120. index = version === 0 ? 12 : 20;
  4121. id = toUnsigned(tkhd[index] << 24 |
  4122. tkhd[index + 1] << 16 |
  4123. tkhd[index + 2] << 8 |
  4124. tkhd[index + 3]);
  4125. mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  4126. if (!mdhd) {
  4127. return null;
  4128. }
  4129. version = mdhd[0];
  4130. index = version === 0 ? 12 : 20;
  4131. result[id] = toUnsigned(mdhd[index] << 24 |
  4132. mdhd[index + 1] << 16 |
  4133. mdhd[index + 2] << 8 |
  4134. mdhd[index + 3]);
  4135. return result;
  4136. }, result);
  4137. };
  4138. /**
  4139. * Determine the base media decode start time, in seconds, for an MP4
  4140. * fragment. If multiple fragments are specified, the earliest time is
  4141. * returned.
  4142. *
  4143. * The base media decode time can be parsed from track fragment
  4144. * metadata:
  4145. * ```
  4146. * moof > traf > tfdt.baseMediaDecodeTime
  4147. * ```
  4148. * It requires the timescale value from the mdhd to interpret.
  4149. *
  4150. * @param timescale {object} a hash of track ids to timescale values.
  4151. * @return {number} the earliest base media decode start time for the
  4152. * fragment, in seconds
  4153. */
  4154. startTime = function(timescale, fragment) {
  4155. var trafs, baseTimes, result;
  4156. // we need info from two childrend of each track fragment box
  4157. trafs = findBox(fragment, ['moof', 'traf']);
  4158. // determine the start times for each track
  4159. baseTimes = [].concat.apply([], trafs.map(function(traf) {
  4160. return findBox(traf, ['tfhd']).map(function(tfhd) {
  4161. var id, scale, baseTime;
  4162. // get the track id from the tfhd
  4163. id = toUnsigned(tfhd[4] << 24 |
  4164. tfhd[5] << 16 |
  4165. tfhd[6] << 8 |
  4166. tfhd[7]);
  4167. // assume a 90kHz clock if no timescale was specified
  4168. scale = timescale[id] || 90e3;
  4169. // get the base media decode time from the tfdt
  4170. baseTime = findBox(traf, ['tfdt']).map(function(tfdt) {
  4171. var version, result;
  4172. version = tfdt[0];
  4173. result = toUnsigned(tfdt[4] << 24 |
  4174. tfdt[5] << 16 |
  4175. tfdt[6] << 8 |
  4176. tfdt[7]);
  4177. if (version === 1) {
  4178. result *= Math.pow(2, 32);
  4179. result += toUnsigned(tfdt[8] << 24 |
  4180. tfdt[9] << 16 |
  4181. tfdt[10] << 8 |
  4182. tfdt[11]);
  4183. }
  4184. return result;
  4185. })[0];
  4186. baseTime = baseTime || Infinity;
  4187. // convert base time to seconds
  4188. return baseTime / scale;
  4189. });
  4190. }));
  4191. // return the minimum
  4192. result = Math.min.apply(null, baseTimes);
  4193. return isFinite(result) ? result : 0;
  4194. };
  4195. /**
  4196. * Determine the composition start, in seconds, for an MP4
  4197. * fragment.
  4198. *
  4199. * The composition start time of a fragment can be calculated using the base
  4200. * media decode time, composition time offset, and timescale, as follows:
  4201. *
  4202. * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
  4203. *
  4204. * All of the aforementioned information is contained within a media fragment's
  4205. * `traf` box, except for timescale info, which comes from the initialization
  4206. * segment, so a track id (also contained within a `traf`) is also necessary to
  4207. * associate it with a timescale
  4208. *
  4209. *
  4210. * @param timescales {object} - a hash of track ids to timescale values.
  4211. * @param fragment {Unit8Array} - the bytes of a media segment
  4212. * @return {number} the composition start time for the fragment, in seconds
  4213. **/
  4214. compositionStartTime = function(timescales, fragment) {
  4215. var trafBoxes = findBox(fragment, ['moof', 'traf']);
  4216. var baseMediaDecodeTime = 0;
  4217. var compositionTimeOffset = 0;
  4218. var trackId;
  4219. if (trafBoxes && trafBoxes.length) {
  4220. // The spec states that track run samples contained within a `traf` box are contiguous, but
  4221. // it does not explicitly state whether the `traf` boxes themselves are contiguous.
  4222. // We will assume that they are, so we only need the first to calculate start time.
  4223. var tfhd = findBox(trafBoxes[0], ['tfhd'])[0];
  4224. var trun = findBox(trafBoxes[0], ['trun'])[0];
  4225. var tfdt = findBox(trafBoxes[0], ['tfdt'])[0];
  4226. if (tfhd) {
  4227. var parsedTfhd = parseTfhd(tfhd);
  4228. trackId = parsedTfhd.trackId;
  4229. }
  4230. if (tfdt) {
  4231. var parsedTfdt = parseTfdt(tfdt);
  4232. baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
  4233. }
  4234. if (trun) {
  4235. var parsedTrun = parseTrun(trun);
  4236. if (parsedTrun.samples && parsedTrun.samples.length) {
  4237. compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
  4238. }
  4239. }
  4240. }
  4241. // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
  4242. // specified.
  4243. var timescale = timescales[trackId] || 90e3;
  4244. // return the composition start time, in seconds
  4245. return (baseMediaDecodeTime + compositionTimeOffset) / timescale;
  4246. };
  4247. /**
  4248. * Find the trackIds of the video tracks in this source.
  4249. * Found by parsing the Handler Reference and Track Header Boxes:
  4250. * moov > trak > mdia > hdlr
  4251. * moov > trak > tkhd
  4252. *
  4253. * @param {Uint8Array} init - The bytes of the init segment for this source
  4254. * @return {Number[]} A list of trackIds
  4255. *
  4256. * @see ISO-BMFF-12/2015, Section 8.4.3
  4257. **/
  4258. getVideoTrackIds = function(init) {
  4259. var traks = findBox(init, ['moov', 'trak']);
  4260. var videoTrackIds = [];
  4261. traks.forEach(function(trak) {
  4262. var hdlrs = findBox(trak, ['mdia', 'hdlr']);
  4263. var tkhds = findBox(trak, ['tkhd']);
  4264. hdlrs.forEach(function(hdlr, index) {
  4265. var handlerType = parseType(hdlr.subarray(8, 12));
  4266. var tkhd = tkhds[index];
  4267. var view;
  4268. var version;
  4269. var trackId;
  4270. if (handlerType === 'vide') {
  4271. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  4272. version = view.getUint8(0);
  4273. trackId = (version === 0) ? view.getUint32(12) : view.getUint32(20);
  4274. videoTrackIds.push(trackId);
  4275. }
  4276. });
  4277. });
  4278. return videoTrackIds;
  4279. };
  4280. getTimescaleFromMediaHeader = function(mdhd) {
  4281. // mdhd is a FullBox, meaning it will have its own version as the first byte
  4282. var version = mdhd[0];
  4283. var index = version === 0 ? 12 : 20;
  4284. return toUnsigned(
  4285. mdhd[index] << 24 |
  4286. mdhd[index + 1] << 16 |
  4287. mdhd[index + 2] << 8 |
  4288. mdhd[index + 3]
  4289. );
  4290. };
  4291. /**
  4292. * Get all the video, audio, and hint tracks from a non fragmented
  4293. * mp4 segment
  4294. */
  4295. getTracks = function(init) {
  4296. var traks = findBox(init, ['moov', 'trak']);
  4297. var tracks = [];
  4298. traks.forEach(function(trak) {
  4299. var track = {};
  4300. var tkhd = findBox(trak, ['tkhd'])[0];
  4301. var view, tkhdVersion;
  4302. // id
  4303. if (tkhd) {
  4304. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  4305. tkhdVersion = view.getUint8(0);
  4306. track.id = (tkhdVersion === 0) ? view.getUint32(12) : view.getUint32(20);
  4307. }
  4308. var hdlr = findBox(trak, ['mdia', 'hdlr'])[0];
  4309. // type
  4310. if (hdlr) {
  4311. var type = parseType(hdlr.subarray(8, 12));
  4312. if (type === 'vide') {
  4313. track.type = 'video';
  4314. } else if (type === 'soun') {
  4315. track.type = 'audio';
  4316. } else {
  4317. track.type = type;
  4318. }
  4319. }
  4320. // codec
  4321. var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  4322. if (stsd) {
  4323. var sampleDescriptions = stsd.subarray(8);
  4324. // gives the codec type string
  4325. track.codec = parseType(sampleDescriptions.subarray(4, 8));
  4326. var codecBox = findBox(sampleDescriptions, [track.codec])[0];
  4327. var codecConfig, codecConfigType;
  4328. if (codecBox) {
  4329. // https://tools.ietf.org/html/rfc6381#section-3.3
  4330. if ((/^[a-z]vc[1-9]$/i).test(track.codec)) {
  4331. // we don't need anything but the "config" parameter of the
  4332. // avc1 codecBox
  4333. codecConfig = codecBox.subarray(78);
  4334. codecConfigType = parseType(codecConfig.subarray(4, 8));
  4335. if (codecConfigType === 'avcC' && codecConfig.length > 11) {
  4336. track.codec += '.';
  4337. // left padded with zeroes for single digit hex
  4338. // profile idc
  4339. track.codec += toHexString(codecConfig[9]);
  4340. // the byte containing the constraint_set flags
  4341. track.codec += toHexString(codecConfig[10]);
  4342. // level idc
  4343. track.codec += toHexString(codecConfig[11]);
  4344. } else {
  4345. // TODO: show a warning that we couldn't parse the codec
  4346. // and are using the default
  4347. track.codec = 'avc1.4d400d';
  4348. }
  4349. } else if ((/^mp4[a,v]$/i).test(track.codec)) {
  4350. // we do not need anything but the streamDescriptor of the mp4a codecBox
  4351. codecConfig = codecBox.subarray(28);
  4352. codecConfigType = parseType(codecConfig.subarray(4, 8));
  4353. if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
  4354. track.codec += '.' + toHexString(codecConfig[19]);
  4355. // this value is only a single digit
  4356. track.codec += '.' + toHexString((codecConfig[20] >>> 2) & 0x3f).replace(/^0/, '');
  4357. } else {
  4358. // TODO: show a warning that we couldn't parse the codec
  4359. // and are using the default
  4360. track.codec = 'mp4a.40.2';
  4361. }
  4362. } else {
  4363. // TODO: show a warning? for unknown codec type
  4364. }
  4365. }
  4366. }
  4367. var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  4368. if (mdhd) {
  4369. track.timescale = getTimescaleFromMediaHeader(mdhd);
  4370. }
  4371. tracks.push(track);
  4372. });
  4373. return tracks;
  4374. };
  4375. module.exports = {
  4376. // export mp4 inspector's findBox and parseType for backwards compatibility
  4377. findBox: findBox,
  4378. parseType: parseType,
  4379. timescale: timescale,
  4380. startTime: startTime,
  4381. compositionStartTime: compositionStartTime,
  4382. videoTrackIds: getVideoTrackIds,
  4383. tracks: getTracks,
  4384. getTimescaleFromMediaHeader: getTimescaleFromMediaHeader
  4385. };
  4386. },{"15":15,"19":19,"25":25,"26":26,"27":27,"28":28}],21:[function(require,module,exports){
  4387. /**
  4388. * mux.js
  4389. *
  4390. * Copyright (c) Brightcove
  4391. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4392. */
  4393. var ONE_SECOND_IN_TS = require(29).ONE_SECOND_IN_TS;
  4394. /**
  4395. * Store information about the start and end of the track and the
  4396. * duration for each frame/sample we process in order to calculate
  4397. * the baseMediaDecodeTime
  4398. */
  4399. var collectDtsInfo = function(track, data) {
  4400. if (typeof data.pts === 'number') {
  4401. if (track.timelineStartInfo.pts === undefined) {
  4402. track.timelineStartInfo.pts = data.pts;
  4403. }
  4404. if (track.minSegmentPts === undefined) {
  4405. track.minSegmentPts = data.pts;
  4406. } else {
  4407. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  4408. }
  4409. if (track.maxSegmentPts === undefined) {
  4410. track.maxSegmentPts = data.pts;
  4411. } else {
  4412. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  4413. }
  4414. }
  4415. if (typeof data.dts === 'number') {
  4416. if (track.timelineStartInfo.dts === undefined) {
  4417. track.timelineStartInfo.dts = data.dts;
  4418. }
  4419. if (track.minSegmentDts === undefined) {
  4420. track.minSegmentDts = data.dts;
  4421. } else {
  4422. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  4423. }
  4424. if (track.maxSegmentDts === undefined) {
  4425. track.maxSegmentDts = data.dts;
  4426. } else {
  4427. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  4428. }
  4429. }
  4430. };
  4431. /**
  4432. * Clear values used to calculate the baseMediaDecodeTime between
  4433. * tracks
  4434. */
  4435. var clearDtsInfo = function(track) {
  4436. delete track.minSegmentDts;
  4437. delete track.maxSegmentDts;
  4438. delete track.minSegmentPts;
  4439. delete track.maxSegmentPts;
  4440. };
  4441. /**
  4442. * Calculate the track's baseMediaDecodeTime based on the earliest
  4443. * DTS the transmuxer has ever seen and the minimum DTS for the
  4444. * current track
  4445. * @param track {object} track metadata configuration
  4446. * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
  4447. * in the source; false to adjust the first segment to start at 0.
  4448. */
  4449. var calculateTrackBaseMediaDecodeTime = function(track, keepOriginalTimestamps) {
  4450. var
  4451. baseMediaDecodeTime,
  4452. scale,
  4453. minSegmentDts = track.minSegmentDts;
  4454. // Optionally adjust the time so the first segment starts at zero.
  4455. if (!keepOriginalTimestamps) {
  4456. minSegmentDts -= track.timelineStartInfo.dts;
  4457. }
  4458. // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  4459. // we want the start of the first segment to be placed
  4460. baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime;
  4461. // Add to that the distance this segment is from the very first
  4462. baseMediaDecodeTime += minSegmentDts;
  4463. // baseMediaDecodeTime must not become negative
  4464. baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
  4465. if (track.type === 'audio') {
  4466. // Audio has a different clock equal to the sampling_rate so we need to
  4467. // scale the PTS values into the clock rate of the track
  4468. scale = track.samplerate / ONE_SECOND_IN_TS;
  4469. baseMediaDecodeTime *= scale;
  4470. baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  4471. }
  4472. return baseMediaDecodeTime;
  4473. };
  4474. module.exports = {
  4475. clearDtsInfo: clearDtsInfo,
  4476. calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  4477. collectDtsInfo: collectDtsInfo
  4478. };
  4479. },{"29":29}],22:[function(require,module,exports){
  4480. /**
  4481. * mux.js
  4482. *
  4483. * Copyright (c) Brightcove
  4484. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4485. *
  4486. * A stream-based mp2t to mp4 converter. This utility can be used to
  4487. * deliver mp4s to a SourceBuffer on platforms that support native
  4488. * Media Source Extensions.
  4489. */
  4490. 'use strict';
  4491. var Stream = require(31);
  4492. var mp4 = require(18);
  4493. var frameUtils = require(16);
  4494. var audioFrameUtils = require(13);
  4495. var trackDecodeInfo = require(21);
  4496. var m2ts = require(9);
  4497. var clock = require(29);
  4498. var AdtsStream = require(3);
  4499. var H264Stream = require(4).H264Stream;
  4500. var AacStream = require(1);
  4501. var isLikelyAacData = require(2).isLikelyAacData;
  4502. var ONE_SECOND_IN_TS = require(29).ONE_SECOND_IN_TS;
  4503. var AUDIO_PROPERTIES = require(5);
  4504. var VIDEO_PROPERTIES = require(6);
  4505. // object types
  4506. var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;
  4507. /**
  4508. * Compare two arrays (even typed) for same-ness
  4509. */
  4510. var arrayEquals = function(a, b) {
  4511. var
  4512. i;
  4513. if (a.length !== b.length) {
  4514. return false;
  4515. }
  4516. // compare the value of each element in the array
  4517. for (i = 0; i < a.length; i++) {
  4518. if (a[i] !== b[i]) {
  4519. return false;
  4520. }
  4521. }
  4522. return true;
  4523. };
  4524. var generateVideoSegmentTimingInfo = function(
  4525. baseMediaDecodeTime,
  4526. startDts,
  4527. startPts,
  4528. endDts,
  4529. endPts,
  4530. prependedContentDuration
  4531. ) {
  4532. var
  4533. ptsOffsetFromDts = startPts - startDts,
  4534. decodeDuration = endDts - startDts,
  4535. presentationDuration = endPts - startPts;
  4536. // The PTS and DTS values are based on the actual stream times from the segment,
  4537. // however, the player time values will reflect a start from the baseMediaDecodeTime.
  4538. // In order to provide relevant values for the player times, base timing info on the
  4539. // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  4540. return {
  4541. start: {
  4542. dts: baseMediaDecodeTime,
  4543. pts: baseMediaDecodeTime + ptsOffsetFromDts
  4544. },
  4545. end: {
  4546. dts: baseMediaDecodeTime + decodeDuration,
  4547. pts: baseMediaDecodeTime + presentationDuration
  4548. },
  4549. prependedContentDuration: prependedContentDuration,
  4550. baseMediaDecodeTime: baseMediaDecodeTime
  4551. };
  4552. };
  4553. /**
  4554. * Constructs a single-track, ISO BMFF media segment from AAC data
  4555. * events. The output of this stream can be fed to a SourceBuffer
  4556. * configured with a suitable initialization segment.
  4557. * @param track {object} track metadata configuration
  4558. * @param options {object} transmuxer options object
  4559. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  4560. * in the source; false to adjust the first segment to start at 0.
  4561. */
  4562. AudioSegmentStream = function(track, options) {
  4563. var
  4564. adtsFrames = [],
  4565. sequenceNumber = 0,
  4566. earliestAllowedDts = 0,
  4567. audioAppendStartTs = 0,
  4568. videoBaseMediaDecodeTime = Infinity;
  4569. options = options || {};
  4570. AudioSegmentStream.prototype.init.call(this);
  4571. this.push = function(data) {
  4572. trackDecodeInfo.collectDtsInfo(track, data);
  4573. if (track) {
  4574. AUDIO_PROPERTIES.forEach(function(prop) {
  4575. track[prop] = data[prop];
  4576. });
  4577. }
  4578. // buffer audio data until end() is called
  4579. adtsFrames.push(data);
  4580. };
  4581. this.setEarliestDts = function(earliestDts) {
  4582. earliestAllowedDts = earliestDts;
  4583. };
  4584. this.setVideoBaseMediaDecodeTime = function(baseMediaDecodeTime) {
  4585. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  4586. };
  4587. this.setAudioAppendStart = function(timestamp) {
  4588. audioAppendStartTs = timestamp;
  4589. };
  4590. this.flush = function() {
  4591. var
  4592. frames,
  4593. moof,
  4594. mdat,
  4595. boxes,
  4596. frameDuration;
  4597. // return early if no audio data has been observed
  4598. if (adtsFrames.length === 0) {
  4599. this.trigger('done', 'AudioSegmentStream');
  4600. return;
  4601. }
  4602. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(
  4603. adtsFrames, track, earliestAllowedDts);
  4604. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(
  4605. track, options.keepOriginalTimestamps);
  4606. audioFrameUtils.prefixWithSilence(
  4607. track, frames, audioAppendStartTs, videoBaseMediaDecodeTime);
  4608. // we have to build the index from byte locations to
  4609. // samples (that is, adts frames) in the audio data
  4610. track.samples = audioFrameUtils.generateSampleTable(frames);
  4611. // concatenate the audio data to constuct the mdat
  4612. mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));
  4613. adtsFrames = [];
  4614. moof = mp4.moof(sequenceNumber, [track]);
  4615. boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
  4616. // bump the sequence number for next time
  4617. sequenceNumber++;
  4618. boxes.set(moof);
  4619. boxes.set(mdat, moof.byteLength);
  4620. trackDecodeInfo.clearDtsInfo(track);
  4621. frameDuration = Math.ceil(ONE_SECOND_IN_TS * 1024 / track.samplerate);
  4622. // TODO this check was added to maintain backwards compatibility (particularly with
  4623. // tests) on adding the timingInfo event. However, it seems unlikely that there's a
  4624. // valid use-case where an init segment/data should be triggered without associated
  4625. // frames. Leaving for now, but should be looked into.
  4626. if (frames.length) {
  4627. this.trigger('timingInfo', {
  4628. start: frames[0].pts,
  4629. end: frames[0].pts + (frames.length * frameDuration)
  4630. });
  4631. }
  4632. this.trigger('data', {track: track, boxes: boxes});
  4633. this.trigger('done', 'AudioSegmentStream');
  4634. };
  4635. this.reset = function() {
  4636. trackDecodeInfo.clearDtsInfo(track);
  4637. adtsFrames = [];
  4638. this.trigger('reset');
  4639. };
  4640. };
  4641. AudioSegmentStream.prototype = new Stream();
  4642. /**
  4643. * Constructs a single-track, ISO BMFF media segment from H264 data
  4644. * events. The output of this stream can be fed to a SourceBuffer
  4645. * configured with a suitable initialization segment.
  4646. * @param track {object} track metadata configuration
  4647. * @param options {object} transmuxer options object
  4648. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  4649. * gopsToAlignWith list when attempting to align gop pts
  4650. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  4651. * in the source; false to adjust the first segment to start at 0.
  4652. */
  4653. VideoSegmentStream = function(track, options) {
  4654. var
  4655. sequenceNumber = 0,
  4656. nalUnits = [],
  4657. gopsToAlignWith = [],
  4658. config,
  4659. pps;
  4660. options = options || {};
  4661. VideoSegmentStream.prototype.init.call(this);
  4662. delete track.minPTS;
  4663. this.gopCache_ = [];
  4664. /**
  4665. * Constructs a ISO BMFF segment given H264 nalUnits
  4666. * @param {Object} nalUnit A data event representing a nalUnit
  4667. * @param {String} nalUnit.nalUnitType
  4668. * @param {Object} nalUnit.config Properties for a mp4 track
  4669. * @param {Uint8Array} nalUnit.data The nalUnit bytes
  4670. * @see lib/codecs/h264.js
  4671. **/
  4672. this.push = function(nalUnit) {
  4673. trackDecodeInfo.collectDtsInfo(track, nalUnit);
  4674. // record the track config
  4675. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  4676. config = nalUnit.config;
  4677. track.sps = [nalUnit.data];
  4678. VIDEO_PROPERTIES.forEach(function(prop) {
  4679. track[prop] = config[prop];
  4680. }, this);
  4681. }
  4682. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' &&
  4683. !pps) {
  4684. pps = nalUnit.data;
  4685. track.pps = [nalUnit.data];
  4686. }
  4687. // buffer video until flush() is called
  4688. nalUnits.push(nalUnit);
  4689. };
  4690. /**
  4691. * Pass constructed ISO BMFF track and boxes on to the
  4692. * next stream in the pipeline
  4693. **/
  4694. this.flush = function() {
  4695. var
  4696. frames,
  4697. gopForFusion,
  4698. gops,
  4699. moof,
  4700. mdat,
  4701. boxes,
  4702. prependedContentDuration = 0,
  4703. firstGop,
  4704. lastGop;
  4705. // Throw away nalUnits at the start of the byte stream until
  4706. // we find the first AUD
  4707. while (nalUnits.length) {
  4708. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  4709. break;
  4710. }
  4711. nalUnits.shift();
  4712. }
  4713. // Return early if no video data has been observed
  4714. if (nalUnits.length === 0) {
  4715. this.resetStream_();
  4716. this.trigger('done', 'VideoSegmentStream');
  4717. return;
  4718. }
  4719. // Organize the raw nal-units into arrays that represent
  4720. // higher-level constructs such as frames and gops
  4721. // (group-of-pictures)
  4722. frames = frameUtils.groupNalsIntoFrames(nalUnits);
  4723. gops = frameUtils.groupFramesIntoGops(frames);
  4724. // If the first frame of this fragment is not a keyframe we have
  4725. // a problem since MSE (on Chrome) requires a leading keyframe.
  4726. //
  4727. // We have two approaches to repairing this situation:
  4728. // 1) GOP-FUSION:
  4729. // This is where we keep track of the GOPS (group-of-pictures)
  4730. // from previous fragments and attempt to find one that we can
  4731. // prepend to the current fragment in order to create a valid
  4732. // fragment.
  4733. // 2) KEYFRAME-PULLING:
  4734. // Here we search for the first keyframe in the fragment and
  4735. // throw away all the frames between the start of the fragment
  4736. // and that keyframe. We then extend the duration and pull the
  4737. // PTS of the keyframe forward so that it covers the time range
  4738. // of the frames that were disposed of.
  4739. //
  4740. // #1 is far prefereable over #2 which can cause "stuttering" but
  4741. // requires more things to be just right.
  4742. if (!gops[0][0].keyFrame) {
  4743. // Search for a gop for fusion from our gopCache
  4744. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  4745. if (gopForFusion) {
  4746. // in order to provide more accurate timing information about the segment, save
  4747. // the number of seconds prepended to the original segment due to GOP fusion
  4748. prependedContentDuration = gopForFusion.duration;
  4749. gops.unshift(gopForFusion);
  4750. // Adjust Gops' metadata to account for the inclusion of the
  4751. // new gop at the beginning
  4752. gops.byteLength += gopForFusion.byteLength;
  4753. gops.nalCount += gopForFusion.nalCount;
  4754. gops.pts = gopForFusion.pts;
  4755. gops.dts = gopForFusion.dts;
  4756. gops.duration += gopForFusion.duration;
  4757. } else {
  4758. // If we didn't find a candidate gop fall back to keyframe-pulling
  4759. gops = frameUtils.extendFirstKeyFrame(gops);
  4760. }
  4761. }
  4762. // Trim gops to align with gopsToAlignWith
  4763. if (gopsToAlignWith.length) {
  4764. var alignedGops;
  4765. if (options.alignGopsAtEnd) {
  4766. alignedGops = this.alignGopsAtEnd_(gops);
  4767. } else {
  4768. alignedGops = this.alignGopsAtStart_(gops);
  4769. }
  4770. if (!alignedGops) {
  4771. // save all the nals in the last GOP into the gop cache
  4772. this.gopCache_.unshift({
  4773. gop: gops.pop(),
  4774. pps: track.pps,
  4775. sps: track.sps
  4776. });
  4777. // Keep a maximum of 6 GOPs in the cache
  4778. this.gopCache_.length = Math.min(6, this.gopCache_.length);
  4779. // Clear nalUnits
  4780. nalUnits = [];
  4781. // return early no gops can be aligned with desired gopsToAlignWith
  4782. this.resetStream_();
  4783. this.trigger('done', 'VideoSegmentStream');
  4784. return;
  4785. }
  4786. // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
  4787. // when recalculated before sending off to CoalesceStream
  4788. trackDecodeInfo.clearDtsInfo(track);
  4789. gops = alignedGops;
  4790. }
  4791. trackDecodeInfo.collectDtsInfo(track, gops);
  4792. // First, we have to build the index from byte locations to
  4793. // samples (that is, frames) in the video data
  4794. track.samples = frameUtils.generateSampleTable(gops);
  4795. // Concatenate the video data and construct the mdat
  4796. mdat = mp4.mdat(frameUtils.concatenateNalData(gops));
  4797. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(
  4798. track, options.keepOriginalTimestamps);
  4799. this.trigger('processedGopsInfo', gops.map(function(gop) {
  4800. return {
  4801. pts: gop.pts,
  4802. dts: gop.dts,
  4803. byteLength: gop.byteLength
  4804. };
  4805. }));
  4806. firstGop = gops[0];
  4807. lastGop = gops[gops.length - 1];
  4808. this.trigger(
  4809. 'segmentTimingInfo',
  4810. generateVideoSegmentTimingInfo(
  4811. track.baseMediaDecodeTime,
  4812. firstGop.dts,
  4813. firstGop.pts,
  4814. lastGop.dts + lastGop.duration,
  4815. lastGop.pts + lastGop.duration,
  4816. prependedContentDuration));
  4817. this.trigger('timingInfo', {
  4818. start: gops[0].pts,
  4819. end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
  4820. });
  4821. // save all the nals in the last GOP into the gop cache
  4822. this.gopCache_.unshift({
  4823. gop: gops.pop(),
  4824. pps: track.pps,
  4825. sps: track.sps
  4826. });
  4827. // Keep a maximum of 6 GOPs in the cache
  4828. this.gopCache_.length = Math.min(6, this.gopCache_.length);
  4829. // Clear nalUnits
  4830. nalUnits = [];
  4831. this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
  4832. this.trigger('timelineStartInfo', track.timelineStartInfo);
  4833. moof = mp4.moof(sequenceNumber, [track]);
  4834. // it would be great to allocate this array up front instead of
  4835. // throwing away hundreds of media segment fragments
  4836. boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
  4837. // Bump the sequence number for next time
  4838. sequenceNumber++;
  4839. boxes.set(moof);
  4840. boxes.set(mdat, moof.byteLength);
  4841. this.trigger('data', {track: track, boxes: boxes});
  4842. this.resetStream_();
  4843. // Continue with the flush process now
  4844. this.trigger('done', 'VideoSegmentStream');
  4845. };
  4846. this.reset = function() {
  4847. this.resetStream_();
  4848. nalUnits = [];
  4849. this.gopCache_.length = 0;
  4850. gopsToAlignWith.length = 0;
  4851. this.trigger('reset');
  4852. };
  4853. this.resetStream_ = function() {
  4854. trackDecodeInfo.clearDtsInfo(track);
  4855. // reset config and pps because they may differ across segments
  4856. // for instance, when we are rendition switching
  4857. config = undefined;
  4858. pps = undefined;
  4859. };
  4860. // Search for a candidate Gop for gop-fusion from the gop cache and
  4861. // return it or return null if no good candidate was found
  4862. this.getGopForFusion_ = function(nalUnit) {
  4863. var
  4864. halfSecond = 45000, // Half-a-second in a 90khz clock
  4865. allowableOverlap = 10000, // About 3 frames @ 30fps
  4866. nearestDistance = Infinity,
  4867. dtsDistance,
  4868. nearestGopObj,
  4869. currentGop,
  4870. currentGopObj,
  4871. i;
  4872. // Search for the GOP nearest to the beginning of this nal unit
  4873. for (i = 0; i < this.gopCache_.length; i++) {
  4874. currentGopObj = this.gopCache_[i];
  4875. currentGop = currentGopObj.gop;
  4876. // Reject Gops with different SPS or PPS
  4877. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) ||
  4878. !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  4879. continue;
  4880. }
  4881. // Reject Gops that would require a negative baseMediaDecodeTime
  4882. if (currentGop.dts < track.timelineStartInfo.dts) {
  4883. continue;
  4884. }
  4885. // The distance between the end of the gop and the start of the nalUnit
  4886. dtsDistance = (nalUnit.dts - currentGop.dts) - currentGop.duration;
  4887. // Only consider GOPS that start before the nal unit and end within
  4888. // a half-second of the nal unit
  4889. if (dtsDistance >= -allowableOverlap &&
  4890. dtsDistance <= halfSecond) {
  4891. // Always use the closest GOP we found if there is more than
  4892. // one candidate
  4893. if (!nearestGopObj ||
  4894. nearestDistance > dtsDistance) {
  4895. nearestGopObj = currentGopObj;
  4896. nearestDistance = dtsDistance;
  4897. }
  4898. }
  4899. }
  4900. if (nearestGopObj) {
  4901. return nearestGopObj.gop;
  4902. }
  4903. return null;
  4904. };
  4905. // trim gop list to the first gop found that has a matching pts with a gop in the list
  4906. // of gopsToAlignWith starting from the START of the list
  4907. this.alignGopsAtStart_ = function(gops) {
  4908. var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
  4909. byteLength = gops.byteLength;
  4910. nalCount = gops.nalCount;
  4911. duration = gops.duration;
  4912. alignIndex = gopIndex = 0;
  4913. while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
  4914. align = gopsToAlignWith[alignIndex];
  4915. gop = gops[gopIndex];
  4916. if (align.pts === gop.pts) {
  4917. break;
  4918. }
  4919. if (gop.pts > align.pts) {
  4920. // this current gop starts after the current gop we want to align on, so increment
  4921. // align index
  4922. alignIndex++;
  4923. continue;
  4924. }
  4925. // current gop starts before the current gop we want to align on. so increment gop
  4926. // index
  4927. gopIndex++;
  4928. byteLength -= gop.byteLength;
  4929. nalCount -= gop.nalCount;
  4930. duration -= gop.duration;
  4931. }
  4932. if (gopIndex === 0) {
  4933. // no gops to trim
  4934. return gops;
  4935. }
  4936. if (gopIndex === gops.length) {
  4937. // all gops trimmed, skip appending all gops
  4938. return null;
  4939. }
  4940. alignedGops = gops.slice(gopIndex);
  4941. alignedGops.byteLength = byteLength;
  4942. alignedGops.duration = duration;
  4943. alignedGops.nalCount = nalCount;
  4944. alignedGops.pts = alignedGops[0].pts;
  4945. alignedGops.dts = alignedGops[0].dts;
  4946. return alignedGops;
  4947. };
  4948. // trim gop list to the first gop found that has a matching pts with a gop in the list
  4949. // of gopsToAlignWith starting from the END of the list
  4950. this.alignGopsAtEnd_ = function(gops) {
  4951. var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
  4952. alignIndex = gopsToAlignWith.length - 1;
  4953. gopIndex = gops.length - 1;
  4954. alignEndIndex = null;
  4955. matchFound = false;
  4956. while (alignIndex >= 0 && gopIndex >= 0) {
  4957. align = gopsToAlignWith[alignIndex];
  4958. gop = gops[gopIndex];
  4959. if (align.pts === gop.pts) {
  4960. matchFound = true;
  4961. break;
  4962. }
  4963. if (align.pts > gop.pts) {
  4964. alignIndex--;
  4965. continue;
  4966. }
  4967. if (alignIndex === gopsToAlignWith.length - 1) {
  4968. // gop.pts is greater than the last alignment candidate. If no match is found
  4969. // by the end of this loop, we still want to append gops that come after this
  4970. // point
  4971. alignEndIndex = gopIndex;
  4972. }
  4973. gopIndex--;
  4974. }
  4975. if (!matchFound && alignEndIndex === null) {
  4976. return null;
  4977. }
  4978. var trimIndex;
  4979. if (matchFound) {
  4980. trimIndex = gopIndex;
  4981. } else {
  4982. trimIndex = alignEndIndex;
  4983. }
  4984. if (trimIndex === 0) {
  4985. return gops;
  4986. }
  4987. var alignedGops = gops.slice(trimIndex);
  4988. var metadata = alignedGops.reduce(function(total, gop) {
  4989. total.byteLength += gop.byteLength;
  4990. total.duration += gop.duration;
  4991. total.nalCount += gop.nalCount;
  4992. return total;
  4993. }, { byteLength: 0, duration: 0, nalCount: 0 });
  4994. alignedGops.byteLength = metadata.byteLength;
  4995. alignedGops.duration = metadata.duration;
  4996. alignedGops.nalCount = metadata.nalCount;
  4997. alignedGops.pts = alignedGops[0].pts;
  4998. alignedGops.dts = alignedGops[0].dts;
  4999. return alignedGops;
  5000. };
  5001. this.alignGopsWith = function(newGopsToAlignWith) {
  5002. gopsToAlignWith = newGopsToAlignWith;
  5003. };
  5004. };
  5005. VideoSegmentStream.prototype = new Stream();
  5006. /**
  5007. * A Stream that can combine multiple streams (ie. audio & video)
  5008. * into a single output segment for MSE. Also supports audio-only
  5009. * and video-only streams.
  5010. * @param options {object} transmuxer options object
  5011. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  5012. * in the source; false to adjust the first segment to start at media timeline start.
  5013. */
  5014. CoalesceStream = function(options, metadataStream) {
  5015. // Number of Tracks per output segment
  5016. // If greater than 1, we combine multiple
  5017. // tracks into a single segment
  5018. this.numberOfTracks = 0;
  5019. this.metadataStream = metadataStream;
  5020. options = options || {};
  5021. if (typeof options.remux !== 'undefined') {
  5022. this.remuxTracks = !!options.remux;
  5023. } else {
  5024. this.remuxTracks = true;
  5025. }
  5026. if (typeof options.keepOriginalTimestamps === 'boolean') {
  5027. this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  5028. } else {
  5029. this.keepOriginalTimestamps = false;
  5030. }
  5031. this.pendingTracks = [];
  5032. this.videoTrack = null;
  5033. this.pendingBoxes = [];
  5034. this.pendingCaptions = [];
  5035. this.pendingMetadata = [];
  5036. this.pendingBytes = 0;
  5037. this.emittedTracks = 0;
  5038. CoalesceStream.prototype.init.call(this);
  5039. // Take output from multiple
  5040. this.push = function(output) {
  5041. // buffer incoming captions until the associated video segment
  5042. // finishes
  5043. if (output.text) {
  5044. return this.pendingCaptions.push(output);
  5045. }
  5046. // buffer incoming id3 tags until the final flush
  5047. if (output.frames) {
  5048. return this.pendingMetadata.push(output);
  5049. }
  5050. // Add this track to the list of pending tracks and store
  5051. // important information required for the construction of
  5052. // the final segment
  5053. this.pendingTracks.push(output.track);
  5054. this.pendingBytes += output.boxes.byteLength;
  5055. // TODO: is there an issue for this against chrome?
  5056. // We unshift audio and push video because
  5057. // as of Chrome 75 when switching from
  5058. // one init segment to another if the video
  5059. // mdat does not appear after the audio mdat
  5060. // only audio will play for the duration of our transmux.
  5061. if (output.track.type === 'video') {
  5062. this.videoTrack = output.track;
  5063. this.pendingBoxes.push(output.boxes);
  5064. }
  5065. if (output.track.type === 'audio') {
  5066. this.audioTrack = output.track;
  5067. this.pendingBoxes.unshift(output.boxes);
  5068. }
  5069. };
  5070. };
  5071. CoalesceStream.prototype = new Stream();
  5072. CoalesceStream.prototype.flush = function(flushSource) {
  5073. var
  5074. offset = 0,
  5075. event = {
  5076. captions: [],
  5077. captionStreams: {},
  5078. metadata: [],
  5079. info: {}
  5080. },
  5081. caption,
  5082. id3,
  5083. initSegment,
  5084. timelineStartPts = 0,
  5085. i;
  5086. if (this.pendingTracks.length < this.numberOfTracks) {
  5087. if (flushSource !== 'VideoSegmentStream' &&
  5088. flushSource !== 'AudioSegmentStream') {
  5089. // Return because we haven't received a flush from a data-generating
  5090. // portion of the segment (meaning that we have only recieved meta-data
  5091. // or captions.)
  5092. return;
  5093. } else if (this.remuxTracks) {
  5094. // Return until we have enough tracks from the pipeline to remux (if we
  5095. // are remuxing audio and video into a single MP4)
  5096. return;
  5097. } else if (this.pendingTracks.length === 0) {
  5098. // In the case where we receive a flush without any data having been
  5099. // received we consider it an emitted track for the purposes of coalescing
  5100. // `done` events.
  5101. // We do this for the case where there is an audio and video track in the
  5102. // segment but no audio data. (seen in several playlists with alternate
  5103. // audio tracks and no audio present in the main TS segments.)
  5104. this.emittedTracks++;
  5105. if (this.emittedTracks >= this.numberOfTracks) {
  5106. this.trigger('done');
  5107. this.emittedTracks = 0;
  5108. }
  5109. return;
  5110. }
  5111. }
  5112. if (this.videoTrack) {
  5113. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  5114. VIDEO_PROPERTIES.forEach(function(prop) {
  5115. event.info[prop] = this.videoTrack[prop];
  5116. }, this);
  5117. } else if (this.audioTrack) {
  5118. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  5119. AUDIO_PROPERTIES.forEach(function(prop) {
  5120. event.info[prop] = this.audioTrack[prop];
  5121. }, this);
  5122. }
  5123. if (this.videoTrack || this.audioTrack) {
  5124. if (this.pendingTracks.length === 1) {
  5125. event.type = this.pendingTracks[0].type;
  5126. } else {
  5127. event.type = 'combined';
  5128. }
  5129. this.emittedTracks += this.pendingTracks.length;
  5130. initSegment = mp4.initSegment(this.pendingTracks);
  5131. // Create a new typed array to hold the init segment
  5132. event.initSegment = new Uint8Array(initSegment.byteLength);
  5133. // Create an init segment containing a moov
  5134. // and track definitions
  5135. event.initSegment.set(initSegment);
  5136. // Create a new typed array to hold the moof+mdats
  5137. event.data = new Uint8Array(this.pendingBytes);
  5138. // Append each moof+mdat (one per track) together
  5139. for (i = 0; i < this.pendingBoxes.length; i++) {
  5140. event.data.set(this.pendingBoxes[i], offset);
  5141. offset += this.pendingBoxes[i].byteLength;
  5142. }
  5143. // Translate caption PTS times into second offsets to match the
  5144. // video timeline for the segment, and add track info
  5145. for (i = 0; i < this.pendingCaptions.length; i++) {
  5146. caption = this.pendingCaptions[i];
  5147. caption.startTime = clock.metadataTsToSeconds(
  5148. caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
  5149. caption.endTime = clock.metadataTsToSeconds(
  5150. caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
  5151. event.captionStreams[caption.stream] = true;
  5152. event.captions.push(caption);
  5153. }
  5154. // Translate ID3 frame PTS times into second offsets to match the
  5155. // video timeline for the segment
  5156. for (i = 0; i < this.pendingMetadata.length; i++) {
  5157. id3 = this.pendingMetadata[i];
  5158. id3.cueTime = clock.metadataTsToSeconds(
  5159. id3.pts, timelineStartPts, this.keepOriginalTimestamps);
  5160. event.metadata.push(id3);
  5161. }
  5162. // We add this to every single emitted segment even though we only need
  5163. // it for the first
  5164. event.metadata.dispatchType = this.metadataStream.dispatchType;
  5165. // Reset stream state
  5166. this.pendingTracks.length = 0;
  5167. this.videoTrack = null;
  5168. this.pendingBoxes.length = 0;
  5169. this.pendingCaptions.length = 0;
  5170. this.pendingBytes = 0;
  5171. this.pendingMetadata.length = 0;
  5172. // Emit the built segment
  5173. // We include captions and ID3 tags for backwards compatibility,
  5174. // ideally we should send only video and audio in the data event
  5175. this.trigger('data', event);
  5176. // Emit each caption to the outside world
  5177. // Ideally, this would happen immediately on parsing captions,
  5178. // but we need to ensure that video data is sent back first
  5179. // so that caption timing can be adjusted to match video timing
  5180. for (i = 0; i < event.captions.length; i++) {
  5181. caption = event.captions[i];
  5182. this.trigger('caption', caption);
  5183. }
  5184. // Emit each id3 tag to the outside world
  5185. // Ideally, this would happen immediately on parsing the tag,
  5186. // but we need to ensure that video data is sent back first
  5187. // so that ID3 frame timing can be adjusted to match video timing
  5188. for (i = 0; i < event.metadata.length; i++) {
  5189. id3 = event.metadata[i];
  5190. this.trigger('id3Frame', id3);
  5191. }
  5192. }
  5193. // Only emit `done` if all tracks have been flushed and emitted
  5194. if (this.emittedTracks >= this.numberOfTracks) {
  5195. this.trigger('done');
  5196. this.emittedTracks = 0;
  5197. }
  5198. };
  5199. CoalesceStream.prototype.setRemux = function(val) {
  5200. this.remuxTracks = val;
  5201. };
  5202. /**
  5203. * A Stream that expects MP2T binary data as input and produces
  5204. * corresponding media segments, suitable for use with Media Source
  5205. * Extension (MSE) implementations that support the ISO BMFF byte
  5206. * stream format, like Chrome.
  5207. */
  5208. Transmuxer = function(options) {
  5209. var
  5210. self = this,
  5211. hasFlushed = true,
  5212. videoTrack,
  5213. audioTrack;
  5214. Transmuxer.prototype.init.call(this);
  5215. options = options || {};
  5216. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  5217. this.transmuxPipeline_ = {};
  5218. mp4.setDuration(options.duration)
  5219. this.setupAacPipeline = function() {
  5220. var pipeline = {};
  5221. this.transmuxPipeline_ = pipeline;
  5222. pipeline.type = 'aac';
  5223. pipeline.metadataStream = new m2ts.MetadataStream();
  5224. // set up the parsing pipeline
  5225. pipeline.aacStream = new AacStream();
  5226. pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
  5227. pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
  5228. pipeline.adtsStream = new AdtsStream();
  5229. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  5230. pipeline.headOfPipeline = pipeline.aacStream;
  5231. pipeline.aacStream
  5232. .pipe(pipeline.audioTimestampRolloverStream)
  5233. .pipe(pipeline.adtsStream);
  5234. pipeline.aacStream
  5235. .pipe(pipeline.timedMetadataTimestampRolloverStream)
  5236. .pipe(pipeline.metadataStream)
  5237. .pipe(pipeline.coalesceStream);
  5238. pipeline.metadataStream.on('timestamp', function(frame) {
  5239. pipeline.aacStream.setTimestamp(frame.timeStamp);
  5240. });
  5241. pipeline.aacStream.on('data', function(data) {
  5242. if ((data.type !== 'timed-metadata' && data.type !== 'audio') || pipeline.audioSegmentStream) {
  5243. return;
  5244. }
  5245. audioTrack = audioTrack || {
  5246. timelineStartInfo: {
  5247. baseMediaDecodeTime: self.baseMediaDecodeTime
  5248. },
  5249. codec: 'adts',
  5250. type: 'audio'
  5251. };
  5252. // hook up the audio segment stream to the first track with aac data
  5253. pipeline.coalesceStream.numberOfTracks++;
  5254. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  5255. pipeline.audioSegmentStream.on('timingInfo',
  5256. self.trigger.bind(self, 'audioTimingInfo'));
  5257. // Set up the final part of the audio pipeline
  5258. pipeline.adtsStream
  5259. .pipe(pipeline.audioSegmentStream)
  5260. .pipe(pipeline.coalesceStream);
  5261. // emit pmt info
  5262. self.trigger('trackinfo', {
  5263. hasAudio: !!audioTrack,
  5264. hasVideo: !!videoTrack
  5265. });
  5266. });
  5267. // Re-emit any data coming from the coalesce stream to the outside world
  5268. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  5269. // Let the consumer know we have finished flushing the entire pipeline
  5270. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  5271. };
  5272. this.setupTsPipeline = function() {
  5273. var pipeline = {};
  5274. this.transmuxPipeline_ = pipeline;
  5275. pipeline.type = 'ts';
  5276. pipeline.metadataStream = new m2ts.MetadataStream();
  5277. // set up the parsing pipeline
  5278. pipeline.packetStream = new m2ts.TransportPacketStream();
  5279. pipeline.parseStream = new m2ts.TransportParseStream();
  5280. pipeline.elementaryStream = new m2ts.ElementaryStream();
  5281. pipeline.timestampRolloverStream = new m2ts.TimestampRolloverStream();
  5282. pipeline.adtsStream = new AdtsStream();
  5283. pipeline.h264Stream = new H264Stream();
  5284. pipeline.captionStream = new m2ts.CaptionStream();
  5285. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  5286. pipeline.headOfPipeline = pipeline.packetStream;
  5287. // disassemble MPEG2-TS packets into elementary streams
  5288. pipeline.packetStream
  5289. .pipe(pipeline.parseStream)
  5290. .pipe(pipeline.elementaryStream)
  5291. .pipe(pipeline.timestampRolloverStream);
  5292. // !!THIS ORDER IS IMPORTANT!!
  5293. // demux the streams
  5294. pipeline.timestampRolloverStream
  5295. .pipe(pipeline.h264Stream);
  5296. pipeline.timestampRolloverStream
  5297. .pipe(pipeline.adtsStream);
  5298. pipeline.timestampRolloverStream
  5299. .pipe(pipeline.metadataStream)
  5300. .pipe(pipeline.coalesceStream);
  5301. // Hook up CEA-608/708 caption stream
  5302. pipeline.h264Stream.pipe(pipeline.captionStream)
  5303. .pipe(pipeline.coalesceStream);
  5304. pipeline.elementaryStream.on('data', function(data) {
  5305. var i;
  5306. if (data.type === 'metadata') {
  5307. i = data.tracks.length;
  5308. // scan the tracks listed in the metadata
  5309. while (i--) {
  5310. if (!videoTrack && data.tracks[i].type === 'video') {
  5311. videoTrack = data.tracks[i];
  5312. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  5313. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  5314. audioTrack = data.tracks[i];
  5315. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  5316. }
  5317. }
  5318. // hook up the video segment stream to the first track with h264 data
  5319. if (videoTrack && !pipeline.videoSegmentStream) {
  5320. pipeline.coalesceStream.numberOfTracks++;
  5321. pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack, options);
  5322. pipeline.videoSegmentStream.on('timelineStartInfo', function(timelineStartInfo) {
  5323. // When video emits timelineStartInfo data after a flush, we forward that
  5324. // info to the AudioSegmentStream, if it exists, because video timeline
  5325. // data takes precedence. Do not do this if keepOriginalTimestamps is set,
  5326. // because this is a particularly subtle form of timestamp alteration.
  5327. if (audioTrack && !options.keepOriginalTimestamps) {
  5328. audioTrack.timelineStartInfo = timelineStartInfo;
  5329. // On the first segment we trim AAC frames that exist before the
  5330. // very earliest DTS we have seen in video because Chrome will
  5331. // interpret any video track with a baseMediaDecodeTime that is
  5332. // non-zero as a gap.
  5333. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
  5334. }
  5335. });
  5336. pipeline.videoSegmentStream.on('processedGopsInfo',
  5337. self.trigger.bind(self, 'gopInfo'));
  5338. pipeline.videoSegmentStream.on('segmentTimingInfo',
  5339. self.trigger.bind(self, 'videoSegmentTimingInfo'));
  5340. pipeline.videoSegmentStream.on('baseMediaDecodeTime', function(baseMediaDecodeTime) {
  5341. if (audioTrack) {
  5342. pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
  5343. }
  5344. });
  5345. pipeline.videoSegmentStream.on('timingInfo',
  5346. self.trigger.bind(self, 'videoTimingInfo'));
  5347. // Set up the final part of the video pipeline
  5348. pipeline.h264Stream
  5349. .pipe(pipeline.videoSegmentStream)
  5350. .pipe(pipeline.coalesceStream);
  5351. }
  5352. if (audioTrack && !pipeline.audioSegmentStream) {
  5353. // hook up the audio segment stream to the first track with aac data
  5354. pipeline.coalesceStream.numberOfTracks++;
  5355. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  5356. pipeline.audioSegmentStream.on('timingInfo',
  5357. self.trigger.bind(self, 'audioTimingInfo'));
  5358. // Set up the final part of the audio pipeline
  5359. pipeline.adtsStream
  5360. .pipe(pipeline.audioSegmentStream)
  5361. .pipe(pipeline.coalesceStream);
  5362. }
  5363. // emit pmt info
  5364. self.trigger('trackinfo', {
  5365. hasAudio: !!audioTrack,
  5366. hasVideo: !!videoTrack
  5367. });
  5368. }
  5369. });
  5370. // Re-emit any data coming from the coalesce stream to the outside world
  5371. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  5372. pipeline.coalesceStream.on('id3Frame', function(id3Frame) {
  5373. id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
  5374. self.trigger('id3Frame', id3Frame);
  5375. });
  5376. pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption'));
  5377. // Let the consumer know we have finished flushing the entire pipeline
  5378. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  5379. };
  5380. // hook up the segment streams once track metadata is delivered
  5381. this.setBaseMediaDecodeTime = function(baseMediaDecodeTime) {
  5382. var pipeline = this.transmuxPipeline_;
  5383. if (!options.keepOriginalTimestamps) {
  5384. this.baseMediaDecodeTime = baseMediaDecodeTime;
  5385. }
  5386. if (audioTrack) {
  5387. audioTrack.timelineStartInfo.dts = undefined;
  5388. audioTrack.timelineStartInfo.pts = undefined;
  5389. trackDecodeInfo.clearDtsInfo(audioTrack);
  5390. if (pipeline.audioTimestampRolloverStream) {
  5391. pipeline.audioTimestampRolloverStream.discontinuity();
  5392. }
  5393. }
  5394. if (videoTrack) {
  5395. if (pipeline.videoSegmentStream) {
  5396. pipeline.videoSegmentStream.gopCache_ = [];
  5397. }
  5398. videoTrack.timelineStartInfo.dts = undefined;
  5399. videoTrack.timelineStartInfo.pts = undefined;
  5400. trackDecodeInfo.clearDtsInfo(videoTrack);
  5401. pipeline.captionStream.reset();
  5402. }
  5403. if (pipeline.timestampRolloverStream) {
  5404. pipeline.timestampRolloverStream.discontinuity();
  5405. }
  5406. };
  5407. this.setAudioAppendStart = function(timestamp) {
  5408. if (audioTrack) {
  5409. this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
  5410. }
  5411. };
  5412. this.setRemux = function(val) {
  5413. var pipeline = this.transmuxPipeline_;
  5414. options.remux = val;
  5415. if (pipeline && pipeline.coalesceStream) {
  5416. pipeline.coalesceStream.setRemux(val);
  5417. }
  5418. };
  5419. this.alignGopsWith = function(gopsToAlignWith) {
  5420. if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
  5421. this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
  5422. }
  5423. };
  5424. // feed incoming data to the front of the parsing pipeline
  5425. this.push = function(data) {
  5426. if (hasFlushed) {
  5427. var isAac = isLikelyAacData(data);
  5428. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  5429. this.setupAacPipeline();
  5430. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  5431. this.setupTsPipeline();
  5432. }
  5433. hasFlushed = false;
  5434. }
  5435. this.transmuxPipeline_.headOfPipeline.push(data);
  5436. };
  5437. // flush any buffered data
  5438. this.flush = function() {
  5439. hasFlushed = true;
  5440. // Start at the top of the pipeline and flush all pending work
  5441. this.transmuxPipeline_.headOfPipeline.flush();
  5442. };
  5443. this.endTimeline = function() {
  5444. this.transmuxPipeline_.headOfPipeline.endTimeline();
  5445. };
  5446. this.reset = function() {
  5447. if (this.transmuxPipeline_.headOfPipeline) {
  5448. this.transmuxPipeline_.headOfPipeline.reset();
  5449. }
  5450. };
  5451. // Caption data has to be reset when seeking outside buffered range
  5452. this.resetCaptions = function() {
  5453. if (this.transmuxPipeline_.captionStream) {
  5454. this.transmuxPipeline_.captionStream.reset();
  5455. }
  5456. };
  5457. };
  5458. Transmuxer.prototype = new Stream();
  5459. module.exports = {
  5460. Transmuxer: Transmuxer,
  5461. VideoSegmentStream: VideoSegmentStream,
  5462. AudioSegmentStream: AudioSegmentStream,
  5463. AUDIO_PROPERTIES: AUDIO_PROPERTIES,
  5464. VIDEO_PROPERTIES: VIDEO_PROPERTIES,
  5465. // exported for testing
  5466. generateVideoSegmentTimingInfo: generateVideoSegmentTimingInfo
  5467. };
  5468. },{"1":1,"13":13,"16":16,"18":18,"2":2,"21":21,"29":29,"3":3,"31":31,"4":4,"5":5,"6":6,"9":9}],23:[function(require,module,exports){
  5469. /**
  5470. * mux.js
  5471. *
  5472. * Copyright (c) Brightcove
  5473. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  5474. *
  5475. * Reads in-band caption information from a video elementary
  5476. * stream. Captions must follow the CEA-708 standard for injection
  5477. * into an MPEG-2 transport streams.
  5478. * @see https://en.wikipedia.org/wiki/CEA-708
  5479. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  5480. */
  5481. 'use strict';
  5482. // Supplemental enhancement information (SEI) NAL units have a
  5483. // payload type field to indicate how they are to be
  5484. // interpreted. CEAS-708 caption content is always transmitted with
  5485. // payload type 0x04.
  5486. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  5487. RBSP_TRAILING_BITS = 128;
  5488. /**
  5489. * Parse a supplemental enhancement information (SEI) NAL unit.
  5490. * Stops parsing once a message of type ITU T T35 has been found.
  5491. *
  5492. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  5493. * @return {object} the parsed SEI payload
  5494. * @see Rec. ITU-T H.264, 7.3.2.3.1
  5495. */
  5496. var parseSei = function(bytes) {
  5497. var
  5498. i = 0,
  5499. result = {
  5500. payloadType: -1,
  5501. payloadSize: 0
  5502. },
  5503. payloadType = 0,
  5504. payloadSize = 0;
  5505. // go through the sei_rbsp parsing each each individual sei_message
  5506. while (i < bytes.byteLength) {
  5507. // stop once we have hit the end of the sei_rbsp
  5508. if (bytes[i] === RBSP_TRAILING_BITS) {
  5509. break;
  5510. }
  5511. // Parse payload type
  5512. while (bytes[i] === 0xFF) {
  5513. payloadType += 255;
  5514. i++;
  5515. }
  5516. payloadType += bytes[i++];
  5517. // Parse payload size
  5518. while (bytes[i] === 0xFF) {
  5519. payloadSize += 255;
  5520. i++;
  5521. }
  5522. payloadSize += bytes[i++];
  5523. // this sei_message is a 608/708 caption so save it and break
  5524. // there can only ever be one caption message in a frame's sei
  5525. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  5526. var userIdentifier = String.fromCharCode(
  5527. bytes[i + 3],
  5528. bytes[i + 4],
  5529. bytes[i + 5],
  5530. bytes[i + 6]);
  5531. if (userIdentifier === 'GA94') {
  5532. result.payloadType = payloadType;
  5533. result.payloadSize = payloadSize;
  5534. result.payload = bytes.subarray(i, i + payloadSize);
  5535. break;
  5536. } else {
  5537. result.payload = void 0;
  5538. }
  5539. }
  5540. // skip the payload and parse the next message
  5541. i += payloadSize;
  5542. payloadType = 0;
  5543. payloadSize = 0;
  5544. }
  5545. return result;
  5546. };
  5547. // see ANSI/SCTE 128-1 (2013), section 8.1
  5548. var parseUserData = function(sei) {
  5549. // itu_t_t35_contry_code must be 181 (United States) for
  5550. // captions
  5551. if (sei.payload[0] !== 181) {
  5552. return null;
  5553. }
  5554. // itu_t_t35_provider_code should be 49 (ATSC) for captions
  5555. if (((sei.payload[1] << 8) | sei.payload[2]) !== 49) {
  5556. return null;
  5557. }
  5558. // the user_identifier should be "GA94" to indicate ATSC1 data
  5559. if (String.fromCharCode(sei.payload[3],
  5560. sei.payload[4],
  5561. sei.payload[5],
  5562. sei.payload[6]) !== 'GA94') {
  5563. return null;
  5564. }
  5565. // finally, user_data_type_code should be 0x03 for caption data
  5566. if (sei.payload[7] !== 0x03) {
  5567. return null;
  5568. }
  5569. // return the user_data_type_structure and strip the trailing
  5570. // marker bits
  5571. return sei.payload.subarray(8, sei.payload.length - 1);
  5572. };
  5573. // see CEA-708-D, section 4.4
  5574. var parseCaptionPackets = function(pts, userData) {
  5575. var results = [], i, count, offset, data;
  5576. // if this is just filler, return immediately
  5577. if (!(userData[0] & 0x40)) {
  5578. return results;
  5579. }
  5580. // parse out the cc_data_1 and cc_data_2 fields
  5581. count = userData[0] & 0x1f;
  5582. for (i = 0; i < count; i++) {
  5583. offset = i * 3;
  5584. data = {
  5585. type: userData[offset + 2] & 0x03,
  5586. pts: pts
  5587. };
  5588. // capture cc data when cc_valid is 1
  5589. if (userData[offset + 2] & 0x04) {
  5590. data.ccData = (userData[offset + 3] << 8) | userData[offset + 4];
  5591. results.push(data);
  5592. }
  5593. }
  5594. return results;
  5595. };
  5596. var discardEmulationPreventionBytes = function(data) {
  5597. var
  5598. length = data.byteLength,
  5599. emulationPreventionBytesPositions = [],
  5600. i = 1,
  5601. newLength, newData;
  5602. // Find all `Emulation Prevention Bytes`
  5603. while (i < length - 2) {
  5604. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  5605. emulationPreventionBytesPositions.push(i + 2);
  5606. i += 2;
  5607. } else {
  5608. i++;
  5609. }
  5610. }
  5611. // If no Emulation Prevention Bytes were found just return the original
  5612. // array
  5613. if (emulationPreventionBytesPositions.length === 0) {
  5614. return data;
  5615. }
  5616. // Create a new array to hold the NAL unit data
  5617. newLength = length - emulationPreventionBytesPositions.length;
  5618. newData = new Uint8Array(newLength);
  5619. var sourceIndex = 0;
  5620. for (i = 0; i < newLength; sourceIndex++, i++) {
  5621. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  5622. // Skip this byte
  5623. sourceIndex++;
  5624. // Remove this position index
  5625. emulationPreventionBytesPositions.shift();
  5626. }
  5627. newData[i] = data[sourceIndex];
  5628. }
  5629. return newData;
  5630. };
  5631. // exports
  5632. module.exports = {
  5633. parseSei: parseSei,
  5634. parseUserData: parseUserData,
  5635. parseCaptionPackets: parseCaptionPackets,
  5636. discardEmulationPreventionBytes: discardEmulationPreventionBytes,
  5637. USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
  5638. };
  5639. },{}],24:[function(require,module,exports){
  5640. var parseSampleFlags = function(flags) {
  5641. return {
  5642. isLeading: (flags[0] & 0x0c) >>> 2,
  5643. dependsOn: flags[0] & 0x03,
  5644. isDependedOn: (flags[1] & 0xc0) >>> 6,
  5645. hasRedundancy: (flags[1] & 0x30) >>> 4,
  5646. paddingValue: (flags[1] & 0x0e) >>> 1,
  5647. isNonSyncSample: flags[1] & 0x01,
  5648. degradationPriority: (flags[2] << 8) | flags[3]
  5649. };
  5650. };
  5651. module.exports = parseSampleFlags;
  5652. },{}],25:[function(require,module,exports){
  5653. var toUnsigned = require(28).toUnsigned;
  5654. var tfdt = function(data) {
  5655. var result = {
  5656. version: data[0],
  5657. flags: new Uint8Array(data.subarray(1, 4)),
  5658. baseMediaDecodeTime: toUnsigned(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7])
  5659. };
  5660. if (result.version === 1) {
  5661. result.baseMediaDecodeTime *= Math.pow(2, 32);
  5662. result.baseMediaDecodeTime += toUnsigned(data[8] << 24 | data[9] << 16 | data[10] << 8 | data[11]);
  5663. }
  5664. return result;
  5665. };
  5666. module.exports = tfdt;
  5667. },{"28":28}],26:[function(require,module,exports){
  5668. var tfhd = function(data) {
  5669. var
  5670. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  5671. result = {
  5672. version: data[0],
  5673. flags: new Uint8Array(data.subarray(1, 4)),
  5674. trackId: view.getUint32(4)
  5675. },
  5676. baseDataOffsetPresent = result.flags[2] & 0x01,
  5677. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  5678. defaultSampleDurationPresent = result.flags[2] & 0x08,
  5679. defaultSampleSizePresent = result.flags[2] & 0x10,
  5680. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  5681. durationIsEmpty = result.flags[0] & 0x010000,
  5682. defaultBaseIsMoof = result.flags[0] & 0x020000,
  5683. i;
  5684. i = 8;
  5685. if (baseDataOffsetPresent) {
  5686. i += 4; // truncate top 4 bytes
  5687. // FIXME: should we read the full 64 bits?
  5688. result.baseDataOffset = view.getUint32(12);
  5689. i += 4;
  5690. }
  5691. if (sampleDescriptionIndexPresent) {
  5692. result.sampleDescriptionIndex = view.getUint32(i);
  5693. i += 4;
  5694. }
  5695. if (defaultSampleDurationPresent) {
  5696. result.defaultSampleDuration = view.getUint32(i);
  5697. i += 4;
  5698. }
  5699. if (defaultSampleSizePresent) {
  5700. result.defaultSampleSize = view.getUint32(i);
  5701. i += 4;
  5702. }
  5703. if (defaultSampleFlagsPresent) {
  5704. result.defaultSampleFlags = view.getUint32(i);
  5705. }
  5706. if (durationIsEmpty) {
  5707. result.durationIsEmpty = true;
  5708. }
  5709. if (!baseDataOffsetPresent && defaultBaseIsMoof) {
  5710. result.baseDataOffsetIsMoof = true;
  5711. }
  5712. return result;
  5713. };
  5714. module.exports = tfhd;
  5715. },{}],27:[function(require,module,exports){
  5716. var parseSampleFlags = require(24);
  5717. var trun = function(data) {
  5718. var
  5719. result = {
  5720. version: data[0],
  5721. flags: new Uint8Array(data.subarray(1, 4)),
  5722. samples: []
  5723. },
  5724. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  5725. // Flag interpretation
  5726. dataOffsetPresent = result.flags[2] & 0x01, // compare with 2nd byte of 0x1
  5727. firstSampleFlagsPresent = result.flags[2] & 0x04, // compare with 2nd byte of 0x4
  5728. sampleDurationPresent = result.flags[1] & 0x01, // compare with 2nd byte of 0x100
  5729. sampleSizePresent = result.flags[1] & 0x02, // compare with 2nd byte of 0x200
  5730. sampleFlagsPresent = result.flags[1] & 0x04, // compare with 2nd byte of 0x400
  5731. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08, // compare with 2nd byte of 0x800
  5732. sampleCount = view.getUint32(4),
  5733. offset = 8,
  5734. sample;
  5735. if (dataOffsetPresent) {
  5736. // 32 bit signed integer
  5737. result.dataOffset = view.getInt32(offset);
  5738. offset += 4;
  5739. }
  5740. // Overrides the flags for the first sample only. The order of
  5741. // optional values will be: duration, size, compositionTimeOffset
  5742. if (firstSampleFlagsPresent && sampleCount) {
  5743. sample = {
  5744. flags: parseSampleFlags(data.subarray(offset, offset + 4))
  5745. };
  5746. offset += 4;
  5747. if (sampleDurationPresent) {
  5748. sample.duration = view.getUint32(offset);
  5749. offset += 4;
  5750. }
  5751. if (sampleSizePresent) {
  5752. sample.size = view.getUint32(offset);
  5753. offset += 4;
  5754. }
  5755. if (sampleCompositionTimeOffsetPresent) {
  5756. if (result.version === 1) {
  5757. sample.compositionTimeOffset = view.getInt32(offset);
  5758. } else {
  5759. sample.compositionTimeOffset = view.getUint32(offset);
  5760. }
  5761. offset += 4;
  5762. }
  5763. result.samples.push(sample);
  5764. sampleCount--;
  5765. }
  5766. while (sampleCount--) {
  5767. sample = {};
  5768. if (sampleDurationPresent) {
  5769. sample.duration = view.getUint32(offset);
  5770. offset += 4;
  5771. }
  5772. if (sampleSizePresent) {
  5773. sample.size = view.getUint32(offset);
  5774. offset += 4;
  5775. }
  5776. if (sampleFlagsPresent) {
  5777. sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
  5778. offset += 4;
  5779. }
  5780. if (sampleCompositionTimeOffsetPresent) {
  5781. if (result.version === 1) {
  5782. sample.compositionTimeOffset = view.getInt32(offset);
  5783. } else {
  5784. sample.compositionTimeOffset = view.getUint32(offset);
  5785. }
  5786. offset += 4;
  5787. }
  5788. result.samples.push(sample);
  5789. }
  5790. return result;
  5791. };
  5792. module.exports = trun;
  5793. },{"24":24}],28:[function(require,module,exports){
  5794. /**
  5795. * mux.js
  5796. *
  5797. * Copyright (c) Brightcove
  5798. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  5799. */
  5800. var toUnsigned = function(value) {
  5801. return value >>> 0;
  5802. };
  5803. var toHexString = function(value) {
  5804. return ('00' + value.toString(16)).slice(-2);
  5805. };
  5806. module.exports = {
  5807. toUnsigned: toUnsigned,
  5808. toHexString: toHexString
  5809. };
  5810. },{}],29:[function(require,module,exports){
  5811. /**
  5812. * mux.js
  5813. *
  5814. * Copyright (c) Brightcove
  5815. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  5816. */
  5817. var
  5818. ONE_SECOND_IN_TS = 90000, // 90kHz clock
  5819. secondsToVideoTs,
  5820. secondsToAudioTs,
  5821. videoTsToSeconds,
  5822. audioTsToSeconds,
  5823. audioTsToVideoTs,
  5824. videoTsToAudioTs,
  5825. metadataTsToSeconds;
  5826. secondsToVideoTs = function(seconds) {
  5827. return seconds * ONE_SECOND_IN_TS;
  5828. };
  5829. secondsToAudioTs = function(seconds, sampleRate) {
  5830. return seconds * sampleRate;
  5831. };
  5832. videoTsToSeconds = function(timestamp) {
  5833. return timestamp / ONE_SECOND_IN_TS;
  5834. };
  5835. audioTsToSeconds = function(timestamp, sampleRate) {
  5836. return timestamp / sampleRate;
  5837. };
  5838. audioTsToVideoTs = function(timestamp, sampleRate) {
  5839. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  5840. };
  5841. videoTsToAudioTs = function(timestamp, sampleRate) {
  5842. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  5843. };
  5844. /**
  5845. * Adjust ID3 tag or caption timing information by the timeline pts values
  5846. * (if keepOriginalTimestamps is false) and convert to seconds
  5847. */
  5848. metadataTsToSeconds = function(timestamp, timelineStartPts, keepOriginalTimestamps) {
  5849. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  5850. };
  5851. module.exports = {
  5852. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS,
  5853. secondsToVideoTs: secondsToVideoTs,
  5854. secondsToAudioTs: secondsToAudioTs,
  5855. videoTsToSeconds: videoTsToSeconds,
  5856. audioTsToSeconds: audioTsToSeconds,
  5857. audioTsToVideoTs: audioTsToVideoTs,
  5858. videoTsToAudioTs: videoTsToAudioTs,
  5859. metadataTsToSeconds: metadataTsToSeconds
  5860. };
  5861. },{}],30:[function(require,module,exports){
  5862. /**
  5863. * mux.js
  5864. *
  5865. * Copyright (c) Brightcove
  5866. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  5867. */
  5868. 'use strict';
  5869. var ExpGolomb;
  5870. /**
  5871. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  5872. * scheme used by h264.
  5873. */
  5874. ExpGolomb = function(workingData) {
  5875. var
  5876. // the number of bytes left to examine in workingData
  5877. workingBytesAvailable = workingData.byteLength,
  5878. // the current word being examined
  5879. workingWord = 0, // :uint
  5880. // the number of bits left to examine in the current word
  5881. workingBitsAvailable = 0; // :uint;
  5882. // ():uint
  5883. this.length = function() {
  5884. return (8 * workingBytesAvailable);
  5885. };
  5886. // ():uint
  5887. this.bitsAvailable = function() {
  5888. return (8 * workingBytesAvailable) + workingBitsAvailable;
  5889. };
  5890. // ():void
  5891. this.loadWord = function() {
  5892. var
  5893. position = workingData.byteLength - workingBytesAvailable,
  5894. workingBytes = new Uint8Array(4),
  5895. availableBytes = Math.min(4, workingBytesAvailable);
  5896. if (availableBytes === 0) {
  5897. throw new Error('no bytes available');
  5898. }
  5899. workingBytes.set(workingData.subarray(position,
  5900. position + availableBytes));
  5901. workingWord = new DataView(workingBytes.buffer).getUint32(0);
  5902. // track the amount of workingData that has been processed
  5903. workingBitsAvailable = availableBytes * 8;
  5904. workingBytesAvailable -= availableBytes;
  5905. };
  5906. // (count:int):void
  5907. this.skipBits = function(count) {
  5908. var skipBytes; // :int
  5909. if (workingBitsAvailable > count) {
  5910. workingWord <<= count;
  5911. workingBitsAvailable -= count;
  5912. } else {
  5913. count -= workingBitsAvailable;
  5914. skipBytes = Math.floor(count / 8);
  5915. count -= (skipBytes * 8);
  5916. workingBytesAvailable -= skipBytes;
  5917. this.loadWord();
  5918. workingWord <<= count;
  5919. workingBitsAvailable -= count;
  5920. }
  5921. };
  5922. // (size:int):uint
  5923. this.readBits = function(size) {
  5924. var
  5925. bits = Math.min(workingBitsAvailable, size), // :uint
  5926. valu = workingWord >>> (32 - bits); // :uint
  5927. // if size > 31, handle error
  5928. workingBitsAvailable -= bits;
  5929. if (workingBitsAvailable > 0) {
  5930. workingWord <<= bits;
  5931. } else if (workingBytesAvailable > 0) {
  5932. this.loadWord();
  5933. }
  5934. bits = size - bits;
  5935. if (bits > 0) {
  5936. return valu << bits | this.readBits(bits);
  5937. }
  5938. return valu;
  5939. };
  5940. // ():uint
  5941. this.skipLeadingZeros = function() {
  5942. var leadingZeroCount; // :uint
  5943. for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
  5944. if ((workingWord & (0x80000000 >>> leadingZeroCount)) !== 0) {
  5945. // the first bit of working word is 1
  5946. workingWord <<= leadingZeroCount;
  5947. workingBitsAvailable -= leadingZeroCount;
  5948. return leadingZeroCount;
  5949. }
  5950. }
  5951. // we exhausted workingWord and still have not found a 1
  5952. this.loadWord();
  5953. return leadingZeroCount + this.skipLeadingZeros();
  5954. };
  5955. // ():void
  5956. this.skipUnsignedExpGolomb = function() {
  5957. this.skipBits(1 + this.skipLeadingZeros());
  5958. };
  5959. // ():void
  5960. this.skipExpGolomb = function() {
  5961. this.skipBits(1 + this.skipLeadingZeros());
  5962. };
  5963. // ():uint
  5964. this.readUnsignedExpGolomb = function() {
  5965. var clz = this.skipLeadingZeros(); // :uint
  5966. return this.readBits(clz + 1) - 1;
  5967. };
  5968. // ():int
  5969. this.readExpGolomb = function() {
  5970. var valu = this.readUnsignedExpGolomb(); // :int
  5971. if (0x01 & valu) {
  5972. // the number is odd if the low order bit is set
  5973. return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2
  5974. }
  5975. return -1 * (valu >>> 1); // divide by two then make it negative
  5976. };
  5977. // Some convenience functions
  5978. // :Boolean
  5979. this.readBoolean = function() {
  5980. return this.readBits(1) === 1;
  5981. };
  5982. // ():int
  5983. this.readUnsignedByte = function() {
  5984. return this.readBits(8);
  5985. };
  5986. this.loadWord();
  5987. };
  5988. module.exports = ExpGolomb;
  5989. },{}],31:[function(require,module,exports){
  5990. /**
  5991. * mux.js
  5992. *
  5993. * Copyright (c) Brightcove
  5994. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  5995. *
  5996. * A lightweight readable stream implemention that handles event dispatching.
  5997. * Objects that inherit from streams should call init in their constructors.
  5998. */
  5999. 'use strict';
  6000. var Stream = function() {
  6001. this.init = function() {
  6002. var listeners = {};
  6003. /**
  6004. * Add a listener for a specified event type.
  6005. * @param type {string} the event name
  6006. * @param listener {function} the callback to be invoked when an event of
  6007. * the specified type occurs
  6008. */
  6009. this.on = function(type, listener) {
  6010. if (!listeners[type]) {
  6011. listeners[type] = [];
  6012. }
  6013. listeners[type] = listeners[type].concat(listener);
  6014. };
  6015. /**
  6016. * Remove a listener for a specified event type.
  6017. * @param type {string} the event name
  6018. * @param listener {function} a function previously registered for this
  6019. * type of event through `on`
  6020. */
  6021. this.off = function(type, listener) {
  6022. var index;
  6023. if (!listeners[type]) {
  6024. return false;
  6025. }
  6026. index = listeners[type].indexOf(listener);
  6027. listeners[type] = listeners[type].slice();
  6028. listeners[type].splice(index, 1);
  6029. return index > -1;
  6030. };
  6031. /**
  6032. * Trigger an event of the specified type on this stream. Any additional
  6033. * arguments to this function are passed as parameters to event listeners.
  6034. * @param type {string} the event name
  6035. */
  6036. this.trigger = function(type) {
  6037. var callbacks, i, length, args;
  6038. callbacks = listeners[type];
  6039. if (!callbacks) {
  6040. return;
  6041. }
  6042. // Slicing the arguments on every invocation of this method
  6043. // can add a significant amount of overhead. Avoid the
  6044. // intermediate object creation for the common case of a
  6045. // single callback argument
  6046. if (arguments.length === 2) {
  6047. length = callbacks.length;
  6048. for (i = 0; i < length; ++i) {
  6049. callbacks[i].call(this, arguments[1]);
  6050. }
  6051. } else {
  6052. args = [];
  6053. i = arguments.length;
  6054. for (i = 1; i < arguments.length; ++i) {
  6055. args.push(arguments[i]);
  6056. }
  6057. length = callbacks.length;
  6058. for (i = 0; i < length; ++i) {
  6059. callbacks[i].apply(this, args);
  6060. }
  6061. }
  6062. };
  6063. /**
  6064. * Destroys the stream and cleans up.
  6065. */
  6066. this.dispose = function() {
  6067. listeners = {};
  6068. };
  6069. };
  6070. };
  6071. /**
  6072. * Forwards all `data` events on this stream to the destination stream. The
  6073. * destination stream should provide a method `push` to receive the data
  6074. * events as they arrive.
  6075. * @param destination {stream} the stream that will receive all `data` events
  6076. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  6077. * when the current stream emits a 'done' event
  6078. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  6079. */
  6080. Stream.prototype.pipe = function(destination) {
  6081. this.on('data', function(data) {
  6082. destination.push(data);
  6083. });
  6084. this.on('done', function(flushSource) {
  6085. destination.flush(flushSource);
  6086. });
  6087. this.on('partialdone', function(flushSource) {
  6088. destination.partialFlush(flushSource);
  6089. });
  6090. this.on('endedtimeline', function(flushSource) {
  6091. destination.endTimeline(flushSource);
  6092. });
  6093. this.on('reset', function(flushSource) {
  6094. destination.reset(flushSource);
  6095. });
  6096. return destination;
  6097. };
  6098. // Default stream functions that are expected to be overridden to perform
  6099. // actual work. These are provided by the prototype as a sort of no-op
  6100. // implementation so that we don't have to check for their existence in the
  6101. // `pipe` function above.
  6102. Stream.prototype.push = function(data) {
  6103. this.trigger('data', data);
  6104. };
  6105. Stream.prototype.flush = function(flushSource) {
  6106. this.trigger('done', flushSource);
  6107. };
  6108. Stream.prototype.partialFlush = function(flushSource) {
  6109. this.trigger('partialdone', flushSource);
  6110. };
  6111. Stream.prototype.endTimeline = function(flushSource) {
  6112. this.trigger('endedtimeline', flushSource);
  6113. };
  6114. Stream.prototype.reset = function(flushSource) {
  6115. this.trigger('reset', flushSource);
  6116. };
  6117. module.exports = Stream;
  6118. },{}]},{},[17])(17)
  6119. });