flv.js 657 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.flvjs = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  2. (function (process,global){
  3. /*!
  4. * @overview es6-promise - a tiny implementation of Promises/A+.
  5. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  6. * @license Licensed under MIT license
  7. * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
  8. * @version 4.1.0
  9. */
  10. (function (global, factory) {
  11. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  12. typeof define === 'function' && define.amd ? define(factory) :
  13. (global.ES6Promise = factory());
  14. }(this, (function () { 'use strict';
  15. function objectOrFunction(x) {
  16. return typeof x === 'function' || typeof x === 'object' && x !== null;
  17. }
  18. function isFunction(x) {
  19. return typeof x === 'function';
  20. }
  21. var _isArray = undefined;
  22. if (!Array.isArray) {
  23. _isArray = function (x) {
  24. return Object.prototype.toString.call(x) === '[object Array]';
  25. };
  26. } else {
  27. _isArray = Array.isArray;
  28. }
  29. var isArray = _isArray;
  30. var len = 0;
  31. var vertxNext = undefined;
  32. var customSchedulerFn = undefined;
  33. var asap = function asap(callback, arg) {
  34. queue[len] = callback;
  35. queue[len + 1] = arg;
  36. len += 2;
  37. if (len === 2) {
  38. // If len is 2, that means that we need to schedule an async flush.
  39. // If additional callbacks are queued before the queue is flushed, they
  40. // will be processed by this flush that we are scheduling.
  41. if (customSchedulerFn) {
  42. customSchedulerFn(flush);
  43. } else {
  44. scheduleFlush();
  45. }
  46. }
  47. };
  48. function setScheduler(scheduleFn) {
  49. customSchedulerFn = scheduleFn;
  50. }
  51. function setAsap(asapFn) {
  52. asap = asapFn;
  53. }
  54. var browserWindow = typeof window !== 'undefined' ? window : undefined;
  55. var browserGlobal = browserWindow || {};
  56. var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
  57. var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
  58. // test for web worker but not in IE10
  59. var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
  60. // node
  61. function useNextTick() {
  62. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  63. // see https://github.com/cujojs/when/issues/410 for details
  64. return function () {
  65. return process.nextTick(flush);
  66. };
  67. }
  68. // vertx
  69. function useVertxTimer() {
  70. if (typeof vertxNext !== 'undefined') {
  71. return function () {
  72. vertxNext(flush);
  73. };
  74. }
  75. return useSetTimeout();
  76. }
  77. function useMutationObserver() {
  78. var iterations = 0;
  79. var observer = new BrowserMutationObserver(flush);
  80. var node = document.createTextNode('');
  81. observer.observe(node, { characterData: true });
  82. return function () {
  83. node.data = iterations = ++iterations % 2;
  84. };
  85. }
  86. // web worker
  87. function useMessageChannel() {
  88. var channel = new MessageChannel();
  89. channel.port1.onmessage = flush;
  90. return function () {
  91. return channel.port2.postMessage(0);
  92. };
  93. }
  94. function useSetTimeout() {
  95. // Store setTimeout reference so es6-promise will be unaffected by
  96. // other code modifying setTimeout (like sinon.useFakeTimers())
  97. var globalSetTimeout = setTimeout;
  98. return function () {
  99. return globalSetTimeout(flush, 1);
  100. };
  101. }
  102. var queue = new Array(1000);
  103. function flush() {
  104. for (var i = 0; i < len; i += 2) {
  105. var callback = queue[i];
  106. var arg = queue[i + 1];
  107. callback(arg);
  108. queue[i] = undefined;
  109. queue[i + 1] = undefined;
  110. }
  111. len = 0;
  112. }
  113. function attemptVertx() {
  114. try {
  115. var r = _dereq_;
  116. var vertx = r('vertx');
  117. vertxNext = vertx.runOnLoop || vertx.runOnContext;
  118. return useVertxTimer();
  119. } catch (e) {
  120. return useSetTimeout();
  121. }
  122. }
  123. var scheduleFlush = undefined;
  124. // Decide what async method to use to triggering processing of queued callbacks:
  125. if (isNode) {
  126. scheduleFlush = useNextTick();
  127. } else if (BrowserMutationObserver) {
  128. scheduleFlush = useMutationObserver();
  129. } else if (isWorker) {
  130. scheduleFlush = useMessageChannel();
  131. } else if (browserWindow === undefined && typeof _dereq_ === 'function') {
  132. scheduleFlush = attemptVertx();
  133. } else {
  134. scheduleFlush = useSetTimeout();
  135. }
  136. function then(onFulfillment, onRejection) {
  137. var _arguments = arguments;
  138. var parent = this;
  139. var child = new this.constructor(noop);
  140. if (child[PROMISE_ID] === undefined) {
  141. makePromise(child);
  142. }
  143. var _state = parent._state;
  144. if (_state) {
  145. (function () {
  146. var callback = _arguments[_state - 1];
  147. asap(function () {
  148. return invokeCallback(_state, child, callback, parent._result);
  149. });
  150. })();
  151. } else {
  152. subscribe(parent, child, onFulfillment, onRejection);
  153. }
  154. return child;
  155. }
  156. /**
  157. `Promise.resolve` returns a promise that will become resolved with the
  158. passed `value`. It is shorthand for the following:
  159. ```javascript
  160. let promise = new Promise(function(resolve, reject){
  161. resolve(1);
  162. });
  163. promise.then(function(value){
  164. // value === 1
  165. });
  166. ```
  167. Instead of writing the above, your code now simply becomes the following:
  168. ```javascript
  169. let promise = Promise.resolve(1);
  170. promise.then(function(value){
  171. // value === 1
  172. });
  173. ```
  174. @method resolve
  175. @static
  176. @param {Any} value value that the returned promise will be resolved with
  177. Useful for tooling.
  178. @return {Promise} a promise that will become fulfilled with the given
  179. `value`
  180. */
  181. function resolve(object) {
  182. /*jshint validthis:true */
  183. var Constructor = this;
  184. if (object && typeof object === 'object' && object.constructor === Constructor) {
  185. return object;
  186. }
  187. var promise = new Constructor(noop);
  188. _resolve(promise, object);
  189. return promise;
  190. }
  191. var PROMISE_ID = Math.random().toString(36).substring(16);
  192. function noop() {}
  193. var PENDING = void 0;
  194. var FULFILLED = 1;
  195. var REJECTED = 2;
  196. var GET_THEN_ERROR = new ErrorObject();
  197. function selfFulfillment() {
  198. return new TypeError("You cannot resolve a promise with itself");
  199. }
  200. function cannotReturnOwn() {
  201. return new TypeError('A promises callback cannot return that same promise.');
  202. }
  203. function getThen(promise) {
  204. try {
  205. return promise.then;
  206. } catch (error) {
  207. GET_THEN_ERROR.error = error;
  208. return GET_THEN_ERROR;
  209. }
  210. }
  211. function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  212. try {
  213. then.call(value, fulfillmentHandler, rejectionHandler);
  214. } catch (e) {
  215. return e;
  216. }
  217. }
  218. function handleForeignThenable(promise, thenable, then) {
  219. asap(function (promise) {
  220. var sealed = false;
  221. var error = tryThen(then, thenable, function (value) {
  222. if (sealed) {
  223. return;
  224. }
  225. sealed = true;
  226. if (thenable !== value) {
  227. _resolve(promise, value);
  228. } else {
  229. fulfill(promise, value);
  230. }
  231. }, function (reason) {
  232. if (sealed) {
  233. return;
  234. }
  235. sealed = true;
  236. _reject(promise, reason);
  237. }, 'Settle: ' + (promise._label || ' unknown promise'));
  238. if (!sealed && error) {
  239. sealed = true;
  240. _reject(promise, error);
  241. }
  242. }, promise);
  243. }
  244. function handleOwnThenable(promise, thenable) {
  245. if (thenable._state === FULFILLED) {
  246. fulfill(promise, thenable._result);
  247. } else if (thenable._state === REJECTED) {
  248. _reject(promise, thenable._result);
  249. } else {
  250. subscribe(thenable, undefined, function (value) {
  251. return _resolve(promise, value);
  252. }, function (reason) {
  253. return _reject(promise, reason);
  254. });
  255. }
  256. }
  257. function handleMaybeThenable(promise, maybeThenable, then$$) {
  258. if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {
  259. handleOwnThenable(promise, maybeThenable);
  260. } else {
  261. if (then$$ === GET_THEN_ERROR) {
  262. _reject(promise, GET_THEN_ERROR.error);
  263. GET_THEN_ERROR.error = null;
  264. } else if (then$$ === undefined) {
  265. fulfill(promise, maybeThenable);
  266. } else if (isFunction(then$$)) {
  267. handleForeignThenable(promise, maybeThenable, then$$);
  268. } else {
  269. fulfill(promise, maybeThenable);
  270. }
  271. }
  272. }
  273. function _resolve(promise, value) {
  274. if (promise === value) {
  275. _reject(promise, selfFulfillment());
  276. } else if (objectOrFunction(value)) {
  277. handleMaybeThenable(promise, value, getThen(value));
  278. } else {
  279. fulfill(promise, value);
  280. }
  281. }
  282. function publishRejection(promise) {
  283. if (promise._onerror) {
  284. promise._onerror(promise._result);
  285. }
  286. publish(promise);
  287. }
  288. function fulfill(promise, value) {
  289. if (promise._state !== PENDING) {
  290. return;
  291. }
  292. promise._result = value;
  293. promise._state = FULFILLED;
  294. if (promise._subscribers.length !== 0) {
  295. asap(publish, promise);
  296. }
  297. }
  298. function _reject(promise, reason) {
  299. if (promise._state !== PENDING) {
  300. return;
  301. }
  302. promise._state = REJECTED;
  303. promise._result = reason;
  304. asap(publishRejection, promise);
  305. }
  306. function subscribe(parent, child, onFulfillment, onRejection) {
  307. var _subscribers = parent._subscribers;
  308. var length = _subscribers.length;
  309. parent._onerror = null;
  310. _subscribers[length] = child;
  311. _subscribers[length + FULFILLED] = onFulfillment;
  312. _subscribers[length + REJECTED] = onRejection;
  313. if (length === 0 && parent._state) {
  314. asap(publish, parent);
  315. }
  316. }
  317. function publish(promise) {
  318. var subscribers = promise._subscribers;
  319. var settled = promise._state;
  320. if (subscribers.length === 0) {
  321. return;
  322. }
  323. var child = undefined,
  324. callback = undefined,
  325. detail = promise._result;
  326. for (var i = 0; i < subscribers.length; i += 3) {
  327. child = subscribers[i];
  328. callback = subscribers[i + settled];
  329. if (child) {
  330. invokeCallback(settled, child, callback, detail);
  331. } else {
  332. callback(detail);
  333. }
  334. }
  335. promise._subscribers.length = 0;
  336. }
  337. function ErrorObject() {
  338. this.error = null;
  339. }
  340. var TRY_CATCH_ERROR = new ErrorObject();
  341. function tryCatch(callback, detail) {
  342. try {
  343. return callback(detail);
  344. } catch (e) {
  345. TRY_CATCH_ERROR.error = e;
  346. return TRY_CATCH_ERROR;
  347. }
  348. }
  349. function invokeCallback(settled, promise, callback, detail) {
  350. var hasCallback = isFunction(callback),
  351. value = undefined,
  352. error = undefined,
  353. succeeded = undefined,
  354. failed = undefined;
  355. if (hasCallback) {
  356. value = tryCatch(callback, detail);
  357. if (value === TRY_CATCH_ERROR) {
  358. failed = true;
  359. error = value.error;
  360. value.error = null;
  361. } else {
  362. succeeded = true;
  363. }
  364. if (promise === value) {
  365. _reject(promise, cannotReturnOwn());
  366. return;
  367. }
  368. } else {
  369. value = detail;
  370. succeeded = true;
  371. }
  372. if (promise._state !== PENDING) {
  373. // noop
  374. } else if (hasCallback && succeeded) {
  375. _resolve(promise, value);
  376. } else if (failed) {
  377. _reject(promise, error);
  378. } else if (settled === FULFILLED) {
  379. fulfill(promise, value);
  380. } else if (settled === REJECTED) {
  381. _reject(promise, value);
  382. }
  383. }
  384. function initializePromise(promise, resolver) {
  385. try {
  386. resolver(function resolvePromise(value) {
  387. _resolve(promise, value);
  388. }, function rejectPromise(reason) {
  389. _reject(promise, reason);
  390. });
  391. } catch (e) {
  392. _reject(promise, e);
  393. }
  394. }
  395. var id = 0;
  396. function nextId() {
  397. return id++;
  398. }
  399. function makePromise(promise) {
  400. promise[PROMISE_ID] = id++;
  401. promise._state = undefined;
  402. promise._result = undefined;
  403. promise._subscribers = [];
  404. }
  405. function Enumerator(Constructor, input) {
  406. this._instanceConstructor = Constructor;
  407. this.promise = new Constructor(noop);
  408. if (!this.promise[PROMISE_ID]) {
  409. makePromise(this.promise);
  410. }
  411. if (isArray(input)) {
  412. this._input = input;
  413. this.length = input.length;
  414. this._remaining = input.length;
  415. this._result = new Array(this.length);
  416. if (this.length === 0) {
  417. fulfill(this.promise, this._result);
  418. } else {
  419. this.length = this.length || 0;
  420. this._enumerate();
  421. if (this._remaining === 0) {
  422. fulfill(this.promise, this._result);
  423. }
  424. }
  425. } else {
  426. _reject(this.promise, validationError());
  427. }
  428. }
  429. function validationError() {
  430. return new Error('Array Methods must be provided an Array');
  431. };
  432. Enumerator.prototype._enumerate = function () {
  433. var length = this.length;
  434. var _input = this._input;
  435. for (var i = 0; this._state === PENDING && i < length; i++) {
  436. this._eachEntry(_input[i], i);
  437. }
  438. };
  439. Enumerator.prototype._eachEntry = function (entry, i) {
  440. var c = this._instanceConstructor;
  441. var resolve$$ = c.resolve;
  442. if (resolve$$ === resolve) {
  443. var _then = getThen(entry);
  444. if (_then === then && entry._state !== PENDING) {
  445. this._settledAt(entry._state, i, entry._result);
  446. } else if (typeof _then !== 'function') {
  447. this._remaining--;
  448. this._result[i] = entry;
  449. } else if (c === Promise) {
  450. var promise = new c(noop);
  451. handleMaybeThenable(promise, entry, _then);
  452. this._willSettleAt(promise, i);
  453. } else {
  454. this._willSettleAt(new c(function (resolve$$) {
  455. return resolve$$(entry);
  456. }), i);
  457. }
  458. } else {
  459. this._willSettleAt(resolve$$(entry), i);
  460. }
  461. };
  462. Enumerator.prototype._settledAt = function (state, i, value) {
  463. var promise = this.promise;
  464. if (promise._state === PENDING) {
  465. this._remaining--;
  466. if (state === REJECTED) {
  467. _reject(promise, value);
  468. } else {
  469. this._result[i] = value;
  470. }
  471. }
  472. if (this._remaining === 0) {
  473. fulfill(promise, this._result);
  474. }
  475. };
  476. Enumerator.prototype._willSettleAt = function (promise, i) {
  477. var enumerator = this;
  478. subscribe(promise, undefined, function (value) {
  479. return enumerator._settledAt(FULFILLED, i, value);
  480. }, function (reason) {
  481. return enumerator._settledAt(REJECTED, i, reason);
  482. });
  483. };
  484. /**
  485. `Promise.all` accepts an array of promises, and returns a new promise which
  486. is fulfilled with an array of fulfillment values for the passed promises, or
  487. rejected with the reason of the first passed promise to be rejected. It casts all
  488. elements of the passed iterable to promises as it runs this algorithm.
  489. Example:
  490. ```javascript
  491. let promise1 = resolve(1);
  492. let promise2 = resolve(2);
  493. let promise3 = resolve(3);
  494. let promises = [ promise1, promise2, promise3 ];
  495. Promise.all(promises).then(function(array){
  496. // The array here would be [ 1, 2, 3 ];
  497. });
  498. ```
  499. If any of the `promises` given to `all` are rejected, the first promise
  500. that is rejected will be given as an argument to the returned promises's
  501. rejection handler. For example:
  502. Example:
  503. ```javascript
  504. let promise1 = resolve(1);
  505. let promise2 = reject(new Error("2"));
  506. let promise3 = reject(new Error("3"));
  507. let promises = [ promise1, promise2, promise3 ];
  508. Promise.all(promises).then(function(array){
  509. // Code here never runs because there are rejected promises!
  510. }, function(error) {
  511. // error.message === "2"
  512. });
  513. ```
  514. @method all
  515. @static
  516. @param {Array} entries array of promises
  517. @param {String} label optional string for labeling the promise.
  518. Useful for tooling.
  519. @return {Promise} promise that is fulfilled when all `promises` have been
  520. fulfilled, or rejected if any of them become rejected.
  521. @static
  522. */
  523. function all(entries) {
  524. return new Enumerator(this, entries).promise;
  525. }
  526. /**
  527. `Promise.race` returns a new promise which is settled in the same way as the
  528. first passed promise to settle.
  529. Example:
  530. ```javascript
  531. let promise1 = new Promise(function(resolve, reject){
  532. setTimeout(function(){
  533. resolve('promise 1');
  534. }, 200);
  535. });
  536. let promise2 = new Promise(function(resolve, reject){
  537. setTimeout(function(){
  538. resolve('promise 2');
  539. }, 100);
  540. });
  541. Promise.race([promise1, promise2]).then(function(result){
  542. // result === 'promise 2' because it was resolved before promise1
  543. // was resolved.
  544. });
  545. ```
  546. `Promise.race` is deterministic in that only the state of the first
  547. settled promise matters. For example, even if other promises given to the
  548. `promises` array argument are resolved, but the first settled promise has
  549. become rejected before the other promises became fulfilled, the returned
  550. promise will become rejected:
  551. ```javascript
  552. let promise1 = new Promise(function(resolve, reject){
  553. setTimeout(function(){
  554. resolve('promise 1');
  555. }, 200);
  556. });
  557. let promise2 = new Promise(function(resolve, reject){
  558. setTimeout(function(){
  559. reject(new Error('promise 2'));
  560. }, 100);
  561. });
  562. Promise.race([promise1, promise2]).then(function(result){
  563. // Code here never runs
  564. }, function(reason){
  565. // reason.message === 'promise 2' because promise 2 became rejected before
  566. // promise 1 became fulfilled
  567. });
  568. ```
  569. An example real-world use case is implementing timeouts:
  570. ```javascript
  571. Promise.race([ajax('foo.json'), timeout(5000)])
  572. ```
  573. @method race
  574. @static
  575. @param {Array} promises array of promises to observe
  576. Useful for tooling.
  577. @return {Promise} a promise which settles in the same way as the first passed
  578. promise to settle.
  579. */
  580. function race(entries) {
  581. /*jshint validthis:true */
  582. var Constructor = this;
  583. if (!isArray(entries)) {
  584. return new Constructor(function (_, reject) {
  585. return reject(new TypeError('You must pass an array to race.'));
  586. });
  587. } else {
  588. return new Constructor(function (resolve, reject) {
  589. var length = entries.length;
  590. for (var i = 0; i < length; i++) {
  591. Constructor.resolve(entries[i]).then(resolve, reject);
  592. }
  593. });
  594. }
  595. }
  596. /**
  597. `Promise.reject` returns a promise rejected with the passed `reason`.
  598. It is shorthand for the following:
  599. ```javascript
  600. let promise = new Promise(function(resolve, reject){
  601. reject(new Error('WHOOPS'));
  602. });
  603. promise.then(function(value){
  604. // Code here doesn't run because the promise is rejected!
  605. }, function(reason){
  606. // reason.message === 'WHOOPS'
  607. });
  608. ```
  609. Instead of writing the above, your code now simply becomes the following:
  610. ```javascript
  611. let promise = Promise.reject(new Error('WHOOPS'));
  612. promise.then(function(value){
  613. // Code here doesn't run because the promise is rejected!
  614. }, function(reason){
  615. // reason.message === 'WHOOPS'
  616. });
  617. ```
  618. @method reject
  619. @static
  620. @param {Any} reason value that the returned promise will be rejected with.
  621. Useful for tooling.
  622. @return {Promise} a promise rejected with the given `reason`.
  623. */
  624. function reject(reason) {
  625. /*jshint validthis:true */
  626. var Constructor = this;
  627. var promise = new Constructor(noop);
  628. _reject(promise, reason);
  629. return promise;
  630. }
  631. function needsResolver() {
  632. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  633. }
  634. function needsNew() {
  635. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  636. }
  637. /**
  638. Promise objects represent the eventual result of an asynchronous operation. The
  639. primary way of interacting with a promise is through its `then` method, which
  640. registers callbacks to receive either a promise's eventual value or the reason
  641. why the promise cannot be fulfilled.
  642. Terminology
  643. -----------
  644. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  645. - `thenable` is an object or function that defines a `then` method.
  646. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  647. - `exception` is a value that is thrown using the throw statement.
  648. - `reason` is a value that indicates why a promise was rejected.
  649. - `settled` the final resting state of a promise, fulfilled or rejected.
  650. A promise can be in one of three states: pending, fulfilled, or rejected.
  651. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  652. state. Promises that are rejected have a rejection reason and are in the
  653. rejected state. A fulfillment value is never a thenable.
  654. Promises can also be said to *resolve* a value. If this value is also a
  655. promise, then the original promise's settled state will match the value's
  656. settled state. So a promise that *resolves* a promise that rejects will
  657. itself reject, and a promise that *resolves* a promise that fulfills will
  658. itself fulfill.
  659. Basic Usage:
  660. ------------
  661. ```js
  662. let promise = new Promise(function(resolve, reject) {
  663. // on success
  664. resolve(value);
  665. // on failure
  666. reject(reason);
  667. });
  668. promise.then(function(value) {
  669. // on fulfillment
  670. }, function(reason) {
  671. // on rejection
  672. });
  673. ```
  674. Advanced Usage:
  675. ---------------
  676. Promises shine when abstracting away asynchronous interactions such as
  677. `XMLHttpRequest`s.
  678. ```js
  679. function getJSON(url) {
  680. return new Promise(function(resolve, reject){
  681. let xhr = new XMLHttpRequest();
  682. xhr.open('GET', url);
  683. xhr.onreadystatechange = handler;
  684. xhr.responseType = 'json';
  685. xhr.setRequestHeader('Accept', 'application/json');
  686. xhr.send();
  687. function handler() {
  688. if (this.readyState === this.DONE) {
  689. if (this.status === 200) {
  690. resolve(this.response);
  691. } else {
  692. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  693. }
  694. }
  695. };
  696. });
  697. }
  698. getJSON('/posts.json').then(function(json) {
  699. // on fulfillment
  700. }, function(reason) {
  701. // on rejection
  702. });
  703. ```
  704. Unlike callbacks, promises are great composable primitives.
  705. ```js
  706. Promise.all([
  707. getJSON('/posts'),
  708. getJSON('/comments')
  709. ]).then(function(values){
  710. values[0] // => postsJSON
  711. values[1] // => commentsJSON
  712. return values;
  713. });
  714. ```
  715. @class Promise
  716. @param {function} resolver
  717. Useful for tooling.
  718. @constructor
  719. */
  720. function Promise(resolver) {
  721. this[PROMISE_ID] = nextId();
  722. this._result = this._state = undefined;
  723. this._subscribers = [];
  724. if (noop !== resolver) {
  725. typeof resolver !== 'function' && needsResolver();
  726. this instanceof Promise ? initializePromise(this, resolver) : needsNew();
  727. }
  728. }
  729. Promise.all = all;
  730. Promise.race = race;
  731. Promise.resolve = resolve;
  732. Promise.reject = reject;
  733. Promise._setScheduler = setScheduler;
  734. Promise._setAsap = setAsap;
  735. Promise._asap = asap;
  736. Promise.prototype = {
  737. constructor: Promise,
  738. /**
  739. The primary way of interacting with a promise is through its `then` method,
  740. which registers callbacks to receive either a promise's eventual value or the
  741. reason why the promise cannot be fulfilled.
  742. ```js
  743. findUser().then(function(user){
  744. // user is available
  745. }, function(reason){
  746. // user is unavailable, and you are given the reason why
  747. });
  748. ```
  749. Chaining
  750. --------
  751. The return value of `then` is itself a promise. This second, 'downstream'
  752. promise is resolved with the return value of the first promise's fulfillment
  753. or rejection handler, or rejected if the handler throws an exception.
  754. ```js
  755. findUser().then(function (user) {
  756. return user.name;
  757. }, function (reason) {
  758. return 'default name';
  759. }).then(function (userName) {
  760. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  761. // will be `'default name'`
  762. });
  763. findUser().then(function (user) {
  764. throw new Error('Found user, but still unhappy');
  765. }, function (reason) {
  766. throw new Error('`findUser` rejected and we're unhappy');
  767. }).then(function (value) {
  768. // never reached
  769. }, function (reason) {
  770. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  771. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  772. });
  773. ```
  774. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  775. ```js
  776. findUser().then(function (user) {
  777. throw new PedagogicalException('Upstream error');
  778. }).then(function (value) {
  779. // never reached
  780. }).then(function (value) {
  781. // never reached
  782. }, function (reason) {
  783. // The `PedgagocialException` is propagated all the way down to here
  784. });
  785. ```
  786. Assimilation
  787. ------------
  788. Sometimes the value you want to propagate to a downstream promise can only be
  789. retrieved asynchronously. This can be achieved by returning a promise in the
  790. fulfillment or rejection handler. The downstream promise will then be pending
  791. until the returned promise is settled. This is called *assimilation*.
  792. ```js
  793. findUser().then(function (user) {
  794. return findCommentsByAuthor(user);
  795. }).then(function (comments) {
  796. // The user's comments are now available
  797. });
  798. ```
  799. If the assimliated promise rejects, then the downstream promise will also reject.
  800. ```js
  801. findUser().then(function (user) {
  802. return findCommentsByAuthor(user);
  803. }).then(function (comments) {
  804. // If `findCommentsByAuthor` fulfills, we'll have the value here
  805. }, function (reason) {
  806. // If `findCommentsByAuthor` rejects, we'll have the reason here
  807. });
  808. ```
  809. Simple Example
  810. --------------
  811. Synchronous Example
  812. ```javascript
  813. let result;
  814. try {
  815. result = findResult();
  816. // success
  817. } catch(reason) {
  818. // failure
  819. }
  820. ```
  821. Errback Example
  822. ```js
  823. findResult(function(result, err){
  824. if (err) {
  825. // failure
  826. } else {
  827. // success
  828. }
  829. });
  830. ```
  831. Promise Example;
  832. ```javascript
  833. findResult().then(function(result){
  834. // success
  835. }, function(reason){
  836. // failure
  837. });
  838. ```
  839. Advanced Example
  840. --------------
  841. Synchronous Example
  842. ```javascript
  843. let author, books;
  844. try {
  845. author = findAuthor();
  846. books = findBooksByAuthor(author);
  847. // success
  848. } catch(reason) {
  849. // failure
  850. }
  851. ```
  852. Errback Example
  853. ```js
  854. function foundBooks(books) {
  855. }
  856. function failure(reason) {
  857. }
  858. findAuthor(function(author, err){
  859. if (err) {
  860. failure(err);
  861. // failure
  862. } else {
  863. try {
  864. findBoooksByAuthor(author, function(books, err) {
  865. if (err) {
  866. failure(err);
  867. } else {
  868. try {
  869. foundBooks(books);
  870. } catch(reason) {
  871. failure(reason);
  872. }
  873. }
  874. });
  875. } catch(error) {
  876. failure(err);
  877. }
  878. // success
  879. }
  880. });
  881. ```
  882. Promise Example;
  883. ```javascript
  884. findAuthor().
  885. then(findBooksByAuthor).
  886. then(function(books){
  887. // found books
  888. }).catch(function(reason){
  889. // something went wrong
  890. });
  891. ```
  892. @method then
  893. @param {Function} onFulfilled
  894. @param {Function} onRejected
  895. Useful for tooling.
  896. @return {Promise}
  897. */
  898. then: then,
  899. /**
  900. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  901. as the catch block of a try/catch statement.
  902. ```js
  903. function findAuthor(){
  904. throw new Error('couldn't find that author');
  905. }
  906. // synchronous
  907. try {
  908. findAuthor();
  909. } catch(reason) {
  910. // something went wrong
  911. }
  912. // async with promises
  913. findAuthor().catch(function(reason){
  914. // something went wrong
  915. });
  916. ```
  917. @method catch
  918. @param {Function} onRejection
  919. Useful for tooling.
  920. @return {Promise}
  921. */
  922. 'catch': function _catch(onRejection) {
  923. return this.then(null, onRejection);
  924. }
  925. };
  926. function polyfill() {
  927. var local = undefined;
  928. if (typeof global !== 'undefined') {
  929. local = global;
  930. } else if (typeof self !== 'undefined') {
  931. local = self;
  932. } else {
  933. try {
  934. local = Function('return this')();
  935. } catch (e) {
  936. throw new Error('polyfill failed because global object is unavailable in this environment');
  937. }
  938. }
  939. var P = local.Promise;
  940. if (P) {
  941. var promiseToString = null;
  942. try {
  943. promiseToString = Object.prototype.toString.call(P.resolve());
  944. } catch (e) {
  945. // silently ignored
  946. }
  947. if (promiseToString === '[object Promise]' && !P.cast) {
  948. return;
  949. }
  950. }
  951. local.Promise = Promise;
  952. }
  953. // Strange compat..
  954. Promise.polyfill = polyfill;
  955. Promise.Promise = Promise;
  956. return Promise;
  957. })));
  958. }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  959. },{"_process":3}],2:[function(_dereq_,module,exports){
  960. // Copyright Joyent, Inc. and other Node contributors.
  961. //
  962. // Permission is hereby granted, free of charge, to any person obtaining a
  963. // copy of this software and associated documentation files (the
  964. // "Software"), to deal in the Software without restriction, including
  965. // without limitation the rights to use, copy, modify, merge, publish,
  966. // distribute, sublicense, and/or sell copies of the Software, and to permit
  967. // persons to whom the Software is furnished to do so, subject to the
  968. // following conditions:
  969. //
  970. // The above copyright notice and this permission notice shall be included
  971. // in all copies or substantial portions of the Software.
  972. //
  973. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  974. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  975. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  976. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  977. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  978. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  979. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  980. function EventEmitter() {
  981. this._events = this._events || {};
  982. this._maxListeners = this._maxListeners || undefined;
  983. }
  984. module.exports = EventEmitter;
  985. // Backwards-compat with node 0.10.x
  986. EventEmitter.EventEmitter = EventEmitter;
  987. EventEmitter.prototype._events = undefined;
  988. EventEmitter.prototype._maxListeners = undefined;
  989. // By default EventEmitters will print a warning if more than 10 listeners are
  990. // added to it. This is a useful default which helps finding memory leaks.
  991. EventEmitter.defaultMaxListeners = 10;
  992. // Obviously not all Emitters should be limited to 10. This function allows
  993. // that to be increased. Set to zero for unlimited.
  994. EventEmitter.prototype.setMaxListeners = function(n) {
  995. if (!isNumber(n) || n < 0 || isNaN(n))
  996. throw TypeError('n must be a positive number');
  997. this._maxListeners = n;
  998. return this;
  999. };
  1000. EventEmitter.prototype.emit = function(type) {
  1001. var er, handler, len, args, i, listeners;
  1002. if (!this._events)
  1003. this._events = {};
  1004. // If there is no 'error' event listener then throw.
  1005. if (type === 'error') {
  1006. if (!this._events.error ||
  1007. (isObject(this._events.error) && !this._events.error.length)) {
  1008. er = arguments[1];
  1009. if (er instanceof Error) {
  1010. throw er; // Unhandled 'error' event
  1011. } else {
  1012. // At least give some kind of context to the user
  1013. var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
  1014. err.context = er;
  1015. throw err;
  1016. }
  1017. }
  1018. }
  1019. handler = this._events[type];
  1020. if (isUndefined(handler))
  1021. return false;
  1022. if (isFunction(handler)) {
  1023. switch (arguments.length) {
  1024. // fast cases
  1025. case 1:
  1026. handler.call(this);
  1027. break;
  1028. case 2:
  1029. handler.call(this, arguments[1]);
  1030. break;
  1031. case 3:
  1032. handler.call(this, arguments[1], arguments[2]);
  1033. break;
  1034. // slower
  1035. default:
  1036. args = Array.prototype.slice.call(arguments, 1);
  1037. handler.apply(this, args);
  1038. }
  1039. } else if (isObject(handler)) {
  1040. args = Array.prototype.slice.call(arguments, 1);
  1041. listeners = handler.slice();
  1042. len = listeners.length;
  1043. for (i = 0; i < len; i++)
  1044. listeners[i].apply(this, args);
  1045. }
  1046. return true;
  1047. };
  1048. EventEmitter.prototype.addListener = function(type, listener) {
  1049. var m;
  1050. if (!isFunction(listener))
  1051. throw TypeError('listener must be a function');
  1052. if (!this._events)
  1053. this._events = {};
  1054. // To avoid recursion in the case that type === "newListener"! Before
  1055. // adding it to the listeners, first emit "newListener".
  1056. if (this._events.newListener)
  1057. this.emit('newListener', type,
  1058. isFunction(listener.listener) ?
  1059. listener.listener : listener);
  1060. if (!this._events[type])
  1061. // Optimize the case of one listener. Don't need the extra array object.
  1062. this._events[type] = listener;
  1063. else if (isObject(this._events[type]))
  1064. // If we've already got an array, just append.
  1065. this._events[type].push(listener);
  1066. else
  1067. // Adding the second element, need to change to array.
  1068. this._events[type] = [this._events[type], listener];
  1069. // Check for listener leak
  1070. if (isObject(this._events[type]) && !this._events[type].warned) {
  1071. if (!isUndefined(this._maxListeners)) {
  1072. m = this._maxListeners;
  1073. } else {
  1074. m = EventEmitter.defaultMaxListeners;
  1075. }
  1076. if (m && m > 0 && this._events[type].length > m) {
  1077. this._events[type].warned = true;
  1078. console.error('(node) warning: possible EventEmitter memory ' +
  1079. 'leak detected. %d listeners added. ' +
  1080. 'Use emitter.setMaxListeners() to increase limit.',
  1081. this._events[type].length);
  1082. if (typeof console.trace === 'function') {
  1083. // not supported in IE 10
  1084. console.trace();
  1085. }
  1086. }
  1087. }
  1088. return this;
  1089. };
  1090. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  1091. EventEmitter.prototype.once = function(type, listener) {
  1092. if (!isFunction(listener))
  1093. throw TypeError('listener must be a function');
  1094. var fired = false;
  1095. function g() {
  1096. this.removeListener(type, g);
  1097. if (!fired) {
  1098. fired = true;
  1099. listener.apply(this, arguments);
  1100. }
  1101. }
  1102. g.listener = listener;
  1103. this.on(type, g);
  1104. return this;
  1105. };
  1106. // emits a 'removeListener' event iff the listener was removed
  1107. EventEmitter.prototype.removeListener = function(type, listener) {
  1108. var list, position, length, i;
  1109. if (!isFunction(listener))
  1110. throw TypeError('listener must be a function');
  1111. if (!this._events || !this._events[type])
  1112. return this;
  1113. list = this._events[type];
  1114. length = list.length;
  1115. position = -1;
  1116. if (list === listener ||
  1117. (isFunction(list.listener) && list.listener === listener)) {
  1118. delete this._events[type];
  1119. if (this._events.removeListener)
  1120. this.emit('removeListener', type, listener);
  1121. } else if (isObject(list)) {
  1122. for (i = length; i-- > 0;) {
  1123. if (list[i] === listener ||
  1124. (list[i].listener && list[i].listener === listener)) {
  1125. position = i;
  1126. break;
  1127. }
  1128. }
  1129. if (position < 0)
  1130. return this;
  1131. if (list.length === 1) {
  1132. list.length = 0;
  1133. delete this._events[type];
  1134. } else {
  1135. list.splice(position, 1);
  1136. }
  1137. if (this._events.removeListener)
  1138. this.emit('removeListener', type, listener);
  1139. }
  1140. return this;
  1141. };
  1142. EventEmitter.prototype.removeAllListeners = function(type) {
  1143. var key, listeners;
  1144. if (!this._events)
  1145. return this;
  1146. // not listening for removeListener, no need to emit
  1147. if (!this._events.removeListener) {
  1148. if (arguments.length === 0)
  1149. this._events = {};
  1150. else if (this._events[type])
  1151. delete this._events[type];
  1152. return this;
  1153. }
  1154. // emit removeListener for all listeners on all events
  1155. if (arguments.length === 0) {
  1156. for (key in this._events) {
  1157. if (key === 'removeListener') continue;
  1158. this.removeAllListeners(key);
  1159. }
  1160. this.removeAllListeners('removeListener');
  1161. this._events = {};
  1162. return this;
  1163. }
  1164. listeners = this._events[type];
  1165. if (isFunction(listeners)) {
  1166. this.removeListener(type, listeners);
  1167. } else if (listeners) {
  1168. // LIFO order
  1169. while (listeners.length)
  1170. this.removeListener(type, listeners[listeners.length - 1]);
  1171. }
  1172. delete this._events[type];
  1173. return this;
  1174. };
  1175. EventEmitter.prototype.listeners = function(type) {
  1176. var ret;
  1177. if (!this._events || !this._events[type])
  1178. ret = [];
  1179. else if (isFunction(this._events[type]))
  1180. ret = [this._events[type]];
  1181. else
  1182. ret = this._events[type].slice();
  1183. return ret;
  1184. };
  1185. EventEmitter.prototype.listenerCount = function(type) {
  1186. if (this._events) {
  1187. var evlistener = this._events[type];
  1188. if (isFunction(evlistener))
  1189. return 1;
  1190. else if (evlistener)
  1191. return evlistener.length;
  1192. }
  1193. return 0;
  1194. };
  1195. EventEmitter.listenerCount = function(emitter, type) {
  1196. return emitter.listenerCount(type);
  1197. };
  1198. function isFunction(arg) {
  1199. return typeof arg === 'function';
  1200. }
  1201. function isNumber(arg) {
  1202. return typeof arg === 'number';
  1203. }
  1204. function isObject(arg) {
  1205. return typeof arg === 'object' && arg !== null;
  1206. }
  1207. function isUndefined(arg) {
  1208. return arg === void 0;
  1209. }
  1210. },{}],3:[function(_dereq_,module,exports){
  1211. // shim for using process in browser
  1212. var process = module.exports = {};
  1213. // cached from whatever global is present so that test runners that stub it
  1214. // don't break things. But we need to wrap it in a try catch in case it is
  1215. // wrapped in strict mode code which doesn't define any globals. It's inside a
  1216. // function because try/catches deoptimize in certain engines.
  1217. var cachedSetTimeout;
  1218. var cachedClearTimeout;
  1219. function defaultSetTimout() {
  1220. throw new Error('setTimeout has not been defined');
  1221. }
  1222. function defaultClearTimeout () {
  1223. throw new Error('clearTimeout has not been defined');
  1224. }
  1225. (function () {
  1226. try {
  1227. if (typeof setTimeout === 'function') {
  1228. cachedSetTimeout = setTimeout;
  1229. } else {
  1230. cachedSetTimeout = defaultSetTimout;
  1231. }
  1232. } catch (e) {
  1233. cachedSetTimeout = defaultSetTimout;
  1234. }
  1235. try {
  1236. if (typeof clearTimeout === 'function') {
  1237. cachedClearTimeout = clearTimeout;
  1238. } else {
  1239. cachedClearTimeout = defaultClearTimeout;
  1240. }
  1241. } catch (e) {
  1242. cachedClearTimeout = defaultClearTimeout;
  1243. }
  1244. } ())
  1245. function runTimeout(fun) {
  1246. if (cachedSetTimeout === setTimeout) {
  1247. //normal enviroments in sane situations
  1248. return setTimeout(fun, 0);
  1249. }
  1250. // if setTimeout wasn't available but was latter defined
  1251. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  1252. cachedSetTimeout = setTimeout;
  1253. return setTimeout(fun, 0);
  1254. }
  1255. try {
  1256. // when when somebody has screwed with setTimeout but no I.E. maddness
  1257. return cachedSetTimeout(fun, 0);
  1258. } catch(e){
  1259. try {
  1260. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  1261. return cachedSetTimeout.call(null, fun, 0);
  1262. } catch(e){
  1263. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  1264. return cachedSetTimeout.call(this, fun, 0);
  1265. }
  1266. }
  1267. }
  1268. function runClearTimeout(marker) {
  1269. if (cachedClearTimeout === clearTimeout) {
  1270. //normal enviroments in sane situations
  1271. return clearTimeout(marker);
  1272. }
  1273. // if clearTimeout wasn't available but was latter defined
  1274. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  1275. cachedClearTimeout = clearTimeout;
  1276. return clearTimeout(marker);
  1277. }
  1278. try {
  1279. // when when somebody has screwed with setTimeout but no I.E. maddness
  1280. return cachedClearTimeout(marker);
  1281. } catch (e){
  1282. try {
  1283. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  1284. return cachedClearTimeout.call(null, marker);
  1285. } catch (e){
  1286. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  1287. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  1288. return cachedClearTimeout.call(this, marker);
  1289. }
  1290. }
  1291. }
  1292. var queue = [];
  1293. var draining = false;
  1294. var currentQueue;
  1295. var queueIndex = -1;
  1296. function cleanUpNextTick() {
  1297. if (!draining || !currentQueue) {
  1298. return;
  1299. }
  1300. draining = false;
  1301. if (currentQueue.length) {
  1302. queue = currentQueue.concat(queue);
  1303. } else {
  1304. queueIndex = -1;
  1305. }
  1306. if (queue.length) {
  1307. drainQueue();
  1308. }
  1309. }
  1310. function drainQueue() {
  1311. if (draining) {
  1312. return;
  1313. }
  1314. var timeout = runTimeout(cleanUpNextTick);
  1315. draining = true;
  1316. var len = queue.length;
  1317. while(len) {
  1318. currentQueue = queue;
  1319. queue = [];
  1320. while (++queueIndex < len) {
  1321. if (currentQueue) {
  1322. currentQueue[queueIndex].run();
  1323. }
  1324. }
  1325. queueIndex = -1;
  1326. len = queue.length;
  1327. }
  1328. currentQueue = null;
  1329. draining = false;
  1330. runClearTimeout(timeout);
  1331. }
  1332. process.nextTick = function (fun) {
  1333. var args = new Array(arguments.length - 1);
  1334. if (arguments.length > 1) {
  1335. for (var i = 1; i < arguments.length; i++) {
  1336. args[i - 1] = arguments[i];
  1337. }
  1338. }
  1339. queue.push(new Item(fun, args));
  1340. if (queue.length === 1 && !draining) {
  1341. runTimeout(drainQueue);
  1342. }
  1343. };
  1344. // v8 likes predictible objects
  1345. function Item(fun, array) {
  1346. this.fun = fun;
  1347. this.array = array;
  1348. }
  1349. Item.prototype.run = function () {
  1350. this.fun.apply(null, this.array);
  1351. };
  1352. process.title = 'browser';
  1353. process.browser = true;
  1354. process.env = {};
  1355. process.argv = [];
  1356. process.version = ''; // empty string to avoid regexp issues
  1357. process.versions = {};
  1358. function noop() {}
  1359. process.on = noop;
  1360. process.addListener = noop;
  1361. process.once = noop;
  1362. process.off = noop;
  1363. process.removeListener = noop;
  1364. process.removeAllListeners = noop;
  1365. process.emit = noop;
  1366. process.prependListener = noop;
  1367. process.prependOnceListener = noop;
  1368. process.listeners = function (name) { return [] }
  1369. process.binding = function (name) {
  1370. throw new Error('process.binding is not supported');
  1371. };
  1372. process.cwd = function () { return '/' };
  1373. process.chdir = function (dir) {
  1374. throw new Error('process.chdir is not supported');
  1375. };
  1376. process.umask = function() { return 0; };
  1377. },{}],4:[function(_dereq_,module,exports){
  1378. var bundleFn = arguments[3];
  1379. var sources = arguments[4];
  1380. var cache = arguments[5];
  1381. var stringify = JSON.stringify;
  1382. module.exports = function (fn, options) {
  1383. var wkey;
  1384. var cacheKeys = Object.keys(cache);
  1385. for (var i = 0, l = cacheKeys.length; i < l; i++) {
  1386. var key = cacheKeys[i];
  1387. var exp = cache[key].exports;
  1388. // Using babel as a transpiler to use esmodule, the export will always
  1389. // be an object with the default export as a property of it. To ensure
  1390. // the existing api and babel esmodule exports are both supported we
  1391. // check for both
  1392. if (exp === fn || exp && exp.default === fn) {
  1393. wkey = key;
  1394. break;
  1395. }
  1396. }
  1397. if (!wkey) {
  1398. wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
  1399. var wcache = {};
  1400. for (var i = 0, l = cacheKeys.length; i < l; i++) {
  1401. var key = cacheKeys[i];
  1402. wcache[key] = key;
  1403. }
  1404. sources[wkey] = [
  1405. Function(['require','module','exports'], '(' + fn + ')(self)'),
  1406. wcache
  1407. ];
  1408. }
  1409. var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
  1410. var scache = {}; scache[wkey] = wkey;
  1411. sources[skey] = [
  1412. Function(['require'], (
  1413. // try to call default if defined to also support babel esmodule
  1414. // exports
  1415. 'var f = require(' + stringify(wkey) + ');' +
  1416. '(f.default ? f.default : f)(self);'
  1417. )),
  1418. scache
  1419. ];
  1420. var workerSources = {};
  1421. resolveSources(skey);
  1422. function resolveSources(key) {
  1423. workerSources[key] = true;
  1424. for (var depPath in sources[key][1]) {
  1425. var depKey = sources[key][1][depPath];
  1426. if (!workerSources[depKey]) {
  1427. resolveSources(depKey);
  1428. }
  1429. }
  1430. }
  1431. var src = '(' + bundleFn + ')({'
  1432. + Object.keys(workerSources).map(function (key) {
  1433. return stringify(key) + ':['
  1434. + sources[key][0]
  1435. + ',' + stringify(sources[key][1]) + ']'
  1436. ;
  1437. }).join(',')
  1438. + '},{},[' + stringify(skey) + '])'
  1439. ;
  1440. var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  1441. var blob = new Blob([src], { type: 'text/javascript' });
  1442. if (options && options.bare) { return blob; }
  1443. var workerUrl = URL.createObjectURL(blob);
  1444. var worker = new Worker(workerUrl);
  1445. worker.objectURL = workerUrl;
  1446. return worker;
  1447. };
  1448. },{}],5:[function(_dereq_,module,exports){
  1449. 'use strict';
  1450. Object.defineProperty(exports, "__esModule", {
  1451. value: true
  1452. });
  1453. exports.createDefaultConfig = createDefaultConfig;
  1454. /*
  1455. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  1456. *
  1457. * @author zheng qian <xqq@xqq.im>
  1458. *
  1459. * Licensed under the Apache License, Version 2.0 (the "License");
  1460. * you may not use this file except in compliance with the License.
  1461. * You may obtain a copy of the License at
  1462. *
  1463. * http://www.apache.org/licenses/LICENSE-2.0
  1464. *
  1465. * Unless required by applicable law or agreed to in writing, software
  1466. * distributed under the License is distributed on an "AS IS" BASIS,
  1467. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1468. * See the License for the specific language governing permissions and
  1469. * limitations under the License.
  1470. */
  1471. var defaultConfig = exports.defaultConfig = {
  1472. enableWorker: false,
  1473. enableStashBuffer: true,
  1474. stashInitialSize: undefined,
  1475. isLive: false,
  1476. lazyLoad: true,
  1477. lazyLoadMaxDuration: 3 * 60,
  1478. lazyLoadRecoverDuration: 30,
  1479. deferLoadAfterSourceOpen: true,
  1480. // autoCleanupSourceBuffer: default as false, leave unspecified
  1481. autoCleanupMaxBackwardDuration: 3 * 60,
  1482. autoCleanupMinBackwardDuration: 2 * 60,
  1483. statisticsInfoReportInterval: 600,
  1484. fixAudioTimestampGap: true,
  1485. accurateSeek: false,
  1486. seekType: 'range', // [range, param, custom]
  1487. seekParamStart: 'bstart',
  1488. seekParamEnd: 'bend',
  1489. rangeLoadZeroStart: false,
  1490. customSeekHandler: undefined,
  1491. reuseRedirectedURL: false
  1492. // referrerPolicy: leave as unspecified
  1493. };
  1494. function createDefaultConfig() {
  1495. return Object.assign({}, defaultConfig);
  1496. }
  1497. },{}],6:[function(_dereq_,module,exports){
  1498. 'use strict';
  1499. Object.defineProperty(exports, "__esModule", {
  1500. value: true
  1501. });
  1502. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  1503. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  1504. *
  1505. * @author zheng qian <xqq@xqq.im>
  1506. *
  1507. * Licensed under the Apache License, Version 2.0 (the "License");
  1508. * you may not use this file except in compliance with the License.
  1509. * You may obtain a copy of the License at
  1510. *
  1511. * http://www.apache.org/licenses/LICENSE-2.0
  1512. *
  1513. * Unless required by applicable law or agreed to in writing, software
  1514. * distributed under the License is distributed on an "AS IS" BASIS,
  1515. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1516. * See the License for the specific language governing permissions and
  1517. * limitations under the License.
  1518. */
  1519. var _ioController = _dereq_('../io/io-controller.js');
  1520. var _ioController2 = _interopRequireDefault(_ioController);
  1521. var _config = _dereq_('../config.js');
  1522. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1523. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1524. var Features = function () {
  1525. function Features() {
  1526. _classCallCheck(this, Features);
  1527. }
  1528. _createClass(Features, null, [{
  1529. key: 'supportMSEH264Playback',
  1530. value: function supportMSEH264Playback() {
  1531. return window.MediaSource && window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
  1532. }
  1533. }, {
  1534. key: 'supportNetworkStreamIO',
  1535. value: function supportNetworkStreamIO() {
  1536. var ioctl = new _ioController2.default({}, (0, _config.createDefaultConfig)());
  1537. var loaderType = ioctl.loaderType;
  1538. ioctl.destroy();
  1539. return loaderType == 'fetch-stream-loader' || loaderType == 'xhr-moz-chunked-loader';
  1540. }
  1541. }, {
  1542. key: 'getNetworkLoaderTypeName',
  1543. value: function getNetworkLoaderTypeName() {
  1544. var ioctl = new _ioController2.default({}, (0, _config.createDefaultConfig)());
  1545. var loaderType = ioctl.loaderType;
  1546. ioctl.destroy();
  1547. return loaderType;
  1548. }
  1549. }, {
  1550. key: 'supportNativeMediaPlayback',
  1551. value: function supportNativeMediaPlayback(mimeType) {
  1552. if (Features.videoElement == undefined) {
  1553. Features.videoElement = window.document.createElement('video');
  1554. }
  1555. var canPlay = Features.videoElement.canPlayType(mimeType);
  1556. return canPlay === 'probably' || canPlay == 'maybe';
  1557. }
  1558. }, {
  1559. key: 'getFeatureList',
  1560. value: function getFeatureList() {
  1561. var features = {
  1562. mseFlvPlayback: false,
  1563. mseLiveFlvPlayback: false,
  1564. networkStreamIO: false,
  1565. networkLoaderName: '',
  1566. nativeMP4H264Playback: false,
  1567. nativeWebmVP8Playback: false,
  1568. nativeWebmVP9Playback: false
  1569. };
  1570. features.mseFlvPlayback = Features.supportMSEH264Playback();
  1571. features.networkStreamIO = Features.supportNetworkStreamIO();
  1572. features.networkLoaderName = Features.getNetworkLoaderTypeName();
  1573. features.mseLiveFlvPlayback = features.mseFlvPlayback && features.networkStreamIO;
  1574. features.nativeMP4H264Playback = Features.supportNativeMediaPlayback('video/mp4; codecs="avc1.42001E, mp4a.40.2"');
  1575. features.nativeWebmVP8Playback = Features.supportNativeMediaPlayback('video/webm; codecs="vp8.0, vorbis"');
  1576. features.nativeWebmVP9Playback = Features.supportNativeMediaPlayback('video/webm; codecs="vp9"');
  1577. return features;
  1578. }
  1579. }]);
  1580. return Features;
  1581. }();
  1582. exports.default = Features;
  1583. },{"../config.js":5,"../io/io-controller.js":23}],7:[function(_dereq_,module,exports){
  1584. "use strict";
  1585. Object.defineProperty(exports, "__esModule", {
  1586. value: true
  1587. });
  1588. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  1589. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1590. /*
  1591. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  1592. *
  1593. * @author zheng qian <xqq@xqq.im>
  1594. *
  1595. * Licensed under the Apache License, Version 2.0 (the "License");
  1596. * you may not use this file except in compliance with the License.
  1597. * You may obtain a copy of the License at
  1598. *
  1599. * http://www.apache.org/licenses/LICENSE-2.0
  1600. *
  1601. * Unless required by applicable law or agreed to in writing, software
  1602. * distributed under the License is distributed on an "AS IS" BASIS,
  1603. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1604. * See the License for the specific language governing permissions and
  1605. * limitations under the License.
  1606. */
  1607. var MediaInfo = function () {
  1608. function MediaInfo() {
  1609. _classCallCheck(this, MediaInfo);
  1610. this.mimeType = null;
  1611. this.duration = null;
  1612. this.hasAudio = null;
  1613. this.hasVideo = null;
  1614. this.audioCodec = null;
  1615. this.videoCodec = null;
  1616. this.audioDataRate = null;
  1617. this.videoDataRate = null;
  1618. this.audioSampleRate = null;
  1619. this.audioChannelCount = null;
  1620. this.width = null;
  1621. this.height = null;
  1622. this.fps = null;
  1623. this.profile = null;
  1624. this.level = null;
  1625. this.refFrames = null;
  1626. this.chromaFormat = null;
  1627. this.sarNum = null;
  1628. this.sarDen = null;
  1629. this.metadata = null;
  1630. this.segments = null; // MediaInfo[]
  1631. this.segmentCount = null;
  1632. this.hasKeyframesIndex = null;
  1633. this.keyframesIndex = null;
  1634. }
  1635. _createClass(MediaInfo, [{
  1636. key: "isComplete",
  1637. value: function isComplete() {
  1638. var audioInfoComplete = this.hasAudio === false || this.hasAudio === true && this.audioCodec != null && this.audioSampleRate != null && this.audioChannelCount != null;
  1639. var videoInfoComplete = this.hasVideo === false || this.hasVideo === true && this.videoCodec != null && this.width != null && this.height != null && this.fps != null && this.profile != null && this.level != null && this.refFrames != null && this.chromaFormat != null && this.sarNum != null && this.sarDen != null;
  1640. // keyframesIndex may not be present
  1641. return this.mimeType != null && this.duration != null && this.metadata != null && this.hasKeyframesIndex != null && audioInfoComplete && videoInfoComplete;
  1642. }
  1643. }, {
  1644. key: "isSeekable",
  1645. value: function isSeekable() {
  1646. return this.hasKeyframesIndex === true;
  1647. }
  1648. }, {
  1649. key: "getNearestKeyframe",
  1650. value: function getNearestKeyframe(milliseconds) {
  1651. if (this.keyframesIndex == null) {
  1652. return null;
  1653. }
  1654. var table = this.keyframesIndex;
  1655. var keyframeIdx = this._search(table.times, milliseconds);
  1656. return {
  1657. index: keyframeIdx,
  1658. milliseconds: table.times[keyframeIdx],
  1659. fileposition: table.filepositions[keyframeIdx]
  1660. };
  1661. }
  1662. }, {
  1663. key: "_search",
  1664. value: function _search(list, value) {
  1665. var idx = 0;
  1666. var last = list.length - 1;
  1667. var mid = 0;
  1668. var lbound = 0;
  1669. var ubound = last;
  1670. if (value < list[0]) {
  1671. idx = 0;
  1672. lbound = ubound + 1; // skip search
  1673. }
  1674. while (lbound <= ubound) {
  1675. mid = lbound + Math.floor((ubound - lbound) / 2);
  1676. if (mid === last || value >= list[mid] && value < list[mid + 1]) {
  1677. idx = mid;
  1678. break;
  1679. } else if (list[mid] < value) {
  1680. lbound = mid + 1;
  1681. } else {
  1682. ubound = mid - 1;
  1683. }
  1684. }
  1685. return idx;
  1686. }
  1687. }]);
  1688. return MediaInfo;
  1689. }();
  1690. exports.default = MediaInfo;
  1691. },{}],8:[function(_dereq_,module,exports){
  1692. "use strict";
  1693. Object.defineProperty(exports, "__esModule", {
  1694. value: true
  1695. });
  1696. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  1697. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1698. /*
  1699. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  1700. *
  1701. * @author zheng qian <xqq@xqq.im>
  1702. *
  1703. * Licensed under the Apache License, Version 2.0 (the "License");
  1704. * you may not use this file except in compliance with the License.
  1705. * You may obtain a copy of the License at
  1706. *
  1707. * http://www.apache.org/licenses/LICENSE-2.0
  1708. *
  1709. * Unless required by applicable law or agreed to in writing, software
  1710. * distributed under the License is distributed on an "AS IS" BASIS,
  1711. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1712. * See the License for the specific language governing permissions and
  1713. * limitations under the License.
  1714. */
  1715. // Represents an media sample (audio / video)
  1716. var SampleInfo = exports.SampleInfo = function SampleInfo(dts, pts, duration, originalDts, isSync) {
  1717. _classCallCheck(this, SampleInfo);
  1718. this.dts = dts;
  1719. this.pts = pts;
  1720. this.duration = duration;
  1721. this.originalDts = originalDts;
  1722. this.isSyncPoint = isSync;
  1723. this.fileposition = null;
  1724. };
  1725. // Media Segment concept is defined in Media Source Extensions spec.
  1726. // Particularly in ISO BMFF format, an Media Segment contains a moof box followed by a mdat box.
  1727. var MediaSegmentInfo = exports.MediaSegmentInfo = function () {
  1728. function MediaSegmentInfo() {
  1729. _classCallCheck(this, MediaSegmentInfo);
  1730. this.beginDts = 0;
  1731. this.endDts = 0;
  1732. this.beginPts = 0;
  1733. this.endPts = 0;
  1734. this.originalBeginDts = 0;
  1735. this.originalEndDts = 0;
  1736. this.syncPoints = []; // SampleInfo[n], for video IDR frames only
  1737. this.firstSample = null; // SampleInfo
  1738. this.lastSample = null; // SampleInfo
  1739. }
  1740. _createClass(MediaSegmentInfo, [{
  1741. key: "appendSyncPoint",
  1742. value: function appendSyncPoint(sampleInfo) {
  1743. // also called Random Access Point
  1744. sampleInfo.isSyncPoint = true;
  1745. this.syncPoints.push(sampleInfo);
  1746. }
  1747. }]);
  1748. return MediaSegmentInfo;
  1749. }();
  1750. // Ordered list for recording video IDR frames, sorted by originalDts
  1751. var IDRSampleList = exports.IDRSampleList = function () {
  1752. function IDRSampleList() {
  1753. _classCallCheck(this, IDRSampleList);
  1754. this._list = [];
  1755. }
  1756. _createClass(IDRSampleList, [{
  1757. key: "clear",
  1758. value: function clear() {
  1759. this._list = [];
  1760. }
  1761. }, {
  1762. key: "appendArray",
  1763. value: function appendArray(syncPoints) {
  1764. var list = this._list;
  1765. if (syncPoints.length === 0) {
  1766. return;
  1767. }
  1768. if (list.length > 0 && syncPoints[0].originalDts < list[list.length - 1].originalDts) {
  1769. this.clear();
  1770. }
  1771. Array.prototype.push.apply(list, syncPoints);
  1772. }
  1773. }, {
  1774. key: "getLastSyncPointBeforeDts",
  1775. value: function getLastSyncPointBeforeDts(dts) {
  1776. if (this._list.length == 0) {
  1777. return null;
  1778. }
  1779. var list = this._list;
  1780. var idx = 0;
  1781. var last = list.length - 1;
  1782. var mid = 0;
  1783. var lbound = 0;
  1784. var ubound = last;
  1785. if (dts < list[0].dts) {
  1786. idx = 0;
  1787. lbound = ubound + 1;
  1788. }
  1789. while (lbound <= ubound) {
  1790. mid = lbound + Math.floor((ubound - lbound) / 2);
  1791. if (mid === last || dts >= list[mid].dts && dts < list[mid + 1].dts) {
  1792. idx = mid;
  1793. break;
  1794. } else if (list[mid].dts < dts) {
  1795. lbound = mid + 1;
  1796. } else {
  1797. ubound = mid - 1;
  1798. }
  1799. }
  1800. return this._list[idx];
  1801. }
  1802. }]);
  1803. return IDRSampleList;
  1804. }();
  1805. // Data structure for recording information of media segments in single track.
  1806. var MediaSegmentInfoList = exports.MediaSegmentInfoList = function () {
  1807. function MediaSegmentInfoList(type) {
  1808. _classCallCheck(this, MediaSegmentInfoList);
  1809. this._type = type;
  1810. this._list = [];
  1811. this._lastAppendLocation = -1; // cached last insert location
  1812. }
  1813. _createClass(MediaSegmentInfoList, [{
  1814. key: "isEmpty",
  1815. value: function isEmpty() {
  1816. return this._list.length === 0;
  1817. }
  1818. }, {
  1819. key: "clear",
  1820. value: function clear() {
  1821. this._list = [];
  1822. this._lastAppendLocation = -1;
  1823. }
  1824. }, {
  1825. key: "_searchNearestSegmentBefore",
  1826. value: function _searchNearestSegmentBefore(originalBeginDts) {
  1827. var list = this._list;
  1828. if (list.length === 0) {
  1829. return -2;
  1830. }
  1831. var last = list.length - 1;
  1832. var mid = 0;
  1833. var lbound = 0;
  1834. var ubound = last;
  1835. var idx = 0;
  1836. if (originalBeginDts < list[0].originalBeginDts) {
  1837. idx = -1;
  1838. return idx;
  1839. }
  1840. while (lbound <= ubound) {
  1841. mid = lbound + Math.floor((ubound - lbound) / 2);
  1842. if (mid === last || originalBeginDts > list[mid].lastSample.originalDts && originalBeginDts < list[mid + 1].originalBeginDts) {
  1843. idx = mid;
  1844. break;
  1845. } else if (list[mid].originalBeginDts < originalBeginDts) {
  1846. lbound = mid + 1;
  1847. } else {
  1848. ubound = mid - 1;
  1849. }
  1850. }
  1851. return idx;
  1852. }
  1853. }, {
  1854. key: "_searchNearestSegmentAfter",
  1855. value: function _searchNearestSegmentAfter(originalBeginDts) {
  1856. return this._searchNearestSegmentBefore(originalBeginDts) + 1;
  1857. }
  1858. }, {
  1859. key: "append",
  1860. value: function append(mediaSegmentInfo) {
  1861. var list = this._list;
  1862. var msi = mediaSegmentInfo;
  1863. var lastAppendIdx = this._lastAppendLocation;
  1864. var insertIdx = 0;
  1865. if (lastAppendIdx !== -1 && lastAppendIdx < list.length && msi.originalBeginDts >= list[lastAppendIdx].lastSample.originalDts && (lastAppendIdx === list.length - 1 || lastAppendIdx < list.length - 1 && msi.originalBeginDts < list[lastAppendIdx + 1].originalBeginDts)) {
  1866. insertIdx = lastAppendIdx + 1; // use cached location idx
  1867. } else {
  1868. if (list.length > 0) {
  1869. insertIdx = this._searchNearestSegmentBefore(msi.originalBeginDts) + 1;
  1870. }
  1871. }
  1872. this._lastAppendLocation = insertIdx;
  1873. this._list.splice(insertIdx, 0, msi);
  1874. }
  1875. }, {
  1876. key: "getLastSegmentBefore",
  1877. value: function getLastSegmentBefore(originalBeginDts) {
  1878. var idx = this._searchNearestSegmentBefore(originalBeginDts);
  1879. if (idx >= 0) {
  1880. return this._list[idx];
  1881. } else {
  1882. // -1
  1883. return null;
  1884. }
  1885. }
  1886. }, {
  1887. key: "getLastSampleBefore",
  1888. value: function getLastSampleBefore(originalBeginDts) {
  1889. var segment = this.getLastSegmentBefore(originalBeginDts);
  1890. if (segment != null) {
  1891. return segment.lastSample;
  1892. } else {
  1893. return null;
  1894. }
  1895. }
  1896. }, {
  1897. key: "getLastSyncPointBefore",
  1898. value: function getLastSyncPointBefore(originalBeginDts) {
  1899. var segmentIdx = this._searchNearestSegmentBefore(originalBeginDts);
  1900. var syncPoints = this._list[segmentIdx].syncPoints;
  1901. while (syncPoints.length === 0 && segmentIdx > 0) {
  1902. segmentIdx--;
  1903. syncPoints = this._list[segmentIdx].syncPoints;
  1904. }
  1905. if (syncPoints.length > 0) {
  1906. return syncPoints[syncPoints.length - 1];
  1907. } else {
  1908. return null;
  1909. }
  1910. }
  1911. }, {
  1912. key: "type",
  1913. get: function get() {
  1914. return this._type;
  1915. }
  1916. }, {
  1917. key: "length",
  1918. get: function get() {
  1919. return this._list.length;
  1920. }
  1921. }]);
  1922. return MediaSegmentInfoList;
  1923. }();
  1924. },{}],9:[function(_dereq_,module,exports){
  1925. 'use strict';
  1926. Object.defineProperty(exports, "__esModule", {
  1927. value: true
  1928. });
  1929. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  1930. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  1931. *
  1932. * @author zheng qian <xqq@xqq.im>
  1933. *
  1934. * Licensed under the Apache License, Version 2.0 (the "License");
  1935. * you may not use this file except in compliance with the License.
  1936. * You may obtain a copy of the License at
  1937. *
  1938. * http://www.apache.org/licenses/LICENSE-2.0
  1939. *
  1940. * Unless required by applicable law or agreed to in writing, software
  1941. * distributed under the License is distributed on an "AS IS" BASIS,
  1942. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1943. * See the License for the specific language governing permissions and
  1944. * limitations under the License.
  1945. */
  1946. var _events = _dereq_('events');
  1947. var _events2 = _interopRequireDefault(_events);
  1948. var _logger = _dereq_('../utils/logger.js');
  1949. var _logger2 = _interopRequireDefault(_logger);
  1950. var _browser = _dereq_('../utils/browser.js');
  1951. var _browser2 = _interopRequireDefault(_browser);
  1952. var _mseEvents = _dereq_('./mse-events.js');
  1953. var _mseEvents2 = _interopRequireDefault(_mseEvents);
  1954. var _mediaSegmentInfo = _dereq_('./media-segment-info.js');
  1955. var _exception = _dereq_('../utils/exception.js');
  1956. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1957. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1958. // Media Source Extensions controller
  1959. var MSEController = function () {
  1960. function MSEController(config) {
  1961. _classCallCheck(this, MSEController);
  1962. this.TAG = 'MSEController';
  1963. this._config = config;
  1964. this._emitter = new _events2.default();
  1965. if (this._config.isLive && this._config.autoCleanupSourceBuffer == undefined) {
  1966. // For live stream, do auto cleanup by default
  1967. this._config.autoCleanupSourceBuffer = true;
  1968. }
  1969. this.e = {
  1970. onSourceOpen: this._onSourceOpen.bind(this),
  1971. onSourceEnded: this._onSourceEnded.bind(this),
  1972. onSourceClose: this._onSourceClose.bind(this),
  1973. onSourceBufferError: this._onSourceBufferError.bind(this),
  1974. onSourceBufferUpdateEnd: this._onSourceBufferUpdateEnd.bind(this)
  1975. };
  1976. this._mediaSource = null;
  1977. this._mediaSourceObjectURL = null;
  1978. this._mediaElement = null;
  1979. this._isBufferFull = false;
  1980. this._hasPendingEos = false;
  1981. this._requireSetMediaDuration = false;
  1982. this._pendingMediaDuration = 0;
  1983. this._pendingSourceBufferInit = [];
  1984. this._mimeTypes = {
  1985. video: null,
  1986. audio: null
  1987. };
  1988. this._sourceBuffers = {
  1989. video: null,
  1990. audio: null
  1991. };
  1992. this._lastInitSegments = {
  1993. video: null,
  1994. audio: null
  1995. };
  1996. this._pendingSegments = {
  1997. video: [],
  1998. audio: []
  1999. };
  2000. this._pendingRemoveRanges = {
  2001. video: [],
  2002. audio: []
  2003. };
  2004. this._idrList = new _mediaSegmentInfo.IDRSampleList();
  2005. }
  2006. _createClass(MSEController, [{
  2007. key: 'destroy',
  2008. value: function destroy() {
  2009. if (this._mediaElement || this._mediaSource) {
  2010. this.detachMediaElement();
  2011. }
  2012. this.e = null;
  2013. this._emitter.removeAllListeners();
  2014. this._emitter = null;
  2015. }
  2016. }, {
  2017. key: 'on',
  2018. value: function on(event, listener) {
  2019. this._emitter.addListener(event, listener);
  2020. }
  2021. }, {
  2022. key: 'off',
  2023. value: function off(event, listener) {
  2024. this._emitter.removeListener(event, listener);
  2025. }
  2026. }, {
  2027. key: 'attachMediaElement',
  2028. value: function attachMediaElement(mediaElement) {
  2029. if (this._mediaSource) {
  2030. throw new _exception.IllegalStateException('MediaSource has been attached to an HTMLMediaElement!');
  2031. }
  2032. var ms = this._mediaSource = new window.MediaSource();
  2033. ms.addEventListener('sourceopen', this.e.onSourceOpen);
  2034. ms.addEventListener('sourceended', this.e.onSourceEnded);
  2035. ms.addEventListener('sourceclose', this.e.onSourceClose);
  2036. this._mediaElement = mediaElement;
  2037. this._mediaSourceObjectURL = window.URL.createObjectURL(this._mediaSource);
  2038. mediaElement.src = this._mediaSourceObjectURL;
  2039. }
  2040. }, {
  2041. key: 'detachMediaElement',
  2042. value: function detachMediaElement() {
  2043. if (this._mediaSource) {
  2044. var ms = this._mediaSource;
  2045. for (var type in this._sourceBuffers) {
  2046. // pending segments should be discard
  2047. var ps = this._pendingSegments[type];
  2048. ps.splice(0, ps.length);
  2049. this._pendingSegments[type] = null;
  2050. this._pendingRemoveRanges[type] = null;
  2051. this._lastInitSegments[type] = null;
  2052. // remove all sourcebuffers
  2053. var sb = this._sourceBuffers[type];
  2054. if (sb) {
  2055. if (ms.readyState !== 'closed') {
  2056. ms.removeSourceBuffer(sb);
  2057. sb.removeEventListener('error', this.e.onSourceBufferError);
  2058. sb.removeEventListener('updateend', this.e.onSourceBufferUpdateEnd);
  2059. }
  2060. this._mimeTypes[type] = null;
  2061. this._sourceBuffers[type] = null;
  2062. }
  2063. }
  2064. if (ms.readyState === 'open') {
  2065. try {
  2066. ms.endOfStream();
  2067. } catch (error) {
  2068. _logger2.default.e(this.TAG, error.message);
  2069. }
  2070. }
  2071. ms.removeEventListener('sourceopen', this.e.onSourceOpen);
  2072. ms.removeEventListener('sourceended', this.e.onSourceEnded);
  2073. ms.removeEventListener('sourceclose', this.e.onSourceClose);
  2074. this._pendingSourceBufferInit = [];
  2075. this._isBufferFull = false;
  2076. this._idrList.clear();
  2077. this._mediaSource = null;
  2078. }
  2079. if (this._mediaElement) {
  2080. this._mediaElement.src = '';
  2081. this._mediaElement.removeAttribute('src');
  2082. this._mediaElement = null;
  2083. }
  2084. if (this._mediaSourceObjectURL) {
  2085. window.URL.revokeObjectURL(this._mediaSourceObjectURL);
  2086. this._mediaSourceObjectURL = null;
  2087. }
  2088. }
  2089. }, {
  2090. key: 'appendInitSegment',
  2091. value: function appendInitSegment(initSegment, deferred) {
  2092. if (!this._mediaSource || this._mediaSource.readyState !== 'open') {
  2093. // sourcebuffer creation requires mediaSource.readyState === 'open'
  2094. // so we defer the sourcebuffer creation, until sourceopen event triggered
  2095. this._pendingSourceBufferInit.push(initSegment);
  2096. // make sure that this InitSegment is in the front of pending segments queue
  2097. this._pendingSegments[initSegment.type].push(initSegment);
  2098. return;
  2099. }
  2100. var is = initSegment;
  2101. var mimeType = '' + is.container;
  2102. if (is.codec && is.codec.length > 0) {
  2103. mimeType += ';codecs=' + is.codec;
  2104. }
  2105. var firstInitSegment = false;
  2106. _logger2.default.v(this.TAG, 'Received Initialization Segment, mimeType: ' + mimeType);
  2107. this._lastInitSegments[is.type] = is;
  2108. if (mimeType !== this._mimeTypes[is.type]) {
  2109. if (!this._mimeTypes[is.type]) {
  2110. // empty, first chance create sourcebuffer
  2111. firstInitSegment = true;
  2112. try {
  2113. var sb = this._sourceBuffers[is.type] = this._mediaSource.addSourceBuffer(mimeType);
  2114. sb.addEventListener('error', this.e.onSourceBufferError);
  2115. sb.addEventListener('updateend', this.e.onSourceBufferUpdateEnd);
  2116. } catch (error) {
  2117. _logger2.default.e(this.TAG, error.message);
  2118. this._emitter.emit(_mseEvents2.default.ERROR, { code: error.code, msg: error.message });
  2119. return;
  2120. }
  2121. } else {
  2122. _logger2.default.v(this.TAG, 'Notice: ' + is.type + ' mimeType changed, origin: ' + this._mimeTypes[is.type] + ', target: ' + mimeType);
  2123. }
  2124. this._mimeTypes[is.type] = mimeType;
  2125. }
  2126. if (!deferred) {
  2127. // deferred means this InitSegment has been pushed to pendingSegments queue
  2128. this._pendingSegments[is.type].push(is);
  2129. }
  2130. if (!firstInitSegment) {
  2131. // append immediately only if init segment in subsequence
  2132. if (this._sourceBuffers[is.type] && !this._sourceBuffers[is.type].updating) {
  2133. this._doAppendSegments();
  2134. }
  2135. }
  2136. if (_browser2.default.safari && is.container === 'audio/mpeg' && is.mediaDuration > 0) {
  2137. // 'audio/mpeg' track under Safari may cause MediaElement's duration to be NaN
  2138. // Manually correct MediaSource.duration to make progress bar seekable, and report right duration
  2139. this._requireSetMediaDuration = true;
  2140. this._pendingMediaDuration = is.mediaDuration / 1000; // in seconds
  2141. this._updateMediaSourceDuration();
  2142. }
  2143. }
  2144. }, {
  2145. key: 'appendMediaSegment',
  2146. value: function appendMediaSegment(mediaSegment) {
  2147. var ms = mediaSegment;
  2148. this._pendingSegments[ms.type].push(ms);
  2149. if (this._config.autoCleanupSourceBuffer && this._needCleanupSourceBuffer()) {
  2150. this._doCleanupSourceBuffer();
  2151. }
  2152. var sb = this._sourceBuffers[ms.type];
  2153. if (sb && !sb.updating && !this._hasPendingRemoveRanges()) {
  2154. this._doAppendSegments();
  2155. }
  2156. }
  2157. }, {
  2158. key: 'seek',
  2159. value: function seek(seconds) {
  2160. // remove all appended buffers
  2161. for (var type in this._sourceBuffers) {
  2162. if (!this._sourceBuffers[type]) {
  2163. continue;
  2164. }
  2165. // abort current buffer append algorithm
  2166. var sb = this._sourceBuffers[type];
  2167. if (this._mediaSource.readyState === 'open') {
  2168. try {
  2169. // If range removal algorithm is running, InvalidStateError will be throwed
  2170. // Ignore it.
  2171. sb.abort();
  2172. } catch (error) {
  2173. _logger2.default.e(this.TAG, error.message);
  2174. }
  2175. }
  2176. // IDRList should be clear
  2177. this._idrList.clear();
  2178. // pending segments should be discard
  2179. var ps = this._pendingSegments[type];
  2180. ps.splice(0, ps.length);
  2181. if (this._mediaSource.readyState === 'closed') {
  2182. // Parent MediaSource object has been detached from HTMLMediaElement
  2183. continue;
  2184. }
  2185. // record ranges to be remove from SourceBuffer
  2186. for (var i = 0; i < sb.buffered.length; i++) {
  2187. var start = sb.buffered.start(i);
  2188. var end = sb.buffered.end(i);
  2189. this._pendingRemoveRanges[type].push({ start: start, end: end });
  2190. }
  2191. // if sb is not updating, let's remove ranges now!
  2192. if (!sb.updating) {
  2193. this._doRemoveRanges();
  2194. }
  2195. // Safari 10 may get InvalidStateError in the later appendBuffer() after SourceBuffer.remove() call
  2196. // Internal parser's state may be invalid at this time. Re-append last InitSegment to workaround.
  2197. // Related issue: https://bugs.webkit.org/show_bug.cgi?id=159230
  2198. if (_browser2.default.safari) {
  2199. var lastInitSegment = this._lastInitSegments[type];
  2200. if (lastInitSegment) {
  2201. this._pendingSegments[type].push(lastInitSegment);
  2202. if (!sb.updating) {
  2203. this._doAppendSegments();
  2204. }
  2205. }
  2206. }
  2207. }
  2208. }
  2209. }, {
  2210. key: 'endOfStream',
  2211. value: function endOfStream() {
  2212. var ms = this._mediaSource;
  2213. var sb = this._sourceBuffers;
  2214. if (!ms || ms.readyState !== 'open') {
  2215. if (ms && ms.readyState === 'closed' && this._hasPendingSegments()) {
  2216. // If MediaSource hasn't turned into open state, and there're pending segments
  2217. // Mark pending endOfStream, defer call until all pending segments appended complete
  2218. this._hasPendingEos = true;
  2219. }
  2220. return;
  2221. }
  2222. if (sb.video && sb.video.updating || sb.audio && sb.audio.updating) {
  2223. // If any sourcebuffer is updating, defer endOfStream operation
  2224. // See _onSourceBufferUpdateEnd()
  2225. this._hasPendingEos = true;
  2226. } else {
  2227. this._hasPendingEos = false;
  2228. // Notify media data loading complete
  2229. // This is helpful for correcting total duration to match last media segment
  2230. // Otherwise MediaElement's ended event may not be triggered
  2231. ms.endOfStream();
  2232. }
  2233. }
  2234. }, {
  2235. key: 'getNearestKeyframe',
  2236. value: function getNearestKeyframe(dts) {
  2237. return this._idrList.getLastSyncPointBeforeDts(dts);
  2238. }
  2239. }, {
  2240. key: '_needCleanupSourceBuffer',
  2241. value: function _needCleanupSourceBuffer() {
  2242. if (!this._config.autoCleanupSourceBuffer) {
  2243. return false;
  2244. }
  2245. var currentTime = this._mediaElement.currentTime;
  2246. for (var type in this._sourceBuffers) {
  2247. var sb = this._sourceBuffers[type];
  2248. if (sb) {
  2249. var buffered = sb.buffered;
  2250. if (buffered.length >= 1) {
  2251. if (currentTime - buffered.start(0) >= this._config.autoCleanupMaxBackwardDuration) {
  2252. return true;
  2253. }
  2254. }
  2255. }
  2256. }
  2257. return false;
  2258. }
  2259. }, {
  2260. key: '_doCleanupSourceBuffer',
  2261. value: function _doCleanupSourceBuffer() {
  2262. var currentTime = this._mediaElement.currentTime;
  2263. for (var type in this._sourceBuffers) {
  2264. var sb = this._sourceBuffers[type];
  2265. if (sb) {
  2266. var buffered = sb.buffered;
  2267. var doRemove = false;
  2268. for (var i = 0; i < buffered.length; i++) {
  2269. var start = buffered.start(i);
  2270. var end = buffered.end(i);
  2271. if (start <= currentTime && currentTime < end + 3) {
  2272. // padding 3 seconds
  2273. if (currentTime - start >= this._config.autoCleanupMaxBackwardDuration) {
  2274. doRemove = true;
  2275. var removeEnd = currentTime - this._config.autoCleanupMinBackwardDuration;
  2276. this._pendingRemoveRanges[type].push({ start: start, end: removeEnd });
  2277. }
  2278. } else if (end < currentTime) {
  2279. doRemove = true;
  2280. this._pendingRemoveRanges[type].push({ start: start, end: end });
  2281. }
  2282. }
  2283. if (doRemove && !sb.updating) {
  2284. this._doRemoveRanges();
  2285. }
  2286. }
  2287. }
  2288. }
  2289. }, {
  2290. key: '_updateMediaSourceDuration',
  2291. value: function _updateMediaSourceDuration() {
  2292. var sb = this._sourceBuffers;
  2293. if (this._mediaElement.readyState === 0 || this._mediaSource.readyState !== 'open') {
  2294. return;
  2295. }
  2296. if (sb.video && sb.video.updating || sb.audio && sb.audio.updating) {
  2297. return;
  2298. }
  2299. var current = this._mediaSource.duration;
  2300. var target = this._pendingMediaDuration;
  2301. if (target > 0 && (isNaN(current) || target > current)) {
  2302. _logger2.default.v(this.TAG, 'Update MediaSource duration from ' + current + ' to ' + target);
  2303. this._mediaSource.duration = target;
  2304. }
  2305. this._requireSetMediaDuration = false;
  2306. this._pendingMediaDuration = 0;
  2307. }
  2308. }, {
  2309. key: '_doRemoveRanges',
  2310. value: function _doRemoveRanges() {
  2311. for (var type in this._pendingRemoveRanges) {
  2312. if (!this._sourceBuffers[type] || this._sourceBuffers[type].updating) {
  2313. continue;
  2314. }
  2315. var sb = this._sourceBuffers[type];
  2316. var ranges = this._pendingRemoveRanges[type];
  2317. while (ranges.length && !sb.updating) {
  2318. var range = ranges.shift();
  2319. sb.remove(range.start, range.end);
  2320. }
  2321. }
  2322. }
  2323. }, {
  2324. key: '_doAppendSegments',
  2325. value: function _doAppendSegments() {
  2326. var pendingSegments = this._pendingSegments;
  2327. for (var type in pendingSegments) {
  2328. if (!this._sourceBuffers[type] || this._sourceBuffers[type].updating) {
  2329. continue;
  2330. }
  2331. if (pendingSegments[type].length > 0) {
  2332. var segment = pendingSegments[type].shift();
  2333. if (segment.timestampOffset) {
  2334. // For MPEG audio stream in MSE, if unbuffered-seeking occurred
  2335. // We need explicitly set timestampOffset to the desired point in timeline for mpeg SourceBuffer.
  2336. var currentOffset = this._sourceBuffers[type].timestampOffset;
  2337. var targetOffset = segment.timestampOffset / 1000; // in seconds
  2338. var delta = Math.abs(currentOffset - targetOffset);
  2339. if (delta > 0.1) {
  2340. // If time delta > 100ms
  2341. _logger2.default.v(this.TAG, 'Update MPEG audio timestampOffset from ' + currentOffset + ' to ' + targetOffset);
  2342. this._sourceBuffers[type].timestampOffset = targetOffset;
  2343. }
  2344. delete segment.timestampOffset;
  2345. }
  2346. if (!segment.data || segment.data.byteLength === 0) {
  2347. // Ignore empty buffer
  2348. continue;
  2349. }
  2350. try {
  2351. this._sourceBuffers[type].appendBuffer(segment.data);
  2352. this._isBufferFull = false;
  2353. if (type === 'video' && segment.hasOwnProperty('info')) {
  2354. this._idrList.appendArray(segment.info.syncPoints);
  2355. }
  2356. } catch (error) {
  2357. this._pendingSegments[type].unshift(segment);
  2358. if (error.code === 22) {
  2359. // QuotaExceededError
  2360. /* Notice that FireFox may not throw QuotaExceededError if SourceBuffer is full
  2361. * Currently we can only do lazy-load to avoid SourceBuffer become scattered.
  2362. * SourceBuffer eviction policy may be changed in future version of FireFox.
  2363. *
  2364. * Related issues:
  2365. * https://bugzilla.mozilla.org/show_bug.cgi?id=1279885
  2366. * https://bugzilla.mozilla.org/show_bug.cgi?id=1280023
  2367. */
  2368. // report buffer full, abort network IO
  2369. if (!this._isBufferFull) {
  2370. this._emitter.emit(_mseEvents2.default.BUFFER_FULL);
  2371. }
  2372. this._isBufferFull = true;
  2373. } else {
  2374. _logger2.default.e(this.TAG, error.message);
  2375. this._emitter.emit(_mseEvents2.default.ERROR, { code: error.code, msg: error.message });
  2376. }
  2377. }
  2378. }
  2379. }
  2380. }
  2381. }, {
  2382. key: '_onSourceOpen',
  2383. value: function _onSourceOpen() {
  2384. _logger2.default.v(this.TAG, 'MediaSource onSourceOpen');
  2385. this._mediaSource.removeEventListener('sourceopen', this.e.onSourceOpen);
  2386. // deferred sourcebuffer creation / initialization
  2387. if (this._pendingSourceBufferInit.length > 0) {
  2388. var pendings = this._pendingSourceBufferInit;
  2389. while (pendings.length) {
  2390. var segment = pendings.shift();
  2391. this.appendInitSegment(segment, true);
  2392. }
  2393. }
  2394. // there may be some pending media segments, append them
  2395. if (this._hasPendingSegments()) {
  2396. this._doAppendSegments();
  2397. }
  2398. this._emitter.emit(_mseEvents2.default.SOURCE_OPEN);
  2399. }
  2400. }, {
  2401. key: '_onSourceEnded',
  2402. value: function _onSourceEnded() {
  2403. // fired on endOfStream
  2404. _logger2.default.v(this.TAG, 'MediaSource onSourceEnded');
  2405. }
  2406. }, {
  2407. key: '_onSourceClose',
  2408. value: function _onSourceClose() {
  2409. // fired on detaching from media element
  2410. _logger2.default.v(this.TAG, 'MediaSource onSourceClose');
  2411. if (this._mediaSource && this.e != null) {
  2412. this._mediaSource.removeEventListener('sourceopen', this.e.onSourceOpen);
  2413. this._mediaSource.removeEventListener('sourceended', this.e.onSourceEnded);
  2414. this._mediaSource.removeEventListener('sourceclose', this.e.onSourceClose);
  2415. }
  2416. }
  2417. }, {
  2418. key: '_hasPendingSegments',
  2419. value: function _hasPendingSegments() {
  2420. var ps = this._pendingSegments;
  2421. return ps.video.length > 0 || ps.audio.length > 0;
  2422. }
  2423. }, {
  2424. key: '_hasPendingRemoveRanges',
  2425. value: function _hasPendingRemoveRanges() {
  2426. var prr = this._pendingRemoveRanges;
  2427. return prr.video.length > 0 || prr.audio.length > 0;
  2428. }
  2429. }, {
  2430. key: '_onSourceBufferUpdateEnd',
  2431. value: function _onSourceBufferUpdateEnd() {
  2432. if (this._requireSetMediaDuration) {
  2433. this._updateMediaSourceDuration();
  2434. } else if (this._hasPendingRemoveRanges()) {
  2435. this._doRemoveRanges();
  2436. } else if (this._hasPendingSegments()) {
  2437. this._doAppendSegments();
  2438. } else if (this._hasPendingEos) {
  2439. this.endOfStream();
  2440. }
  2441. this._emitter.emit(_mseEvents2.default.UPDATE_END);
  2442. }
  2443. }, {
  2444. key: '_onSourceBufferError',
  2445. value: function _onSourceBufferError(e) {
  2446. _logger2.default.e(this.TAG, 'SourceBuffer Error: ' + e);
  2447. // this error might not always be fatal, just ignore it
  2448. }
  2449. }]);
  2450. return MSEController;
  2451. }();
  2452. exports.default = MSEController;
  2453. },{"../utils/browser.js":39,"../utils/exception.js":40,"../utils/logger.js":41,"./media-segment-info.js":8,"./mse-events.js":10,"events":2}],10:[function(_dereq_,module,exports){
  2454. 'use strict';
  2455. Object.defineProperty(exports, "__esModule", {
  2456. value: true
  2457. });
  2458. /*
  2459. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  2460. *
  2461. * @author zheng qian <xqq@xqq.im>
  2462. *
  2463. * Licensed under the Apache License, Version 2.0 (the "License");
  2464. * you may not use this file except in compliance with the License.
  2465. * You may obtain a copy of the License at
  2466. *
  2467. * http://www.apache.org/licenses/LICENSE-2.0
  2468. *
  2469. * Unless required by applicable law or agreed to in writing, software
  2470. * distributed under the License is distributed on an "AS IS" BASIS,
  2471. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2472. * See the License for the specific language governing permissions and
  2473. * limitations under the License.
  2474. */
  2475. var MSEEvents = {
  2476. ERROR: 'error',
  2477. SOURCE_OPEN: 'source_open',
  2478. UPDATE_END: 'update_end',
  2479. BUFFER_FULL: 'buffer_full'
  2480. };
  2481. exports.default = MSEEvents;
  2482. },{}],11:[function(_dereq_,module,exports){
  2483. 'use strict';
  2484. Object.defineProperty(exports, "__esModule", {
  2485. value: true
  2486. });
  2487. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  2488. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  2489. *
  2490. * @author zheng qian <xqq@xqq.im>
  2491. *
  2492. * Licensed under the Apache License, Version 2.0 (the "License");
  2493. * you may not use this file except in compliance with the License.
  2494. * You may obtain a copy of the License at
  2495. *
  2496. * http://www.apache.org/licenses/LICENSE-2.0
  2497. *
  2498. * Unless required by applicable law or agreed to in writing, software
  2499. * distributed under the License is distributed on an "AS IS" BASIS,
  2500. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2501. * See the License for the specific language governing permissions and
  2502. * limitations under the License.
  2503. */
  2504. var _events = _dereq_('events');
  2505. var _events2 = _interopRequireDefault(_events);
  2506. var _logger = _dereq_('../utils/logger.js');
  2507. var _logger2 = _interopRequireDefault(_logger);
  2508. var _loggingControl = _dereq_('../utils/logging-control.js');
  2509. var _loggingControl2 = _interopRequireDefault(_loggingControl);
  2510. var _transmuxingController = _dereq_('./transmuxing-controller.js');
  2511. var _transmuxingController2 = _interopRequireDefault(_transmuxingController);
  2512. var _transmuxingEvents = _dereq_('./transmuxing-events.js');
  2513. var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
  2514. var _transmuxingWorker = _dereq_('./transmuxing-worker.js');
  2515. var _transmuxingWorker2 = _interopRequireDefault(_transmuxingWorker);
  2516. var _mediaInfo = _dereq_('./media-info.js');
  2517. var _mediaInfo2 = _interopRequireDefault(_mediaInfo);
  2518. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2519. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2520. var Transmuxer = function () {
  2521. function Transmuxer(mediaDataSource, config) {
  2522. _classCallCheck(this, Transmuxer);
  2523. this.TAG = 'Transmuxer';
  2524. this._emitter = new _events2.default();
  2525. if (config.enableWorker && typeof Worker !== 'undefined') {
  2526. try {
  2527. var work = _dereq_('webworkify');
  2528. this._worker = work(_transmuxingWorker2.default);
  2529. this._workerDestroying = false;
  2530. this._worker.addEventListener('message', this._onWorkerMessage.bind(this));
  2531. this._worker.postMessage({ cmd: 'init', param: [mediaDataSource, config] });
  2532. this.e = {
  2533. onLoggingConfigChanged: this._onLoggingConfigChanged.bind(this)
  2534. };
  2535. _loggingControl2.default.registerListener(this.e.onLoggingConfigChanged);
  2536. this._worker.postMessage({ cmd: 'logging_config', param: _loggingControl2.default.getConfig() });
  2537. } catch (error) {
  2538. _logger2.default.e(this.TAG, 'Error while initialize transmuxing worker, fallback to inline transmuxing');
  2539. this._worker = null;
  2540. this._controller = new _transmuxingController2.default(mediaDataSource, config);
  2541. }
  2542. } else {
  2543. this._controller = new _transmuxingController2.default(mediaDataSource, config);
  2544. }
  2545. if (this._controller) {
  2546. var ctl = this._controller;
  2547. ctl.on(_transmuxingEvents2.default.IO_ERROR, this._onIOError.bind(this));
  2548. ctl.on(_transmuxingEvents2.default.DEMUX_ERROR, this._onDemuxError.bind(this));
  2549. ctl.on(_transmuxingEvents2.default.INIT_SEGMENT, this._onInitSegment.bind(this));
  2550. ctl.on(_transmuxingEvents2.default.MEDIA_SEGMENT, this._onMediaSegment.bind(this));
  2551. ctl.on(_transmuxingEvents2.default.LOADING_COMPLETE, this._onLoadingComplete.bind(this));
  2552. ctl.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF, this._onRecoveredEarlyEof.bind(this));
  2553. ctl.on(_transmuxingEvents2.default.MEDIA_INFO, this._onMediaInfo.bind(this));
  2554. ctl.on(_transmuxingEvents2.default.STATISTICS_INFO, this._onStatisticsInfo.bind(this));
  2555. ctl.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, this._onRecommendSeekpoint.bind(this));
  2556. }
  2557. }
  2558. _createClass(Transmuxer, [{
  2559. key: 'destroy',
  2560. value: function destroy() {
  2561. if (this._worker) {
  2562. if (!this._workerDestroying) {
  2563. this._workerDestroying = true;
  2564. this._worker.postMessage({ cmd: 'destroy' });
  2565. _loggingControl2.default.removeListener(this.e.onLoggingConfigChanged);
  2566. this.e = null;
  2567. }
  2568. } else {
  2569. this._controller.destroy();
  2570. this._controller = null;
  2571. }
  2572. this._emitter.removeAllListeners();
  2573. this._emitter = null;
  2574. }
  2575. }, {
  2576. key: 'on',
  2577. value: function on(event, listener) {
  2578. this._emitter.addListener(event, listener);
  2579. }
  2580. }, {
  2581. key: 'off',
  2582. value: function off(event, listener) {
  2583. this._emitter.removeListener(event, listener);
  2584. }
  2585. }, {
  2586. key: 'hasWorker',
  2587. value: function hasWorker() {
  2588. return this._worker != null;
  2589. }
  2590. }, {
  2591. key: 'open',
  2592. value: function open() {
  2593. if (this._worker) {
  2594. this._worker.postMessage({ cmd: 'start' });
  2595. } else {
  2596. this._controller.start();
  2597. }
  2598. }
  2599. }, {
  2600. key: 'close',
  2601. value: function close() {
  2602. if (this._worker) {
  2603. this._worker.postMessage({ cmd: 'stop' });
  2604. } else {
  2605. this._controller.stop();
  2606. }
  2607. }
  2608. }, {
  2609. key: 'seek',
  2610. value: function seek(milliseconds) {
  2611. if (this._worker) {
  2612. this._worker.postMessage({ cmd: 'seek', param: milliseconds });
  2613. } else {
  2614. this._controller.seek(milliseconds);
  2615. }
  2616. }
  2617. }, {
  2618. key: 'pause',
  2619. value: function pause() {
  2620. if (this._worker) {
  2621. this._worker.postMessage({ cmd: 'pause' });
  2622. } else {
  2623. this._controller.pause();
  2624. }
  2625. }
  2626. }, {
  2627. key: 'resume',
  2628. value: function resume() {
  2629. if (this._worker) {
  2630. this._worker.postMessage({ cmd: 'resume' });
  2631. } else {
  2632. this._controller.resume();
  2633. }
  2634. }
  2635. }, {
  2636. key: '_onInitSegment',
  2637. value: function _onInitSegment(type, initSegment) {
  2638. var _this = this;
  2639. // do async invoke
  2640. Promise.resolve().then(function () {
  2641. _this._emitter.emit(_transmuxingEvents2.default.INIT_SEGMENT, type, initSegment);
  2642. });
  2643. }
  2644. }, {
  2645. key: '_onMediaSegment',
  2646. value: function _onMediaSegment(type, mediaSegment) {
  2647. var _this2 = this;
  2648. Promise.resolve().then(function () {
  2649. _this2._emitter.emit(_transmuxingEvents2.default.MEDIA_SEGMENT, type, mediaSegment);
  2650. });
  2651. }
  2652. }, {
  2653. key: '_onLoadingComplete',
  2654. value: function _onLoadingComplete() {
  2655. var _this3 = this;
  2656. Promise.resolve().then(function () {
  2657. _this3._emitter.emit(_transmuxingEvents2.default.LOADING_COMPLETE);
  2658. });
  2659. }
  2660. }, {
  2661. key: '_onRecoveredEarlyEof',
  2662. value: function _onRecoveredEarlyEof() {
  2663. var _this4 = this;
  2664. Promise.resolve().then(function () {
  2665. _this4._emitter.emit(_transmuxingEvents2.default.RECOVERED_EARLY_EOF);
  2666. });
  2667. }
  2668. }, {
  2669. key: '_onMediaInfo',
  2670. value: function _onMediaInfo(mediaInfo) {
  2671. var _this5 = this;
  2672. Promise.resolve().then(function () {
  2673. _this5._emitter.emit(_transmuxingEvents2.default.MEDIA_INFO, mediaInfo);
  2674. });
  2675. }
  2676. }, {
  2677. key: '_onStatisticsInfo',
  2678. value: function _onStatisticsInfo(statisticsInfo) {
  2679. var _this6 = this;
  2680. Promise.resolve().then(function () {
  2681. _this6._emitter.emit(_transmuxingEvents2.default.STATISTICS_INFO, statisticsInfo);
  2682. });
  2683. }
  2684. }, {
  2685. key: '_onIOError',
  2686. value: function _onIOError(type, info) {
  2687. var _this7 = this;
  2688. Promise.resolve().then(function () {
  2689. _this7._emitter.emit(_transmuxingEvents2.default.IO_ERROR, type, info);
  2690. });
  2691. }
  2692. }, {
  2693. key: '_onDemuxError',
  2694. value: function _onDemuxError(type, info) {
  2695. var _this8 = this;
  2696. Promise.resolve().then(function () {
  2697. _this8._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR, type, info);
  2698. });
  2699. }
  2700. }, {
  2701. key: '_onRecommendSeekpoint',
  2702. value: function _onRecommendSeekpoint(milliseconds) {
  2703. var _this9 = this;
  2704. Promise.resolve().then(function () {
  2705. _this9._emitter.emit(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, milliseconds);
  2706. });
  2707. }
  2708. }, {
  2709. key: '_onLoggingConfigChanged',
  2710. value: function _onLoggingConfigChanged(config) {
  2711. if (this._worker) {
  2712. this._worker.postMessage({ cmd: 'logging_config', param: config });
  2713. }
  2714. }
  2715. }, {
  2716. key: '_onWorkerMessage',
  2717. value: function _onWorkerMessage(e) {
  2718. var message = e.data;
  2719. var data = message.data;
  2720. if (message.msg === 'destroyed' || this._workerDestroying) {
  2721. this._workerDestroying = false;
  2722. this._worker.terminate();
  2723. this._worker = null;
  2724. return;
  2725. }
  2726. switch (message.msg) {
  2727. case _transmuxingEvents2.default.INIT_SEGMENT:
  2728. case _transmuxingEvents2.default.MEDIA_SEGMENT:
  2729. this._emitter.emit(message.msg, data.type, data.data);
  2730. break;
  2731. case _transmuxingEvents2.default.LOADING_COMPLETE:
  2732. case _transmuxingEvents2.default.RECOVERED_EARLY_EOF:
  2733. this._emitter.emit(message.msg);
  2734. break;
  2735. case _transmuxingEvents2.default.MEDIA_INFO:
  2736. Object.setPrototypeOf(data, _mediaInfo2.default.prototype);
  2737. this._emitter.emit(message.msg, data);
  2738. break;
  2739. case _transmuxingEvents2.default.STATISTICS_INFO:
  2740. this._emitter.emit(message.msg, data);
  2741. break;
  2742. case _transmuxingEvents2.default.IO_ERROR:
  2743. case _transmuxingEvents2.default.DEMUX_ERROR:
  2744. this._emitter.emit(message.msg, data.type, data.info);
  2745. break;
  2746. case _transmuxingEvents2.default.RECOMMEND_SEEKPOINT:
  2747. this._emitter.emit(message.msg, data);
  2748. break;
  2749. case 'logcat_callback':
  2750. _logger2.default.emitter.emit('log', data.type, data.logcat);
  2751. break;
  2752. default:
  2753. break;
  2754. }
  2755. }
  2756. }]);
  2757. return Transmuxer;
  2758. }();
  2759. exports.default = Transmuxer;
  2760. },{"../utils/logger.js":41,"../utils/logging-control.js":42,"./media-info.js":7,"./transmuxing-controller.js":12,"./transmuxing-events.js":13,"./transmuxing-worker.js":14,"events":2,"webworkify":4}],12:[function(_dereq_,module,exports){
  2761. 'use strict';
  2762. Object.defineProperty(exports, "__esModule", {
  2763. value: true
  2764. });
  2765. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  2766. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  2767. *
  2768. * @author zheng qian <xqq@xqq.im>
  2769. *
  2770. * Licensed under the Apache License, Version 2.0 (the "License");
  2771. * you may not use this file except in compliance with the License.
  2772. * You may obtain a copy of the License at
  2773. *
  2774. * http://www.apache.org/licenses/LICENSE-2.0
  2775. *
  2776. * Unless required by applicable law or agreed to in writing, software
  2777. * distributed under the License is distributed on an "AS IS" BASIS,
  2778. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2779. * See the License for the specific language governing permissions and
  2780. * limitations under the License.
  2781. */
  2782. var _events = _dereq_('events');
  2783. var _events2 = _interopRequireDefault(_events);
  2784. var _logger = _dereq_('../utils/logger.js');
  2785. var _logger2 = _interopRequireDefault(_logger);
  2786. var _browser = _dereq_('../utils/browser.js');
  2787. var _browser2 = _interopRequireDefault(_browser);
  2788. var _mediaInfo = _dereq_('./media-info.js');
  2789. var _mediaInfo2 = _interopRequireDefault(_mediaInfo);
  2790. var _flvDemuxer = _dereq_('../demux/flv-demuxer.js');
  2791. var _flvDemuxer2 = _interopRequireDefault(_flvDemuxer);
  2792. var _mp4Remuxer = _dereq_('../remux/mp4-remuxer.js');
  2793. var _mp4Remuxer2 = _interopRequireDefault(_mp4Remuxer);
  2794. var _demuxErrors = _dereq_('../demux/demux-errors.js');
  2795. var _demuxErrors2 = _interopRequireDefault(_demuxErrors);
  2796. var _ioController = _dereq_('../io/io-controller.js');
  2797. var _ioController2 = _interopRequireDefault(_ioController);
  2798. var _transmuxingEvents = _dereq_('./transmuxing-events.js');
  2799. var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
  2800. var _loader = _dereq_('../io/loader.js');
  2801. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2802. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2803. // Transmuxing (IO, Demuxing, Remuxing) controller, with multipart support
  2804. var TransmuxingController = function () {
  2805. function TransmuxingController(mediaDataSource, config) {
  2806. _classCallCheck(this, TransmuxingController);
  2807. this.TAG = 'TransmuxingController';
  2808. this._emitter = new _events2.default();
  2809. this._config = config;
  2810. // treat single part media as multipart media, which has only one segment
  2811. if (!mediaDataSource.segments) {
  2812. mediaDataSource.segments = [{
  2813. duration: mediaDataSource.duration,
  2814. filesize: mediaDataSource.filesize,
  2815. url: mediaDataSource.url
  2816. }];
  2817. }
  2818. // fill in default IO params if not exists
  2819. if (typeof mediaDataSource.cors !== 'boolean') {
  2820. mediaDataSource.cors = true;
  2821. }
  2822. if (typeof mediaDataSource.withCredentials !== 'boolean') {
  2823. mediaDataSource.withCredentials = false;
  2824. }
  2825. this._mediaDataSource = mediaDataSource;
  2826. this._currentSegmentIndex = 0;
  2827. var totalDuration = 0;
  2828. this._mediaDataSource.segments.forEach(function (segment) {
  2829. // timestampBase for each segment, and calculate total duration
  2830. segment.timestampBase = totalDuration;
  2831. totalDuration += segment.duration;
  2832. // params needed by IOController
  2833. segment.cors = mediaDataSource.cors;
  2834. segment.withCredentials = mediaDataSource.withCredentials;
  2835. // referrer policy control, if exist
  2836. if (config.referrerPolicy) {
  2837. segment.referrerPolicy = config.referrerPolicy;
  2838. }
  2839. });
  2840. if (!isNaN(totalDuration) && this._mediaDataSource.duration !== totalDuration) {
  2841. this._mediaDataSource.duration = totalDuration;
  2842. }
  2843. this._mediaInfo = null;
  2844. this._demuxer = null;
  2845. this._remuxer = null;
  2846. this._ioctl = null;
  2847. this._pendingSeekTime = null;
  2848. this._pendingResolveSeekPoint = null;
  2849. this._statisticsReporter = null;
  2850. }
  2851. _createClass(TransmuxingController, [{
  2852. key: 'destroy',
  2853. value: function destroy() {
  2854. this._mediaInfo = null;
  2855. this._mediaDataSource = null;
  2856. if (this._statisticsReporter) {
  2857. this._disableStatisticsReporter();
  2858. }
  2859. if (this._ioctl) {
  2860. this._ioctl.destroy();
  2861. this._ioctl = null;
  2862. }
  2863. if (this._demuxer) {
  2864. this._demuxer.destroy();
  2865. this._demuxer = null;
  2866. }
  2867. if (this._remuxer) {
  2868. this._remuxer.destroy();
  2869. this._remuxer = null;
  2870. }
  2871. this._emitter.removeAllListeners();
  2872. this._emitter = null;
  2873. }
  2874. }, {
  2875. key: 'on',
  2876. value: function on(event, listener) {
  2877. this._emitter.addListener(event, listener);
  2878. }
  2879. }, {
  2880. key: 'off',
  2881. value: function off(event, listener) {
  2882. this._emitter.removeListener(event, listener);
  2883. }
  2884. }, {
  2885. key: 'start',
  2886. value: function start() {
  2887. this._loadSegment(0);
  2888. this._enableStatisticsReporter();
  2889. }
  2890. }, {
  2891. key: '_loadSegment',
  2892. value: function _loadSegment(segmentIndex, optionalFrom) {
  2893. this._currentSegmentIndex = segmentIndex;
  2894. var dataSource = this._mediaDataSource.segments[segmentIndex];
  2895. var ioctl = this._ioctl = new _ioController2.default(dataSource, this._config, segmentIndex);
  2896. ioctl.onError = this._onIOException.bind(this);
  2897. ioctl.onSeeked = this._onIOSeeked.bind(this);
  2898. ioctl.onComplete = this._onIOComplete.bind(this);
  2899. ioctl.onRedirect = this._onIORedirect.bind(this);
  2900. ioctl.onRecoveredEarlyEof = this._onIORecoveredEarlyEof.bind(this);
  2901. if (optionalFrom) {
  2902. this._demuxer.bindDataSource(this._ioctl);
  2903. } else {
  2904. ioctl.onDataArrival = this._onInitChunkArrival.bind(this);
  2905. }
  2906. ioctl.open(optionalFrom);
  2907. }
  2908. }, {
  2909. key: 'stop',
  2910. value: function stop() {
  2911. this._internalAbort();
  2912. this._disableStatisticsReporter();
  2913. }
  2914. }, {
  2915. key: '_internalAbort',
  2916. value: function _internalAbort() {
  2917. if (this._ioctl) {
  2918. this._ioctl.destroy();
  2919. this._ioctl = null;
  2920. }
  2921. }
  2922. }, {
  2923. key: 'pause',
  2924. value: function pause() {
  2925. // take a rest
  2926. if (this._ioctl && this._ioctl.isWorking()) {
  2927. this._ioctl.pause();
  2928. this._disableStatisticsReporter();
  2929. }
  2930. }
  2931. }, {
  2932. key: 'resume',
  2933. value: function resume() {
  2934. if (this._ioctl && this._ioctl.isPaused()) {
  2935. this._ioctl.resume();
  2936. this._enableStatisticsReporter();
  2937. }
  2938. }
  2939. }, {
  2940. key: 'seek',
  2941. value: function seek(milliseconds) {
  2942. if (this._mediaInfo == null || !this._mediaInfo.isSeekable()) {
  2943. return;
  2944. }
  2945. var targetSegmentIndex = this._searchSegmentIndexContains(milliseconds);
  2946. if (targetSegmentIndex === this._currentSegmentIndex) {
  2947. // intra-segment seeking
  2948. var segmentInfo = this._mediaInfo.segments[targetSegmentIndex];
  2949. if (segmentInfo == undefined) {
  2950. // current segment loading started, but mediainfo hasn't received yet
  2951. // wait for the metadata loaded, then seek to expected position
  2952. this._pendingSeekTime = milliseconds;
  2953. } else {
  2954. var keyframe = segmentInfo.getNearestKeyframe(milliseconds);
  2955. this._remuxer.seek(keyframe.milliseconds);
  2956. this._ioctl.seek(keyframe.fileposition);
  2957. // Will be resolved in _onRemuxerMediaSegmentArrival()
  2958. this._pendingResolveSeekPoint = keyframe.milliseconds;
  2959. }
  2960. } else {
  2961. // cross-segment seeking
  2962. var targetSegmentInfo = this._mediaInfo.segments[targetSegmentIndex];
  2963. if (targetSegmentInfo == undefined) {
  2964. // target segment hasn't been loaded. We need metadata then seek to expected time
  2965. this._pendingSeekTime = milliseconds;
  2966. this._internalAbort();
  2967. this._remuxer.seek();
  2968. this._remuxer.insertDiscontinuity();
  2969. this._loadSegment(targetSegmentIndex);
  2970. // Here we wait for the metadata loaded, then seek to expected position
  2971. } else {
  2972. // We have target segment's metadata, direct seek to target position
  2973. var _keyframe = targetSegmentInfo.getNearestKeyframe(milliseconds);
  2974. this._internalAbort();
  2975. this._remuxer.seek(milliseconds);
  2976. this._remuxer.insertDiscontinuity();
  2977. this._demuxer.resetMediaInfo();
  2978. this._demuxer.timestampBase = this._mediaDataSource.segments[targetSegmentIndex].timestampBase;
  2979. this._loadSegment(targetSegmentIndex, _keyframe.fileposition);
  2980. this._pendingResolveSeekPoint = _keyframe.milliseconds;
  2981. this._reportSegmentMediaInfo(targetSegmentIndex);
  2982. }
  2983. }
  2984. this._enableStatisticsReporter();
  2985. }
  2986. }, {
  2987. key: '_searchSegmentIndexContains',
  2988. value: function _searchSegmentIndexContains(milliseconds) {
  2989. var segments = this._mediaDataSource.segments;
  2990. var idx = segments.length - 1;
  2991. for (var i = 0; i < segments.length; i++) {
  2992. if (milliseconds < segments[i].timestampBase) {
  2993. idx = i - 1;
  2994. break;
  2995. }
  2996. }
  2997. return idx;
  2998. }
  2999. }, {
  3000. key: '_onInitChunkArrival',
  3001. value: function _onInitChunkArrival(data, byteStart) {
  3002. var _this = this;
  3003. var probeData = null;
  3004. var consumed = 0;
  3005. if (byteStart > 0) {
  3006. // IOController seeked immediately after opened, byteStart > 0 callback may received
  3007. this._demuxer.bindDataSource(this._ioctl);
  3008. this._demuxer.timestampBase = this._mediaDataSource.segments[this._currentSegmentIndex].timestampBase;
  3009. consumed = this._demuxer.parseChunks(data, byteStart);
  3010. } else if ((probeData = _flvDemuxer2.default.probe(data)).match) {
  3011. // Always create new FLVDemuxer
  3012. this._demuxer = new _flvDemuxer2.default(probeData, this._config);
  3013. if (!this._remuxer) {
  3014. this._remuxer = new _mp4Remuxer2.default(this._config);
  3015. }
  3016. var mds = this._mediaDataSource;
  3017. if (mds.duration != undefined && !isNaN(mds.duration)) {
  3018. this._demuxer.overridedDuration = mds.duration;
  3019. }
  3020. if (typeof mds.hasAudio === 'boolean') {
  3021. this._demuxer.overridedHasAudio = mds.hasAudio;
  3022. }
  3023. if (typeof mds.hasVideo === 'boolean') {
  3024. this._demuxer.overridedHasVideo = mds.hasVideo;
  3025. }
  3026. this._demuxer.timestampBase = mds.segments[this._currentSegmentIndex].timestampBase;
  3027. this._demuxer.onError = this._onDemuxException.bind(this);
  3028. this._demuxer.onMediaInfo = this._onMediaInfo.bind(this);
  3029. this._remuxer.bindDataSource(this._demuxer.bindDataSource(this._ioctl));
  3030. this._remuxer.onInitSegment = this._onRemuxerInitSegmentArrival.bind(this);
  3031. this._remuxer.onMediaSegment = this._onRemuxerMediaSegmentArrival.bind(this);
  3032. consumed = this._demuxer.parseChunks(data, byteStart);
  3033. } else {
  3034. probeData = null;
  3035. _logger2.default.e(this.TAG, 'Non-FLV, Unsupported media type!');
  3036. Promise.resolve().then(function () {
  3037. _this._internalAbort();
  3038. });
  3039. this._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR, _demuxErrors2.default.FORMAT_UNSUPPORTED, 'Non-FLV, Unsupported media type');
  3040. consumed = 0;
  3041. }
  3042. return consumed;
  3043. }
  3044. }, {
  3045. key: '_onMediaInfo',
  3046. value: function _onMediaInfo(mediaInfo) {
  3047. var _this2 = this;
  3048. if (this._mediaInfo == null) {
  3049. // Store first segment's mediainfo as global mediaInfo
  3050. this._mediaInfo = Object.assign({}, mediaInfo);
  3051. this._mediaInfo.keyframesIndex = null;
  3052. this._mediaInfo.segments = [];
  3053. this._mediaInfo.segmentCount = this._mediaDataSource.segments.length;
  3054. Object.setPrototypeOf(this._mediaInfo, _mediaInfo2.default.prototype);
  3055. }
  3056. var segmentInfo = Object.assign({}, mediaInfo);
  3057. Object.setPrototypeOf(segmentInfo, _mediaInfo2.default.prototype);
  3058. this._mediaInfo.segments[this._currentSegmentIndex] = segmentInfo;
  3059. // notify mediaInfo update
  3060. this._reportSegmentMediaInfo(this._currentSegmentIndex);
  3061. if (this._pendingSeekTime != null) {
  3062. Promise.resolve().then(function () {
  3063. var target = _this2._pendingSeekTime;
  3064. _this2._pendingSeekTime = null;
  3065. _this2.seek(target);
  3066. });
  3067. }
  3068. }
  3069. }, {
  3070. key: '_onIOSeeked',
  3071. value: function _onIOSeeked() {
  3072. this._remuxer.insertDiscontinuity();
  3073. }
  3074. }, {
  3075. key: '_onIOComplete',
  3076. value: function _onIOComplete(extraData) {
  3077. var segmentIndex = extraData;
  3078. var nextSegmentIndex = segmentIndex + 1;
  3079. if (nextSegmentIndex < this._mediaDataSource.segments.length) {
  3080. this._internalAbort();
  3081. this._loadSegment(nextSegmentIndex);
  3082. } else {
  3083. this._remuxer.flushStashedSamples();
  3084. this._emitter.emit(_transmuxingEvents2.default.LOADING_COMPLETE);
  3085. this._disableStatisticsReporter();
  3086. }
  3087. }
  3088. }, {
  3089. key: '_onIORedirect',
  3090. value: function _onIORedirect(redirectedURL) {
  3091. var segmentIndex = this._ioctl.extraData;
  3092. this._mediaDataSource.segments[segmentIndex].redirectedURL = redirectedURL;
  3093. }
  3094. }, {
  3095. key: '_onIORecoveredEarlyEof',
  3096. value: function _onIORecoveredEarlyEof() {
  3097. this._emitter.emit(_transmuxingEvents2.default.RECOVERED_EARLY_EOF);
  3098. }
  3099. }, {
  3100. key: '_onIOException',
  3101. value: function _onIOException(type, info) {
  3102. _logger2.default.e(this.TAG, 'IOException: type = ' + type + ', code = ' + info.code + ', msg = ' + info.msg);
  3103. this._emitter.emit(_transmuxingEvents2.default.IO_ERROR, type, info);
  3104. this._disableStatisticsReporter();
  3105. }
  3106. }, {
  3107. key: '_onDemuxException',
  3108. value: function _onDemuxException(type, info) {
  3109. _logger2.default.e(this.TAG, 'DemuxException: type = ' + type + ', info = ' + info);
  3110. this._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR, type, info);
  3111. }
  3112. }, {
  3113. key: '_onRemuxerInitSegmentArrival',
  3114. value: function _onRemuxerInitSegmentArrival(type, initSegment) {
  3115. this._emitter.emit(_transmuxingEvents2.default.INIT_SEGMENT, type, initSegment);
  3116. }
  3117. }, {
  3118. key: '_onRemuxerMediaSegmentArrival',
  3119. value: function _onRemuxerMediaSegmentArrival(type, mediaSegment) {
  3120. if (this._pendingSeekTime != null) {
  3121. // Media segments after new-segment cross-seeking should be dropped.
  3122. return;
  3123. }
  3124. this._emitter.emit(_transmuxingEvents2.default.MEDIA_SEGMENT, type, mediaSegment);
  3125. // Resolve pending seekPoint
  3126. if (this._pendingResolveSeekPoint != null && type === 'video') {
  3127. var syncPoints = mediaSegment.info.syncPoints;
  3128. var seekpoint = this._pendingResolveSeekPoint;
  3129. this._pendingResolveSeekPoint = null;
  3130. // Safari: Pass PTS for recommend_seekpoint
  3131. if (_browser2.default.safari && syncPoints.length > 0 && syncPoints[0].originalDts === seekpoint) {
  3132. seekpoint = syncPoints[0].pts;
  3133. }
  3134. // else: use original DTS (keyframe.milliseconds)
  3135. this._emitter.emit(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, seekpoint);
  3136. }
  3137. }
  3138. }, {
  3139. key: '_enableStatisticsReporter',
  3140. value: function _enableStatisticsReporter() {
  3141. if (this._statisticsReporter == null) {
  3142. this._statisticsReporter = self.setInterval(this._reportStatisticsInfo.bind(this), this._config.statisticsInfoReportInterval);
  3143. }
  3144. }
  3145. }, {
  3146. key: '_disableStatisticsReporter',
  3147. value: function _disableStatisticsReporter() {
  3148. if (this._statisticsReporter) {
  3149. self.clearInterval(this._statisticsReporter);
  3150. this._statisticsReporter = null;
  3151. }
  3152. }
  3153. }, {
  3154. key: '_reportSegmentMediaInfo',
  3155. value: function _reportSegmentMediaInfo(segmentIndex) {
  3156. var segmentInfo = this._mediaInfo.segments[segmentIndex];
  3157. var exportInfo = Object.assign({}, segmentInfo);
  3158. exportInfo.duration = this._mediaInfo.duration;
  3159. exportInfo.segmentCount = this._mediaInfo.segmentCount;
  3160. delete exportInfo.segments;
  3161. delete exportInfo.keyframesIndex;
  3162. this._emitter.emit(_transmuxingEvents2.default.MEDIA_INFO, exportInfo);
  3163. }
  3164. }, {
  3165. key: '_reportStatisticsInfo',
  3166. value: function _reportStatisticsInfo() {
  3167. var info = {};
  3168. info.url = this._ioctl.currentURL;
  3169. info.hasRedirect = this._ioctl.hasRedirect;
  3170. if (info.hasRedirect) {
  3171. info.redirectedURL = this._ioctl.currentRedirectedURL;
  3172. }
  3173. info.speed = this._ioctl.currentSpeed;
  3174. info.loaderType = this._ioctl.loaderType;
  3175. info.currentSegmentIndex = this._currentSegmentIndex;
  3176. info.totalSegmentCount = this._mediaDataSource.segments.length;
  3177. this._emitter.emit(_transmuxingEvents2.default.STATISTICS_INFO, info);
  3178. }
  3179. }]);
  3180. return TransmuxingController;
  3181. }();
  3182. exports.default = TransmuxingController;
  3183. },{"../demux/demux-errors.js":16,"../demux/flv-demuxer.js":18,"../io/io-controller.js":23,"../io/loader.js":24,"../remux/mp4-remuxer.js":38,"../utils/browser.js":39,"../utils/logger.js":41,"./media-info.js":7,"./transmuxing-events.js":13,"events":2}],13:[function(_dereq_,module,exports){
  3184. 'use strict';
  3185. Object.defineProperty(exports, "__esModule", {
  3186. value: true
  3187. });
  3188. /*
  3189. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  3190. *
  3191. * @author zheng qian <xqq@xqq.im>
  3192. *
  3193. * Licensed under the Apache License, Version 2.0 (the "License");
  3194. * you may not use this file except in compliance with the License.
  3195. * You may obtain a copy of the License at
  3196. *
  3197. * http://www.apache.org/licenses/LICENSE-2.0
  3198. *
  3199. * Unless required by applicable law or agreed to in writing, software
  3200. * distributed under the License is distributed on an "AS IS" BASIS,
  3201. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3202. * See the License for the specific language governing permissions and
  3203. * limitations under the License.
  3204. */
  3205. var TransmuxingEvents = {
  3206. IO_ERROR: 'io_error',
  3207. DEMUX_ERROR: 'demux_error',
  3208. INIT_SEGMENT: 'init_segment',
  3209. MEDIA_SEGMENT: 'media_segment',
  3210. LOADING_COMPLETE: 'loading_complete',
  3211. RECOVERED_EARLY_EOF: 'recovered_early_eof',
  3212. MEDIA_INFO: 'media_info',
  3213. STATISTICS_INFO: 'statistics_info',
  3214. RECOMMEND_SEEKPOINT: 'recommend_seekpoint'
  3215. };
  3216. exports.default = TransmuxingEvents;
  3217. },{}],14:[function(_dereq_,module,exports){
  3218. 'use strict';
  3219. Object.defineProperty(exports, "__esModule", {
  3220. value: true
  3221. });
  3222. var _logger = _dereq_('../utils/logger.js');
  3223. var _logger2 = _interopRequireDefault(_logger);
  3224. var _loggingControl = _dereq_('../utils/logging-control.js');
  3225. var _loggingControl2 = _interopRequireDefault(_loggingControl);
  3226. var _polyfill = _dereq_('../utils/polyfill.js');
  3227. var _polyfill2 = _interopRequireDefault(_polyfill);
  3228. var _transmuxingController = _dereq_('./transmuxing-controller.js');
  3229. var _transmuxingController2 = _interopRequireDefault(_transmuxingController);
  3230. var _transmuxingEvents = _dereq_('./transmuxing-events.js');
  3231. var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
  3232. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  3233. /* post message to worker:
  3234. data: {
  3235. cmd: string
  3236. param: any
  3237. }
  3238. receive message from worker:
  3239. data: {
  3240. msg: string,
  3241. data: any
  3242. }
  3243. */
  3244. var TransmuxingWorker = function TransmuxingWorker(self) {
  3245. var TAG = 'TransmuxingWorker';
  3246. var controller = null;
  3247. var logcatListener = onLogcatCallback.bind(this);
  3248. _polyfill2.default.install();
  3249. self.addEventListener('message', function (e) {
  3250. switch (e.data.cmd) {
  3251. case 'init':
  3252. controller = new _transmuxingController2.default(e.data.param[0], e.data.param[1]);
  3253. controller.on(_transmuxingEvents2.default.IO_ERROR, onIOError.bind(this));
  3254. controller.on(_transmuxingEvents2.default.DEMUX_ERROR, onDemuxError.bind(this));
  3255. controller.on(_transmuxingEvents2.default.INIT_SEGMENT, onInitSegment.bind(this));
  3256. controller.on(_transmuxingEvents2.default.MEDIA_SEGMENT, onMediaSegment.bind(this));
  3257. controller.on(_transmuxingEvents2.default.LOADING_COMPLETE, onLoadingComplete.bind(this));
  3258. controller.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF, onRecoveredEarlyEof.bind(this));
  3259. controller.on(_transmuxingEvents2.default.MEDIA_INFO, onMediaInfo.bind(this));
  3260. controller.on(_transmuxingEvents2.default.STATISTICS_INFO, onStatisticsInfo.bind(this));
  3261. controller.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, onRecommendSeekpoint.bind(this));
  3262. break;
  3263. case 'destroy':
  3264. if (controller) {
  3265. controller.destroy();
  3266. controller = null;
  3267. }
  3268. self.postMessage({ msg: 'destroyed' });
  3269. break;
  3270. case 'start':
  3271. controller.start();
  3272. break;
  3273. case 'stop':
  3274. controller.stop();
  3275. break;
  3276. case 'seek':
  3277. controller.seek(e.data.param);
  3278. break;
  3279. case 'pause':
  3280. controller.pause();
  3281. break;
  3282. case 'resume':
  3283. controller.resume();
  3284. break;
  3285. case 'logging_config':
  3286. {
  3287. var config = e.data.param;
  3288. _loggingControl2.default.applyConfig(config);
  3289. if (config.enableCallback === true) {
  3290. _loggingControl2.default.addLogListener(logcatListener);
  3291. } else {
  3292. _loggingControl2.default.removeLogListener(logcatListener);
  3293. }
  3294. break;
  3295. }
  3296. }
  3297. });
  3298. function onInitSegment(type, initSegment) {
  3299. var obj = {
  3300. msg: _transmuxingEvents2.default.INIT_SEGMENT,
  3301. data: {
  3302. type: type,
  3303. data: initSegment
  3304. }
  3305. };
  3306. self.postMessage(obj, [initSegment.data]); // data: ArrayBuffer
  3307. }
  3308. function onMediaSegment(type, mediaSegment) {
  3309. var obj = {
  3310. msg: _transmuxingEvents2.default.MEDIA_SEGMENT,
  3311. data: {
  3312. type: type,
  3313. data: mediaSegment
  3314. }
  3315. };
  3316. self.postMessage(obj, [mediaSegment.data]); // data: ArrayBuffer
  3317. }
  3318. function onLoadingComplete() {
  3319. var obj = {
  3320. msg: _transmuxingEvents2.default.LOADING_COMPLETE
  3321. };
  3322. self.postMessage(obj);
  3323. }
  3324. function onRecoveredEarlyEof() {
  3325. var obj = {
  3326. msg: _transmuxingEvents2.default.RECOVERED_EARLY_EOF
  3327. };
  3328. self.postMessage(obj);
  3329. }
  3330. function onMediaInfo(mediaInfo) {
  3331. var obj = {
  3332. msg: _transmuxingEvents2.default.MEDIA_INFO,
  3333. data: mediaInfo
  3334. };
  3335. self.postMessage(obj);
  3336. }
  3337. function onStatisticsInfo(statInfo) {
  3338. var obj = {
  3339. msg: _transmuxingEvents2.default.STATISTICS_INFO,
  3340. data: statInfo
  3341. };
  3342. self.postMessage(obj);
  3343. }
  3344. function onIOError(type, info) {
  3345. self.postMessage({
  3346. msg: _transmuxingEvents2.default.IO_ERROR,
  3347. data: {
  3348. type: type,
  3349. info: info
  3350. }
  3351. });
  3352. }
  3353. function onDemuxError(type, info) {
  3354. self.postMessage({
  3355. msg: _transmuxingEvents2.default.DEMUX_ERROR,
  3356. data: {
  3357. type: type,
  3358. info: info
  3359. }
  3360. });
  3361. }
  3362. function onRecommendSeekpoint(milliseconds) {
  3363. self.postMessage({
  3364. msg: _transmuxingEvents2.default.RECOMMEND_SEEKPOINT,
  3365. data: milliseconds
  3366. });
  3367. }
  3368. function onLogcatCallback(type, str) {
  3369. self.postMessage({
  3370. msg: 'logcat_callback',
  3371. data: {
  3372. type: type,
  3373. logcat: str
  3374. }
  3375. });
  3376. }
  3377. }; /*
  3378. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  3379. *
  3380. * @author zheng qian <xqq@xqq.im>
  3381. *
  3382. * Licensed under the Apache License, Version 2.0 (the "License");
  3383. * you may not use this file except in compliance with the License.
  3384. * You may obtain a copy of the License at
  3385. *
  3386. * http://www.apache.org/licenses/LICENSE-2.0
  3387. *
  3388. * Unless required by applicable law or agreed to in writing, software
  3389. * distributed under the License is distributed on an "AS IS" BASIS,
  3390. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3391. * See the License for the specific language governing permissions and
  3392. * limitations under the License.
  3393. */
  3394. exports.default = TransmuxingWorker;
  3395. },{"../utils/logger.js":41,"../utils/logging-control.js":42,"../utils/polyfill.js":43,"./transmuxing-controller.js":12,"./transmuxing-events.js":13}],15:[function(_dereq_,module,exports){
  3396. 'use strict';
  3397. Object.defineProperty(exports, "__esModule", {
  3398. value: true
  3399. });
  3400. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  3401. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  3402. *
  3403. * @author zheng qian <xqq@xqq.im>
  3404. *
  3405. * Licensed under the Apache License, Version 2.0 (the "License");
  3406. * you may not use this file except in compliance with the License.
  3407. * You may obtain a copy of the License at
  3408. *
  3409. * http://www.apache.org/licenses/LICENSE-2.0
  3410. *
  3411. * Unless required by applicable law or agreed to in writing, software
  3412. * distributed under the License is distributed on an "AS IS" BASIS,
  3413. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3414. * See the License for the specific language governing permissions and
  3415. * limitations under the License.
  3416. */
  3417. var _logger = _dereq_('../utils/logger.js');
  3418. var _logger2 = _interopRequireDefault(_logger);
  3419. var _utf8Conv = _dereq_('../utils/utf8-conv.js');
  3420. var _utf8Conv2 = _interopRequireDefault(_utf8Conv);
  3421. var _exception = _dereq_('../utils/exception.js');
  3422. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  3423. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3424. var le = function () {
  3425. var buf = new ArrayBuffer(2);
  3426. new DataView(buf).setInt16(0, 256, true); // little-endian write
  3427. return new Int16Array(buf)[0] === 256; // platform-spec read, if equal then LE
  3428. }();
  3429. var AMF = function () {
  3430. function AMF() {
  3431. _classCallCheck(this, AMF);
  3432. }
  3433. _createClass(AMF, null, [{
  3434. key: 'parseScriptData',
  3435. value: function parseScriptData(arrayBuffer, dataOffset, dataSize) {
  3436. var data = {};
  3437. try {
  3438. var name = AMF.parseValue(arrayBuffer, dataOffset, dataSize);
  3439. var value = AMF.parseValue(arrayBuffer, dataOffset + name.size, dataSize - name.size);
  3440. data[name.data] = value.data;
  3441. } catch (e) {
  3442. _logger2.default.e('AMF', e.toString());
  3443. }
  3444. return data;
  3445. }
  3446. }, {
  3447. key: 'parseObject',
  3448. value: function parseObject(arrayBuffer, dataOffset, dataSize) {
  3449. if (dataSize < 3) {
  3450. throw new _exception.IllegalStateException('Data not enough when parse ScriptDataObject');
  3451. }
  3452. var name = AMF.parseString(arrayBuffer, dataOffset, dataSize);
  3453. var value = AMF.parseValue(arrayBuffer, dataOffset + name.size, dataSize - name.size);
  3454. var isObjectEnd = value.objectEnd;
  3455. return {
  3456. data: {
  3457. name: name.data,
  3458. value: value.data
  3459. },
  3460. size: name.size + value.size,
  3461. objectEnd: isObjectEnd
  3462. };
  3463. }
  3464. }, {
  3465. key: 'parseVariable',
  3466. value: function parseVariable(arrayBuffer, dataOffset, dataSize) {
  3467. return AMF.parseObject(arrayBuffer, dataOffset, dataSize);
  3468. }
  3469. }, {
  3470. key: 'parseString',
  3471. value: function parseString(arrayBuffer, dataOffset, dataSize) {
  3472. if (dataSize < 2) {
  3473. throw new _exception.IllegalStateException('Data not enough when parse String');
  3474. }
  3475. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  3476. var length = v.getUint16(0, !le);
  3477. var str = void 0;
  3478. if (length > 0) {
  3479. str = (0, _utf8Conv2.default)(new Uint8Array(arrayBuffer, dataOffset + 2, length));
  3480. } else {
  3481. str = '';
  3482. }
  3483. return {
  3484. data: str,
  3485. size: 2 + length
  3486. };
  3487. }
  3488. }, {
  3489. key: 'parseLongString',
  3490. value: function parseLongString(arrayBuffer, dataOffset, dataSize) {
  3491. if (dataSize < 4) {
  3492. throw new _exception.IllegalStateException('Data not enough when parse LongString');
  3493. }
  3494. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  3495. var length = v.getUint32(0, !le);
  3496. var str = void 0;
  3497. if (length > 0) {
  3498. str = (0, _utf8Conv2.default)(new Uint8Array(arrayBuffer, dataOffset + 4, length));
  3499. } else {
  3500. str = '';
  3501. }
  3502. return {
  3503. data: str,
  3504. size: 4 + length
  3505. };
  3506. }
  3507. }, {
  3508. key: 'parseDate',
  3509. value: function parseDate(arrayBuffer, dataOffset, dataSize) {
  3510. if (dataSize < 10) {
  3511. throw new _exception.IllegalStateException('Data size invalid when parse Date');
  3512. }
  3513. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  3514. var timestamp = v.getFloat64(0, !le);
  3515. var localTimeOffset = v.getInt16(8, !le);
  3516. timestamp += localTimeOffset * 60 * 1000; // get UTC time
  3517. return {
  3518. data: new Date(timestamp),
  3519. size: 8 + 2
  3520. };
  3521. }
  3522. }, {
  3523. key: 'parseValue',
  3524. value: function parseValue(arrayBuffer, dataOffset, dataSize) {
  3525. if (dataSize < 1) {
  3526. throw new _exception.IllegalStateException('Data not enough when parse Value');
  3527. }
  3528. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  3529. var offset = 1;
  3530. var type = v.getUint8(0);
  3531. var value = void 0;
  3532. var objectEnd = false;
  3533. try {
  3534. switch (type) {
  3535. case 0:
  3536. // Number(Double) type
  3537. value = v.getFloat64(1, !le);
  3538. offset += 8;
  3539. break;
  3540. case 1:
  3541. {
  3542. // Boolean type
  3543. var b = v.getUint8(1);
  3544. value = b ? true : false;
  3545. offset += 1;
  3546. break;
  3547. }
  3548. case 2:
  3549. {
  3550. // String type
  3551. var amfstr = AMF.parseString(arrayBuffer, dataOffset + 1, dataSize - 1);
  3552. value = amfstr.data;
  3553. offset += amfstr.size;
  3554. break;
  3555. }
  3556. case 3:
  3557. {
  3558. // Object(s) type
  3559. value = {};
  3560. var terminal = 0; // workaround for malformed Objects which has missing ScriptDataObjectEnd
  3561. if ((v.getUint32(dataSize - 4, !le) & 0x00FFFFFF) === 9) {
  3562. terminal = 3;
  3563. }
  3564. while (offset < dataSize - 4) {
  3565. // 4 === type(UI8) + ScriptDataObjectEnd(UI24)
  3566. var amfobj = AMF.parseObject(arrayBuffer, dataOffset + offset, dataSize - offset - terminal);
  3567. if (amfobj.objectEnd) break;
  3568. value[amfobj.data.name] = amfobj.data.value;
  3569. offset += amfobj.size;
  3570. }
  3571. if (offset <= dataSize - 3) {
  3572. var marker = v.getUint32(offset - 1, !le) & 0x00FFFFFF;
  3573. if (marker === 9) {
  3574. offset += 3;
  3575. }
  3576. }
  3577. break;
  3578. }
  3579. case 8:
  3580. {
  3581. // ECMA array type (Mixed array)
  3582. value = {};
  3583. offset += 4; // ECMAArrayLength(UI32)
  3584. var _terminal = 0; // workaround for malformed MixedArrays which has missing ScriptDataObjectEnd
  3585. if ((v.getUint32(dataSize - 4, !le) & 0x00FFFFFF) === 9) {
  3586. _terminal = 3;
  3587. }
  3588. while (offset < dataSize - 8) {
  3589. // 8 === type(UI8) + ECMAArrayLength(UI32) + ScriptDataVariableEnd(UI24)
  3590. var amfvar = AMF.parseVariable(arrayBuffer, dataOffset + offset, dataSize - offset - _terminal);
  3591. if (amfvar.objectEnd) break;
  3592. value[amfvar.data.name] = amfvar.data.value;
  3593. offset += amfvar.size;
  3594. }
  3595. if (offset <= dataSize - 3) {
  3596. var _marker = v.getUint32(offset - 1, !le) & 0x00FFFFFF;
  3597. if (_marker === 9) {
  3598. offset += 3;
  3599. }
  3600. }
  3601. break;
  3602. }
  3603. case 9:
  3604. // ScriptDataObjectEnd
  3605. value = undefined;
  3606. offset = 1;
  3607. objectEnd = true;
  3608. break;
  3609. case 10:
  3610. {
  3611. // Strict array type
  3612. // ScriptDataValue[n]. NOTE: according to video_file_format_spec_v10_1.pdf
  3613. value = [];
  3614. var strictArrayLength = v.getUint32(1, !le);
  3615. offset += 4;
  3616. for (var i = 0; i < strictArrayLength; i++) {
  3617. var val = AMF.parseValue(arrayBuffer, dataOffset + offset, dataSize - offset);
  3618. value.push(val.data);
  3619. offset += val.size;
  3620. }
  3621. break;
  3622. }
  3623. case 11:
  3624. {
  3625. // Date type
  3626. var date = AMF.parseDate(arrayBuffer, dataOffset + 1, dataSize - 1);
  3627. value = date.data;
  3628. offset += date.size;
  3629. break;
  3630. }
  3631. case 12:
  3632. {
  3633. // Long string type
  3634. var amfLongStr = AMF.parseString(arrayBuffer, dataOffset + 1, dataSize - 1);
  3635. value = amfLongStr.data;
  3636. offset += amfLongStr.size;
  3637. break;
  3638. }
  3639. default:
  3640. // ignore and skip
  3641. offset = dataSize;
  3642. _logger2.default.w('AMF', 'Unsupported AMF value type ' + type);
  3643. }
  3644. } catch (e) {
  3645. _logger2.default.e('AMF', e.toString());
  3646. }
  3647. return {
  3648. data: value,
  3649. size: offset,
  3650. objectEnd: objectEnd
  3651. };
  3652. }
  3653. }]);
  3654. return AMF;
  3655. }();
  3656. exports.default = AMF;
  3657. },{"../utils/exception.js":40,"../utils/logger.js":41,"../utils/utf8-conv.js":44}],16:[function(_dereq_,module,exports){
  3658. 'use strict';
  3659. Object.defineProperty(exports, "__esModule", {
  3660. value: true
  3661. });
  3662. /*
  3663. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  3664. *
  3665. * @author zheng qian <xqq@xqq.im>
  3666. *
  3667. * Licensed under the Apache License, Version 2.0 (the "License");
  3668. * you may not use this file except in compliance with the License.
  3669. * You may obtain a copy of the License at
  3670. *
  3671. * http://www.apache.org/licenses/LICENSE-2.0
  3672. *
  3673. * Unless required by applicable law or agreed to in writing, software
  3674. * distributed under the License is distributed on an "AS IS" BASIS,
  3675. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3676. * See the License for the specific language governing permissions and
  3677. * limitations under the License.
  3678. */
  3679. var DemuxErrors = {
  3680. OK: 'OK',
  3681. FORMAT_ERROR: 'FormatError',
  3682. FORMAT_UNSUPPORTED: 'FormatUnsupported',
  3683. CODEC_UNSUPPORTED: 'CodecUnsupported'
  3684. };
  3685. exports.default = DemuxErrors;
  3686. },{}],17:[function(_dereq_,module,exports){
  3687. 'use strict';
  3688. Object.defineProperty(exports, "__esModule", {
  3689. value: true
  3690. });
  3691. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  3692. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  3693. *
  3694. * @author zheng qian <xqq@xqq.im>
  3695. *
  3696. * Licensed under the Apache License, Version 2.0 (the "License");
  3697. * you may not use this file except in compliance with the License.
  3698. * You may obtain a copy of the License at
  3699. *
  3700. * http://www.apache.org/licenses/LICENSE-2.0
  3701. *
  3702. * Unless required by applicable law or agreed to in writing, software
  3703. * distributed under the License is distributed on an "AS IS" BASIS,
  3704. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3705. * See the License for the specific language governing permissions and
  3706. * limitations under the License.
  3707. */
  3708. var _exception = _dereq_('../utils/exception.js');
  3709. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3710. // Exponential-Golomb buffer decoder
  3711. var ExpGolomb = function () {
  3712. function ExpGolomb(uint8array) {
  3713. _classCallCheck(this, ExpGolomb);
  3714. this.TAG = 'ExpGolomb';
  3715. this._buffer = uint8array;
  3716. this._buffer_index = 0;
  3717. this._total_bytes = uint8array.byteLength;
  3718. this._total_bits = uint8array.byteLength * 8;
  3719. this._current_word = 0;
  3720. this._current_word_bits_left = 0;
  3721. }
  3722. _createClass(ExpGolomb, [{
  3723. key: 'destroy',
  3724. value: function destroy() {
  3725. this._buffer = null;
  3726. }
  3727. }, {
  3728. key: '_fillCurrentWord',
  3729. value: function _fillCurrentWord() {
  3730. var buffer_bytes_left = this._total_bytes - this._buffer_index;
  3731. if (buffer_bytes_left <= 0) throw new _exception.IllegalStateException('ExpGolomb: _fillCurrentWord() but no bytes available');
  3732. var bytes_read = Math.min(4, buffer_bytes_left);
  3733. var word = new Uint8Array(4);
  3734. word.set(this._buffer.subarray(this._buffer_index, this._buffer_index + bytes_read));
  3735. this._current_word = new DataView(word.buffer).getUint32(0, false);
  3736. this._buffer_index += bytes_read;
  3737. this._current_word_bits_left = bytes_read * 8;
  3738. }
  3739. }, {
  3740. key: 'readBits',
  3741. value: function readBits(bits) {
  3742. if (bits > 32) throw new _exception.InvalidArgumentException('ExpGolomb: readBits() bits exceeded max 32bits!');
  3743. if (bits <= this._current_word_bits_left) {
  3744. var _result = this._current_word >>> 32 - bits;
  3745. this._current_word <<= bits;
  3746. this._current_word_bits_left -= bits;
  3747. return _result;
  3748. }
  3749. var result = this._current_word_bits_left ? this._current_word : 0;
  3750. result = result >>> 32 - this._current_word_bits_left;
  3751. var bits_need_left = bits - this._current_word_bits_left;
  3752. this._fillCurrentWord();
  3753. var bits_read_next = Math.min(bits_need_left, this._current_word_bits_left);
  3754. var result2 = this._current_word >>> 32 - bits_read_next;
  3755. this._current_word <<= bits_read_next;
  3756. this._current_word_bits_left -= bits_read_next;
  3757. result = result << bits_read_next | result2;
  3758. return result;
  3759. }
  3760. }, {
  3761. key: 'readBool',
  3762. value: function readBool() {
  3763. return this.readBits(1) === 1;
  3764. }
  3765. }, {
  3766. key: 'readByte',
  3767. value: function readByte() {
  3768. return this.readBits(8);
  3769. }
  3770. }, {
  3771. key: '_skipLeadingZero',
  3772. value: function _skipLeadingZero() {
  3773. var zero_count = void 0;
  3774. for (zero_count = 0; zero_count < this._current_word_bits_left; zero_count++) {
  3775. if (0 !== (this._current_word & 0x80000000 >>> zero_count)) {
  3776. this._current_word <<= zero_count;
  3777. this._current_word_bits_left -= zero_count;
  3778. return zero_count;
  3779. }
  3780. }
  3781. this._fillCurrentWord();
  3782. return zero_count + this._skipLeadingZero();
  3783. }
  3784. }, {
  3785. key: 'readUEG',
  3786. value: function readUEG() {
  3787. // unsigned exponential golomb
  3788. var leading_zeros = this._skipLeadingZero();
  3789. return this.readBits(leading_zeros + 1) - 1;
  3790. }
  3791. }, {
  3792. key: 'readSEG',
  3793. value: function readSEG() {
  3794. // signed exponential golomb
  3795. var value = this.readUEG();
  3796. if (value & 0x01) {
  3797. return value + 1 >>> 1;
  3798. } else {
  3799. return -1 * (value >>> 1);
  3800. }
  3801. }
  3802. }]);
  3803. return ExpGolomb;
  3804. }();
  3805. exports.default = ExpGolomb;
  3806. },{"../utils/exception.js":40}],18:[function(_dereq_,module,exports){
  3807. 'use strict';
  3808. Object.defineProperty(exports, "__esModule", {
  3809. value: true
  3810. });
  3811. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  3812. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  3813. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  3814. *
  3815. * @author zheng qian <xqq@xqq.im>
  3816. *
  3817. * Licensed under the Apache License, Version 2.0 (the "License");
  3818. * you may not use this file except in compliance with the License.
  3819. * You may obtain a copy of the License at
  3820. *
  3821. * http://www.apache.org/licenses/LICENSE-2.0
  3822. *
  3823. * Unless required by applicable law or agreed to in writing, software
  3824. * distributed under the License is distributed on an "AS IS" BASIS,
  3825. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3826. * See the License for the specific language governing permissions and
  3827. * limitations under the License.
  3828. */
  3829. var _logger = _dereq_('../utils/logger.js');
  3830. var _logger2 = _interopRequireDefault(_logger);
  3831. var _amfParser = _dereq_('./amf-parser.js');
  3832. var _amfParser2 = _interopRequireDefault(_amfParser);
  3833. var _spsParser = _dereq_('./sps-parser.js');
  3834. var _spsParser2 = _interopRequireDefault(_spsParser);
  3835. var _demuxErrors = _dereq_('./demux-errors.js');
  3836. var _demuxErrors2 = _interopRequireDefault(_demuxErrors);
  3837. var _mediaInfo = _dereq_('../core/media-info.js');
  3838. var _mediaInfo2 = _interopRequireDefault(_mediaInfo);
  3839. var _exception = _dereq_('../utils/exception.js');
  3840. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  3841. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3842. function Swap16(src) {
  3843. return src >>> 8 & 0xFF | (src & 0xFF) << 8;
  3844. }
  3845. function Swap32(src) {
  3846. return (src & 0xFF000000) >>> 24 | (src & 0x00FF0000) >>> 8 | (src & 0x0000FF00) << 8 | (src & 0x000000FF) << 24;
  3847. }
  3848. function ReadBig32(array, index) {
  3849. return array[index] << 24 | array[index + 1] << 16 | array[index + 2] << 8 | array[index + 3];
  3850. }
  3851. var FLVDemuxer = function () {
  3852. function FLVDemuxer(probeData, config) {
  3853. _classCallCheck(this, FLVDemuxer);
  3854. this.TAG = 'FLVDemuxer';
  3855. this._config = config;
  3856. this._onError = null;
  3857. this._onMediaInfo = null;
  3858. this._onTrackMetadata = null;
  3859. this._onDataAvailable = null;
  3860. this._dataOffset = probeData.dataOffset;
  3861. this._firstParse = true;
  3862. this._dispatch = false;
  3863. this._hasAudio = probeData.hasAudioTrack;
  3864. this._hasVideo = probeData.hasVideoTrack;
  3865. this._hasAudioFlagOverrided = false;
  3866. this._hasVideoFlagOverrided = false;
  3867. this._audioInitialMetadataDispatched = false;
  3868. this._videoInitialMetadataDispatched = false;
  3869. this._mediaInfo = new _mediaInfo2.default();
  3870. this._mediaInfo.hasAudio = this._hasAudio;
  3871. this._mediaInfo.hasVideo = this._hasVideo;
  3872. this._metadata = null;
  3873. this._audioMetadata = null;
  3874. this._videoMetadata = null;
  3875. this._naluLengthSize = 4;
  3876. this._timestampBase = 0; // int32, in milliseconds
  3877. this._timescale = 1000;
  3878. this._duration = 0; // int32, in milliseconds
  3879. this._durationOverrided = false;
  3880. this._referenceFrameRate = {
  3881. fixed: true,
  3882. fps: 23.976,
  3883. fps_num: 23976,
  3884. fps_den: 1000
  3885. };
  3886. this._flvSoundRateTable = [5500, 11025, 22050, 44100, 48000];
  3887. this._mpegSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  3888. this._mpegAudioV10SampleRateTable = [44100, 48000, 32000, 0];
  3889. this._mpegAudioV20SampleRateTable = [22050, 24000, 16000, 0];
  3890. this._mpegAudioV25SampleRateTable = [11025, 12000, 8000, 0];
  3891. this._mpegAudioL1BitRateTable = [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, -1];
  3892. this._mpegAudioL2BitRateTable = [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, -1];
  3893. this._mpegAudioL3BitRateTable = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1];
  3894. this._videoTrack = { type: 'video', id: 1, sequenceNumber: 0, samples: [], length: 0 };
  3895. this._audioTrack = { type: 'audio', id: 2, sequenceNumber: 0, samples: [], length: 0 };
  3896. this._littleEndian = function () {
  3897. var buf = new ArrayBuffer(2);
  3898. new DataView(buf).setInt16(0, 256, true); // little-endian write
  3899. return new Int16Array(buf)[0] === 256; // platform-spec read, if equal then LE
  3900. }();
  3901. }
  3902. _createClass(FLVDemuxer, [{
  3903. key: 'destroy',
  3904. value: function destroy() {
  3905. this._mediaInfo = null;
  3906. this._metadata = null;
  3907. this._audioMetadata = null;
  3908. this._videoMetadata = null;
  3909. this._videoTrack = null;
  3910. this._audioTrack = null;
  3911. this._onError = null;
  3912. this._onMediaInfo = null;
  3913. this._onTrackMetadata = null;
  3914. this._onDataAvailable = null;
  3915. }
  3916. }, {
  3917. key: 'bindDataSource',
  3918. value: function bindDataSource(loader) {
  3919. loader.onDataArrival = this.parseChunks.bind(this);
  3920. return this;
  3921. }
  3922. // prototype: function(type: string, metadata: any): void
  3923. }, {
  3924. key: 'resetMediaInfo',
  3925. value: function resetMediaInfo() {
  3926. this._mediaInfo = new _mediaInfo2.default();
  3927. }
  3928. }, {
  3929. key: '_isInitialMetadataDispatched',
  3930. value: function _isInitialMetadataDispatched() {
  3931. if (this._hasAudio && this._hasVideo) {
  3932. // both audio & video
  3933. return this._audioInitialMetadataDispatched && this._videoInitialMetadataDispatched;
  3934. }
  3935. if (this._hasAudio && !this._hasVideo) {
  3936. // audio only
  3937. return this._audioInitialMetadataDispatched;
  3938. }
  3939. if (!this._hasAudio && this._hasVideo) {
  3940. // video only
  3941. return this._videoInitialMetadataDispatched;
  3942. }
  3943. return false;
  3944. }
  3945. // function parseChunks(chunk: ArrayBuffer, byteStart: number): number;
  3946. }, {
  3947. key: 'parseChunks',
  3948. value: function parseChunks(chunk, byteStart) {
  3949. if (!this._onError || !this._onMediaInfo || !this._onTrackMetadata || !this._onDataAvailable) {
  3950. throw new _exception.IllegalStateException('Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified');
  3951. }
  3952. var offset = 0;
  3953. var le = this._littleEndian;
  3954. if (byteStart === 0) {
  3955. // buffer with FLV header
  3956. if (chunk.byteLength > 13) {
  3957. var probeData = FLVDemuxer.probe(chunk);
  3958. offset = probeData.dataOffset;
  3959. } else {
  3960. return 0;
  3961. }
  3962. }
  3963. if (this._firstParse) {
  3964. // handle PreviousTagSize0 before Tag1
  3965. this._firstParse = false;
  3966. if (byteStart + offset !== this._dataOffset) {
  3967. _logger2.default.w(this.TAG, 'First time parsing but chunk byteStart invalid!');
  3968. }
  3969. var v = new DataView(chunk, offset);
  3970. var prevTagSize0 = v.getUint32(0, !le);
  3971. if (prevTagSize0 !== 0) {
  3972. _logger2.default.w(this.TAG, 'PrevTagSize0 !== 0 !!!');
  3973. }
  3974. offset += 4;
  3975. }
  3976. while (offset < chunk.byteLength) {
  3977. this._dispatch = true;
  3978. var _v = new DataView(chunk, offset);
  3979. if (offset + 11 + 4 > chunk.byteLength) {
  3980. // data not enough for parsing an flv tag
  3981. break;
  3982. }
  3983. var tagType = _v.getUint8(0);
  3984. var dataSize = _v.getUint32(0, !le) & 0x00FFFFFF;
  3985. if (offset + 11 + dataSize + 4 > chunk.byteLength) {
  3986. // data not enough for parsing actual data body
  3987. break;
  3988. }
  3989. if (tagType !== 8 && tagType !== 9 && tagType !== 18) {
  3990. _logger2.default.w(this.TAG, 'Unsupported tag type ' + tagType + ', skipped');
  3991. // consume the whole tag (skip it)
  3992. offset += 11 + dataSize + 4;
  3993. continue;
  3994. }
  3995. var ts2 = _v.getUint8(4);
  3996. var ts1 = _v.getUint8(5);
  3997. var ts0 = _v.getUint8(6);
  3998. var ts3 = _v.getUint8(7);
  3999. var timestamp = ts0 | ts1 << 8 | ts2 << 16 | ts3 << 24;
  4000. var streamId = _v.getUint32(7, !le) & 0x00FFFFFF;
  4001. if (streamId !== 0) {
  4002. _logger2.default.w(this.TAG, 'Meet tag which has StreamID != 0!');
  4003. }
  4004. var dataOffset = offset + 11;
  4005. switch (tagType) {
  4006. case 8:
  4007. // Audio
  4008. this._parseAudioData(chunk, dataOffset, dataSize, timestamp);
  4009. break;
  4010. case 9:
  4011. // Video
  4012. this._parseVideoData(chunk, dataOffset, dataSize, timestamp, byteStart + offset);
  4013. break;
  4014. case 18:
  4015. // ScriptDataObject
  4016. this._parseScriptData(chunk, dataOffset, dataSize);
  4017. break;
  4018. }
  4019. var prevTagSize = _v.getUint32(11 + dataSize, !le);
  4020. if (prevTagSize !== 11 + dataSize) {
  4021. _logger2.default.w(this.TAG, 'Invalid PrevTagSize ' + prevTagSize);
  4022. }
  4023. offset += 11 + dataSize + 4; // tagBody + dataSize + prevTagSize
  4024. }
  4025. // dispatch parsed frames to consumer (typically, the remuxer)
  4026. if (this._isInitialMetadataDispatched()) {
  4027. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  4028. this._onDataAvailable(this._audioTrack, this._videoTrack);
  4029. }
  4030. }
  4031. return offset; // consumed bytes, just equals latest offset index
  4032. }
  4033. }, {
  4034. key: '_parseScriptData',
  4035. value: function _parseScriptData(arrayBuffer, dataOffset, dataSize) {
  4036. var scriptData = _amfParser2.default.parseScriptData(arrayBuffer, dataOffset, dataSize);
  4037. if (scriptData.hasOwnProperty('onMetaData')) {
  4038. if (scriptData.onMetaData == null || _typeof(scriptData.onMetaData) !== 'object') {
  4039. _logger2.default.w(this.TAG, 'Invalid onMetaData structure!');
  4040. return;
  4041. }
  4042. if (this._metadata) {
  4043. _logger2.default.w(this.TAG, 'Found another onMetaData tag!');
  4044. }
  4045. this._metadata = scriptData;
  4046. var onMetaData = this._metadata.onMetaData;
  4047. if (typeof onMetaData.hasAudio === 'boolean') {
  4048. // hasAudio
  4049. if (this._hasAudioFlagOverrided === false) {
  4050. this._hasAudio = onMetaData.hasAudio;
  4051. this._mediaInfo.hasAudio = this._hasAudio;
  4052. }
  4053. }
  4054. if (typeof onMetaData.hasVideo === 'boolean') {
  4055. // hasVideo
  4056. if (this._hasVideoFlagOverrided === false) {
  4057. this._hasVideo = onMetaData.hasVideo;
  4058. this._mediaInfo.hasVideo = this._hasVideo;
  4059. }
  4060. }
  4061. if (typeof onMetaData.audiodatarate === 'number') {
  4062. // audiodatarate
  4063. this._mediaInfo.audioDataRate = onMetaData.audiodatarate;
  4064. }
  4065. if (typeof onMetaData.videodatarate === 'number') {
  4066. // videodatarate
  4067. this._mediaInfo.videoDataRate = onMetaData.videodatarate;
  4068. }
  4069. if (typeof onMetaData.width === 'number') {
  4070. // width
  4071. this._mediaInfo.width = onMetaData.width;
  4072. }
  4073. if (typeof onMetaData.height === 'number') {
  4074. // height
  4075. this._mediaInfo.height = onMetaData.height;
  4076. }
  4077. if (typeof onMetaData.duration === 'number') {
  4078. // duration
  4079. if (!this._durationOverrided) {
  4080. var duration = Math.floor(onMetaData.duration * this._timescale);
  4081. this._duration = duration;
  4082. this._mediaInfo.duration = duration;
  4083. }
  4084. } else {
  4085. this._mediaInfo.duration = 0;
  4086. }
  4087. if (typeof onMetaData.framerate === 'number') {
  4088. // framerate
  4089. var fps_num = Math.floor(onMetaData.framerate * 1000);
  4090. if (fps_num > 0) {
  4091. var fps = fps_num / 1000;
  4092. this._referenceFrameRate.fixed = true;
  4093. this._referenceFrameRate.fps = fps;
  4094. this._referenceFrameRate.fps_num = fps_num;
  4095. this._referenceFrameRate.fps_den = 1000;
  4096. this._mediaInfo.fps = fps;
  4097. }
  4098. }
  4099. if (_typeof(onMetaData.keyframes) === 'object') {
  4100. // keyframes
  4101. this._mediaInfo.hasKeyframesIndex = true;
  4102. var keyframes = onMetaData.keyframes;
  4103. this._mediaInfo.keyframesIndex = this._parseKeyframesIndex(keyframes);
  4104. onMetaData.keyframes = null; // keyframes has been extracted, remove it
  4105. } else {
  4106. this._mediaInfo.hasKeyframesIndex = false;
  4107. }
  4108. this._dispatch = false;
  4109. this._mediaInfo.metadata = onMetaData;
  4110. _logger2.default.v(this.TAG, 'Parsed onMetaData');
  4111. if (this._mediaInfo.isComplete()) {
  4112. this._onMediaInfo(this._mediaInfo);
  4113. }
  4114. }
  4115. }
  4116. }, {
  4117. key: '_parseKeyframesIndex',
  4118. value: function _parseKeyframesIndex(keyframes) {
  4119. var times = [];
  4120. var filepositions = [];
  4121. // ignore first keyframe which is actually AVC Sequence Header (AVCDecoderConfigurationRecord)
  4122. for (var i = 1; i < keyframes.times.length; i++) {
  4123. var time = this._timestampBase + Math.floor(keyframes.times[i] * 1000);
  4124. times.push(time);
  4125. filepositions.push(keyframes.filepositions[i]);
  4126. }
  4127. return {
  4128. times: times,
  4129. filepositions: filepositions
  4130. };
  4131. }
  4132. }, {
  4133. key: '_parseAudioData',
  4134. value: function _parseAudioData(arrayBuffer, dataOffset, dataSize, tagTimestamp) {
  4135. if (dataSize <= 1) {
  4136. _logger2.default.w(this.TAG, 'Flv: Invalid audio packet, missing SoundData payload!');
  4137. return;
  4138. }
  4139. if (this._hasAudioFlagOverrided === true && this._hasAudio === false) {
  4140. // If hasAudio: false indicated explicitly in MediaDataSource,
  4141. // Ignore all the audio packets
  4142. return;
  4143. }
  4144. var le = this._littleEndian;
  4145. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  4146. var soundSpec = v.getUint8(0);
  4147. var soundFormat = soundSpec >>> 4;
  4148. if (soundFormat !== 2 && soundFormat !== 10) {
  4149. // MP3 or AAC
  4150. this._onError(_demuxErrors2.default.CODEC_UNSUPPORTED, 'Flv: Unsupported audio codec idx: ' + soundFormat);
  4151. return;
  4152. }
  4153. var soundRate = 0;
  4154. var soundRateIndex = (soundSpec & 12) >>> 2;
  4155. if (soundRateIndex >= 0 && soundRateIndex <= 4) {
  4156. soundRate = this._flvSoundRateTable[soundRateIndex];
  4157. } else {
  4158. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid audio sample rate idx: ' + soundRateIndex);
  4159. return;
  4160. }
  4161. var soundSize = (soundSpec & 2) >>> 1; // unused
  4162. var soundType = soundSpec & 1;
  4163. var meta = this._audioMetadata;
  4164. var track = this._audioTrack;
  4165. if (!meta) {
  4166. if (this._hasAudio === false && this._hasAudioFlagOverrided === false) {
  4167. this._hasAudio = true;
  4168. this._mediaInfo.hasAudio = true;
  4169. }
  4170. // initial metadata
  4171. meta = this._audioMetadata = {};
  4172. meta.type = 'audio';
  4173. meta.id = track.id;
  4174. meta.timescale = this._timescale;
  4175. meta.duration = this._duration;
  4176. meta.audioSampleRate = soundRate;
  4177. meta.channelCount = soundType === 0 ? 1 : 2;
  4178. }
  4179. if (soundFormat === 10) {
  4180. // AAC
  4181. var aacData = this._parseAACAudioData(arrayBuffer, dataOffset + 1, dataSize - 1);
  4182. if (aacData == undefined) {
  4183. return;
  4184. }
  4185. if (aacData.packetType === 0) {
  4186. // AAC sequence header (AudioSpecificConfig)
  4187. if (meta.config) {
  4188. _logger2.default.w(this.TAG, 'Found another AudioSpecificConfig!');
  4189. }
  4190. var misc = aacData.data;
  4191. meta.audioSampleRate = misc.samplingRate;
  4192. meta.channelCount = misc.channelCount;
  4193. meta.codec = misc.codec;
  4194. meta.originalCodec = misc.originalCodec;
  4195. meta.config = misc.config;
  4196. // The decode result of an aac sample is 1024 PCM samples
  4197. meta.refSampleDuration = 1024 / meta.audioSampleRate * meta.timescale;
  4198. _logger2.default.v(this.TAG, 'Parsed AudioSpecificConfig');
  4199. if (this._isInitialMetadataDispatched()) {
  4200. // Non-initial metadata, force dispatch (or flush) parsed frames to remuxer
  4201. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  4202. this._onDataAvailable(this._audioTrack, this._videoTrack);
  4203. }
  4204. } else {
  4205. this._audioInitialMetadataDispatched = true;
  4206. }
  4207. // then notify new metadata
  4208. this._dispatch = false;
  4209. this._onTrackMetadata('audio', meta);
  4210. var mi = this._mediaInfo;
  4211. mi.audioCodec = meta.originalCodec;
  4212. mi.audioSampleRate = meta.audioSampleRate;
  4213. mi.audioChannelCount = meta.channelCount;
  4214. if (mi.hasVideo) {
  4215. if (mi.videoCodec != null) {
  4216. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
  4217. }
  4218. } else {
  4219. mi.mimeType = 'video/x-flv; codecs="' + mi.audioCodec + '"';
  4220. }
  4221. if (mi.isComplete()) {
  4222. this._onMediaInfo(mi);
  4223. }
  4224. } else if (aacData.packetType === 1) {
  4225. // AAC raw frame data
  4226. var dts = this._timestampBase + tagTimestamp;
  4227. var aacSample = { unit: aacData.data, length: aacData.data.byteLength, dts: dts, pts: dts };
  4228. track.samples.push(aacSample);
  4229. track.length += aacData.data.length;
  4230. } else {
  4231. _logger2.default.e(this.TAG, 'Flv: Unsupported AAC data type ' + aacData.packetType);
  4232. }
  4233. } else if (soundFormat === 2) {
  4234. // MP3
  4235. if (!meta.codec) {
  4236. // We need metadata for mp3 audio track, extract info from frame header
  4237. var _misc = this._parseMP3AudioData(arrayBuffer, dataOffset + 1, dataSize - 1, true);
  4238. if (_misc == undefined) {
  4239. return;
  4240. }
  4241. meta.audioSampleRate = _misc.samplingRate;
  4242. meta.channelCount = _misc.channelCount;
  4243. meta.codec = _misc.codec;
  4244. meta.originalCodec = _misc.originalCodec;
  4245. // The decode result of an mp3 sample is 1152 PCM samples
  4246. meta.refSampleDuration = 1152 / meta.audioSampleRate * meta.timescale;
  4247. _logger2.default.v(this.TAG, 'Parsed MPEG Audio Frame Header');
  4248. this._audioInitialMetadataDispatched = true;
  4249. this._onTrackMetadata('audio', meta);
  4250. var _mi = this._mediaInfo;
  4251. _mi.audioCodec = meta.codec;
  4252. _mi.audioSampleRate = meta.audioSampleRate;
  4253. _mi.audioChannelCount = meta.channelCount;
  4254. _mi.audioDataRate = _misc.bitRate;
  4255. if (_mi.hasVideo) {
  4256. if (_mi.videoCodec != null) {
  4257. _mi.mimeType = 'video/x-flv; codecs="' + _mi.videoCodec + ',' + _mi.audioCodec + '"';
  4258. }
  4259. } else {
  4260. _mi.mimeType = 'video/x-flv; codecs="' + _mi.audioCodec + '"';
  4261. }
  4262. if (_mi.isComplete()) {
  4263. this._onMediaInfo(_mi);
  4264. }
  4265. }
  4266. // This packet is always a valid audio packet, extract it
  4267. var data = this._parseMP3AudioData(arrayBuffer, dataOffset + 1, dataSize - 1, false);
  4268. if (data == undefined) {
  4269. return;
  4270. }
  4271. var _dts = this._timestampBase + tagTimestamp;
  4272. var mp3Sample = { unit: data, length: data.byteLength, dts: _dts, pts: _dts };
  4273. track.samples.push(mp3Sample);
  4274. track.length += data.length;
  4275. }
  4276. }
  4277. }, {
  4278. key: '_parseAACAudioData',
  4279. value: function _parseAACAudioData(arrayBuffer, dataOffset, dataSize) {
  4280. if (dataSize <= 1) {
  4281. _logger2.default.w(this.TAG, 'Flv: Invalid AAC packet, missing AACPacketType or/and Data!');
  4282. return;
  4283. }
  4284. var result = {};
  4285. var array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  4286. result.packetType = array[0];
  4287. if (array[0] === 0) {
  4288. result.data = this._parseAACAudioSpecificConfig(arrayBuffer, dataOffset + 1, dataSize - 1);
  4289. } else {
  4290. result.data = array.subarray(1);
  4291. }
  4292. return result;
  4293. }
  4294. }, {
  4295. key: '_parseAACAudioSpecificConfig',
  4296. value: function _parseAACAudioSpecificConfig(arrayBuffer, dataOffset, dataSize) {
  4297. var array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  4298. var config = null;
  4299. /* Audio Object Type:
  4300. 0: Null
  4301. 1: AAC Main
  4302. 2: AAC LC
  4303. 3: AAC SSR (Scalable Sample Rate)
  4304. 4: AAC LTP (Long Term Prediction)
  4305. 5: HE-AAC / SBR (Spectral Band Replication)
  4306. 6: AAC Scalable
  4307. */
  4308. var audioObjectType = 0;
  4309. var originalAudioObjectType = 0;
  4310. var audioExtensionObjectType = null;
  4311. var samplingIndex = 0;
  4312. var extensionSamplingIndex = null;
  4313. // 5 bits
  4314. audioObjectType = originalAudioObjectType = array[0] >>> 3;
  4315. // 4 bits
  4316. samplingIndex = (array[0] & 0x07) << 1 | array[1] >>> 7;
  4317. if (samplingIndex < 0 || samplingIndex >= this._mpegSamplingRates.length) {
  4318. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: AAC invalid sampling frequency index!');
  4319. return;
  4320. }
  4321. var samplingFrequence = this._mpegSamplingRates[samplingIndex];
  4322. // 4 bits
  4323. var channelConfig = (array[1] & 0x78) >>> 3;
  4324. if (channelConfig < 0 || channelConfig >= 8) {
  4325. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: AAC invalid channel configuration');
  4326. return;
  4327. }
  4328. if (audioObjectType === 5) {
  4329. // HE-AAC?
  4330. // 4 bits
  4331. extensionSamplingIndex = (array[1] & 0x07) << 1 | array[2] >>> 7;
  4332. // 5 bits
  4333. audioExtensionObjectType = (array[2] & 0x7C) >>> 2;
  4334. }
  4335. // workarounds for various browsers
  4336. var userAgent = self.navigator.userAgent.toLowerCase();
  4337. if (userAgent.indexOf('firefox') !== -1) {
  4338. // firefox: use SBR (HE-AAC) if freq less than 24kHz
  4339. if (samplingIndex >= 6) {
  4340. audioObjectType = 5;
  4341. config = new Array(4);
  4342. extensionSamplingIndex = samplingIndex - 3;
  4343. } else {
  4344. // use LC-AAC
  4345. audioObjectType = 2;
  4346. config = new Array(2);
  4347. extensionSamplingIndex = samplingIndex;
  4348. }
  4349. } else if (userAgent.indexOf('android') !== -1) {
  4350. // android: always use LC-AAC
  4351. audioObjectType = 2;
  4352. config = new Array(2);
  4353. extensionSamplingIndex = samplingIndex;
  4354. } else {
  4355. // for other browsers, e.g. chrome...
  4356. // Always use HE-AAC to make it easier to switch aac codec profile
  4357. audioObjectType = 5;
  4358. extensionSamplingIndex = samplingIndex;
  4359. config = new Array(4);
  4360. if (samplingIndex >= 6) {
  4361. extensionSamplingIndex = samplingIndex - 3;
  4362. } else if (channelConfig === 1) {
  4363. // Mono channel
  4364. audioObjectType = 2;
  4365. config = new Array(2);
  4366. extensionSamplingIndex = samplingIndex;
  4367. }
  4368. }
  4369. config[0] = audioObjectType << 3;
  4370. config[0] |= (samplingIndex & 0x0F) >>> 1;
  4371. config[1] = (samplingIndex & 0x0F) << 7;
  4372. config[1] |= (channelConfig & 0x0F) << 3;
  4373. if (audioObjectType === 5) {
  4374. config[1] |= (extensionSamplingIndex & 0x0F) >>> 1;
  4375. config[2] = (extensionSamplingIndex & 0x01) << 7;
  4376. // extended audio object type: force to 2 (LC-AAC)
  4377. config[2] |= 2 << 2;
  4378. config[3] = 0;
  4379. }
  4380. return {
  4381. config: config,
  4382. samplingRate: samplingFrequence,
  4383. channelCount: channelConfig,
  4384. codec: 'mp4a.40.' + audioObjectType,
  4385. originalCodec: 'mp4a.40.' + originalAudioObjectType
  4386. };
  4387. }
  4388. }, {
  4389. key: '_parseMP3AudioData',
  4390. value: function _parseMP3AudioData(arrayBuffer, dataOffset, dataSize, requestHeader) {
  4391. if (dataSize < 4) {
  4392. _logger2.default.w(this.TAG, 'Flv: Invalid MP3 packet, header missing!');
  4393. return;
  4394. }
  4395. var le = this._littleEndian;
  4396. var array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  4397. var result = null;
  4398. if (requestHeader) {
  4399. if (array[0] !== 0xFF) {
  4400. return;
  4401. }
  4402. var ver = array[1] >>> 3 & 0x03;
  4403. var layer = (array[1] & 0x06) >> 1;
  4404. var bitrate_index = (array[2] & 0xF0) >>> 4;
  4405. var sampling_freq_index = (array[2] & 0x0C) >>> 2;
  4406. var channel_mode = array[3] >>> 6 & 0x03;
  4407. var channel_count = channel_mode !== 3 ? 2 : 1;
  4408. var sample_rate = 0;
  4409. var bit_rate = 0;
  4410. var object_type = 34; // Layer-3, listed in MPEG-4 Audio Object Types
  4411. var codec = 'mp3';
  4412. switch (ver) {
  4413. case 0:
  4414. // MPEG 2.5
  4415. sample_rate = this._mpegAudioV25SampleRateTable[sampling_freq_index];
  4416. break;
  4417. case 2:
  4418. // MPEG 2
  4419. sample_rate = this._mpegAudioV20SampleRateTable[sampling_freq_index];
  4420. break;
  4421. case 3:
  4422. // MPEG 1
  4423. sample_rate = this._mpegAudioV10SampleRateTable[sampling_freq_index];
  4424. break;
  4425. }
  4426. switch (layer) {
  4427. case 1:
  4428. // Layer 3
  4429. object_type = 34;
  4430. if (bitrate_index < this._mpegAudioL3BitRateTable.length) {
  4431. bit_rate = this._mpegAudioL3BitRateTable[bitrate_index];
  4432. }
  4433. break;
  4434. case 2:
  4435. // Layer 2
  4436. object_type = 33;
  4437. if (bitrate_index < this._mpegAudioL2BitRateTable.length) {
  4438. bit_rate = this._mpegAudioL2BitRateTable[bitrate_index];
  4439. }
  4440. break;
  4441. case 3:
  4442. // Layer 1
  4443. object_type = 32;
  4444. if (bitrate_index < this._mpegAudioL1BitRateTable.length) {
  4445. bit_rate = this._mpegAudioL1BitRateTable[bitrate_index];
  4446. }
  4447. break;
  4448. }
  4449. result = {
  4450. bitRate: bit_rate,
  4451. samplingRate: sample_rate,
  4452. channelCount: channel_count,
  4453. codec: codec,
  4454. originalCodec: codec
  4455. };
  4456. } else {
  4457. result = array;
  4458. }
  4459. return result;
  4460. }
  4461. }, {
  4462. key: '_parseVideoData',
  4463. value: function _parseVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition) {
  4464. if (dataSize <= 1) {
  4465. _logger2.default.w(this.TAG, 'Flv: Invalid video packet, missing VideoData payload!');
  4466. return;
  4467. }
  4468. if (this._hasVideoFlagOverrided === true && this._hasVideo === false) {
  4469. // If hasVideo: false indicated explicitly in MediaDataSource,
  4470. // Ignore all the video packets
  4471. return;
  4472. }
  4473. var spec = new Uint8Array(arrayBuffer, dataOffset, dataSize)[0];
  4474. var frameType = (spec & 240) >>> 4;
  4475. var codecId = spec & 15;
  4476. if (codecId !== 7) {
  4477. this._onError(_demuxErrors2.default.CODEC_UNSUPPORTED, 'Flv: Unsupported codec in video frame: ' + codecId);
  4478. return;
  4479. }
  4480. this._parseAVCVideoPacket(arrayBuffer, dataOffset + 1, dataSize - 1, tagTimestamp, tagPosition, frameType);
  4481. }
  4482. }, {
  4483. key: '_parseAVCVideoPacket',
  4484. value: function _parseAVCVideoPacket(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType) {
  4485. if (dataSize < 4) {
  4486. _logger2.default.w(this.TAG, 'Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime');
  4487. return;
  4488. }
  4489. var le = this._littleEndian;
  4490. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  4491. var packetType = v.getUint8(0);
  4492. var cts_unsigned = v.getUint32(0, !le) & 0x00FFFFFF;
  4493. var cts = cts_unsigned << 8 >> 8; // convert to 24-bit signed int
  4494. if (packetType === 0) {
  4495. // AVCDecoderConfigurationRecord
  4496. this._parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset + 4, dataSize - 4);
  4497. } else if (packetType === 1) {
  4498. // One or more Nalus
  4499. this._parseAVCVideoData(arrayBuffer, dataOffset + 4, dataSize - 4, tagTimestamp, tagPosition, frameType, cts);
  4500. } else if (packetType === 2) {
  4501. // empty, AVC end of sequence
  4502. } else {
  4503. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid video packet type ' + packetType);
  4504. return;
  4505. }
  4506. }
  4507. }, {
  4508. key: '_parseAVCDecoderConfigurationRecord',
  4509. value: function _parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset, dataSize) {
  4510. if (dataSize < 7) {
  4511. _logger2.default.w(this.TAG, 'Flv: Invalid AVCDecoderConfigurationRecord, lack of data!');
  4512. return;
  4513. }
  4514. var meta = this._videoMetadata;
  4515. var track = this._videoTrack;
  4516. var le = this._littleEndian;
  4517. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  4518. if (!meta) {
  4519. if (this._hasVideo === false && this._hasVideoFlagOverrided === false) {
  4520. this._hasVideo = true;
  4521. this._mediaInfo.hasVideo = true;
  4522. }
  4523. meta = this._videoMetadata = {};
  4524. meta.type = 'video';
  4525. meta.id = track.id;
  4526. meta.timescale = this._timescale;
  4527. meta.duration = this._duration;
  4528. } else {
  4529. if (typeof meta.avcc !== 'undefined') {
  4530. _logger2.default.w(this.TAG, 'Found another AVCDecoderConfigurationRecord!');
  4531. }
  4532. }
  4533. var version = v.getUint8(0); // configurationVersion
  4534. var avcProfile = v.getUint8(1); // avcProfileIndication
  4535. var profileCompatibility = v.getUint8(2); // profile_compatibility
  4536. var avcLevel = v.getUint8(3); // AVCLevelIndication
  4537. if (version !== 1 || avcProfile === 0) {
  4538. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord');
  4539. return;
  4540. }
  4541. this._naluLengthSize = (v.getUint8(4) & 3) + 1; // lengthSizeMinusOne
  4542. if (this._naluLengthSize !== 3 && this._naluLengthSize !== 4) {
  4543. // holy shit!!!
  4544. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Strange NaluLengthSizeMinusOne: ' + (this._naluLengthSize - 1));
  4545. return;
  4546. }
  4547. var spsCount = v.getUint8(5) & 31; // numOfSequenceParameterSets
  4548. if (spsCount === 0) {
  4549. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord: No SPS');
  4550. return;
  4551. } else if (spsCount > 1) {
  4552. _logger2.default.w(this.TAG, 'Flv: Strange AVCDecoderConfigurationRecord: SPS Count = ' + spsCount);
  4553. }
  4554. var offset = 6;
  4555. for (var i = 0; i < spsCount; i++) {
  4556. var len = v.getUint16(offset, !le); // sequenceParameterSetLength
  4557. offset += 2;
  4558. if (len === 0) {
  4559. continue;
  4560. }
  4561. // Notice: Nalu without startcode header (00 00 00 01)
  4562. var sps = new Uint8Array(arrayBuffer, dataOffset + offset, len);
  4563. offset += len;
  4564. var config = _spsParser2.default.parseSPS(sps);
  4565. if (i !== 0) {
  4566. // ignore other sps's config
  4567. continue;
  4568. }
  4569. meta.codecWidth = config.codec_size.width;
  4570. meta.codecHeight = config.codec_size.height;
  4571. meta.presentWidth = config.present_size.width;
  4572. meta.presentHeight = config.present_size.height;
  4573. meta.profile = config.profile_string;
  4574. meta.level = config.level_string;
  4575. meta.bitDepth = config.bit_depth;
  4576. meta.chromaFormat = config.chroma_format;
  4577. meta.sarRatio = config.sar_ratio;
  4578. meta.frameRate = config.frame_rate;
  4579. if (config.frame_rate.fixed === false || config.frame_rate.fps_num === 0 || config.frame_rate.fps_den === 0) {
  4580. meta.frameRate = this._referenceFrameRate;
  4581. }
  4582. var fps_den = meta.frameRate.fps_den;
  4583. var fps_num = meta.frameRate.fps_num;
  4584. meta.refSampleDuration = meta.timescale * (fps_den / fps_num);
  4585. var codecArray = sps.subarray(1, 4);
  4586. var codecString = 'avc1.';
  4587. for (var j = 0; j < 3; j++) {
  4588. var h = codecArray[j].toString(16);
  4589. if (h.length < 2) {
  4590. h = '0' + h;
  4591. }
  4592. codecString += h;
  4593. }
  4594. meta.codec = codecString;
  4595. var mi = this._mediaInfo;
  4596. mi.width = meta.codecWidth;
  4597. mi.height = meta.codecHeight;
  4598. mi.fps = meta.frameRate.fps;
  4599. mi.profile = meta.profile;
  4600. mi.level = meta.level;
  4601. mi.refFrames = config.ref_frames;
  4602. mi.chromaFormat = config.chroma_format_string;
  4603. mi.sarNum = meta.sarRatio.width;
  4604. mi.sarDen = meta.sarRatio.height;
  4605. mi.videoCodec = codecString;
  4606. if (mi.hasAudio) {
  4607. if (mi.audioCodec != null) {
  4608. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
  4609. }
  4610. } else {
  4611. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + '"';
  4612. }
  4613. if (mi.isComplete()) {
  4614. this._onMediaInfo(mi);
  4615. }
  4616. }
  4617. var ppsCount = v.getUint8(offset); // numOfPictureParameterSets
  4618. if (ppsCount === 0) {
  4619. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord: No PPS');
  4620. return;
  4621. } else if (ppsCount > 1) {
  4622. _logger2.default.w(this.TAG, 'Flv: Strange AVCDecoderConfigurationRecord: PPS Count = ' + ppsCount);
  4623. }
  4624. offset++;
  4625. for (var _i = 0; _i < ppsCount; _i++) {
  4626. var _len = v.getUint16(offset, !le); // pictureParameterSetLength
  4627. offset += 2;
  4628. if (_len === 0) {
  4629. continue;
  4630. }
  4631. // pps is useless for extracting video information
  4632. offset += _len;
  4633. }
  4634. meta.avcc = new Uint8Array(dataSize);
  4635. meta.avcc.set(new Uint8Array(arrayBuffer, dataOffset, dataSize), 0);
  4636. _logger2.default.v(this.TAG, 'Parsed AVCDecoderConfigurationRecord');
  4637. if (this._isInitialMetadataDispatched()) {
  4638. // flush parsed frames
  4639. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  4640. this._onDataAvailable(this._audioTrack, this._videoTrack);
  4641. }
  4642. } else {
  4643. this._videoInitialMetadataDispatched = true;
  4644. }
  4645. // notify new metadata
  4646. this._dispatch = false;
  4647. this._onTrackMetadata('video', meta);
  4648. }
  4649. }, {
  4650. key: '_parseAVCVideoData',
  4651. value: function _parseAVCVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType, cts) {
  4652. var le = this._littleEndian;
  4653. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  4654. var units = [],
  4655. length = 0;
  4656. var offset = 0;
  4657. var lengthSize = this._naluLengthSize;
  4658. var dts = this._timestampBase + tagTimestamp;
  4659. var keyframe = frameType === 1; // from FLV Frame Type constants
  4660. while (offset < dataSize) {
  4661. if (offset + 4 >= dataSize) {
  4662. _logger2.default.w(this.TAG, 'Malformed Nalu near timestamp ' + dts + ', offset = ' + offset + ', dataSize = ' + dataSize);
  4663. break; // data not enough for next Nalu
  4664. }
  4665. // Nalu with length-header (AVC1)
  4666. var naluSize = v.getUint32(offset, !le); // Big-Endian read
  4667. if (lengthSize === 3) {
  4668. naluSize >>>= 8;
  4669. }
  4670. if (naluSize > dataSize - lengthSize) {
  4671. _logger2.default.w(this.TAG, 'Malformed Nalus near timestamp ' + dts + ', NaluSize > DataSize!');
  4672. return;
  4673. }
  4674. var unitType = v.getUint8(offset + lengthSize) & 0x1F;
  4675. if (unitType === 5) {
  4676. // IDR
  4677. keyframe = true;
  4678. }
  4679. var data = new Uint8Array(arrayBuffer, dataOffset + offset, lengthSize + naluSize);
  4680. var unit = { type: unitType, data: data };
  4681. units.push(unit);
  4682. length += data.byteLength;
  4683. offset += lengthSize + naluSize;
  4684. }
  4685. if (units.length) {
  4686. var track = this._videoTrack;
  4687. var avcSample = {
  4688. units: units,
  4689. length: length,
  4690. isKeyframe: keyframe,
  4691. dts: dts,
  4692. cts: cts,
  4693. pts: dts + cts
  4694. };
  4695. if (keyframe) {
  4696. avcSample.fileposition = tagPosition;
  4697. }
  4698. track.samples.push(avcSample);
  4699. track.length += length;
  4700. }
  4701. }
  4702. }, {
  4703. key: 'onTrackMetadata',
  4704. get: function get() {
  4705. return this._onTrackMetadata;
  4706. },
  4707. set: function set(callback) {
  4708. this._onTrackMetadata = callback;
  4709. }
  4710. // prototype: function(mediaInfo: MediaInfo): void
  4711. }, {
  4712. key: 'onMediaInfo',
  4713. get: function get() {
  4714. return this._onMediaInfo;
  4715. },
  4716. set: function set(callback) {
  4717. this._onMediaInfo = callback;
  4718. }
  4719. // prototype: function(type: number, info: string): void
  4720. }, {
  4721. key: 'onError',
  4722. get: function get() {
  4723. return this._onError;
  4724. },
  4725. set: function set(callback) {
  4726. this._onError = callback;
  4727. }
  4728. // prototype: function(videoTrack: any, audioTrack: any): void
  4729. }, {
  4730. key: 'onDataAvailable',
  4731. get: function get() {
  4732. return this._onDataAvailable;
  4733. },
  4734. set: function set(callback) {
  4735. this._onDataAvailable = callback;
  4736. }
  4737. // timestamp base for output samples, must be in milliseconds
  4738. }, {
  4739. key: 'timestampBase',
  4740. get: function get() {
  4741. return this._timestampBase;
  4742. },
  4743. set: function set(base) {
  4744. this._timestampBase = base;
  4745. }
  4746. }, {
  4747. key: 'overridedDuration',
  4748. get: function get() {
  4749. return this._duration;
  4750. }
  4751. // Force-override media duration. Must be in milliseconds, int32
  4752. ,
  4753. set: function set(duration) {
  4754. this._durationOverrided = true;
  4755. this._duration = duration;
  4756. this._mediaInfo.duration = duration;
  4757. }
  4758. // Force-override audio track present flag, boolean
  4759. }, {
  4760. key: 'overridedHasAudio',
  4761. set: function set(hasAudio) {
  4762. this._hasAudioFlagOverrided = true;
  4763. this._hasAudio = hasAudio;
  4764. this._mediaInfo.hasAudio = hasAudio;
  4765. }
  4766. // Force-override video track present flag, boolean
  4767. }, {
  4768. key: 'overridedHasVideo',
  4769. set: function set(hasVideo) {
  4770. this._hasVideoFlagOverrided = true;
  4771. this._hasVideo = hasVideo;
  4772. this._mediaInfo.hasVideo = hasVideo;
  4773. }
  4774. }], [{
  4775. key: 'probe',
  4776. value: function probe(buffer) {
  4777. var data = new Uint8Array(buffer);
  4778. var mismatch = { match: false };
  4779. if (data[0] !== 0x46 || data[1] !== 0x4C || data[2] !== 0x56 || data[3] !== 0x01) {
  4780. return mismatch;
  4781. }
  4782. var hasAudio = (data[4] & 4) >>> 2 !== 0;
  4783. var hasVideo = (data[4] & 1) !== 0;
  4784. var offset = ReadBig32(data, 5);
  4785. if (offset < 9) {
  4786. return mismatch;
  4787. }
  4788. return {
  4789. match: true,
  4790. consumed: offset,
  4791. dataOffset: offset,
  4792. hasAudioTrack: hasAudio,
  4793. hasVideoTrack: hasVideo
  4794. };
  4795. }
  4796. }]);
  4797. return FLVDemuxer;
  4798. }();
  4799. exports.default = FLVDemuxer;
  4800. },{"../core/media-info.js":7,"../utils/exception.js":40,"../utils/logger.js":41,"./amf-parser.js":15,"./demux-errors.js":16,"./sps-parser.js":19}],19:[function(_dereq_,module,exports){
  4801. 'use strict';
  4802. Object.defineProperty(exports, "__esModule", {
  4803. value: true
  4804. });
  4805. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  4806. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  4807. *
  4808. * @author zheng qian <xqq@xqq.im>
  4809. *
  4810. * Licensed under the Apache License, Version 2.0 (the "License");
  4811. * you may not use this file except in compliance with the License.
  4812. * You may obtain a copy of the License at
  4813. *
  4814. * http://www.apache.org/licenses/LICENSE-2.0
  4815. *
  4816. * Unless required by applicable law or agreed to in writing, software
  4817. * distributed under the License is distributed on an "AS IS" BASIS,
  4818. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4819. * See the License for the specific language governing permissions and
  4820. * limitations under the License.
  4821. */
  4822. var _expGolomb = _dereq_('./exp-golomb.js');
  4823. var _expGolomb2 = _interopRequireDefault(_expGolomb);
  4824. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  4825. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4826. var SPSParser = function () {
  4827. function SPSParser() {
  4828. _classCallCheck(this, SPSParser);
  4829. }
  4830. _createClass(SPSParser, null, [{
  4831. key: '_ebsp2rbsp',
  4832. value: function _ebsp2rbsp(uint8array) {
  4833. var src = uint8array;
  4834. var src_length = src.byteLength;
  4835. var dst = new Uint8Array(src_length);
  4836. var dst_idx = 0;
  4837. for (var i = 0; i < src_length; i++) {
  4838. if (i >= 2) {
  4839. // Unescape: Skip 0x03 after 00 00
  4840. if (src[i] === 0x03 && src[i - 1] === 0x00 && src[i - 2] === 0x00) {
  4841. continue;
  4842. }
  4843. }
  4844. dst[dst_idx] = src[i];
  4845. dst_idx++;
  4846. }
  4847. return new Uint8Array(dst.buffer, 0, dst_idx);
  4848. }
  4849. }, {
  4850. key: 'parseSPS',
  4851. value: function parseSPS(uint8array) {
  4852. var rbsp = SPSParser._ebsp2rbsp(uint8array);
  4853. var gb = new _expGolomb2.default(rbsp);
  4854. gb.readByte();
  4855. var profile_idc = gb.readByte(); // profile_idc
  4856. gb.readByte(); // constraint_set_flags[5] + reserved_zero[3]
  4857. var level_idc = gb.readByte(); // level_idc
  4858. gb.readUEG(); // seq_parameter_set_id
  4859. var profile_string = SPSParser.getProfileString(profile_idc);
  4860. var level_string = SPSParser.getLevelString(level_idc);
  4861. var chroma_format_idc = 1;
  4862. var chroma_format = 420;
  4863. var chroma_format_table = [0, 420, 422, 444];
  4864. var bit_depth = 8;
  4865. if (profile_idc === 100 || profile_idc === 110 || profile_idc === 122 || profile_idc === 244 || profile_idc === 44 || profile_idc === 83 || profile_idc === 86 || profile_idc === 118 || profile_idc === 128 || profile_idc === 138 || profile_idc === 144) {
  4866. chroma_format_idc = gb.readUEG();
  4867. if (chroma_format_idc === 3) {
  4868. gb.readBits(1); // separate_colour_plane_flag
  4869. }
  4870. if (chroma_format_idc <= 3) {
  4871. chroma_format = chroma_format_table[chroma_format_idc];
  4872. }
  4873. bit_depth = gb.readUEG() + 8; // bit_depth_luma_minus8
  4874. gb.readUEG(); // bit_depth_chroma_minus8
  4875. gb.readBits(1); // qpprime_y_zero_transform_bypass_flag
  4876. if (gb.readBool()) {
  4877. // seq_scaling_matrix_present_flag
  4878. var scaling_list_count = chroma_format_idc !== 3 ? 8 : 12;
  4879. for (var i = 0; i < scaling_list_count; i++) {
  4880. if (gb.readBool()) {
  4881. // seq_scaling_list_present_flag
  4882. if (i < 6) {
  4883. SPSParser._skipScalingList(gb, 16);
  4884. } else {
  4885. SPSParser._skipScalingList(gb, 64);
  4886. }
  4887. }
  4888. }
  4889. }
  4890. }
  4891. gb.readUEG(); // log2_max_frame_num_minus4
  4892. var pic_order_cnt_type = gb.readUEG();
  4893. if (pic_order_cnt_type === 0) {
  4894. gb.readUEG(); // log2_max_pic_order_cnt_lsb_minus_4
  4895. } else if (pic_order_cnt_type === 1) {
  4896. gb.readBits(1); // delta_pic_order_always_zero_flag
  4897. gb.readSEG(); // offset_for_non_ref_pic
  4898. gb.readSEG(); // offset_for_top_to_bottom_field
  4899. var num_ref_frames_in_pic_order_cnt_cycle = gb.readUEG();
  4900. for (var _i = 0; _i < num_ref_frames_in_pic_order_cnt_cycle; _i++) {
  4901. gb.readSEG(); // offset_for_ref_frame
  4902. }
  4903. }
  4904. var ref_frames = gb.readUEG(); // max_num_ref_frames
  4905. gb.readBits(1); // gaps_in_frame_num_value_allowed_flag
  4906. var pic_width_in_mbs_minus1 = gb.readUEG();
  4907. var pic_height_in_map_units_minus1 = gb.readUEG();
  4908. var frame_mbs_only_flag = gb.readBits(1);
  4909. if (frame_mbs_only_flag === 0) {
  4910. gb.readBits(1); // mb_adaptive_frame_field_flag
  4911. }
  4912. gb.readBits(1); // direct_8x8_inference_flag
  4913. var frame_crop_left_offset = 0;
  4914. var frame_crop_right_offset = 0;
  4915. var frame_crop_top_offset = 0;
  4916. var frame_crop_bottom_offset = 0;
  4917. var frame_cropping_flag = gb.readBool();
  4918. if (frame_cropping_flag) {
  4919. frame_crop_left_offset = gb.readUEG();
  4920. frame_crop_right_offset = gb.readUEG();
  4921. frame_crop_top_offset = gb.readUEG();
  4922. frame_crop_bottom_offset = gb.readUEG();
  4923. }
  4924. var sar_width = 1,
  4925. sar_height = 1;
  4926. var fps = 0,
  4927. fps_fixed = true,
  4928. fps_num = 0,
  4929. fps_den = 0;
  4930. var vui_parameters_present_flag = gb.readBool();
  4931. if (vui_parameters_present_flag) {
  4932. if (gb.readBool()) {
  4933. // aspect_ratio_info_present_flag
  4934. var aspect_ratio_idc = gb.readByte();
  4935. var sar_w_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2];
  4936. var sar_h_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
  4937. if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) {
  4938. sar_width = sar_w_table[aspect_ratio_idc - 1];
  4939. sar_height = sar_h_table[aspect_ratio_idc - 1];
  4940. } else if (aspect_ratio_idc === 255) {
  4941. sar_width = gb.readByte() << 8 | gb.readByte();
  4942. sar_height = gb.readByte() << 8 | gb.readByte();
  4943. }
  4944. }
  4945. if (gb.readBool()) {
  4946. // overscan_info_present_flag
  4947. gb.readBool(); // overscan_appropriate_flag
  4948. }
  4949. if (gb.readBool()) {
  4950. // video_signal_type_present_flag
  4951. gb.readBits(4); // video_format & video_full_range_flag
  4952. if (gb.readBool()) {
  4953. // colour_description_present_flag
  4954. gb.readBits(24); // colour_primaries & transfer_characteristics & matrix_coefficients
  4955. }
  4956. }
  4957. if (gb.readBool()) {
  4958. // chroma_loc_info_present_flag
  4959. gb.readUEG(); // chroma_sample_loc_type_top_field
  4960. gb.readUEG(); // chroma_sample_loc_type_bottom_field
  4961. }
  4962. if (gb.readBool()) {
  4963. // timing_info_present_flag
  4964. var num_units_in_tick = gb.readBits(32);
  4965. var time_scale = gb.readBits(32);
  4966. fps_fixed = gb.readBool(); // fixed_frame_rate_flag
  4967. fps_num = time_scale;
  4968. fps_den = num_units_in_tick * 2;
  4969. fps = fps_num / fps_den;
  4970. }
  4971. }
  4972. var sarScale = 1;
  4973. if (sar_width !== 1 || sar_height !== 1) {
  4974. sarScale = sar_width / sar_height;
  4975. }
  4976. var crop_unit_x = 0,
  4977. crop_unit_y = 0;
  4978. if (chroma_format_idc === 0) {
  4979. crop_unit_x = 1;
  4980. crop_unit_y = 2 - frame_mbs_only_flag;
  4981. } else {
  4982. var sub_wc = chroma_format_idc === 3 ? 1 : 2;
  4983. var sub_hc = chroma_format_idc === 1 ? 2 : 1;
  4984. crop_unit_x = sub_wc;
  4985. crop_unit_y = sub_hc * (2 - frame_mbs_only_flag);
  4986. }
  4987. var codec_width = (pic_width_in_mbs_minus1 + 1) * 16;
  4988. var codec_height = (2 - frame_mbs_only_flag) * ((pic_height_in_map_units_minus1 + 1) * 16);
  4989. codec_width -= (frame_crop_left_offset + frame_crop_right_offset) * crop_unit_x;
  4990. codec_height -= (frame_crop_top_offset + frame_crop_bottom_offset) * crop_unit_y;
  4991. var present_width = Math.ceil(codec_width * sarScale);
  4992. gb.destroy();
  4993. gb = null;
  4994. return {
  4995. profile_string: profile_string, // baseline, high, high10, ...
  4996. level_string: level_string, // 3, 3.1, 4, 4.1, 5, 5.1, ...
  4997. bit_depth: bit_depth, // 8bit, 10bit, ...
  4998. ref_frames: ref_frames,
  4999. chroma_format: chroma_format, // 4:2:0, 4:2:2, ...
  5000. chroma_format_string: SPSParser.getChromaFormatString(chroma_format),
  5001. frame_rate: {
  5002. fixed: fps_fixed,
  5003. fps: fps,
  5004. fps_den: fps_den,
  5005. fps_num: fps_num
  5006. },
  5007. sar_ratio: {
  5008. width: sar_width,
  5009. height: sar_height
  5010. },
  5011. codec_size: {
  5012. width: codec_width,
  5013. height: codec_height
  5014. },
  5015. present_size: {
  5016. width: present_width,
  5017. height: codec_height
  5018. }
  5019. };
  5020. }
  5021. }, {
  5022. key: '_skipScalingList',
  5023. value: function _skipScalingList(gb, count) {
  5024. var last_scale = 8,
  5025. next_scale = 8;
  5026. var delta_scale = 0;
  5027. for (var i = 0; i < count; i++) {
  5028. if (next_scale !== 0) {
  5029. delta_scale = gb.readSEG();
  5030. next_scale = (last_scale + delta_scale + 256) % 256;
  5031. }
  5032. last_scale = next_scale === 0 ? last_scale : next_scale;
  5033. }
  5034. }
  5035. }, {
  5036. key: 'getProfileString',
  5037. value: function getProfileString(profile_idc) {
  5038. switch (profile_idc) {
  5039. case 66:
  5040. return 'Baseline';
  5041. case 77:
  5042. return 'Main';
  5043. case 88:
  5044. return 'Extended';
  5045. case 100:
  5046. return 'High';
  5047. case 110:
  5048. return 'High10';
  5049. case 122:
  5050. return 'High422';
  5051. case 244:
  5052. return 'High444';
  5053. default:
  5054. return 'Unknown';
  5055. }
  5056. }
  5057. }, {
  5058. key: 'getLevelString',
  5059. value: function getLevelString(level_idc) {
  5060. return (level_idc / 10).toFixed(1);
  5061. }
  5062. }, {
  5063. key: 'getChromaFormatString',
  5064. value: function getChromaFormatString(chroma) {
  5065. switch (chroma) {
  5066. case 420:
  5067. return '4:2:0';
  5068. case 422:
  5069. return '4:2:2';
  5070. case 444:
  5071. return '4:4:4';
  5072. default:
  5073. return 'Unknown';
  5074. }
  5075. }
  5076. }]);
  5077. return SPSParser;
  5078. }();
  5079. exports.default = SPSParser;
  5080. },{"./exp-golomb.js":17}],20:[function(_dereq_,module,exports){
  5081. 'use strict';
  5082. Object.defineProperty(exports, "__esModule", {
  5083. value: true
  5084. });
  5085. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /*
  5086. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  5087. *
  5088. * @author zheng qian <xqq@xqq.im>
  5089. *
  5090. * Licensed under the Apache License, Version 2.0 (the "License");
  5091. * you may not use this file except in compliance with the License.
  5092. * You may obtain a copy of the License at
  5093. *
  5094. * http://www.apache.org/licenses/LICENSE-2.0
  5095. *
  5096. * Unless required by applicable law or agreed to in writing, software
  5097. * distributed under the License is distributed on an "AS IS" BASIS,
  5098. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5099. * See the License for the specific language governing permissions and
  5100. * limitations under the License.
  5101. */
  5102. var _polyfill = _dereq_('./utils/polyfill.js');
  5103. var _polyfill2 = _interopRequireDefault(_polyfill);
  5104. var _features = _dereq_('./core/features.js');
  5105. var _features2 = _interopRequireDefault(_features);
  5106. var _flvPlayer = _dereq_('./player/flv-player.js');
  5107. var _flvPlayer2 = _interopRequireDefault(_flvPlayer);
  5108. var _nativePlayer = _dereq_('./player/native-player.js');
  5109. var _nativePlayer2 = _interopRequireDefault(_nativePlayer);
  5110. var _playerEvents = _dereq_('./player/player-events.js');
  5111. var _playerEvents2 = _interopRequireDefault(_playerEvents);
  5112. var _playerErrors = _dereq_('./player/player-errors.js');
  5113. var _loggingControl = _dereq_('./utils/logging-control.js');
  5114. var _loggingControl2 = _interopRequireDefault(_loggingControl);
  5115. var _exception = _dereq_('./utils/exception.js');
  5116. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5117. // here are all the interfaces
  5118. // install polyfills
  5119. _polyfill2.default.install();
  5120. // factory method
  5121. function createPlayer(mediaDataSource, optionalConfig) {
  5122. var mds = mediaDataSource;
  5123. if (mds == null || (typeof mds === 'undefined' ? 'undefined' : _typeof(mds)) !== 'object') {
  5124. throw new _exception.InvalidArgumentException('MediaDataSource must be an javascript object!');
  5125. }
  5126. if (!mds.hasOwnProperty('type')) {
  5127. throw new _exception.InvalidArgumentException('MediaDataSource must has type field to indicate video file type!');
  5128. }
  5129. switch (mds.type) {
  5130. case 'flv':
  5131. return new _flvPlayer2.default(mds, optionalConfig);
  5132. default:
  5133. return new _nativePlayer2.default(mds, optionalConfig);
  5134. }
  5135. }
  5136. // feature detection
  5137. function isSupported() {
  5138. return _features2.default.supportMSEH264Playback();
  5139. }
  5140. function getFeatureList() {
  5141. return _features2.default.getFeatureList();
  5142. }
  5143. // interfaces
  5144. var flvjs = {};
  5145. flvjs.createPlayer = createPlayer;
  5146. flvjs.isSupported = isSupported;
  5147. flvjs.getFeatureList = getFeatureList;
  5148. flvjs.Events = _playerEvents2.default;
  5149. flvjs.ErrorTypes = _playerErrors.ErrorTypes;
  5150. flvjs.ErrorDetails = _playerErrors.ErrorDetails;
  5151. flvjs.FlvPlayer = _flvPlayer2.default;
  5152. flvjs.NativePlayer = _nativePlayer2.default;
  5153. flvjs.LoggingControl = _loggingControl2.default;
  5154. Object.defineProperty(flvjs, 'version', {
  5155. enumerable: true,
  5156. get: function get() {
  5157. // replaced by browserify-versionify transform
  5158. return '1.4.0';
  5159. }
  5160. });
  5161. exports.default = flvjs;
  5162. },{"./core/features.js":6,"./player/flv-player.js":32,"./player/native-player.js":33,"./player/player-errors.js":34,"./player/player-events.js":35,"./utils/exception.js":40,"./utils/logging-control.js":42,"./utils/polyfill.js":43}],21:[function(_dereq_,module,exports){
  5163. 'use strict';
  5164. // entry/index file
  5165. // make it compatible with browserify's umd wrapper
  5166. module.exports = _dereq_('./flv.js').default;
  5167. },{"./flv.js":20}],22:[function(_dereq_,module,exports){
  5168. 'use strict';
  5169. Object.defineProperty(exports, "__esModule", {
  5170. value: true
  5171. });
  5172. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  5173. var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
  5174. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  5175. var _logger = _dereq_('../utils/logger.js');
  5176. var _logger2 = _interopRequireDefault(_logger);
  5177. var _browser = _dereq_('../utils/browser.js');
  5178. var _browser2 = _interopRequireDefault(_browser);
  5179. var _loader = _dereq_('./loader.js');
  5180. var _exception = _dereq_('../utils/exception.js');
  5181. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5182. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5183. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  5184. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*
  5185. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  5186. *
  5187. * @author zheng qian <xqq@xqq.im>
  5188. *
  5189. * Licensed under the Apache License, Version 2.0 (the "License");
  5190. * you may not use this file except in compliance with the License.
  5191. * You may obtain a copy of the License at
  5192. *
  5193. * http://www.apache.org/licenses/LICENSE-2.0
  5194. *
  5195. * Unless required by applicable law or agreed to in writing, software
  5196. * distributed under the License is distributed on an "AS IS" BASIS,
  5197. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5198. * See the License for the specific language governing permissions and
  5199. * limitations under the License.
  5200. */
  5201. /* fetch + stream IO loader. Currently working on chrome 43+.
  5202. * fetch provides a better alternative http API to XMLHttpRequest
  5203. *
  5204. * fetch spec https://fetch.spec.whatwg.org/
  5205. * stream spec https://streams.spec.whatwg.org/
  5206. */
  5207. var FetchStreamLoader = function (_BaseLoader) {
  5208. _inherits(FetchStreamLoader, _BaseLoader);
  5209. _createClass(FetchStreamLoader, null, [{
  5210. key: 'isSupported',
  5211. value: function isSupported() {
  5212. try {
  5213. // fetch + stream is broken on Microsoft Edge. Disable before build 15048.
  5214. // see https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8196907/
  5215. // Fixed in Jan 10, 2017. Build 15048+ removed from blacklist.
  5216. var isWorkWellEdge = _browser2.default.msedge && _browser2.default.version.minor >= 15048;
  5217. var browserNotBlacklisted = _browser2.default.msedge ? isWorkWellEdge : true;
  5218. return self.fetch && self.ReadableStream && browserNotBlacklisted;
  5219. } catch (e) {
  5220. return false;
  5221. }
  5222. }
  5223. }]);
  5224. function FetchStreamLoader(seekHandler, config) {
  5225. _classCallCheck(this, FetchStreamLoader);
  5226. var _this = _possibleConstructorReturn(this, (FetchStreamLoader.__proto__ || Object.getPrototypeOf(FetchStreamLoader)).call(this, 'fetch-stream-loader'));
  5227. _this.TAG = 'FetchStreamLoader';
  5228. _this._seekHandler = seekHandler;
  5229. _this._config = config;
  5230. _this._needStash = true;
  5231. _this._requestAbort = false;
  5232. _this._contentLength = null;
  5233. _this._receivedLength = 0;
  5234. return _this;
  5235. }
  5236. _createClass(FetchStreamLoader, [{
  5237. key: 'destroy',
  5238. value: function destroy() {
  5239. if (this.isWorking()) {
  5240. this.abort();
  5241. }
  5242. _get(FetchStreamLoader.prototype.__proto__ || Object.getPrototypeOf(FetchStreamLoader.prototype), 'destroy', this).call(this);
  5243. }
  5244. }, {
  5245. key: 'open',
  5246. value: function open(dataSource, range) {
  5247. var _this2 = this;
  5248. this._dataSource = dataSource;
  5249. this._range = range;
  5250. var sourceURL = dataSource.url;
  5251. if (this._config.reuseRedirectedURL && dataSource.redirectedURL != undefined) {
  5252. sourceURL = dataSource.redirectedURL;
  5253. }
  5254. var seekConfig = this._seekHandler.getConfig(sourceURL, range);
  5255. var headers = new self.Headers();
  5256. if (_typeof(seekConfig.headers) === 'object') {
  5257. var configHeaders = seekConfig.headers;
  5258. for (var key in configHeaders) {
  5259. if (configHeaders.hasOwnProperty(key)) {
  5260. headers.append(key, configHeaders[key]);
  5261. }
  5262. }
  5263. }
  5264. var params = {
  5265. method: 'GET',
  5266. headers: headers,
  5267. mode: 'cors',
  5268. cache: 'default',
  5269. // The default policy of Fetch API in the whatwg standard
  5270. // Safari incorrectly indicates 'no-referrer' as default policy, fuck it
  5271. referrerPolicy: 'no-referrer-when-downgrade'
  5272. };
  5273. // cors is enabled by default
  5274. if (dataSource.cors === false) {
  5275. // no-cors means 'disregard cors policy', which can only be used in ServiceWorker
  5276. params.mode = 'same-origin';
  5277. }
  5278. // withCredentials is disabled by default
  5279. if (dataSource.withCredentials) {
  5280. params.credentials = 'include';
  5281. }
  5282. // referrerPolicy from config
  5283. if (dataSource.referrerPolicy) {
  5284. params.referrerPolicy = dataSource.referrerPolicy;
  5285. }
  5286. this._status = _loader.LoaderStatus.kConnecting;
  5287. self.fetch(seekConfig.url, params).then(function (res) {
  5288. if (_this2._requestAbort) {
  5289. _this2._requestAbort = false;
  5290. _this2._status = _loader.LoaderStatus.kIdle;
  5291. return;
  5292. }
  5293. if (res.ok && res.status >= 200 && res.status <= 299) {
  5294. if (res.url !== seekConfig.url) {
  5295. if (_this2._onURLRedirect) {
  5296. var redirectedURL = _this2._seekHandler.removeURLParameters(res.url);
  5297. _this2._onURLRedirect(redirectedURL);
  5298. }
  5299. }
  5300. var lengthHeader = res.headers.get('Content-Length');
  5301. if (lengthHeader != null) {
  5302. _this2._contentLength = parseInt(lengthHeader);
  5303. if (_this2._contentLength !== 0) {
  5304. if (_this2._onContentLengthKnown) {
  5305. _this2._onContentLengthKnown(_this2._contentLength);
  5306. }
  5307. }
  5308. }
  5309. return _this2._pump.call(_this2, res.body.getReader());
  5310. } else {
  5311. _this2._status = _loader.LoaderStatus.kError;
  5312. if (_this2._onError) {
  5313. _this2._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: res.status, msg: res.statusText });
  5314. } else {
  5315. throw new _exception.RuntimeException('FetchStreamLoader: Http code invalid, ' + res.status + ' ' + res.statusText);
  5316. }
  5317. }
  5318. }).catch(function (e) {
  5319. _this2._status = _loader.LoaderStatus.kError;
  5320. if (_this2._onError) {
  5321. _this2._onError(_loader.LoaderErrors.EXCEPTION, { code: -1, msg: e.message });
  5322. } else {
  5323. throw e;
  5324. }
  5325. });
  5326. }
  5327. }, {
  5328. key: 'abort',
  5329. value: function abort() {
  5330. this._requestAbort = true;
  5331. }
  5332. }, {
  5333. key: '_pump',
  5334. value: function _pump(reader) {
  5335. var _this3 = this;
  5336. // ReadableStreamReader
  5337. return reader.read().then(function (result) {
  5338. if (result.done) {
  5339. _this3._status = _loader.LoaderStatus.kComplete;
  5340. if (_this3._onComplete) {
  5341. _this3._onComplete(_this3._range.from, _this3._range.from + _this3._receivedLength - 1);
  5342. }
  5343. } else {
  5344. if (_this3._requestAbort === true) {
  5345. _this3._requestAbort = false;
  5346. _this3._status = _loader.LoaderStatus.kComplete;
  5347. return reader.cancel();
  5348. }
  5349. _this3._status = _loader.LoaderStatus.kBuffering;
  5350. var chunk = result.value.buffer;
  5351. var byteStart = _this3._range.from + _this3._receivedLength;
  5352. _this3._receivedLength += chunk.byteLength;
  5353. if (_this3._onDataArrival) {
  5354. _this3._onDataArrival(chunk, byteStart, _this3._receivedLength);
  5355. }
  5356. _this3._pump(reader);
  5357. }
  5358. }).catch(function (e) {
  5359. if (e.code === 11 && _browser2.default.msedge) {
  5360. // InvalidStateError on Microsoft Edge
  5361. // Workaround: Edge may throw InvalidStateError after ReadableStreamReader.cancel() call
  5362. // Ignore the unknown exception.
  5363. // Related issue: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/11265202/
  5364. return;
  5365. }
  5366. _this3._status = _loader.LoaderStatus.kError;
  5367. var type = 0;
  5368. var info = null;
  5369. if ((e.code === 19 || e.message === 'network error') && ( // NETWORK_ERR
  5370. _this3._contentLength === null || _this3._contentLength !== null && _this3._receivedLength < _this3._contentLength)) {
  5371. type = _loader.LoaderErrors.EARLY_EOF;
  5372. info = { code: e.code, msg: 'Fetch stream meet Early-EOF' };
  5373. } else {
  5374. type = _loader.LoaderErrors.EXCEPTION;
  5375. info = { code: e.code, msg: e.message };
  5376. }
  5377. if (_this3._onError) {
  5378. _this3._onError(type, info);
  5379. } else {
  5380. throw new _exception.RuntimeException(info.msg);
  5381. }
  5382. });
  5383. }
  5384. }]);
  5385. return FetchStreamLoader;
  5386. }(_loader.BaseLoader);
  5387. exports.default = FetchStreamLoader;
  5388. },{"../utils/browser.js":39,"../utils/exception.js":40,"../utils/logger.js":41,"./loader.js":24}],23:[function(_dereq_,module,exports){
  5389. 'use strict';
  5390. Object.defineProperty(exports, "__esModule", {
  5391. value: true
  5392. });
  5393. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  5394. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  5395. *
  5396. * @author zheng qian <xqq@xqq.im>
  5397. *
  5398. * Licensed under the Apache License, Version 2.0 (the "License");
  5399. * you may not use this file except in compliance with the License.
  5400. * You may obtain a copy of the License at
  5401. *
  5402. * http://www.apache.org/licenses/LICENSE-2.0
  5403. *
  5404. * Unless required by applicable law or agreed to in writing, software
  5405. * distributed under the License is distributed on an "AS IS" BASIS,
  5406. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5407. * See the License for the specific language governing permissions and
  5408. * limitations under the License.
  5409. */
  5410. var _logger = _dereq_('../utils/logger.js');
  5411. var _logger2 = _interopRequireDefault(_logger);
  5412. var _speedSampler = _dereq_('./speed-sampler.js');
  5413. var _speedSampler2 = _interopRequireDefault(_speedSampler);
  5414. var _loader = _dereq_('./loader.js');
  5415. var _fetchStreamLoader = _dereq_('./fetch-stream-loader.js');
  5416. var _fetchStreamLoader2 = _interopRequireDefault(_fetchStreamLoader);
  5417. var _xhrMozChunkedLoader = _dereq_('./xhr-moz-chunked-loader.js');
  5418. var _xhrMozChunkedLoader2 = _interopRequireDefault(_xhrMozChunkedLoader);
  5419. var _xhrMsstreamLoader = _dereq_('./xhr-msstream-loader.js');
  5420. var _xhrMsstreamLoader2 = _interopRequireDefault(_xhrMsstreamLoader);
  5421. var _xhrRangeLoader = _dereq_('./xhr-range-loader.js');
  5422. var _xhrRangeLoader2 = _interopRequireDefault(_xhrRangeLoader);
  5423. var _websocketLoader = _dereq_('./websocket-loader.js');
  5424. var _websocketLoader2 = _interopRequireDefault(_websocketLoader);
  5425. var _rangeSeekHandler = _dereq_('./range-seek-handler.js');
  5426. var _rangeSeekHandler2 = _interopRequireDefault(_rangeSeekHandler);
  5427. var _paramSeekHandler = _dereq_('./param-seek-handler.js');
  5428. var _paramSeekHandler2 = _interopRequireDefault(_paramSeekHandler);
  5429. var _exception = _dereq_('../utils/exception.js');
  5430. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5431. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5432. /**
  5433. * DataSource: {
  5434. * url: string,
  5435. * filesize: number,
  5436. * cors: boolean,
  5437. * withCredentials: boolean
  5438. * }
  5439. *
  5440. */
  5441. // Manage IO Loaders
  5442. var IOController = function () {
  5443. function IOController(dataSource, config, extraData) {
  5444. _classCallCheck(this, IOController);
  5445. this.TAG = 'IOController';
  5446. this._config = config;
  5447. this._extraData = extraData;
  5448. this._stashInitialSize = 1024 * 384; // default initial size: 384KB
  5449. if (config.stashInitialSize != undefined && config.stashInitialSize > 0) {
  5450. // apply from config
  5451. this._stashInitialSize = config.stashInitialSize;
  5452. }
  5453. this._stashUsed = 0;
  5454. this._stashSize = this._stashInitialSize;
  5455. this._bufferSize = 1024 * 1024 * 3; // initial size: 3MB
  5456. this._stashBuffer = new ArrayBuffer(this._bufferSize);
  5457. this._stashByteStart = 0;
  5458. this._enableStash = true;
  5459. if (config.enableStashBuffer === false) {
  5460. this._enableStash = false;
  5461. }
  5462. this._loader = null;
  5463. this._loaderClass = null;
  5464. this._seekHandler = null;
  5465. this._dataSource = dataSource;
  5466. this._isWebSocketURL = /wss?:\/\/(.+?)/.test(dataSource.url);
  5467. this._refTotalLength = dataSource.filesize ? dataSource.filesize : null;
  5468. this._totalLength = this._refTotalLength;
  5469. this._fullRequestFlag = false;
  5470. this._currentRange = null;
  5471. this._redirectedURL = null;
  5472. this._speedNormalized = 0;
  5473. this._speedSampler = new _speedSampler2.default();
  5474. this._speedNormalizeList = [64, 128, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096];
  5475. this._isEarlyEofReconnecting = false;
  5476. this._paused = false;
  5477. this._resumeFrom = 0;
  5478. this._onDataArrival = null;
  5479. this._onSeeked = null;
  5480. this._onError = null;
  5481. this._onComplete = null;
  5482. this._onRedirect = null;
  5483. this._onRecoveredEarlyEof = null;
  5484. this._selectSeekHandler();
  5485. this._selectLoader();
  5486. this._createLoader();
  5487. }
  5488. _createClass(IOController, [{
  5489. key: 'destroy',
  5490. value: function destroy() {
  5491. if (this._loader.isWorking()) {
  5492. this._loader.abort();
  5493. }
  5494. this._loader.destroy();
  5495. this._loader = null;
  5496. this._loaderClass = null;
  5497. this._dataSource = null;
  5498. this._stashBuffer = null;
  5499. this._stashUsed = this._stashSize = this._bufferSize = this._stashByteStart = 0;
  5500. this._currentRange = null;
  5501. this._speedSampler = null;
  5502. this._isEarlyEofReconnecting = false;
  5503. this._onDataArrival = null;
  5504. this._onSeeked = null;
  5505. this._onError = null;
  5506. this._onComplete = null;
  5507. this._onRedirect = null;
  5508. this._onRecoveredEarlyEof = null;
  5509. this._extraData = null;
  5510. }
  5511. }, {
  5512. key: 'isWorking',
  5513. value: function isWorking() {
  5514. return this._loader && this._loader.isWorking() && !this._paused;
  5515. }
  5516. }, {
  5517. key: 'isPaused',
  5518. value: function isPaused() {
  5519. return this._paused;
  5520. }
  5521. }, {
  5522. key: '_selectSeekHandler',
  5523. value: function _selectSeekHandler() {
  5524. var config = this._config;
  5525. if (config.seekType === 'range') {
  5526. this._seekHandler = new _rangeSeekHandler2.default(this._config.rangeLoadZeroStart);
  5527. } else if (config.seekType === 'param') {
  5528. var paramStart = config.seekParamStart || 'bstart';
  5529. var paramEnd = config.seekParamEnd || 'bend';
  5530. this._seekHandler = new _paramSeekHandler2.default(paramStart, paramEnd);
  5531. } else if (config.seekType === 'custom') {
  5532. if (typeof config.customSeekHandler !== 'function') {
  5533. throw new _exception.InvalidArgumentException('Custom seekType specified in config but invalid customSeekHandler!');
  5534. }
  5535. this._seekHandler = new config.customSeekHandler();
  5536. } else {
  5537. throw new _exception.InvalidArgumentException('Invalid seekType in config: ' + config.seekType);
  5538. }
  5539. }
  5540. }, {
  5541. key: '_selectLoader',
  5542. value: function _selectLoader() {
  5543. if (this._isWebSocketURL) {
  5544. this._loaderClass = _websocketLoader2.default;
  5545. } else if (_fetchStreamLoader2.default.isSupported()) {
  5546. this._loaderClass = _fetchStreamLoader2.default;
  5547. } else if (_xhrMozChunkedLoader2.default.isSupported()) {
  5548. this._loaderClass = _xhrMozChunkedLoader2.default;
  5549. } else if (_xhrRangeLoader2.default.isSupported()) {
  5550. this._loaderClass = _xhrRangeLoader2.default;
  5551. } else {
  5552. throw new _exception.RuntimeException('Your browser doesn\'t support xhr with arraybuffer responseType!');
  5553. }
  5554. }
  5555. }, {
  5556. key: '_createLoader',
  5557. value: function _createLoader() {
  5558. this._loader = new this._loaderClass(this._seekHandler, this._config);
  5559. if (this._loader.needStashBuffer === false) {
  5560. this._enableStash = false;
  5561. }
  5562. this._loader.onContentLengthKnown = this._onContentLengthKnown.bind(this);
  5563. this._loader.onURLRedirect = this._onURLRedirect.bind(this);
  5564. this._loader.onDataArrival = this._onLoaderChunkArrival.bind(this);
  5565. this._loader.onComplete = this._onLoaderComplete.bind(this);
  5566. this._loader.onError = this._onLoaderError.bind(this);
  5567. }
  5568. }, {
  5569. key: 'open',
  5570. value: function open(optionalFrom) {
  5571. this._currentRange = { from: 0, to: -1 };
  5572. if (optionalFrom) {
  5573. this._currentRange.from = optionalFrom;
  5574. }
  5575. this._speedSampler.reset();
  5576. if (!optionalFrom) {
  5577. this._fullRequestFlag = true;
  5578. }
  5579. this._loader.open(this._dataSource, Object.assign({}, this._currentRange));
  5580. }
  5581. }, {
  5582. key: 'abort',
  5583. value: function abort() {
  5584. this._loader.abort();
  5585. if (this._paused) {
  5586. this._paused = false;
  5587. this._resumeFrom = 0;
  5588. }
  5589. }
  5590. }, {
  5591. key: 'pause',
  5592. value: function pause() {
  5593. if (this.isWorking()) {
  5594. this._loader.abort();
  5595. if (this._stashUsed !== 0) {
  5596. this._resumeFrom = this._stashByteStart;
  5597. this._currentRange.to = this._stashByteStart - 1;
  5598. } else {
  5599. this._resumeFrom = this._currentRange.to + 1;
  5600. }
  5601. this._stashUsed = 0;
  5602. this._stashByteStart = 0;
  5603. this._paused = true;
  5604. }
  5605. }
  5606. }, {
  5607. key: 'resume',
  5608. value: function resume() {
  5609. if (this._paused) {
  5610. this._paused = false;
  5611. var bytes = this._resumeFrom;
  5612. this._resumeFrom = 0;
  5613. this._internalSeek(bytes, true);
  5614. }
  5615. }
  5616. }, {
  5617. key: 'seek',
  5618. value: function seek(bytes) {
  5619. this._paused = false;
  5620. this._stashUsed = 0;
  5621. this._stashByteStart = 0;
  5622. this._internalSeek(bytes, true);
  5623. }
  5624. /**
  5625. * When seeking request is from media seeking, unconsumed stash data should be dropped
  5626. * However, stash data shouldn't be dropped if seeking requested from http reconnection
  5627. *
  5628. * @dropUnconsumed: Ignore and discard all unconsumed data in stash buffer
  5629. */
  5630. }, {
  5631. key: '_internalSeek',
  5632. value: function _internalSeek(bytes, dropUnconsumed) {
  5633. if (this._loader.isWorking()) {
  5634. this._loader.abort();
  5635. }
  5636. // dispatch & flush stash buffer before seek
  5637. this._flushStashBuffer(dropUnconsumed);
  5638. this._loader.destroy();
  5639. this._loader = null;
  5640. var requestRange = { from: bytes, to: -1 };
  5641. this._currentRange = { from: requestRange.from, to: -1 };
  5642. this._speedSampler.reset();
  5643. this._stashSize = this._stashInitialSize;
  5644. this._createLoader();
  5645. this._loader.open(this._dataSource, requestRange);
  5646. if (this._onSeeked) {
  5647. this._onSeeked();
  5648. }
  5649. }
  5650. }, {
  5651. key: 'updateUrl',
  5652. value: function updateUrl(url) {
  5653. if (!url || typeof url !== 'string' || url.length === 0) {
  5654. throw new _exception.InvalidArgumentException('Url must be a non-empty string!');
  5655. }
  5656. this._dataSource.url = url;
  5657. // TODO: replace with new url
  5658. }
  5659. }, {
  5660. key: '_expandBuffer',
  5661. value: function _expandBuffer(expectedBytes) {
  5662. var bufferNewSize = this._stashSize;
  5663. while (bufferNewSize + 1024 * 1024 * 1 < expectedBytes) {
  5664. bufferNewSize *= 2;
  5665. }
  5666. bufferNewSize += 1024 * 1024 * 1; // bufferSize = stashSize + 1MB
  5667. if (bufferNewSize === this._bufferSize) {
  5668. return;
  5669. }
  5670. var newBuffer = new ArrayBuffer(bufferNewSize);
  5671. if (this._stashUsed > 0) {
  5672. // copy existing data into new buffer
  5673. var stashOldArray = new Uint8Array(this._stashBuffer, 0, this._stashUsed);
  5674. var stashNewArray = new Uint8Array(newBuffer, 0, bufferNewSize);
  5675. stashNewArray.set(stashOldArray, 0);
  5676. }
  5677. this._stashBuffer = newBuffer;
  5678. this._bufferSize = bufferNewSize;
  5679. }
  5680. }, {
  5681. key: '_normalizeSpeed',
  5682. value: function _normalizeSpeed(input) {
  5683. var list = this._speedNormalizeList;
  5684. var last = list.length - 1;
  5685. var mid = 0;
  5686. var lbound = 0;
  5687. var ubound = last;
  5688. if (input < list[0]) {
  5689. return list[0];
  5690. }
  5691. // binary search
  5692. while (lbound <= ubound) {
  5693. mid = lbound + Math.floor((ubound - lbound) / 2);
  5694. if (mid === last || input >= list[mid] && input < list[mid + 1]) {
  5695. return list[mid];
  5696. } else if (list[mid] < input) {
  5697. lbound = mid + 1;
  5698. } else {
  5699. ubound = mid - 1;
  5700. }
  5701. }
  5702. }
  5703. }, {
  5704. key: '_adjustStashSize',
  5705. value: function _adjustStashSize(normalized) {
  5706. var stashSizeKB = 0;
  5707. if (this._config.isLive) {
  5708. // live stream: always use single normalized speed for size of stashSizeKB
  5709. stashSizeKB = normalized;
  5710. } else {
  5711. if (normalized < 512) {
  5712. stashSizeKB = normalized;
  5713. } else if (normalized >= 512 && normalized <= 1024) {
  5714. stashSizeKB = Math.floor(normalized * 1.5);
  5715. } else {
  5716. stashSizeKB = normalized * 2;
  5717. }
  5718. }
  5719. if (stashSizeKB > 8192) {
  5720. stashSizeKB = 8192;
  5721. }
  5722. var bufferSize = stashSizeKB * 1024 + 1024 * 1024 * 1; // stashSize + 1MB
  5723. if (this._bufferSize < bufferSize) {
  5724. this._expandBuffer(bufferSize);
  5725. }
  5726. this._stashSize = stashSizeKB * 1024;
  5727. }
  5728. }, {
  5729. key: '_dispatchChunks',
  5730. value: function _dispatchChunks(chunks, byteStart) {
  5731. this._currentRange.to = byteStart + chunks.byteLength - 1;
  5732. return this._onDataArrival(chunks, byteStart);
  5733. }
  5734. }, {
  5735. key: '_onURLRedirect',
  5736. value: function _onURLRedirect(redirectedURL) {
  5737. this._redirectedURL = redirectedURL;
  5738. if (this._onRedirect) {
  5739. this._onRedirect(redirectedURL);
  5740. }
  5741. }
  5742. }, {
  5743. key: '_onContentLengthKnown',
  5744. value: function _onContentLengthKnown(contentLength) {
  5745. if (contentLength && this._fullRequestFlag) {
  5746. this._totalLength = contentLength;
  5747. this._fullRequestFlag = false;
  5748. }
  5749. }
  5750. }, {
  5751. key: '_onLoaderChunkArrival',
  5752. value: function _onLoaderChunkArrival(chunk, byteStart, receivedLength) {
  5753. if (!this._onDataArrival) {
  5754. throw new _exception.IllegalStateException('IOController: No existing consumer (onDataArrival) callback!');
  5755. }
  5756. if (this._paused) {
  5757. return;
  5758. }
  5759. if (this._isEarlyEofReconnecting) {
  5760. // Auto-reconnect for EarlyEof succeed, notify to upper-layer by callback
  5761. this._isEarlyEofReconnecting = false;
  5762. if (this._onRecoveredEarlyEof) {
  5763. this._onRecoveredEarlyEof();
  5764. }
  5765. }
  5766. this._speedSampler.addBytes(chunk.byteLength);
  5767. // adjust stash buffer size according to network speed dynamically
  5768. var KBps = this._speedSampler.lastSecondKBps;
  5769. if (KBps !== 0) {
  5770. var normalized = this._normalizeSpeed(KBps);
  5771. if (this._speedNormalized !== normalized) {
  5772. this._speedNormalized = normalized;
  5773. this._adjustStashSize(normalized);
  5774. }
  5775. }
  5776. if (!this._enableStash) {
  5777. // disable stash
  5778. if (this._stashUsed === 0) {
  5779. // dispatch chunk directly to consumer;
  5780. // check ret value (consumed bytes) and stash unconsumed to stashBuffer
  5781. var consumed = this._dispatchChunks(chunk, byteStart);
  5782. if (consumed < chunk.byteLength) {
  5783. // unconsumed data remain.
  5784. var remain = chunk.byteLength - consumed;
  5785. if (remain > this._bufferSize) {
  5786. this._expandBuffer(remain);
  5787. }
  5788. var stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  5789. stashArray.set(new Uint8Array(chunk, consumed), 0);
  5790. this._stashUsed += remain;
  5791. this._stashByteStart = byteStart + consumed;
  5792. }
  5793. } else {
  5794. // else: Merge chunk into stashBuffer, and dispatch stashBuffer to consumer.
  5795. if (this._stashUsed + chunk.byteLength > this._bufferSize) {
  5796. this._expandBuffer(this._stashUsed + chunk.byteLength);
  5797. }
  5798. var _stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  5799. _stashArray.set(new Uint8Array(chunk), this._stashUsed);
  5800. this._stashUsed += chunk.byteLength;
  5801. var _consumed = this._dispatchChunks(this._stashBuffer.slice(0, this._stashUsed), this._stashByteStart);
  5802. if (_consumed < this._stashUsed && _consumed > 0) {
  5803. // unconsumed data remain
  5804. var remainArray = new Uint8Array(this._stashBuffer, _consumed);
  5805. _stashArray.set(remainArray, 0);
  5806. }
  5807. this._stashUsed -= _consumed;
  5808. this._stashByteStart += _consumed;
  5809. }
  5810. } else {
  5811. // enable stash
  5812. if (this._stashUsed === 0 && this._stashByteStart === 0) {
  5813. // seeked? or init chunk?
  5814. // This is the first chunk after seek action
  5815. this._stashByteStart = byteStart;
  5816. }
  5817. if (this._stashUsed + chunk.byteLength <= this._stashSize) {
  5818. // just stash
  5819. var _stashArray2 = new Uint8Array(this._stashBuffer, 0, this._stashSize);
  5820. _stashArray2.set(new Uint8Array(chunk), this._stashUsed);
  5821. this._stashUsed += chunk.byteLength;
  5822. } else {
  5823. // stashUsed + chunkSize > stashSize, size limit exceeded
  5824. var _stashArray3 = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  5825. if (this._stashUsed > 0) {
  5826. // There're stash datas in buffer
  5827. // dispatch the whole stashBuffer, and stash remain data
  5828. // then append chunk to stashBuffer (stash)
  5829. var buffer = this._stashBuffer.slice(0, this._stashUsed);
  5830. var _consumed2 = this._dispatchChunks(buffer, this._stashByteStart);
  5831. if (_consumed2 < buffer.byteLength) {
  5832. if (_consumed2 > 0) {
  5833. var _remainArray = new Uint8Array(buffer, _consumed2);
  5834. _stashArray3.set(_remainArray, 0);
  5835. this._stashUsed = _remainArray.byteLength;
  5836. this._stashByteStart += _consumed2;
  5837. }
  5838. } else {
  5839. this._stashUsed = 0;
  5840. this._stashByteStart += _consumed2;
  5841. }
  5842. if (this._stashUsed + chunk.byteLength > this._bufferSize) {
  5843. this._expandBuffer(this._stashUsed + chunk.byteLength);
  5844. _stashArray3 = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  5845. }
  5846. _stashArray3.set(new Uint8Array(chunk), this._stashUsed);
  5847. this._stashUsed += chunk.byteLength;
  5848. } else {
  5849. // stash buffer empty, but chunkSize > stashSize (oh, holy shit)
  5850. // dispatch chunk directly and stash remain data
  5851. var _consumed3 = this._dispatchChunks(chunk, byteStart);
  5852. if (_consumed3 < chunk.byteLength) {
  5853. var _remain = chunk.byteLength - _consumed3;
  5854. if (_remain > this._bufferSize) {
  5855. this._expandBuffer(_remain);
  5856. _stashArray3 = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  5857. }
  5858. _stashArray3.set(new Uint8Array(chunk, _consumed3), 0);
  5859. this._stashUsed += _remain;
  5860. this._stashByteStart = byteStart + _consumed3;
  5861. }
  5862. }
  5863. }
  5864. }
  5865. }
  5866. }, {
  5867. key: '_flushStashBuffer',
  5868. value: function _flushStashBuffer(dropUnconsumed) {
  5869. if (this._stashUsed > 0) {
  5870. var buffer = this._stashBuffer.slice(0, this._stashUsed);
  5871. var consumed = this._dispatchChunks(buffer, this._stashByteStart);
  5872. var remain = buffer.byteLength - consumed;
  5873. if (consumed < buffer.byteLength) {
  5874. if (dropUnconsumed) {
  5875. _logger2.default.w(this.TAG, remain + ' bytes unconsumed data remain when flush buffer, dropped');
  5876. } else {
  5877. if (consumed > 0) {
  5878. var stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  5879. var remainArray = new Uint8Array(buffer, consumed);
  5880. stashArray.set(remainArray, 0);
  5881. this._stashUsed = remainArray.byteLength;
  5882. this._stashByteStart += consumed;
  5883. }
  5884. return 0;
  5885. }
  5886. }
  5887. this._stashUsed = 0;
  5888. this._stashByteStart = 0;
  5889. return remain;
  5890. }
  5891. return 0;
  5892. }
  5893. }, {
  5894. key: '_onLoaderComplete',
  5895. value: function _onLoaderComplete(from, to) {
  5896. // Force-flush stash buffer, and drop unconsumed data
  5897. this._flushStashBuffer(true);
  5898. if (this._onComplete) {
  5899. this._onComplete(this._extraData);
  5900. }
  5901. }
  5902. }, {
  5903. key: '_onLoaderError',
  5904. value: function _onLoaderError(type, data) {
  5905. _logger2.default.e(this.TAG, 'Loader error, code = ' + data.code + ', msg = ' + data.msg);
  5906. this._flushStashBuffer(false);
  5907. if (this._isEarlyEofReconnecting) {
  5908. // Auto-reconnect for EarlyEof failed, throw UnrecoverableEarlyEof error to upper-layer
  5909. this._isEarlyEofReconnecting = false;
  5910. type = _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF;
  5911. }
  5912. switch (type) {
  5913. case _loader.LoaderErrors.EARLY_EOF:
  5914. {
  5915. if (!this._config.isLive) {
  5916. // Do internal http reconnect if not live stream
  5917. if (this._totalLength) {
  5918. var nextFrom = this._currentRange.to + 1;
  5919. if (nextFrom < this._totalLength) {
  5920. _logger2.default.w(this.TAG, 'Connection lost, trying reconnect...');
  5921. this._isEarlyEofReconnecting = true;
  5922. this._internalSeek(nextFrom, false);
  5923. }
  5924. return;
  5925. }
  5926. // else: We don't know totalLength, throw UnrecoverableEarlyEof
  5927. }
  5928. // live stream: throw UnrecoverableEarlyEof error to upper-layer
  5929. type = _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF;
  5930. break;
  5931. }
  5932. case _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF:
  5933. case _loader.LoaderErrors.CONNECTING_TIMEOUT:
  5934. case _loader.LoaderErrors.HTTP_STATUS_CODE_INVALID:
  5935. case _loader.LoaderErrors.EXCEPTION:
  5936. break;
  5937. }
  5938. if (this._onError) {
  5939. this._onError(type, data);
  5940. } else {
  5941. throw new _exception.RuntimeException('IOException: ' + data.msg);
  5942. }
  5943. }
  5944. }, {
  5945. key: 'status',
  5946. get: function get() {
  5947. return this._loader.status;
  5948. }
  5949. }, {
  5950. key: 'extraData',
  5951. get: function get() {
  5952. return this._extraData;
  5953. },
  5954. set: function set(data) {
  5955. this._extraData = data;
  5956. }
  5957. // prototype: function onDataArrival(chunks: ArrayBuffer, byteStart: number): number
  5958. }, {
  5959. key: 'onDataArrival',
  5960. get: function get() {
  5961. return this._onDataArrival;
  5962. },
  5963. set: function set(callback) {
  5964. this._onDataArrival = callback;
  5965. }
  5966. }, {
  5967. key: 'onSeeked',
  5968. get: function get() {
  5969. return this._onSeeked;
  5970. },
  5971. set: function set(callback) {
  5972. this._onSeeked = callback;
  5973. }
  5974. // prototype: function onError(type: number, info: {code: number, msg: string}): void
  5975. }, {
  5976. key: 'onError',
  5977. get: function get() {
  5978. return this._onError;
  5979. },
  5980. set: function set(callback) {
  5981. this._onError = callback;
  5982. }
  5983. }, {
  5984. key: 'onComplete',
  5985. get: function get() {
  5986. return this._onComplete;
  5987. },
  5988. set: function set(callback) {
  5989. this._onComplete = callback;
  5990. }
  5991. }, {
  5992. key: 'onRedirect',
  5993. get: function get() {
  5994. return this._onRedirect;
  5995. },
  5996. set: function set(callback) {
  5997. this._onRedirect = callback;
  5998. }
  5999. }, {
  6000. key: 'onRecoveredEarlyEof',
  6001. get: function get() {
  6002. return this._onRecoveredEarlyEof;
  6003. },
  6004. set: function set(callback) {
  6005. this._onRecoveredEarlyEof = callback;
  6006. }
  6007. }, {
  6008. key: 'currentURL',
  6009. get: function get() {
  6010. return this._dataSource.url;
  6011. }
  6012. }, {
  6013. key: 'hasRedirect',
  6014. get: function get() {
  6015. return this._redirectedURL != null || this._dataSource.redirectedURL != undefined;
  6016. }
  6017. }, {
  6018. key: 'currentRedirectedURL',
  6019. get: function get() {
  6020. return this._redirectedURL || this._dataSource.redirectedURL;
  6021. }
  6022. // in KB/s
  6023. }, {
  6024. key: 'currentSpeed',
  6025. get: function get() {
  6026. if (this._loaderClass === _xhrRangeLoader2.default) {
  6027. // SpeedSampler is inaccuracy if loader is RangeLoader
  6028. return this._loader.currentSpeed;
  6029. }
  6030. return this._speedSampler.lastSecondKBps;
  6031. }
  6032. }, {
  6033. key: 'loaderType',
  6034. get: function get() {
  6035. return this._loader.type;
  6036. }
  6037. }]);
  6038. return IOController;
  6039. }();
  6040. exports.default = IOController;
  6041. },{"../utils/exception.js":40,"../utils/logger.js":41,"./fetch-stream-loader.js":22,"./loader.js":24,"./param-seek-handler.js":25,"./range-seek-handler.js":26,"./speed-sampler.js":27,"./websocket-loader.js":28,"./xhr-moz-chunked-loader.js":29,"./xhr-msstream-loader.js":30,"./xhr-range-loader.js":31}],24:[function(_dereq_,module,exports){
  6042. 'use strict';
  6043. Object.defineProperty(exports, "__esModule", {
  6044. value: true
  6045. });
  6046. exports.BaseLoader = exports.LoaderErrors = exports.LoaderStatus = undefined;
  6047. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  6048. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  6049. *
  6050. * @author zheng qian <xqq@xqq.im>
  6051. *
  6052. * Licensed under the Apache License, Version 2.0 (the "License");
  6053. * you may not use this file except in compliance with the License.
  6054. * You may obtain a copy of the License at
  6055. *
  6056. * http://www.apache.org/licenses/LICENSE-2.0
  6057. *
  6058. * Unless required by applicable law or agreed to in writing, software
  6059. * distributed under the License is distributed on an "AS IS" BASIS,
  6060. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6061. * See the License for the specific language governing permissions and
  6062. * limitations under the License.
  6063. */
  6064. var _exception = _dereq_('../utils/exception.js');
  6065. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6066. var LoaderStatus = exports.LoaderStatus = {
  6067. kIdle: 0,
  6068. kConnecting: 1,
  6069. kBuffering: 2,
  6070. kError: 3,
  6071. kComplete: 4
  6072. };
  6073. var LoaderErrors = exports.LoaderErrors = {
  6074. OK: 'OK',
  6075. EXCEPTION: 'Exception',
  6076. HTTP_STATUS_CODE_INVALID: 'HttpStatusCodeInvalid',
  6077. CONNECTING_TIMEOUT: 'ConnectingTimeout',
  6078. EARLY_EOF: 'EarlyEof',
  6079. UNRECOVERABLE_EARLY_EOF: 'UnrecoverableEarlyEof'
  6080. };
  6081. /* Loader has callbacks which have following prototypes:
  6082. * function onContentLengthKnown(contentLength: number): void
  6083. * function onURLRedirect(url: string): void
  6084. * function onDataArrival(chunk: ArrayBuffer, byteStart: number, receivedLength: number): void
  6085. * function onError(errorType: number, errorInfo: {code: number, msg: string}): void
  6086. * function onComplete(rangeFrom: number, rangeTo: number): void
  6087. */
  6088. var BaseLoader = exports.BaseLoader = function () {
  6089. function BaseLoader(typeName) {
  6090. _classCallCheck(this, BaseLoader);
  6091. this._type = typeName || 'undefined';
  6092. this._status = LoaderStatus.kIdle;
  6093. this._needStash = false;
  6094. // callbacks
  6095. this._onContentLengthKnown = null;
  6096. this._onURLRedirect = null;
  6097. this._onDataArrival = null;
  6098. this._onError = null;
  6099. this._onComplete = null;
  6100. }
  6101. _createClass(BaseLoader, [{
  6102. key: 'destroy',
  6103. value: function destroy() {
  6104. this._status = LoaderStatus.kIdle;
  6105. this._onContentLengthKnown = null;
  6106. this._onURLRedirect = null;
  6107. this._onDataArrival = null;
  6108. this._onError = null;
  6109. this._onComplete = null;
  6110. }
  6111. }, {
  6112. key: 'isWorking',
  6113. value: function isWorking() {
  6114. return this._status === LoaderStatus.kConnecting || this._status === LoaderStatus.kBuffering;
  6115. }
  6116. }, {
  6117. key: 'open',
  6118. // pure virtual
  6119. value: function open(dataSource, range) {
  6120. throw new _exception.NotImplementedException('Unimplemented abstract function!');
  6121. }
  6122. }, {
  6123. key: 'abort',
  6124. value: function abort() {
  6125. throw new _exception.NotImplementedException('Unimplemented abstract function!');
  6126. }
  6127. }, {
  6128. key: 'type',
  6129. get: function get() {
  6130. return this._type;
  6131. }
  6132. }, {
  6133. key: 'status',
  6134. get: function get() {
  6135. return this._status;
  6136. }
  6137. }, {
  6138. key: 'needStashBuffer',
  6139. get: function get() {
  6140. return this._needStash;
  6141. }
  6142. }, {
  6143. key: 'onContentLengthKnown',
  6144. get: function get() {
  6145. return this._onContentLengthKnown;
  6146. },
  6147. set: function set(callback) {
  6148. this._onContentLengthKnown = callback;
  6149. }
  6150. }, {
  6151. key: 'onURLRedirect',
  6152. get: function get() {
  6153. return this._onURLRedirect;
  6154. },
  6155. set: function set(callback) {
  6156. this._onURLRedirect = callback;
  6157. }
  6158. }, {
  6159. key: 'onDataArrival',
  6160. get: function get() {
  6161. return this._onDataArrival;
  6162. },
  6163. set: function set(callback) {
  6164. this._onDataArrival = callback;
  6165. }
  6166. }, {
  6167. key: 'onError',
  6168. get: function get() {
  6169. return this._onError;
  6170. },
  6171. set: function set(callback) {
  6172. this._onError = callback;
  6173. }
  6174. }, {
  6175. key: 'onComplete',
  6176. get: function get() {
  6177. return this._onComplete;
  6178. },
  6179. set: function set(callback) {
  6180. this._onComplete = callback;
  6181. }
  6182. }]);
  6183. return BaseLoader;
  6184. }();
  6185. },{"../utils/exception.js":40}],25:[function(_dereq_,module,exports){
  6186. 'use strict';
  6187. Object.defineProperty(exports, "__esModule", {
  6188. value: true
  6189. });
  6190. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  6191. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6192. /*
  6193. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  6194. *
  6195. * @author zheng qian <xqq@xqq.im>
  6196. *
  6197. * Licensed under the Apache License, Version 2.0 (the "License");
  6198. * you may not use this file except in compliance with the License.
  6199. * You may obtain a copy of the License at
  6200. *
  6201. * http://www.apache.org/licenses/LICENSE-2.0
  6202. *
  6203. * Unless required by applicable law or agreed to in writing, software
  6204. * distributed under the License is distributed on an "AS IS" BASIS,
  6205. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6206. * See the License for the specific language governing permissions and
  6207. * limitations under the License.
  6208. */
  6209. var ParamSeekHandler = function () {
  6210. function ParamSeekHandler(paramStart, paramEnd) {
  6211. _classCallCheck(this, ParamSeekHandler);
  6212. this._startName = paramStart;
  6213. this._endName = paramEnd;
  6214. }
  6215. _createClass(ParamSeekHandler, [{
  6216. key: 'getConfig',
  6217. value: function getConfig(baseUrl, range) {
  6218. var url = baseUrl;
  6219. if (range.from !== 0 || range.to !== -1) {
  6220. var needAnd = true;
  6221. if (url.indexOf('?') === -1) {
  6222. url += '?';
  6223. needAnd = false;
  6224. }
  6225. if (needAnd) {
  6226. url += '&';
  6227. }
  6228. url += this._startName + '=' + range.from.toString();
  6229. if (range.to !== -1) {
  6230. url += '&' + this._endName + '=' + range.to.toString();
  6231. }
  6232. }
  6233. return {
  6234. url: url,
  6235. headers: {}
  6236. };
  6237. }
  6238. }, {
  6239. key: 'removeURLParameters',
  6240. value: function removeURLParameters(seekedURL) {
  6241. var baseURL = seekedURL.split('?')[0];
  6242. var params = undefined;
  6243. var queryIndex = seekedURL.indexOf('?');
  6244. if (queryIndex !== -1) {
  6245. params = seekedURL.substring(queryIndex + 1);
  6246. }
  6247. var resultParams = '';
  6248. if (params != undefined && params.length > 0) {
  6249. var pairs = params.split('&');
  6250. for (var i = 0; i < pairs.length; i++) {
  6251. var pair = pairs[i].split('=');
  6252. var requireAnd = i > 0;
  6253. if (pair[0] !== this._startName && pair[0] !== this._endName) {
  6254. if (requireAnd) {
  6255. resultParams += '&';
  6256. }
  6257. resultParams += pairs[i];
  6258. }
  6259. }
  6260. }
  6261. return resultParams.length === 0 ? baseURL : baseURL + '?' + resultParams;
  6262. }
  6263. }]);
  6264. return ParamSeekHandler;
  6265. }();
  6266. exports.default = ParamSeekHandler;
  6267. },{}],26:[function(_dereq_,module,exports){
  6268. 'use strict';
  6269. Object.defineProperty(exports, "__esModule", {
  6270. value: true
  6271. });
  6272. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  6273. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6274. /*
  6275. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  6276. *
  6277. * @author zheng qian <xqq@xqq.im>
  6278. *
  6279. * Licensed under the Apache License, Version 2.0 (the "License");
  6280. * you may not use this file except in compliance with the License.
  6281. * You may obtain a copy of the License at
  6282. *
  6283. * http://www.apache.org/licenses/LICENSE-2.0
  6284. *
  6285. * Unless required by applicable law or agreed to in writing, software
  6286. * distributed under the License is distributed on an "AS IS" BASIS,
  6287. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6288. * See the License for the specific language governing permissions and
  6289. * limitations under the License.
  6290. */
  6291. var RangeSeekHandler = function () {
  6292. function RangeSeekHandler(zeroStart) {
  6293. _classCallCheck(this, RangeSeekHandler);
  6294. this._zeroStart = zeroStart || false;
  6295. }
  6296. _createClass(RangeSeekHandler, [{
  6297. key: 'getConfig',
  6298. value: function getConfig(url, range) {
  6299. var headers = {};
  6300. if (range.from !== 0 || range.to !== -1) {
  6301. var param = void 0;
  6302. if (range.to !== -1) {
  6303. param = 'bytes=' + range.from.toString() + '-' + range.to.toString();
  6304. } else {
  6305. param = 'bytes=' + range.from.toString() + '-';
  6306. }
  6307. headers['Range'] = param;
  6308. } else if (this._zeroStart) {
  6309. headers['Range'] = 'bytes=0-';
  6310. }
  6311. return {
  6312. url: url,
  6313. headers: headers
  6314. };
  6315. }
  6316. }, {
  6317. key: 'removeURLParameters',
  6318. value: function removeURLParameters(seekedURL) {
  6319. return seekedURL;
  6320. }
  6321. }]);
  6322. return RangeSeekHandler;
  6323. }();
  6324. exports.default = RangeSeekHandler;
  6325. },{}],27:[function(_dereq_,module,exports){
  6326. "use strict";
  6327. Object.defineProperty(exports, "__esModule", {
  6328. value: true
  6329. });
  6330. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  6331. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6332. /*
  6333. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  6334. *
  6335. * @author zheng qian <xqq@xqq.im>
  6336. *
  6337. * Licensed under the Apache License, Version 2.0 (the "License");
  6338. * you may not use this file except in compliance with the License.
  6339. * You may obtain a copy of the License at
  6340. *
  6341. * http://www.apache.org/licenses/LICENSE-2.0
  6342. *
  6343. * Unless required by applicable law or agreed to in writing, software
  6344. * distributed under the License is distributed on an "AS IS" BASIS,
  6345. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6346. * See the License for the specific language governing permissions and
  6347. * limitations under the License.
  6348. */
  6349. // Utility class to calculate realtime network I/O speed
  6350. var SpeedSampler = function () {
  6351. function SpeedSampler() {
  6352. _classCallCheck(this, SpeedSampler);
  6353. // milliseconds
  6354. this._firstCheckpoint = 0;
  6355. this._lastCheckpoint = 0;
  6356. this._intervalBytes = 0;
  6357. this._totalBytes = 0;
  6358. this._lastSecondBytes = 0;
  6359. // compatibility detection
  6360. if (self.performance && self.performance.now) {
  6361. this._now = self.performance.now.bind(self.performance);
  6362. } else {
  6363. this._now = Date.now;
  6364. }
  6365. }
  6366. _createClass(SpeedSampler, [{
  6367. key: "reset",
  6368. value: function reset() {
  6369. this._firstCheckpoint = this._lastCheckpoint = 0;
  6370. this._totalBytes = this._intervalBytes = 0;
  6371. this._lastSecondBytes = 0;
  6372. }
  6373. }, {
  6374. key: "addBytes",
  6375. value: function addBytes(bytes) {
  6376. if (this._firstCheckpoint === 0) {
  6377. this._firstCheckpoint = this._now();
  6378. this._lastCheckpoint = this._firstCheckpoint;
  6379. this._intervalBytes += bytes;
  6380. this._totalBytes += bytes;
  6381. } else if (this._now() - this._lastCheckpoint < 1000) {
  6382. this._intervalBytes += bytes;
  6383. this._totalBytes += bytes;
  6384. } else {
  6385. // duration >= 1000
  6386. this._lastSecondBytes = this._intervalBytes;
  6387. this._intervalBytes = bytes;
  6388. this._totalBytes += bytes;
  6389. this._lastCheckpoint = this._now();
  6390. }
  6391. }
  6392. }, {
  6393. key: "currentKBps",
  6394. get: function get() {
  6395. this.addBytes(0);
  6396. var durationSeconds = (this._now() - this._lastCheckpoint) / 1000;
  6397. if (durationSeconds == 0) durationSeconds = 1;
  6398. return this._intervalBytes / durationSeconds / 1024;
  6399. }
  6400. }, {
  6401. key: "lastSecondKBps",
  6402. get: function get() {
  6403. this.addBytes(0);
  6404. if (this._lastSecondBytes !== 0) {
  6405. return this._lastSecondBytes / 1024;
  6406. } else {
  6407. // lastSecondBytes === 0
  6408. if (this._now() - this._lastCheckpoint >= 500) {
  6409. // if time interval since last checkpoint has exceeded 500ms
  6410. // the speed is nearly accurate
  6411. return this.currentKBps;
  6412. } else {
  6413. // We don't know
  6414. return 0;
  6415. }
  6416. }
  6417. }
  6418. }, {
  6419. key: "averageKBps",
  6420. get: function get() {
  6421. var durationSeconds = (this._now() - this._firstCheckpoint) / 1000;
  6422. return this._totalBytes / durationSeconds / 1024;
  6423. }
  6424. }]);
  6425. return SpeedSampler;
  6426. }();
  6427. exports.default = SpeedSampler;
  6428. },{}],28:[function(_dereq_,module,exports){
  6429. 'use strict';
  6430. Object.defineProperty(exports, "__esModule", {
  6431. value: true
  6432. });
  6433. var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
  6434. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  6435. var _logger = _dereq_('../utils/logger.js');
  6436. var _logger2 = _interopRequireDefault(_logger);
  6437. var _loader = _dereq_('./loader.js');
  6438. var _exception = _dereq_('../utils/exception.js');
  6439. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6440. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6441. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  6442. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*
  6443. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  6444. *
  6445. * @author zheng qian <xqq@xqq.im>
  6446. *
  6447. * Licensed under the Apache License, Version 2.0 (the "License");
  6448. * you may not use this file except in compliance with the License.
  6449. * You may obtain a copy of the License at
  6450. *
  6451. * http://www.apache.org/licenses/LICENSE-2.0
  6452. *
  6453. * Unless required by applicable law or agreed to in writing, software
  6454. * distributed under the License is distributed on an "AS IS" BASIS,
  6455. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6456. * See the License for the specific language governing permissions and
  6457. * limitations under the License.
  6458. */
  6459. // For FLV over WebSocket live stream
  6460. var WebSocketLoader = function (_BaseLoader) {
  6461. _inherits(WebSocketLoader, _BaseLoader);
  6462. _createClass(WebSocketLoader, null, [{
  6463. key: 'isSupported',
  6464. value: function isSupported() {
  6465. try {
  6466. return typeof self.WebSocket !== 'undefined';
  6467. } catch (e) {
  6468. return false;
  6469. }
  6470. }
  6471. }]);
  6472. function WebSocketLoader() {
  6473. _classCallCheck(this, WebSocketLoader);
  6474. var _this = _possibleConstructorReturn(this, (WebSocketLoader.__proto__ || Object.getPrototypeOf(WebSocketLoader)).call(this, 'websocket-loader'));
  6475. _this.TAG = 'WebSocketLoader';
  6476. _this._needStash = true;
  6477. _this._ws = null;
  6478. _this._requestAbort = false;
  6479. _this._receivedLength = 0;
  6480. return _this;
  6481. }
  6482. _createClass(WebSocketLoader, [{
  6483. key: 'destroy',
  6484. value: function destroy() {
  6485. if (this._ws) {
  6486. this.abort();
  6487. }
  6488. _get(WebSocketLoader.prototype.__proto__ || Object.getPrototypeOf(WebSocketLoader.prototype), 'destroy', this).call(this);
  6489. }
  6490. }, {
  6491. key: 'open',
  6492. value: function open(dataSource) {
  6493. try {
  6494. var ws = this._ws = new self.WebSocket(dataSource.url);
  6495. ws.binaryType = 'arraybuffer';
  6496. ws.onopen = this._onWebSocketOpen.bind(this);
  6497. ws.onclose = this._onWebSocketClose.bind(this);
  6498. ws.onmessage = this._onWebSocketMessage.bind(this);
  6499. ws.onerror = this._onWebSocketError.bind(this);
  6500. this._status = _loader.LoaderStatus.kConnecting;
  6501. } catch (e) {
  6502. this._status = _loader.LoaderStatus.kError;
  6503. var info = { code: e.code, msg: e.message };
  6504. if (this._onError) {
  6505. this._onError(_loader.LoaderErrors.EXCEPTION, info);
  6506. } else {
  6507. throw new _exception.RuntimeException(info.msg);
  6508. }
  6509. }
  6510. }
  6511. }, {
  6512. key: 'abort',
  6513. value: function abort() {
  6514. var ws = this._ws;
  6515. if (ws && (ws.readyState === 0 || ws.readyState === 1)) {
  6516. // CONNECTING || OPEN
  6517. this._requestAbort = true;
  6518. ws.close();
  6519. }
  6520. this._ws = null;
  6521. this._status = _loader.LoaderStatus.kComplete;
  6522. }
  6523. }, {
  6524. key: '_onWebSocketOpen',
  6525. value: function _onWebSocketOpen(e) {
  6526. this._status = _loader.LoaderStatus.kBuffering;
  6527. }
  6528. }, {
  6529. key: '_onWebSocketClose',
  6530. value: function _onWebSocketClose(e) {
  6531. if (this._requestAbort === true) {
  6532. this._requestAbort = false;
  6533. return;
  6534. }
  6535. this._status = _loader.LoaderStatus.kComplete;
  6536. if (this._onComplete) {
  6537. this._onComplete(0, this._receivedLength - 1);
  6538. }
  6539. }
  6540. }, {
  6541. key: '_onWebSocketMessage',
  6542. value: function _onWebSocketMessage(e) {
  6543. var _this2 = this;
  6544. if (e.data instanceof ArrayBuffer) {
  6545. this._dispatchArrayBuffer(e.data);
  6546. } else if (e.data instanceof Blob) {
  6547. var reader = new FileReader();
  6548. reader.onload = function () {
  6549. _this2._dispatchArrayBuffer(reader.result);
  6550. };
  6551. reader.readAsArrayBuffer(e.data);
  6552. } else {
  6553. this._status = _loader.LoaderStatus.kError;
  6554. var info = { code: -1, msg: 'Unsupported WebSocket message type: ' + e.data.constructor.name };
  6555. if (this._onError) {
  6556. this._onError(_loader.LoaderErrors.EXCEPTION, info);
  6557. } else {
  6558. throw new _exception.RuntimeException(info.msg);
  6559. }
  6560. }
  6561. }
  6562. }, {
  6563. key: '_dispatchArrayBuffer',
  6564. value: function _dispatchArrayBuffer(arraybuffer) {
  6565. var chunk = arraybuffer;
  6566. var byteStart = this._receivedLength;
  6567. this._receivedLength += chunk.byteLength;
  6568. if (this._onDataArrival) {
  6569. this._onDataArrival(chunk, byteStart, this._receivedLength);
  6570. }
  6571. }
  6572. }, {
  6573. key: '_onWebSocketError',
  6574. value: function _onWebSocketError(e) {
  6575. this._status = _loader.LoaderStatus.kError;
  6576. var info = {
  6577. code: e.code,
  6578. msg: e.message
  6579. };
  6580. if (this._onError) {
  6581. this._onError(_loader.LoaderErrors.EXCEPTION, info);
  6582. } else {
  6583. throw new _exception.RuntimeException(info.msg);
  6584. }
  6585. }
  6586. }]);
  6587. return WebSocketLoader;
  6588. }(_loader.BaseLoader);
  6589. exports.default = WebSocketLoader;
  6590. },{"../utils/exception.js":40,"../utils/logger.js":41,"./loader.js":24}],29:[function(_dereq_,module,exports){
  6591. 'use strict';
  6592. Object.defineProperty(exports, "__esModule", {
  6593. value: true
  6594. });
  6595. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  6596. var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
  6597. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  6598. var _logger = _dereq_('../utils/logger.js');
  6599. var _logger2 = _interopRequireDefault(_logger);
  6600. var _loader = _dereq_('./loader.js');
  6601. var _exception = _dereq_('../utils/exception.js');
  6602. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6603. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6604. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  6605. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*
  6606. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  6607. *
  6608. * @author zheng qian <xqq@xqq.im>
  6609. *
  6610. * Licensed under the Apache License, Version 2.0 (the "License");
  6611. * you may not use this file except in compliance with the License.
  6612. * You may obtain a copy of the License at
  6613. *
  6614. * http://www.apache.org/licenses/LICENSE-2.0
  6615. *
  6616. * Unless required by applicable law or agreed to in writing, software
  6617. * distributed under the License is distributed on an "AS IS" BASIS,
  6618. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6619. * See the License for the specific language governing permissions and
  6620. * limitations under the License.
  6621. */
  6622. // For FireFox browser which supports `xhr.responseType = 'moz-chunked-arraybuffer'`
  6623. var MozChunkedLoader = function (_BaseLoader) {
  6624. _inherits(MozChunkedLoader, _BaseLoader);
  6625. _createClass(MozChunkedLoader, null, [{
  6626. key: 'isSupported',
  6627. value: function isSupported() {
  6628. try {
  6629. var xhr = new XMLHttpRequest();
  6630. // Firefox 37- requires .open() to be called before setting responseType
  6631. xhr.open('GET', 'https://example.com', true);
  6632. xhr.responseType = 'moz-chunked-arraybuffer';
  6633. return xhr.responseType === 'moz-chunked-arraybuffer';
  6634. } catch (e) {
  6635. _logger2.default.w('MozChunkedLoader', e.message);
  6636. return false;
  6637. }
  6638. }
  6639. }]);
  6640. function MozChunkedLoader(seekHandler, config) {
  6641. _classCallCheck(this, MozChunkedLoader);
  6642. var _this = _possibleConstructorReturn(this, (MozChunkedLoader.__proto__ || Object.getPrototypeOf(MozChunkedLoader)).call(this, 'xhr-moz-chunked-loader'));
  6643. _this.TAG = 'MozChunkedLoader';
  6644. _this._seekHandler = seekHandler;
  6645. _this._config = config;
  6646. _this._needStash = true;
  6647. _this._xhr = null;
  6648. _this._requestAbort = false;
  6649. _this._contentLength = null;
  6650. _this._receivedLength = 0;
  6651. return _this;
  6652. }
  6653. _createClass(MozChunkedLoader, [{
  6654. key: 'destroy',
  6655. value: function destroy() {
  6656. if (this.isWorking()) {
  6657. this.abort();
  6658. }
  6659. if (this._xhr) {
  6660. this._xhr.onreadystatechange = null;
  6661. this._xhr.onprogress = null;
  6662. this._xhr.onloadend = null;
  6663. this._xhr.onerror = null;
  6664. this._xhr = null;
  6665. }
  6666. _get(MozChunkedLoader.prototype.__proto__ || Object.getPrototypeOf(MozChunkedLoader.prototype), 'destroy', this).call(this);
  6667. }
  6668. }, {
  6669. key: 'open',
  6670. value: function open(dataSource, range) {
  6671. this._dataSource = dataSource;
  6672. this._range = range;
  6673. var sourceURL = dataSource.url;
  6674. if (this._config.reuseRedirectedURL && dataSource.redirectedURL != undefined) {
  6675. sourceURL = dataSource.redirectedURL;
  6676. }
  6677. var seekConfig = this._seekHandler.getConfig(sourceURL, range);
  6678. this._requestURL = seekConfig.url;
  6679. var xhr = this._xhr = new XMLHttpRequest();
  6680. xhr.open('GET', seekConfig.url, true);
  6681. xhr.responseType = 'moz-chunked-arraybuffer';
  6682. xhr.onreadystatechange = this._onReadyStateChange.bind(this);
  6683. xhr.onprogress = this._onProgress.bind(this);
  6684. xhr.onloadend = this._onLoadEnd.bind(this);
  6685. xhr.onerror = this._onXhrError.bind(this);
  6686. // cors is auto detected and enabled by xhr
  6687. // withCredentials is disabled by default
  6688. if (dataSource.withCredentials) {
  6689. xhr.withCredentials = true;
  6690. }
  6691. if (_typeof(seekConfig.headers) === 'object') {
  6692. var headers = seekConfig.headers;
  6693. for (var key in headers) {
  6694. if (headers.hasOwnProperty(key)) {
  6695. xhr.setRequestHeader(key, headers[key]);
  6696. }
  6697. }
  6698. }
  6699. this._status = _loader.LoaderStatus.kConnecting;
  6700. xhr.send();
  6701. }
  6702. }, {
  6703. key: 'abort',
  6704. value: function abort() {
  6705. this._requestAbort = true;
  6706. if (this._xhr) {
  6707. this._xhr.abort();
  6708. }
  6709. this._status = _loader.LoaderStatus.kComplete;
  6710. }
  6711. }, {
  6712. key: '_onReadyStateChange',
  6713. value: function _onReadyStateChange(e) {
  6714. var xhr = e.target;
  6715. if (xhr.readyState === 2) {
  6716. // HEADERS_RECEIVED
  6717. if (xhr.responseURL != undefined && xhr.responseURL !== this._requestURL) {
  6718. if (this._onURLRedirect) {
  6719. var redirectedURL = this._seekHandler.removeURLParameters(xhr.responseURL);
  6720. this._onURLRedirect(redirectedURL);
  6721. }
  6722. }
  6723. if (xhr.status !== 0 && (xhr.status < 200 || xhr.status > 299)) {
  6724. this._status = _loader.LoaderStatus.kError;
  6725. if (this._onError) {
  6726. this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: xhr.status, msg: xhr.statusText });
  6727. } else {
  6728. throw new _exception.RuntimeException('MozChunkedLoader: Http code invalid, ' + xhr.status + ' ' + xhr.statusText);
  6729. }
  6730. } else {
  6731. this._status = _loader.LoaderStatus.kBuffering;
  6732. }
  6733. }
  6734. }
  6735. }, {
  6736. key: '_onProgress',
  6737. value: function _onProgress(e) {
  6738. if (this._status === _loader.LoaderStatus.kError) {
  6739. // Ignore error response
  6740. return;
  6741. }
  6742. if (this._contentLength === null) {
  6743. if (e.total !== null && e.total !== 0) {
  6744. this._contentLength = e.total;
  6745. if (this._onContentLengthKnown) {
  6746. this._onContentLengthKnown(this._contentLength);
  6747. }
  6748. }
  6749. }
  6750. var chunk = e.target.response;
  6751. var byteStart = this._range.from + this._receivedLength;
  6752. this._receivedLength += chunk.byteLength;
  6753. if (this._onDataArrival) {
  6754. this._onDataArrival(chunk, byteStart, this._receivedLength);
  6755. }
  6756. }
  6757. }, {
  6758. key: '_onLoadEnd',
  6759. value: function _onLoadEnd(e) {
  6760. if (this._requestAbort === true) {
  6761. this._requestAbort = false;
  6762. return;
  6763. } else if (this._status === _loader.LoaderStatus.kError) {
  6764. return;
  6765. }
  6766. this._status = _loader.LoaderStatus.kComplete;
  6767. if (this._onComplete) {
  6768. this._onComplete(this._range.from, this._range.from + this._receivedLength - 1);
  6769. }
  6770. }
  6771. }, {
  6772. key: '_onXhrError',
  6773. value: function _onXhrError(e) {
  6774. this._status = _loader.LoaderStatus.kError;
  6775. var type = 0;
  6776. var info = null;
  6777. if (this._contentLength && e.loaded < this._contentLength) {
  6778. type = _loader.LoaderErrors.EARLY_EOF;
  6779. info = { code: -1, msg: 'Moz-Chunked stream meet Early-Eof' };
  6780. } else {
  6781. type = _loader.LoaderErrors.EXCEPTION;
  6782. info = { code: -1, msg: e.constructor.name + ' ' + e.type };
  6783. }
  6784. if (this._onError) {
  6785. this._onError(type, info);
  6786. } else {
  6787. throw new _exception.RuntimeException(info.msg);
  6788. }
  6789. }
  6790. }]);
  6791. return MozChunkedLoader;
  6792. }(_loader.BaseLoader);
  6793. exports.default = MozChunkedLoader;
  6794. },{"../utils/exception.js":40,"../utils/logger.js":41,"./loader.js":24}],30:[function(_dereq_,module,exports){
  6795. 'use strict';
  6796. Object.defineProperty(exports, "__esModule", {
  6797. value: true
  6798. });
  6799. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  6800. var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
  6801. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  6802. var _logger = _dereq_('../utils/logger.js');
  6803. var _logger2 = _interopRequireDefault(_logger);
  6804. var _loader = _dereq_('./loader.js');
  6805. var _exception = _dereq_('../utils/exception.js');
  6806. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6807. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6808. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  6809. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*
  6810. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  6811. *
  6812. * @author zheng qian <xqq@xqq.im>
  6813. *
  6814. * Licensed under the Apache License, Version 2.0 (the "License");
  6815. * you may not use this file except in compliance with the License.
  6816. * You may obtain a copy of the License at
  6817. *
  6818. * http://www.apache.org/licenses/LICENSE-2.0
  6819. *
  6820. * Unless required by applicable law or agreed to in writing, software
  6821. * distributed under the License is distributed on an "AS IS" BASIS,
  6822. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6823. * See the License for the specific language governing permissions and
  6824. * limitations under the License.
  6825. */
  6826. /* Notice: ms-stream may cause IE/Edge browser crash if seek too frequently!!!
  6827. * The browser may crash in wininet.dll. Disable for now.
  6828. *
  6829. * For IE11/Edge browser by microsoft which supports `xhr.responseType = 'ms-stream'`
  6830. * Notice that ms-stream API sucks. The buffer is always expanding along with downloading.
  6831. *
  6832. * We need to abort the xhr if buffer size exceeded limit size (e.g. 16 MiB), then do reconnect.
  6833. * in order to release previous ArrayBuffer to avoid memory leak
  6834. *
  6835. * Otherwise, the ArrayBuffer will increase to a terrible size that equals final file size.
  6836. */
  6837. var MSStreamLoader = function (_BaseLoader) {
  6838. _inherits(MSStreamLoader, _BaseLoader);
  6839. _createClass(MSStreamLoader, null, [{
  6840. key: 'isSupported',
  6841. value: function isSupported() {
  6842. try {
  6843. if (typeof self.MSStream === 'undefined' || typeof self.MSStreamReader === 'undefined') {
  6844. return false;
  6845. }
  6846. var xhr = new XMLHttpRequest();
  6847. xhr.open('GET', 'https://example.com', true);
  6848. xhr.responseType = 'ms-stream';
  6849. return xhr.responseType === 'ms-stream';
  6850. } catch (e) {
  6851. _logger2.default.w('MSStreamLoader', e.message);
  6852. return false;
  6853. }
  6854. }
  6855. }]);
  6856. function MSStreamLoader(seekHandler, config) {
  6857. _classCallCheck(this, MSStreamLoader);
  6858. var _this = _possibleConstructorReturn(this, (MSStreamLoader.__proto__ || Object.getPrototypeOf(MSStreamLoader)).call(this, 'xhr-msstream-loader'));
  6859. _this.TAG = 'MSStreamLoader';
  6860. _this._seekHandler = seekHandler;
  6861. _this._config = config;
  6862. _this._needStash = true;
  6863. _this._xhr = null;
  6864. _this._reader = null; // MSStreamReader
  6865. _this._totalRange = null;
  6866. _this._currentRange = null;
  6867. _this._currentRequestURL = null;
  6868. _this._currentRedirectedURL = null;
  6869. _this._contentLength = null;
  6870. _this._receivedLength = 0;
  6871. _this._bufferLimit = 16 * 1024 * 1024; // 16MB
  6872. _this._lastTimeBufferSize = 0;
  6873. _this._isReconnecting = false;
  6874. return _this;
  6875. }
  6876. _createClass(MSStreamLoader, [{
  6877. key: 'destroy',
  6878. value: function destroy() {
  6879. if (this.isWorking()) {
  6880. this.abort();
  6881. }
  6882. if (this._reader) {
  6883. this._reader.onprogress = null;
  6884. this._reader.onload = null;
  6885. this._reader.onerror = null;
  6886. this._reader = null;
  6887. }
  6888. if (this._xhr) {
  6889. this._xhr.onreadystatechange = null;
  6890. this._xhr = null;
  6891. }
  6892. _get(MSStreamLoader.prototype.__proto__ || Object.getPrototypeOf(MSStreamLoader.prototype), 'destroy', this).call(this);
  6893. }
  6894. }, {
  6895. key: 'open',
  6896. value: function open(dataSource, range) {
  6897. this._internalOpen(dataSource, range, false);
  6898. }
  6899. }, {
  6900. key: '_internalOpen',
  6901. value: function _internalOpen(dataSource, range, isSubrange) {
  6902. this._dataSource = dataSource;
  6903. if (!isSubrange) {
  6904. this._totalRange = range;
  6905. } else {
  6906. this._currentRange = range;
  6907. }
  6908. var sourceURL = dataSource.url;
  6909. if (this._config.reuseRedirectedURL) {
  6910. if (this._currentRedirectedURL != undefined) {
  6911. sourceURL = this._currentRedirectedURL;
  6912. } else if (dataSource.redirectedURL != undefined) {
  6913. sourceURL = dataSource.redirectedURL;
  6914. }
  6915. }
  6916. var seekConfig = this._seekHandler.getConfig(sourceURL, range);
  6917. this._currentRequestURL = seekConfig.url;
  6918. var reader = this._reader = new self.MSStreamReader();
  6919. reader.onprogress = this._msrOnProgress.bind(this);
  6920. reader.onload = this._msrOnLoad.bind(this);
  6921. reader.onerror = this._msrOnError.bind(this);
  6922. var xhr = this._xhr = new XMLHttpRequest();
  6923. xhr.open('GET', seekConfig.url, true);
  6924. xhr.responseType = 'ms-stream';
  6925. xhr.onreadystatechange = this._xhrOnReadyStateChange.bind(this);
  6926. xhr.onerror = this._xhrOnError.bind(this);
  6927. if (dataSource.withCredentials) {
  6928. xhr.withCredentials = true;
  6929. }
  6930. if (_typeof(seekConfig.headers) === 'object') {
  6931. var headers = seekConfig.headers;
  6932. for (var key in headers) {
  6933. if (headers.hasOwnProperty(key)) {
  6934. xhr.setRequestHeader(key, headers[key]);
  6935. }
  6936. }
  6937. }
  6938. if (this._isReconnecting) {
  6939. this._isReconnecting = false;
  6940. } else {
  6941. this._status = _loader.LoaderStatus.kConnecting;
  6942. }
  6943. xhr.send();
  6944. }
  6945. }, {
  6946. key: 'abort',
  6947. value: function abort() {
  6948. this._internalAbort();
  6949. this._status = _loader.LoaderStatus.kComplete;
  6950. }
  6951. }, {
  6952. key: '_internalAbort',
  6953. value: function _internalAbort() {
  6954. if (this._reader) {
  6955. if (this._reader.readyState === 1) {
  6956. // LOADING
  6957. this._reader.abort();
  6958. }
  6959. this._reader.onprogress = null;
  6960. this._reader.onload = null;
  6961. this._reader.onerror = null;
  6962. this._reader = null;
  6963. }
  6964. if (this._xhr) {
  6965. this._xhr.abort();
  6966. this._xhr.onreadystatechange = null;
  6967. this._xhr = null;
  6968. }
  6969. }
  6970. }, {
  6971. key: '_xhrOnReadyStateChange',
  6972. value: function _xhrOnReadyStateChange(e) {
  6973. var xhr = e.target;
  6974. if (xhr.readyState === 2) {
  6975. // HEADERS_RECEIVED
  6976. if (xhr.status >= 200 && xhr.status <= 299) {
  6977. this._status = _loader.LoaderStatus.kBuffering;
  6978. if (xhr.responseURL != undefined) {
  6979. var redirectedURL = this._seekHandler.removeURLParameters(xhr.responseURL);
  6980. if (xhr.responseURL !== this._currentRequestURL && redirectedURL !== this._currentRedirectedURL) {
  6981. this._currentRedirectedURL = redirectedURL;
  6982. if (this._onURLRedirect) {
  6983. this._onURLRedirect(redirectedURL);
  6984. }
  6985. }
  6986. }
  6987. var lengthHeader = xhr.getResponseHeader('Content-Length');
  6988. if (lengthHeader != null && this._contentLength == null) {
  6989. var length = parseInt(lengthHeader);
  6990. if (length > 0) {
  6991. this._contentLength = length;
  6992. if (this._onContentLengthKnown) {
  6993. this._onContentLengthKnown(this._contentLength);
  6994. }
  6995. }
  6996. }
  6997. } else {
  6998. this._status = _loader.LoaderStatus.kError;
  6999. if (this._onError) {
  7000. this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: xhr.status, msg: xhr.statusText });
  7001. } else {
  7002. throw new _exception.RuntimeException('MSStreamLoader: Http code invalid, ' + xhr.status + ' ' + xhr.statusText);
  7003. }
  7004. }
  7005. } else if (xhr.readyState === 3) {
  7006. // LOADING
  7007. if (xhr.status >= 200 && xhr.status <= 299) {
  7008. this._status = _loader.LoaderStatus.kBuffering;
  7009. var msstream = xhr.response;
  7010. this._reader.readAsArrayBuffer(msstream);
  7011. }
  7012. }
  7013. }
  7014. }, {
  7015. key: '_xhrOnError',
  7016. value: function _xhrOnError(e) {
  7017. this._status = _loader.LoaderStatus.kError;
  7018. var type = _loader.LoaderErrors.EXCEPTION;
  7019. var info = { code: -1, msg: e.constructor.name + ' ' + e.type };
  7020. if (this._onError) {
  7021. this._onError(type, info);
  7022. } else {
  7023. throw new _exception.RuntimeException(info.msg);
  7024. }
  7025. }
  7026. }, {
  7027. key: '_msrOnProgress',
  7028. value: function _msrOnProgress(e) {
  7029. var reader = e.target;
  7030. var bigbuffer = reader.result;
  7031. if (bigbuffer == null) {
  7032. // result may be null, workaround for buggy M$
  7033. this._doReconnectIfNeeded();
  7034. return;
  7035. }
  7036. var slice = bigbuffer.slice(this._lastTimeBufferSize);
  7037. this._lastTimeBufferSize = bigbuffer.byteLength;
  7038. var byteStart = this._totalRange.from + this._receivedLength;
  7039. this._receivedLength += slice.byteLength;
  7040. if (this._onDataArrival) {
  7041. this._onDataArrival(slice, byteStart, this._receivedLength);
  7042. }
  7043. if (bigbuffer.byteLength >= this._bufferLimit) {
  7044. _logger2.default.v(this.TAG, 'MSStream buffer exceeded max size near ' + (byteStart + slice.byteLength) + ', reconnecting...');
  7045. this._doReconnectIfNeeded();
  7046. }
  7047. }
  7048. }, {
  7049. key: '_doReconnectIfNeeded',
  7050. value: function _doReconnectIfNeeded() {
  7051. if (this._contentLength == null || this._receivedLength < this._contentLength) {
  7052. this._isReconnecting = true;
  7053. this._lastTimeBufferSize = 0;
  7054. this._internalAbort();
  7055. var range = {
  7056. from: this._totalRange.from + this._receivedLength,
  7057. to: -1
  7058. };
  7059. this._internalOpen(this._dataSource, range, true);
  7060. }
  7061. }
  7062. }, {
  7063. key: '_msrOnLoad',
  7064. value: function _msrOnLoad(e) {
  7065. // actually it is onComplete event
  7066. this._status = _loader.LoaderStatus.kComplete;
  7067. if (this._onComplete) {
  7068. this._onComplete(this._totalRange.from, this._totalRange.from + this._receivedLength - 1);
  7069. }
  7070. }
  7071. }, {
  7072. key: '_msrOnError',
  7073. value: function _msrOnError(e) {
  7074. this._status = _loader.LoaderStatus.kError;
  7075. var type = 0;
  7076. var info = null;
  7077. if (this._contentLength && this._receivedLength < this._contentLength) {
  7078. type = _loader.LoaderErrors.EARLY_EOF;
  7079. info = { code: -1, msg: 'MSStream meet Early-Eof' };
  7080. } else {
  7081. type = _loader.LoaderErrors.EARLY_EOF;
  7082. info = { code: -1, msg: e.constructor.name + ' ' + e.type };
  7083. }
  7084. if (this._onError) {
  7085. this._onError(type, info);
  7086. } else {
  7087. throw new _exception.RuntimeException(info.msg);
  7088. }
  7089. }
  7090. }]);
  7091. return MSStreamLoader;
  7092. }(_loader.BaseLoader);
  7093. exports.default = MSStreamLoader;
  7094. },{"../utils/exception.js":40,"../utils/logger.js":41,"./loader.js":24}],31:[function(_dereq_,module,exports){
  7095. 'use strict';
  7096. Object.defineProperty(exports, "__esModule", {
  7097. value: true
  7098. });
  7099. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  7100. var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
  7101. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  7102. var _logger = _dereq_('../utils/logger.js');
  7103. var _logger2 = _interopRequireDefault(_logger);
  7104. var _speedSampler = _dereq_('./speed-sampler.js');
  7105. var _speedSampler2 = _interopRequireDefault(_speedSampler);
  7106. var _loader = _dereq_('./loader.js');
  7107. var _exception = _dereq_('../utils/exception.js');
  7108. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  7109. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7110. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  7111. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*
  7112. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  7113. *
  7114. * @author zheng qian <xqq@xqq.im>
  7115. *
  7116. * Licensed under the Apache License, Version 2.0 (the "License");
  7117. * you may not use this file except in compliance with the License.
  7118. * You may obtain a copy of the License at
  7119. *
  7120. * http://www.apache.org/licenses/LICENSE-2.0
  7121. *
  7122. * Unless required by applicable law or agreed to in writing, software
  7123. * distributed under the License is distributed on an "AS IS" BASIS,
  7124. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7125. * See the License for the specific language governing permissions and
  7126. * limitations under the License.
  7127. */
  7128. // Universal IO Loader, implemented by adding Range header in xhr's request header
  7129. var RangeLoader = function (_BaseLoader) {
  7130. _inherits(RangeLoader, _BaseLoader);
  7131. _createClass(RangeLoader, null, [{
  7132. key: 'isSupported',
  7133. value: function isSupported() {
  7134. try {
  7135. var xhr = new XMLHttpRequest();
  7136. xhr.open('GET', 'https://example.com', true);
  7137. xhr.responseType = 'arraybuffer';
  7138. return xhr.responseType === 'arraybuffer';
  7139. } catch (e) {
  7140. _logger2.default.w('RangeLoader', e.message);
  7141. return false;
  7142. }
  7143. }
  7144. }]);
  7145. function RangeLoader(seekHandler, config) {
  7146. _classCallCheck(this, RangeLoader);
  7147. var _this = _possibleConstructorReturn(this, (RangeLoader.__proto__ || Object.getPrototypeOf(RangeLoader)).call(this, 'xhr-range-loader'));
  7148. _this.TAG = 'RangeLoader';
  7149. _this._seekHandler = seekHandler;
  7150. _this._config = config;
  7151. _this._needStash = false;
  7152. _this._chunkSizeKBList = [128, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 5120, 6144, 7168, 8192];
  7153. _this._currentChunkSizeKB = 384;
  7154. _this._currentSpeedNormalized = 0;
  7155. _this._zeroSpeedChunkCount = 0;
  7156. _this._xhr = null;
  7157. _this._speedSampler = new _speedSampler2.default();
  7158. _this._requestAbort = false;
  7159. _this._waitForTotalLength = false;
  7160. _this._totalLengthReceived = false;
  7161. _this._currentRequestURL = null;
  7162. _this._currentRedirectedURL = null;
  7163. _this._currentRequestRange = null;
  7164. _this._totalLength = null; // size of the entire file
  7165. _this._contentLength = null; // Content-Length of entire request range
  7166. _this._receivedLength = 0; // total received bytes
  7167. _this._lastTimeLoaded = 0; // received bytes of current request sub-range
  7168. return _this;
  7169. }
  7170. _createClass(RangeLoader, [{
  7171. key: 'destroy',
  7172. value: function destroy() {
  7173. if (this.isWorking()) {
  7174. this.abort();
  7175. }
  7176. if (this._xhr) {
  7177. this._xhr.onreadystatechange = null;
  7178. this._xhr.onprogress = null;
  7179. this._xhr.onload = null;
  7180. this._xhr.onerror = null;
  7181. this._xhr = null;
  7182. }
  7183. _get(RangeLoader.prototype.__proto__ || Object.getPrototypeOf(RangeLoader.prototype), 'destroy', this).call(this);
  7184. }
  7185. }, {
  7186. key: 'open',
  7187. value: function open(dataSource, range) {
  7188. this._dataSource = dataSource;
  7189. this._range = range;
  7190. this._status = _loader.LoaderStatus.kConnecting;
  7191. var useRefTotalLength = false;
  7192. if (this._dataSource.filesize != undefined && this._dataSource.filesize !== 0) {
  7193. useRefTotalLength = true;
  7194. this._totalLength = this._dataSource.filesize;
  7195. }
  7196. if (!this._totalLengthReceived && !useRefTotalLength) {
  7197. // We need total filesize
  7198. this._waitForTotalLength = true;
  7199. this._internalOpen(this._dataSource, { from: 0, to: -1 });
  7200. } else {
  7201. // We have filesize, start loading
  7202. this._openSubRange();
  7203. }
  7204. }
  7205. }, {
  7206. key: '_openSubRange',
  7207. value: function _openSubRange() {
  7208. var chunkSize = this._currentChunkSizeKB * 1024;
  7209. var from = this._range.from + this._receivedLength;
  7210. var to = from + chunkSize;
  7211. if (this._contentLength != null) {
  7212. if (to - this._range.from >= this._contentLength) {
  7213. to = this._range.from + this._contentLength - 1;
  7214. }
  7215. }
  7216. this._currentRequestRange = { from: from, to: to };
  7217. this._internalOpen(this._dataSource, this._currentRequestRange);
  7218. }
  7219. }, {
  7220. key: '_internalOpen',
  7221. value: function _internalOpen(dataSource, range) {
  7222. this._lastTimeLoaded = 0;
  7223. var sourceURL = dataSource.url;
  7224. if (this._config.reuseRedirectedURL) {
  7225. if (this._currentRedirectedURL != undefined) {
  7226. sourceURL = this._currentRedirectedURL;
  7227. } else if (dataSource.redirectedURL != undefined) {
  7228. sourceURL = dataSource.redirectedURL;
  7229. }
  7230. }
  7231. var seekConfig = this._seekHandler.getConfig(sourceURL, range);
  7232. this._currentRequestURL = seekConfig.url;
  7233. var xhr = this._xhr = new XMLHttpRequest();
  7234. xhr.open('GET', seekConfig.url, true);
  7235. xhr.responseType = 'arraybuffer';
  7236. xhr.onreadystatechange = this._onReadyStateChange.bind(this);
  7237. xhr.onprogress = this._onProgress.bind(this);
  7238. xhr.onload = this._onLoad.bind(this);
  7239. xhr.onerror = this._onXhrError.bind(this);
  7240. if (dataSource.withCredentials) {
  7241. xhr.withCredentials = true;
  7242. }
  7243. if (_typeof(seekConfig.headers) === 'object') {
  7244. var headers = seekConfig.headers;
  7245. for (var key in headers) {
  7246. if (headers.hasOwnProperty(key)) {
  7247. xhr.setRequestHeader(key, headers[key]);
  7248. }
  7249. }
  7250. }
  7251. xhr.send();
  7252. }
  7253. }, {
  7254. key: 'abort',
  7255. value: function abort() {
  7256. this._requestAbort = true;
  7257. this._internalAbort();
  7258. this._status = _loader.LoaderStatus.kComplete;
  7259. }
  7260. }, {
  7261. key: '_internalAbort',
  7262. value: function _internalAbort() {
  7263. if (this._xhr) {
  7264. this._xhr.onreadystatechange = null;
  7265. this._xhr.onprogress = null;
  7266. this._xhr.onload = null;
  7267. this._xhr.onerror = null;
  7268. this._xhr.abort();
  7269. this._xhr = null;
  7270. }
  7271. }
  7272. }, {
  7273. key: '_onReadyStateChange',
  7274. value: function _onReadyStateChange(e) {
  7275. var xhr = e.target;
  7276. if (xhr.readyState === 2) {
  7277. // HEADERS_RECEIVED
  7278. if (xhr.responseURL != undefined) {
  7279. // if the browser support this property
  7280. var redirectedURL = this._seekHandler.removeURLParameters(xhr.responseURL);
  7281. if (xhr.responseURL !== this._currentRequestURL && redirectedURL !== this._currentRedirectedURL) {
  7282. this._currentRedirectedURL = redirectedURL;
  7283. if (this._onURLRedirect) {
  7284. this._onURLRedirect(redirectedURL);
  7285. }
  7286. }
  7287. }
  7288. if (xhr.status >= 200 && xhr.status <= 299) {
  7289. if (this._waitForTotalLength) {
  7290. return;
  7291. }
  7292. this._status = _loader.LoaderStatus.kBuffering;
  7293. } else {
  7294. this._status = _loader.LoaderStatus.kError;
  7295. if (this._onError) {
  7296. this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: xhr.status, msg: xhr.statusText });
  7297. } else {
  7298. throw new _exception.RuntimeException('RangeLoader: Http code invalid, ' + xhr.status + ' ' + xhr.statusText);
  7299. }
  7300. }
  7301. }
  7302. }
  7303. }, {
  7304. key: '_onProgress',
  7305. value: function _onProgress(e) {
  7306. if (this._status === _loader.LoaderStatus.kError) {
  7307. // Ignore error response
  7308. return;
  7309. }
  7310. if (this._contentLength === null) {
  7311. var openNextRange = false;
  7312. if (this._waitForTotalLength) {
  7313. this._waitForTotalLength = false;
  7314. this._totalLengthReceived = true;
  7315. openNextRange = true;
  7316. var total = e.total;
  7317. this._internalAbort();
  7318. if (total != null & total !== 0) {
  7319. this._totalLength = total;
  7320. }
  7321. }
  7322. // calculate currrent request range's contentLength
  7323. if (this._range.to === -1) {
  7324. this._contentLength = this._totalLength - this._range.from;
  7325. } else {
  7326. // to !== -1
  7327. this._contentLength = this._range.to - this._range.from + 1;
  7328. }
  7329. if (openNextRange) {
  7330. this._openSubRange();
  7331. return;
  7332. }
  7333. if (this._onContentLengthKnown) {
  7334. this._onContentLengthKnown(this._contentLength);
  7335. }
  7336. }
  7337. var delta = e.loaded - this._lastTimeLoaded;
  7338. this._lastTimeLoaded = e.loaded;
  7339. this._speedSampler.addBytes(delta);
  7340. }
  7341. }, {
  7342. key: '_normalizeSpeed',
  7343. value: function _normalizeSpeed(input) {
  7344. var list = this._chunkSizeKBList;
  7345. var last = list.length - 1;
  7346. var mid = 0;
  7347. var lbound = 0;
  7348. var ubound = last;
  7349. if (input < list[0]) {
  7350. return list[0];
  7351. }
  7352. while (lbound <= ubound) {
  7353. mid = lbound + Math.floor((ubound - lbound) / 2);
  7354. if (mid === last || input >= list[mid] && input < list[mid + 1]) {
  7355. return list[mid];
  7356. } else if (list[mid] < input) {
  7357. lbound = mid + 1;
  7358. } else {
  7359. ubound = mid - 1;
  7360. }
  7361. }
  7362. }
  7363. }, {
  7364. key: '_onLoad',
  7365. value: function _onLoad(e) {
  7366. if (this._status === _loader.LoaderStatus.kError) {
  7367. // Ignore error response
  7368. return;
  7369. }
  7370. if (this._waitForTotalLength) {
  7371. this._waitForTotalLength = false;
  7372. return;
  7373. }
  7374. this._lastTimeLoaded = 0;
  7375. var KBps = this._speedSampler.lastSecondKBps;
  7376. if (KBps === 0) {
  7377. this._zeroSpeedChunkCount++;
  7378. if (this._zeroSpeedChunkCount >= 3) {
  7379. // Try get currentKBps after 3 chunks
  7380. KBps = this._speedSampler.currentKBps;
  7381. }
  7382. }
  7383. if (KBps !== 0) {
  7384. var normalized = this._normalizeSpeed(KBps);
  7385. if (this._currentSpeedNormalized !== normalized) {
  7386. this._currentSpeedNormalized = normalized;
  7387. this._currentChunkSizeKB = normalized;
  7388. }
  7389. }
  7390. var chunk = e.target.response;
  7391. var byteStart = this._range.from + this._receivedLength;
  7392. this._receivedLength += chunk.byteLength;
  7393. var reportComplete = false;
  7394. if (this._contentLength != null && this._receivedLength < this._contentLength) {
  7395. // continue load next chunk
  7396. this._openSubRange();
  7397. } else {
  7398. reportComplete = true;
  7399. }
  7400. // dispatch received chunk
  7401. if (this._onDataArrival) {
  7402. this._onDataArrival(chunk, byteStart, this._receivedLength);
  7403. }
  7404. if (reportComplete) {
  7405. this._status = _loader.LoaderStatus.kComplete;
  7406. if (this._onComplete) {
  7407. this._onComplete(this._range.from, this._range.from + this._receivedLength - 1);
  7408. }
  7409. }
  7410. }
  7411. }, {
  7412. key: '_onXhrError',
  7413. value: function _onXhrError(e) {
  7414. this._status = _loader.LoaderStatus.kError;
  7415. var type = 0;
  7416. var info = null;
  7417. if (this._contentLength && this._receivedLength > 0 && this._receivedLength < this._contentLength) {
  7418. type = _loader.LoaderErrors.EARLY_EOF;
  7419. info = { code: -1, msg: 'RangeLoader meet Early-Eof' };
  7420. } else {
  7421. type = _loader.LoaderErrors.EXCEPTION;
  7422. info = { code: -1, msg: e.constructor.name + ' ' + e.type };
  7423. }
  7424. if (this._onError) {
  7425. this._onError(type, info);
  7426. } else {
  7427. throw new _exception.RuntimeException(info.msg);
  7428. }
  7429. }
  7430. }, {
  7431. key: 'currentSpeed',
  7432. get: function get() {
  7433. return this._speedSampler.lastSecondKBps;
  7434. }
  7435. }]);
  7436. return RangeLoader;
  7437. }(_loader.BaseLoader);
  7438. exports.default = RangeLoader;
  7439. },{"../utils/exception.js":40,"../utils/logger.js":41,"./loader.js":24,"./speed-sampler.js":27}],32:[function(_dereq_,module,exports){
  7440. 'use strict';
  7441. Object.defineProperty(exports, "__esModule", {
  7442. value: true
  7443. });
  7444. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  7445. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  7446. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  7447. *
  7448. * @author zheng qian <xqq@xqq.im>
  7449. *
  7450. * Licensed under the Apache License, Version 2.0 (the "License");
  7451. * you may not use this file except in compliance with the License.
  7452. * You may obtain a copy of the License at
  7453. *
  7454. * http://www.apache.org/licenses/LICENSE-2.0
  7455. *
  7456. * Unless required by applicable law or agreed to in writing, software
  7457. * distributed under the License is distributed on an "AS IS" BASIS,
  7458. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7459. * See the License for the specific language governing permissions and
  7460. * limitations under the License.
  7461. */
  7462. var _events = _dereq_('events');
  7463. var _events2 = _interopRequireDefault(_events);
  7464. var _logger = _dereq_('../utils/logger.js');
  7465. var _logger2 = _interopRequireDefault(_logger);
  7466. var _browser = _dereq_('../utils/browser.js');
  7467. var _browser2 = _interopRequireDefault(_browser);
  7468. var _playerEvents = _dereq_('./player-events.js');
  7469. var _playerEvents2 = _interopRequireDefault(_playerEvents);
  7470. var _transmuxer = _dereq_('../core/transmuxer.js');
  7471. var _transmuxer2 = _interopRequireDefault(_transmuxer);
  7472. var _transmuxingEvents = _dereq_('../core/transmuxing-events.js');
  7473. var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
  7474. var _mseController = _dereq_('../core/mse-controller.js');
  7475. var _mseController2 = _interopRequireDefault(_mseController);
  7476. var _mseEvents = _dereq_('../core/mse-events.js');
  7477. var _mseEvents2 = _interopRequireDefault(_mseEvents);
  7478. var _playerErrors = _dereq_('./player-errors.js');
  7479. var _config = _dereq_('../config.js');
  7480. var _exception = _dereq_('../utils/exception.js');
  7481. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  7482. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7483. var FlvPlayer = function () {
  7484. function FlvPlayer(mediaDataSource, config) {
  7485. _classCallCheck(this, FlvPlayer);
  7486. this.TAG = 'FlvPlayer';
  7487. this._type = 'FlvPlayer';
  7488. this._emitter = new _events2.default();
  7489. this._config = (0, _config.createDefaultConfig)();
  7490. if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object') {
  7491. Object.assign(this._config, config);
  7492. }
  7493. if (mediaDataSource.type.toLowerCase() !== 'flv') {
  7494. throw new _exception.InvalidArgumentException('FlvPlayer requires an flv MediaDataSource input!');
  7495. }
  7496. if (mediaDataSource.isLive === true) {
  7497. this._config.isLive = true;
  7498. }
  7499. this.e = {
  7500. onvLoadedMetadata: this._onvLoadedMetadata.bind(this),
  7501. onvSeeking: this._onvSeeking.bind(this),
  7502. onvCanPlay: this._onvCanPlay.bind(this),
  7503. onvStalled: this._onvStalled.bind(this),
  7504. onvProgress: this._onvProgress.bind(this)
  7505. };
  7506. if (self.performance && self.performance.now) {
  7507. this._now = self.performance.now.bind(self.performance);
  7508. } else {
  7509. this._now = Date.now;
  7510. }
  7511. this._pendingSeekTime = null; // in seconds
  7512. this._requestSetTime = false;
  7513. this._seekpointRecord = null;
  7514. this._progressChecker = null;
  7515. this._mediaDataSource = mediaDataSource;
  7516. this._mediaElement = null;
  7517. this._msectl = null;
  7518. this._transmuxer = null;
  7519. this._mseSourceOpened = false;
  7520. this._hasPendingLoad = false;
  7521. this._receivedCanPlay = false;
  7522. this._mediaInfo = null;
  7523. this._statisticsInfo = null;
  7524. var chromeNeedIDRFix = _browser2.default.chrome && (_browser2.default.version.major < 50 || _browser2.default.version.major === 50 && _browser2.default.version.build < 2661);
  7525. this._alwaysSeekKeyframe = chromeNeedIDRFix || _browser2.default.msedge || _browser2.default.msie ? true : false;
  7526. if (this._alwaysSeekKeyframe) {
  7527. this._config.accurateSeek = false;
  7528. }
  7529. }
  7530. _createClass(FlvPlayer, [{
  7531. key: 'destroy',
  7532. value: function destroy() {
  7533. if (this._progressChecker != null) {
  7534. window.clearInterval(this._progressChecker);
  7535. this._progressChecker = null;
  7536. }
  7537. if (this._transmuxer) {
  7538. this.unload();
  7539. }
  7540. if (this._mediaElement) {
  7541. this.detachMediaElement();
  7542. }
  7543. this.e = null;
  7544. this._mediaDataSource = null;
  7545. this._emitter.removeAllListeners();
  7546. this._emitter = null;
  7547. }
  7548. }, {
  7549. key: 'on',
  7550. value: function on(event, listener) {
  7551. var _this = this;
  7552. if (event === _playerEvents2.default.MEDIA_INFO) {
  7553. if (this._mediaInfo != null) {
  7554. Promise.resolve().then(function () {
  7555. _this._emitter.emit(_playerEvents2.default.MEDIA_INFO, _this.mediaInfo);
  7556. });
  7557. }
  7558. } else if (event === _playerEvents2.default.STATISTICS_INFO) {
  7559. if (this._statisticsInfo != null) {
  7560. Promise.resolve().then(function () {
  7561. _this._emitter.emit(_playerEvents2.default.STATISTICS_INFO, _this.statisticsInfo);
  7562. });
  7563. }
  7564. }
  7565. this._emitter.addListener(event, listener);
  7566. }
  7567. }, {
  7568. key: 'off',
  7569. value: function off(event, listener) {
  7570. this._emitter.removeListener(event, listener);
  7571. }
  7572. }, {
  7573. key: 'attachMediaElement',
  7574. value: function attachMediaElement(mediaElement) {
  7575. var _this2 = this;
  7576. this._mediaElement = mediaElement;
  7577. mediaElement.addEventListener('loadedmetadata', this.e.onvLoadedMetadata);
  7578. mediaElement.addEventListener('seeking', this.e.onvSeeking);
  7579. mediaElement.addEventListener('canplay', this.e.onvCanPlay);
  7580. mediaElement.addEventListener('stalled', this.e.onvStalled);
  7581. mediaElement.addEventListener('progress', this.e.onvProgress);
  7582. this._msectl = new _mseController2.default(this._config);
  7583. this._msectl.on(_mseEvents2.default.UPDATE_END, this._onmseUpdateEnd.bind(this));
  7584. this._msectl.on(_mseEvents2.default.BUFFER_FULL, this._onmseBufferFull.bind(this));
  7585. this._msectl.on(_mseEvents2.default.SOURCE_OPEN, function () {
  7586. _this2._mseSourceOpened = true;
  7587. if (_this2._hasPendingLoad) {
  7588. _this2._hasPendingLoad = false;
  7589. _this2.load();
  7590. }
  7591. });
  7592. this._msectl.on(_mseEvents2.default.ERROR, function (info) {
  7593. _this2._emitter.emit(_playerEvents2.default.ERROR, _playerErrors.ErrorTypes.MEDIA_ERROR, _playerErrors.ErrorDetails.MEDIA_MSE_ERROR, info);
  7594. });
  7595. this._msectl.attachMediaElement(mediaElement);
  7596. if (this._pendingSeekTime != null) {
  7597. try {
  7598. mediaElement.currentTime = this._pendingSeekTime;
  7599. this._pendingSeekTime = null;
  7600. } catch (e) {
  7601. // IE11 may throw InvalidStateError if readyState === 0
  7602. // We can defer set currentTime operation after loadedmetadata
  7603. }
  7604. }
  7605. }
  7606. }, {
  7607. key: 'detachMediaElement',
  7608. value: function detachMediaElement() {
  7609. if (this._mediaElement) {
  7610. this._msectl.detachMediaElement();
  7611. this._mediaElement.removeEventListener('loadedmetadata', this.e.onvLoadedMetadata);
  7612. this._mediaElement.removeEventListener('seeking', this.e.onvSeeking);
  7613. this._mediaElement.removeEventListener('canplay', this.e.onvCanPlay);
  7614. this._mediaElement.removeEventListener('stalled', this.e.onvStalled);
  7615. this._mediaElement.removeEventListener('progress', this.e.onvProgress);
  7616. this._mediaElement = null;
  7617. }
  7618. if (this._msectl) {
  7619. this._msectl.destroy();
  7620. this._msectl = null;
  7621. }
  7622. }
  7623. }, {
  7624. key: 'load',
  7625. value: function load() {
  7626. var _this3 = this;
  7627. if (!this._mediaElement) {
  7628. throw new _exception.IllegalStateException('HTMLMediaElement must be attached before load()!');
  7629. }
  7630. if (this._transmuxer) {
  7631. throw new _exception.IllegalStateException('FlvPlayer.load() has been called, please call unload() first!');
  7632. }
  7633. if (this._hasPendingLoad) {
  7634. return;
  7635. }
  7636. if (this._config.deferLoadAfterSourceOpen && this._mseSourceOpened === false) {
  7637. this._hasPendingLoad = true;
  7638. return;
  7639. }
  7640. if (this._mediaElement.readyState > 0) {
  7641. this._requestSetTime = true;
  7642. // IE11 may throw InvalidStateError if readyState === 0
  7643. this._mediaElement.currentTime = 0;
  7644. }
  7645. this._transmuxer = new _transmuxer2.default(this._mediaDataSource, this._config);
  7646. this._transmuxer.on(_transmuxingEvents2.default.INIT_SEGMENT, function (type, is) {
  7647. _this3._msectl.appendInitSegment(is);
  7648. });
  7649. this._transmuxer.on(_transmuxingEvents2.default.MEDIA_SEGMENT, function (type, ms) {
  7650. _this3._msectl.appendMediaSegment(ms);
  7651. // lazyLoad check
  7652. if (_this3._config.lazyLoad && !_this3._config.isLive) {
  7653. var currentTime = _this3._mediaElement.currentTime;
  7654. if (ms.info.endDts >= (currentTime + _this3._config.lazyLoadMaxDuration) * 1000) {
  7655. if (_this3._progressChecker == null) {
  7656. _logger2.default.v(_this3.TAG, 'Maximum buffering duration exceeded, suspend transmuxing task');
  7657. _this3._suspendTransmuxer();
  7658. }
  7659. }
  7660. }
  7661. });
  7662. this._transmuxer.on(_transmuxingEvents2.default.LOADING_COMPLETE, function () {
  7663. _this3._msectl.endOfStream();
  7664. _this3._emitter.emit(_playerEvents2.default.LOADING_COMPLETE);
  7665. });
  7666. this._transmuxer.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF, function () {
  7667. _this3._emitter.emit(_playerEvents2.default.RECOVERED_EARLY_EOF);
  7668. });
  7669. this._transmuxer.on(_transmuxingEvents2.default.IO_ERROR, function (detail, info) {
  7670. _this3._emitter.emit(_playerEvents2.default.ERROR, _playerErrors.ErrorTypes.NETWORK_ERROR, detail, info);
  7671. });
  7672. this._transmuxer.on(_transmuxingEvents2.default.DEMUX_ERROR, function (detail, info) {
  7673. _this3._emitter.emit(_playerEvents2.default.ERROR, _playerErrors.ErrorTypes.MEDIA_ERROR, detail, { code: -1, msg: info });
  7674. });
  7675. this._transmuxer.on(_transmuxingEvents2.default.MEDIA_INFO, function (mediaInfo) {
  7676. _this3._mediaInfo = mediaInfo;
  7677. _this3._emitter.emit(_playerEvents2.default.MEDIA_INFO, Object.assign({}, mediaInfo));
  7678. });
  7679. this._transmuxer.on(_transmuxingEvents2.default.STATISTICS_INFO, function (statInfo) {
  7680. _this3._statisticsInfo = _this3._fillStatisticsInfo(statInfo);
  7681. _this3._emitter.emit(_playerEvents2.default.STATISTICS_INFO, Object.assign({}, _this3._statisticsInfo));
  7682. });
  7683. this._transmuxer.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, function (milliseconds) {
  7684. if (_this3._mediaElement && !_this3._config.accurateSeek) {
  7685. _this3._requestSetTime = true;
  7686. _this3._mediaElement.currentTime = milliseconds / 1000;
  7687. }
  7688. });
  7689. this._transmuxer.open();
  7690. }
  7691. }, {
  7692. key: 'unload',
  7693. value: function unload() {
  7694. if (this._mediaElement) {
  7695. this._mediaElement.pause();
  7696. }
  7697. if (this._msectl) {
  7698. this._msectl.seek(0);
  7699. }
  7700. if (this._transmuxer) {
  7701. this._transmuxer.close();
  7702. this._transmuxer.destroy();
  7703. this._transmuxer = null;
  7704. }
  7705. }
  7706. }, {
  7707. key: 'play',
  7708. value: function play() {
  7709. return this._mediaElement.play();
  7710. }
  7711. }, {
  7712. key: 'pause',
  7713. value: function pause() {
  7714. this._mediaElement.pause();
  7715. }
  7716. }, {
  7717. key: '_fillStatisticsInfo',
  7718. value: function _fillStatisticsInfo(statInfo) {
  7719. statInfo.playerType = this._type;
  7720. if (!(this._mediaElement instanceof HTMLVideoElement)) {
  7721. return statInfo;
  7722. }
  7723. var hasQualityInfo = true;
  7724. var decoded = 0;
  7725. var dropped = 0;
  7726. if (this._mediaElement.getVideoPlaybackQuality) {
  7727. var quality = this._mediaElement.getVideoPlaybackQuality();
  7728. decoded = quality.totalVideoFrames;
  7729. dropped = quality.droppedVideoFrames;
  7730. } else if (this._mediaElement.webkitDecodedFrameCount != undefined) {
  7731. decoded = this._mediaElement.webkitDecodedFrameCount;
  7732. dropped = this._mediaElement.webkitDroppedFrameCount;
  7733. } else {
  7734. hasQualityInfo = false;
  7735. }
  7736. if (hasQualityInfo) {
  7737. statInfo.decodedFrames = decoded;
  7738. statInfo.droppedFrames = dropped;
  7739. }
  7740. return statInfo;
  7741. }
  7742. }, {
  7743. key: '_onmseUpdateEnd',
  7744. value: function _onmseUpdateEnd() {
  7745. if (!this._config.lazyLoad || this._config.isLive) {
  7746. return;
  7747. }
  7748. var buffered = this._mediaElement.buffered;
  7749. var currentTime = this._mediaElement.currentTime;
  7750. var currentRangeStart = 0;
  7751. var currentRangeEnd = 0;
  7752. for (var i = 0; i < buffered.length; i++) {
  7753. var start = buffered.start(i);
  7754. var end = buffered.end(i);
  7755. if (start <= currentTime && currentTime < end) {
  7756. currentRangeStart = start;
  7757. currentRangeEnd = end;
  7758. break;
  7759. }
  7760. }
  7761. if (currentRangeEnd >= currentTime + this._config.lazyLoadMaxDuration && this._progressChecker == null) {
  7762. _logger2.default.v(this.TAG, 'Maximum buffering duration exceeded, suspend transmuxing task');
  7763. this._suspendTransmuxer();
  7764. }
  7765. }
  7766. }, {
  7767. key: '_onmseBufferFull',
  7768. value: function _onmseBufferFull() {
  7769. _logger2.default.v(this.TAG, 'MSE SourceBuffer is full, suspend transmuxing task');
  7770. if (this._progressChecker == null) {
  7771. this._suspendTransmuxer();
  7772. }
  7773. }
  7774. }, {
  7775. key: '_suspendTransmuxer',
  7776. value: function _suspendTransmuxer() {
  7777. if (this._transmuxer) {
  7778. this._transmuxer.pause();
  7779. if (this._progressChecker == null) {
  7780. this._progressChecker = window.setInterval(this._checkProgressAndResume.bind(this), 1000);
  7781. }
  7782. }
  7783. }
  7784. }, {
  7785. key: '_checkProgressAndResume',
  7786. value: function _checkProgressAndResume() {
  7787. var currentTime = this._mediaElement.currentTime;
  7788. var buffered = this._mediaElement.buffered;
  7789. var needResume = false;
  7790. for (var i = 0; i < buffered.length; i++) {
  7791. var from = buffered.start(i);
  7792. var to = buffered.end(i);
  7793. if (currentTime >= from && currentTime < to) {
  7794. if (currentTime >= to - this._config.lazyLoadRecoverDuration) {
  7795. needResume = true;
  7796. }
  7797. break;
  7798. }
  7799. }
  7800. if (needResume) {
  7801. window.clearInterval(this._progressChecker);
  7802. this._progressChecker = null;
  7803. if (needResume) {
  7804. _logger2.default.v(this.TAG, 'Continue loading from paused position');
  7805. this._transmuxer.resume();
  7806. }
  7807. }
  7808. }
  7809. }, {
  7810. key: '_isTimepointBuffered',
  7811. value: function _isTimepointBuffered(seconds) {
  7812. var buffered = this._mediaElement.buffered;
  7813. for (var i = 0; i < buffered.length; i++) {
  7814. var from = buffered.start(i);
  7815. var to = buffered.end(i);
  7816. if (seconds >= from && seconds < to) {
  7817. return true;
  7818. }
  7819. }
  7820. return false;
  7821. }
  7822. }, {
  7823. key: '_internalSeek',
  7824. value: function _internalSeek(seconds) {
  7825. var directSeek = this._isTimepointBuffered(seconds);
  7826. var directSeekBegin = false;
  7827. var directSeekBeginTime = 0;
  7828. if (seconds < 1.0 && this._mediaElement.buffered.length > 0) {
  7829. var videoBeginTime = this._mediaElement.buffered.start(0);
  7830. if (videoBeginTime < 1.0 && seconds < videoBeginTime || _browser2.default.safari) {
  7831. directSeekBegin = true;
  7832. // also workaround for Safari: Seek to 0 may cause video stuck, use 0.1 to avoid
  7833. directSeekBeginTime = _browser2.default.safari ? 0.1 : videoBeginTime;
  7834. }
  7835. }
  7836. if (directSeekBegin) {
  7837. // seek to video begin, set currentTime directly if beginPTS buffered
  7838. this._requestSetTime = true;
  7839. this._mediaElement.currentTime = directSeekBeginTime;
  7840. } else if (directSeek) {
  7841. // buffered position
  7842. if (!this._alwaysSeekKeyframe) {
  7843. this._requestSetTime = true;
  7844. this._mediaElement.currentTime = seconds;
  7845. } else {
  7846. var idr = this._msectl.getNearestKeyframe(Math.floor(seconds * 1000));
  7847. this._requestSetTime = true;
  7848. if (idr != null) {
  7849. this._mediaElement.currentTime = idr.dts / 1000;
  7850. } else {
  7851. this._mediaElement.currentTime = seconds;
  7852. }
  7853. }
  7854. if (this._progressChecker != null) {
  7855. this._checkProgressAndResume();
  7856. }
  7857. } else {
  7858. if (this._progressChecker != null) {
  7859. window.clearInterval(this._progressChecker);
  7860. this._progressChecker = null;
  7861. }
  7862. this._msectl.seek(seconds);
  7863. this._transmuxer.seek(Math.floor(seconds * 1000)); // in milliseconds
  7864. // no need to set mediaElement.currentTime if non-accurateSeek,
  7865. // just wait for the recommend_seekpoint callback
  7866. if (this._config.accurateSeek) {
  7867. this._requestSetTime = true;
  7868. this._mediaElement.currentTime = seconds;
  7869. }
  7870. }
  7871. }
  7872. }, {
  7873. key: '_checkAndApplyUnbufferedSeekpoint',
  7874. value: function _checkAndApplyUnbufferedSeekpoint() {
  7875. if (this._seekpointRecord) {
  7876. if (this._seekpointRecord.recordTime <= this._now() - 100) {
  7877. var target = this._mediaElement.currentTime;
  7878. this._seekpointRecord = null;
  7879. if (!this._isTimepointBuffered(target)) {
  7880. if (this._progressChecker != null) {
  7881. window.clearTimeout(this._progressChecker);
  7882. this._progressChecker = null;
  7883. }
  7884. // .currentTime is consists with .buffered timestamp
  7885. // Chrome/Edge use DTS, while FireFox/Safari use PTS
  7886. this._msectl.seek(target);
  7887. this._transmuxer.seek(Math.floor(target * 1000));
  7888. // set currentTime if accurateSeek, or wait for recommend_seekpoint callback
  7889. if (this._config.accurateSeek) {
  7890. this._requestSetTime = true;
  7891. this._mediaElement.currentTime = target;
  7892. }
  7893. }
  7894. } else {
  7895. window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this), 50);
  7896. }
  7897. }
  7898. }
  7899. }, {
  7900. key: '_checkAndResumeStuckPlayback',
  7901. value: function _checkAndResumeStuckPlayback(stalled) {
  7902. var media = this._mediaElement;
  7903. if (stalled || !this._receivedCanPlay || media.readyState < 2) {
  7904. // HAVE_CURRENT_DATA
  7905. var buffered = media.buffered;
  7906. if (buffered.length > 0 && media.currentTime < buffered.start(0)) {
  7907. _logger2.default.w(this.TAG, 'Playback seems stuck at ' + media.currentTime + ', seek to ' + buffered.start(0));
  7908. this._requestSetTime = true;
  7909. this._mediaElement.currentTime = buffered.start(0);
  7910. this._mediaElement.removeEventListener('progress', this.e.onvProgress);
  7911. }
  7912. } else {
  7913. // Playback didn't stuck, remove progress event listener
  7914. this._mediaElement.removeEventListener('progress', this.e.onvProgress);
  7915. }
  7916. }
  7917. }, {
  7918. key: '_onvLoadedMetadata',
  7919. value: function _onvLoadedMetadata(e) {
  7920. if (this._pendingSeekTime != null) {
  7921. this._mediaElement.currentTime = this._pendingSeekTime;
  7922. this._pendingSeekTime = null;
  7923. }
  7924. }
  7925. }, {
  7926. key: '_onvSeeking',
  7927. value: function _onvSeeking(e) {
  7928. // handle seeking request from browser's progress bar
  7929. var target = this._mediaElement.currentTime;
  7930. var buffered = this._mediaElement.buffered;
  7931. if (this._requestSetTime) {
  7932. this._requestSetTime = false;
  7933. return;
  7934. }
  7935. if (target < 1.0 && buffered.length > 0) {
  7936. // seek to video begin, set currentTime directly if beginPTS buffered
  7937. var videoBeginTime = buffered.start(0);
  7938. if (videoBeginTime < 1.0 && target < videoBeginTime || _browser2.default.safari) {
  7939. this._requestSetTime = true;
  7940. // also workaround for Safari: Seek to 0 may cause video stuck, use 0.1 to avoid
  7941. this._mediaElement.currentTime = _browser2.default.safari ? 0.1 : videoBeginTime;
  7942. return;
  7943. }
  7944. }
  7945. if (this._isTimepointBuffered(target)) {
  7946. if (this._alwaysSeekKeyframe) {
  7947. var idr = this._msectl.getNearestKeyframe(Math.floor(target * 1000));
  7948. if (idr != null) {
  7949. this._requestSetTime = true;
  7950. this._mediaElement.currentTime = idr.dts / 1000;
  7951. }
  7952. }
  7953. if (this._progressChecker != null) {
  7954. this._checkProgressAndResume();
  7955. }
  7956. return;
  7957. }
  7958. this._seekpointRecord = {
  7959. seekPoint: target,
  7960. recordTime: this._now()
  7961. };
  7962. window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this), 50);
  7963. }
  7964. }, {
  7965. key: '_onvCanPlay',
  7966. value: function _onvCanPlay(e) {
  7967. this._receivedCanPlay = true;
  7968. this._mediaElement.removeEventListener('canplay', this.e.onvCanPlay);
  7969. }
  7970. }, {
  7971. key: '_onvStalled',
  7972. value: function _onvStalled(e) {
  7973. this._checkAndResumeStuckPlayback(true);
  7974. }
  7975. }, {
  7976. key: '_onvProgress',
  7977. value: function _onvProgress(e) {
  7978. this._checkAndResumeStuckPlayback();
  7979. }
  7980. }, {
  7981. key: 'type',
  7982. get: function get() {
  7983. return this._type;
  7984. }
  7985. }, {
  7986. key: 'buffered',
  7987. get: function get() {
  7988. return this._mediaElement.buffered;
  7989. }
  7990. }, {
  7991. key: 'duration',
  7992. get: function get() {
  7993. return this._mediaElement.duration;
  7994. }
  7995. }, {
  7996. key: 'volume',
  7997. get: function get() {
  7998. return this._mediaElement.volume;
  7999. },
  8000. set: function set(value) {
  8001. this._mediaElement.volume = value;
  8002. }
  8003. }, {
  8004. key: 'muted',
  8005. get: function get() {
  8006. return this._mediaElement.muted;
  8007. },
  8008. set: function set(muted) {
  8009. this._mediaElement.muted = muted;
  8010. }
  8011. }, {
  8012. key: 'currentTime',
  8013. get: function get() {
  8014. if (this._mediaElement) {
  8015. return this._mediaElement.currentTime;
  8016. }
  8017. return 0;
  8018. },
  8019. set: function set(seconds) {
  8020. if (this._mediaElement) {
  8021. this._internalSeek(seconds);
  8022. } else {
  8023. this._pendingSeekTime = seconds;
  8024. }
  8025. }
  8026. }, {
  8027. key: 'mediaInfo',
  8028. get: function get() {
  8029. return Object.assign({}, this._mediaInfo);
  8030. }
  8031. }, {
  8032. key: 'statisticsInfo',
  8033. get: function get() {
  8034. if (this._statisticsInfo == null) {
  8035. this._statisticsInfo = {};
  8036. }
  8037. this._statisticsInfo = this._fillStatisticsInfo(this._statisticsInfo);
  8038. return Object.assign({}, this._statisticsInfo);
  8039. }
  8040. }]);
  8041. return FlvPlayer;
  8042. }();
  8043. exports.default = FlvPlayer;
  8044. },{"../config.js":5,"../core/mse-controller.js":9,"../core/mse-events.js":10,"../core/transmuxer.js":11,"../core/transmuxing-events.js":13,"../utils/browser.js":39,"../utils/exception.js":40,"../utils/logger.js":41,"./player-errors.js":34,"./player-events.js":35,"events":2}],33:[function(_dereq_,module,exports){
  8045. 'use strict';
  8046. Object.defineProperty(exports, "__esModule", {
  8047. value: true
  8048. });
  8049. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  8050. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  8051. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  8052. *
  8053. * @author zheng qian <xqq@xqq.im>
  8054. *
  8055. * Licensed under the Apache License, Version 2.0 (the "License");
  8056. * you may not use this file except in compliance with the License.
  8057. * You may obtain a copy of the License at
  8058. *
  8059. * http://www.apache.org/licenses/LICENSE-2.0
  8060. *
  8061. * Unless required by applicable law or agreed to in writing, software
  8062. * distributed under the License is distributed on an "AS IS" BASIS,
  8063. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8064. * See the License for the specific language governing permissions and
  8065. * limitations under the License.
  8066. */
  8067. var _events = _dereq_('events');
  8068. var _events2 = _interopRequireDefault(_events);
  8069. var _playerEvents = _dereq_('./player-events.js');
  8070. var _playerEvents2 = _interopRequireDefault(_playerEvents);
  8071. var _config = _dereq_('../config.js');
  8072. var _exception = _dereq_('../utils/exception.js');
  8073. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8074. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8075. // Player wrapper for browser's native player (HTMLVideoElement) without MediaSource src.
  8076. var NativePlayer = function () {
  8077. function NativePlayer(mediaDataSource, config) {
  8078. _classCallCheck(this, NativePlayer);
  8079. this.TAG = 'NativePlayer';
  8080. this._type = 'NativePlayer';
  8081. this._emitter = new _events2.default();
  8082. this._config = (0, _config.createDefaultConfig)();
  8083. if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object') {
  8084. Object.assign(this._config, config);
  8085. }
  8086. if (mediaDataSource.type.toLowerCase() === 'flv') {
  8087. throw new _exception.InvalidArgumentException('NativePlayer does\'t support flv MediaDataSource input!');
  8088. }
  8089. if (mediaDataSource.hasOwnProperty('segments')) {
  8090. throw new _exception.InvalidArgumentException('NativePlayer(' + mediaDataSource.type + ') doesn\'t support multipart playback!');
  8091. }
  8092. this.e = {
  8093. onvLoadedMetadata: this._onvLoadedMetadata.bind(this)
  8094. };
  8095. this._pendingSeekTime = null;
  8096. this._statisticsReporter = null;
  8097. this._mediaDataSource = mediaDataSource;
  8098. this._mediaElement = null;
  8099. }
  8100. _createClass(NativePlayer, [{
  8101. key: 'destroy',
  8102. value: function destroy() {
  8103. if (this._mediaElement) {
  8104. this.unload();
  8105. this.detachMediaElement();
  8106. }
  8107. this.e = null;
  8108. this._mediaDataSource = null;
  8109. this._emitter.removeAllListeners();
  8110. this._emitter = null;
  8111. }
  8112. }, {
  8113. key: 'on',
  8114. value: function on(event, listener) {
  8115. var _this = this;
  8116. if (event === _playerEvents2.default.MEDIA_INFO) {
  8117. if (this._mediaElement != null && this._mediaElement.readyState !== 0) {
  8118. // HAVE_NOTHING
  8119. Promise.resolve().then(function () {
  8120. _this._emitter.emit(_playerEvents2.default.MEDIA_INFO, _this.mediaInfo);
  8121. });
  8122. }
  8123. } else if (event === _playerEvents2.default.STATISTICS_INFO) {
  8124. if (this._mediaElement != null && this._mediaElement.readyState !== 0) {
  8125. Promise.resolve().then(function () {
  8126. _this._emitter.emit(_playerEvents2.default.STATISTICS_INFO, _this.statisticsInfo);
  8127. });
  8128. }
  8129. }
  8130. this._emitter.addListener(event, listener);
  8131. }
  8132. }, {
  8133. key: 'off',
  8134. value: function off(event, listener) {
  8135. this._emitter.removeListener(event, listener);
  8136. }
  8137. }, {
  8138. key: 'attachMediaElement',
  8139. value: function attachMediaElement(mediaElement) {
  8140. this._mediaElement = mediaElement;
  8141. mediaElement.addEventListener('loadedmetadata', this.e.onvLoadedMetadata);
  8142. if (this._pendingSeekTime != null) {
  8143. try {
  8144. mediaElement.currentTime = this._pendingSeekTime;
  8145. this._pendingSeekTime = null;
  8146. } catch (e) {
  8147. // IE11 may throw InvalidStateError if readyState === 0
  8148. // Defer set currentTime operation after loadedmetadata
  8149. }
  8150. }
  8151. }
  8152. }, {
  8153. key: 'detachMediaElement',
  8154. value: function detachMediaElement() {
  8155. if (this._mediaElement) {
  8156. this._mediaElement.src = '';
  8157. this._mediaElement.removeAttribute('src');
  8158. this._mediaElement.removeEventListener('loadedmetadata', this.e.onvLoadedMetadata);
  8159. this._mediaElement = null;
  8160. }
  8161. if (this._statisticsReporter != null) {
  8162. window.clearInterval(this._statisticsReporter);
  8163. this._statisticsReporter = null;
  8164. }
  8165. }
  8166. }, {
  8167. key: 'load',
  8168. value: function load() {
  8169. if (!this._mediaElement) {
  8170. throw new _exception.IllegalStateException('HTMLMediaElement must be attached before load()!');
  8171. }
  8172. this._mediaElement.src = this._mediaDataSource.url;
  8173. if (this._mediaElement.readyState > 0) {
  8174. this._mediaElement.currentTime = 0;
  8175. }
  8176. this._mediaElement.preload = 'auto';
  8177. this._mediaElement.load();
  8178. this._statisticsReporter = window.setInterval(this._reportStatisticsInfo.bind(this), this._config.statisticsInfoReportInterval);
  8179. }
  8180. }, {
  8181. key: 'unload',
  8182. value: function unload() {
  8183. if (this._mediaElement) {
  8184. this._mediaElement.src = '';
  8185. this._mediaElement.removeAttribute('src');
  8186. }
  8187. if (this._statisticsReporter != null) {
  8188. window.clearInterval(this._statisticsReporter);
  8189. this._statisticsReporter = null;
  8190. }
  8191. }
  8192. }, {
  8193. key: 'play',
  8194. value: function play() {
  8195. return this._mediaElement.play();
  8196. }
  8197. }, {
  8198. key: 'pause',
  8199. value: function pause() {
  8200. this._mediaElement.pause();
  8201. }
  8202. }, {
  8203. key: '_onvLoadedMetadata',
  8204. value: function _onvLoadedMetadata(e) {
  8205. if (this._pendingSeekTime != null) {
  8206. this._mediaElement.currentTime = this._pendingSeekTime;
  8207. this._pendingSeekTime = null;
  8208. }
  8209. this._emitter.emit(_playerEvents2.default.MEDIA_INFO, this.mediaInfo);
  8210. }
  8211. }, {
  8212. key: '_reportStatisticsInfo',
  8213. value: function _reportStatisticsInfo() {
  8214. this._emitter.emit(_playerEvents2.default.STATISTICS_INFO, this.statisticsInfo);
  8215. }
  8216. }, {
  8217. key: 'type',
  8218. get: function get() {
  8219. return this._type;
  8220. }
  8221. }, {
  8222. key: 'buffered',
  8223. get: function get() {
  8224. return this._mediaElement.buffered;
  8225. }
  8226. }, {
  8227. key: 'duration',
  8228. get: function get() {
  8229. return this._mediaElement.duration;
  8230. }
  8231. }, {
  8232. key: 'volume',
  8233. get: function get() {
  8234. return this._mediaElement.volume;
  8235. },
  8236. set: function set(value) {
  8237. this._mediaElement.volume = value;
  8238. }
  8239. }, {
  8240. key: 'muted',
  8241. get: function get() {
  8242. return this._mediaElement.muted;
  8243. },
  8244. set: function set(muted) {
  8245. this._mediaElement.muted = muted;
  8246. }
  8247. }, {
  8248. key: 'currentTime',
  8249. get: function get() {
  8250. if (this._mediaElement) {
  8251. return this._mediaElement.currentTime;
  8252. }
  8253. return 0;
  8254. },
  8255. set: function set(seconds) {
  8256. if (this._mediaElement) {
  8257. this._mediaElement.currentTime = seconds;
  8258. } else {
  8259. this._pendingSeekTime = seconds;
  8260. }
  8261. }
  8262. }, {
  8263. key: 'mediaInfo',
  8264. get: function get() {
  8265. var mediaPrefix = this._mediaElement instanceof HTMLAudioElement ? 'audio/' : 'video/';
  8266. var info = {
  8267. mimeType: mediaPrefix + this._mediaDataSource.type
  8268. };
  8269. if (this._mediaElement) {
  8270. info.duration = Math.floor(this._mediaElement.duration * 1000);
  8271. if (this._mediaElement instanceof HTMLVideoElement) {
  8272. info.width = this._mediaElement.videoWidth;
  8273. info.height = this._mediaElement.videoHeight;
  8274. }
  8275. }
  8276. return info;
  8277. }
  8278. }, {
  8279. key: 'statisticsInfo',
  8280. get: function get() {
  8281. var info = {
  8282. playerType: this._type,
  8283. url: this._mediaDataSource.url
  8284. };
  8285. if (!(this._mediaElement instanceof HTMLVideoElement)) {
  8286. return info;
  8287. }
  8288. var hasQualityInfo = true;
  8289. var decoded = 0;
  8290. var dropped = 0;
  8291. if (this._mediaElement.getVideoPlaybackQuality) {
  8292. var quality = this._mediaElement.getVideoPlaybackQuality();
  8293. decoded = quality.totalVideoFrames;
  8294. dropped = quality.droppedVideoFrames;
  8295. } else if (this._mediaElement.webkitDecodedFrameCount != undefined) {
  8296. decoded = this._mediaElement.webkitDecodedFrameCount;
  8297. dropped = this._mediaElement.webkitDroppedFrameCount;
  8298. } else {
  8299. hasQualityInfo = false;
  8300. }
  8301. if (hasQualityInfo) {
  8302. info.decodedFrames = decoded;
  8303. info.droppedFrames = dropped;
  8304. }
  8305. return info;
  8306. }
  8307. }]);
  8308. return NativePlayer;
  8309. }();
  8310. exports.default = NativePlayer;
  8311. },{"../config.js":5,"../utils/exception.js":40,"./player-events.js":35,"events":2}],34:[function(_dereq_,module,exports){
  8312. 'use strict';
  8313. Object.defineProperty(exports, "__esModule", {
  8314. value: true
  8315. });
  8316. exports.ErrorDetails = exports.ErrorTypes = undefined;
  8317. var _loader = _dereq_('../io/loader.js');
  8318. var _demuxErrors = _dereq_('../demux/demux-errors.js');
  8319. var _demuxErrors2 = _interopRequireDefault(_demuxErrors);
  8320. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8321. /*
  8322. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  8323. *
  8324. * @author zheng qian <xqq@xqq.im>
  8325. *
  8326. * Licensed under the Apache License, Version 2.0 (the "License");
  8327. * you may not use this file except in compliance with the License.
  8328. * You may obtain a copy of the License at
  8329. *
  8330. * http://www.apache.org/licenses/LICENSE-2.0
  8331. *
  8332. * Unless required by applicable law or agreed to in writing, software
  8333. * distributed under the License is distributed on an "AS IS" BASIS,
  8334. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8335. * See the License for the specific language governing permissions and
  8336. * limitations under the License.
  8337. */
  8338. var ErrorTypes = exports.ErrorTypes = {
  8339. NETWORK_ERROR: 'NetworkError',
  8340. MEDIA_ERROR: 'MediaError',
  8341. OTHER_ERROR: 'OtherError'
  8342. };
  8343. var ErrorDetails = exports.ErrorDetails = {
  8344. NETWORK_EXCEPTION: _loader.LoaderErrors.EXCEPTION,
  8345. NETWORK_STATUS_CODE_INVALID: _loader.LoaderErrors.HTTP_STATUS_CODE_INVALID,
  8346. NETWORK_TIMEOUT: _loader.LoaderErrors.CONNECTING_TIMEOUT,
  8347. NETWORK_UNRECOVERABLE_EARLY_EOF: _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF,
  8348. MEDIA_MSE_ERROR: 'MediaMSEError',
  8349. MEDIA_FORMAT_ERROR: _demuxErrors2.default.FORMAT_ERROR,
  8350. MEDIA_FORMAT_UNSUPPORTED: _demuxErrors2.default.FORMAT_UNSUPPORTED,
  8351. MEDIA_CODEC_UNSUPPORTED: _demuxErrors2.default.CODEC_UNSUPPORTED
  8352. };
  8353. },{"../demux/demux-errors.js":16,"../io/loader.js":24}],35:[function(_dereq_,module,exports){
  8354. 'use strict';
  8355. Object.defineProperty(exports, "__esModule", {
  8356. value: true
  8357. });
  8358. /*
  8359. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  8360. *
  8361. * @author zheng qian <xqq@xqq.im>
  8362. *
  8363. * Licensed under the Apache License, Version 2.0 (the "License");
  8364. * you may not use this file except in compliance with the License.
  8365. * You may obtain a copy of the License at
  8366. *
  8367. * http://www.apache.org/licenses/LICENSE-2.0
  8368. *
  8369. * Unless required by applicable law or agreed to in writing, software
  8370. * distributed under the License is distributed on an "AS IS" BASIS,
  8371. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8372. * See the License for the specific language governing permissions and
  8373. * limitations under the License.
  8374. */
  8375. var PlayerEvents = {
  8376. ERROR: 'error',
  8377. LOADING_COMPLETE: 'loading_complete',
  8378. RECOVERED_EARLY_EOF: 'recovered_early_eof',
  8379. MEDIA_INFO: 'media_info',
  8380. STATISTICS_INFO: 'statistics_info'
  8381. };
  8382. exports.default = PlayerEvents;
  8383. },{}],36:[function(_dereq_,module,exports){
  8384. 'use strict';
  8385. Object.defineProperty(exports, "__esModule", {
  8386. value: true
  8387. });
  8388. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  8389. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8390. /*
  8391. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  8392. *
  8393. * This file is modified from dailymotion's hls.js library (hls.js/src/helper/aac.js)
  8394. * @author zheng qian <xqq@xqq.im>
  8395. *
  8396. * Licensed under the Apache License, Version 2.0 (the "License");
  8397. * you may not use this file except in compliance with the License.
  8398. * You may obtain a copy of the License at
  8399. *
  8400. * http://www.apache.org/licenses/LICENSE-2.0
  8401. *
  8402. * Unless required by applicable law or agreed to in writing, software
  8403. * distributed under the License is distributed on an "AS IS" BASIS,
  8404. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8405. * See the License for the specific language governing permissions and
  8406. * limitations under the License.
  8407. */
  8408. var AAC = function () {
  8409. function AAC() {
  8410. _classCallCheck(this, AAC);
  8411. }
  8412. _createClass(AAC, null, [{
  8413. key: 'getSilentFrame',
  8414. value: function getSilentFrame(codec, channelCount) {
  8415. if (codec === 'mp4a.40.2') {
  8416. // handle LC-AAC
  8417. if (channelCount === 1) {
  8418. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  8419. } else if (channelCount === 2) {
  8420. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  8421. } else if (channelCount === 3) {
  8422. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  8423. } else if (channelCount === 4) {
  8424. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  8425. } else if (channelCount === 5) {
  8426. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  8427. } else if (channelCount === 6) {
  8428. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]);
  8429. }
  8430. } else {
  8431. // handle HE-AAC (mp4a.40.5 / mp4a.40.29)
  8432. if (channelCount === 1) {
  8433. // ffmpeg -y -f lavfi -i "aevalsrc=0:d=0.05" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
  8434. return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
  8435. } else if (channelCount === 2) {
  8436. // ffmpeg -y -f lavfi -i "aevalsrc=0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
  8437. return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
  8438. } else if (channelCount === 3) {
  8439. // ffmpeg -y -f lavfi -i "aevalsrc=0|0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
  8440. return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
  8441. }
  8442. }
  8443. return null;
  8444. }
  8445. }]);
  8446. return AAC;
  8447. }();
  8448. exports.default = AAC;
  8449. },{}],37:[function(_dereq_,module,exports){
  8450. 'use strict';
  8451. Object.defineProperty(exports, "__esModule", {
  8452. value: true
  8453. });
  8454. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  8455. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8456. /*
  8457. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  8458. *
  8459. * This file is derived from dailymotion's hls.js library (hls.js/src/remux/mp4-generator.js)
  8460. * @author zheng qian <xqq@xqq.im>
  8461. *
  8462. * Licensed under the Apache License, Version 2.0 (the "License");
  8463. * you may not use this file except in compliance with the License.
  8464. * You may obtain a copy of the License at
  8465. *
  8466. * http://www.apache.org/licenses/LICENSE-2.0
  8467. *
  8468. * Unless required by applicable law or agreed to in writing, software
  8469. * distributed under the License is distributed on an "AS IS" BASIS,
  8470. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8471. * See the License for the specific language governing permissions and
  8472. * limitations under the License.
  8473. */
  8474. // MP4 boxes generator for ISO BMFF (ISO Base Media File Format, defined in ISO/IEC 14496-12)
  8475. var MP4 = function () {
  8476. function MP4() {
  8477. _classCallCheck(this, MP4);
  8478. }
  8479. _createClass(MP4, null, [{
  8480. key: 'init',
  8481. value: function init() {
  8482. MP4.types = {
  8483. avc1: [], avcC: [], btrt: [], dinf: [],
  8484. dref: [], esds: [], ftyp: [], hdlr: [],
  8485. mdat: [], mdhd: [], mdia: [], mfhd: [],
  8486. minf: [], moof: [], moov: [], mp4a: [],
  8487. mvex: [], mvhd: [], sdtp: [], stbl: [],
  8488. stco: [], stsc: [], stsd: [], stsz: [],
  8489. stts: [], tfdt: [], tfhd: [], traf: [],
  8490. trak: [], trun: [], trex: [], tkhd: [],
  8491. vmhd: [], smhd: [], '.mp3': []
  8492. };
  8493. for (var name in MP4.types) {
  8494. if (MP4.types.hasOwnProperty(name)) {
  8495. MP4.types[name] = [name.charCodeAt(0), name.charCodeAt(1), name.charCodeAt(2), name.charCodeAt(3)];
  8496. }
  8497. }
  8498. var constants = MP4.constants = {};
  8499. constants.FTYP = new Uint8Array([0x69, 0x73, 0x6F, 0x6D, // major_brand: isom
  8500. 0x0, 0x0, 0x0, 0x1, // minor_version: 0x01
  8501. 0x69, 0x73, 0x6F, 0x6D, // isom
  8502. 0x61, 0x76, 0x63, 0x31 // avc1
  8503. ]);
  8504. constants.STSD_PREFIX = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8505. 0x00, 0x00, 0x00, 0x01 // entry_count
  8506. ]);
  8507. constants.STTS = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8508. 0x00, 0x00, 0x00, 0x00 // entry_count
  8509. ]);
  8510. constants.STSC = constants.STCO = constants.STTS;
  8511. constants.STSZ = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8512. 0x00, 0x00, 0x00, 0x00, // sample_size
  8513. 0x00, 0x00, 0x00, 0x00 // sample_count
  8514. ]);
  8515. constants.HDLR_VIDEO = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8516. 0x00, 0x00, 0x00, 0x00, // pre_defined
  8517. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  8518. 0x00, 0x00, 0x00, 0x00, // reserved: 3 * 4 bytes
  8519. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x69, 0x64, 0x65, 0x6F, 0x48, 0x61, 0x6E, 0x64, 0x6C, 0x65, 0x72, 0x00 // name: VideoHandler
  8520. ]);
  8521. constants.HDLR_AUDIO = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8522. 0x00, 0x00, 0x00, 0x00, // pre_defined
  8523. 0x73, 0x6F, 0x75, 0x6E, // handler_type: 'soun'
  8524. 0x00, 0x00, 0x00, 0x00, // reserved: 3 * 4 bytes
  8525. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x6F, 0x75, 0x6E, 0x64, 0x48, 0x61, 0x6E, 0x64, 0x6C, 0x65, 0x72, 0x00 // name: SoundHandler
  8526. ]);
  8527. constants.DREF = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8528. 0x00, 0x00, 0x00, 0x01, // entry_count
  8529. 0x00, 0x00, 0x00, 0x0C, // entry_size
  8530. 0x75, 0x72, 0x6C, 0x20, // type 'url '
  8531. 0x00, 0x00, 0x00, 0x01 // version(0) + flags
  8532. ]);
  8533. // Sound media header
  8534. constants.SMHD = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8535. 0x00, 0x00, 0x00, 0x00 // balance(2) + reserved(2)
  8536. ]);
  8537. // video media header
  8538. constants.VMHD = new Uint8Array([0x00, 0x00, 0x00, 0x01, // version(0) + flags
  8539. 0x00, 0x00, // graphicsmode: 2 bytes
  8540. 0x00, 0x00, 0x00, 0x00, // opcolor: 3 * 2 bytes
  8541. 0x00, 0x00]);
  8542. }
  8543. // Generate a box
  8544. }, {
  8545. key: 'box',
  8546. value: function box(type) {
  8547. var size = 8;
  8548. var result = null;
  8549. var datas = Array.prototype.slice.call(arguments, 1);
  8550. var arrayCount = datas.length;
  8551. for (var i = 0; i < arrayCount; i++) {
  8552. size += datas[i].byteLength;
  8553. }
  8554. result = new Uint8Array(size);
  8555. result[0] = size >>> 24 & 0xFF; // size
  8556. result[1] = size >>> 16 & 0xFF;
  8557. result[2] = size >>> 8 & 0xFF;
  8558. result[3] = size & 0xFF;
  8559. result.set(type, 4); // type
  8560. var offset = 8;
  8561. for (var _i = 0; _i < arrayCount; _i++) {
  8562. // data body
  8563. result.set(datas[_i], offset);
  8564. offset += datas[_i].byteLength;
  8565. }
  8566. return result;
  8567. }
  8568. // emit ftyp & moov
  8569. }, {
  8570. key: 'generateInitSegment',
  8571. value: function generateInitSegment(meta) {
  8572. var ftyp = MP4.box(MP4.types.ftyp, MP4.constants.FTYP);
  8573. var moov = MP4.moov(meta);
  8574. var result = new Uint8Array(ftyp.byteLength + moov.byteLength);
  8575. result.set(ftyp, 0);
  8576. result.set(moov, ftyp.byteLength);
  8577. return result;
  8578. }
  8579. // Movie metadata box
  8580. }, {
  8581. key: 'moov',
  8582. value: function moov(meta) {
  8583. var mvhd = MP4.mvhd(meta.timescale, meta.duration);
  8584. var trak = MP4.trak(meta);
  8585. var mvex = MP4.mvex(meta);
  8586. return MP4.box(MP4.types.moov, mvhd, trak, mvex);
  8587. }
  8588. // Movie header box
  8589. }, {
  8590. key: 'mvhd',
  8591. value: function mvhd(timescale, duration) {
  8592. return MP4.box(MP4.types.mvhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8593. 0x00, 0x00, 0x00, 0x00, // creation_time
  8594. 0x00, 0x00, 0x00, 0x00, // modification_time
  8595. timescale >>> 24 & 0xFF, // timescale: 4 bytes
  8596. timescale >>> 16 & 0xFF, timescale >>> 8 & 0xFF, timescale & 0xFF, duration >>> 24 & 0xFF, // duration: 4 bytes
  8597. duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x00, 0x01, 0x00, 0x00, // Preferred rate: 1.0
  8598. 0x01, 0x00, 0x00, 0x00, // PreferredVolume(1.0, 2bytes) + reserved(2bytes)
  8599. 0x00, 0x00, 0x00, 0x00, // reserved: 4 + 4 bytes
  8600. 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, // ----begin composition matrix----
  8601. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // ----end composition matrix----
  8602. 0x00, 0x00, 0x00, 0x00, // ----begin pre_defined 6 * 4 bytes----
  8603. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ----end pre_defined 6 * 4 bytes----
  8604. 0xFF, 0xFF, 0xFF, 0xFF // next_track_ID
  8605. ]));
  8606. }
  8607. // Track box
  8608. }, {
  8609. key: 'trak',
  8610. value: function trak(meta) {
  8611. return MP4.box(MP4.types.trak, MP4.tkhd(meta), MP4.mdia(meta));
  8612. }
  8613. // Track header box
  8614. }, {
  8615. key: 'tkhd',
  8616. value: function tkhd(meta) {
  8617. var trackId = meta.id,
  8618. duration = meta.duration;
  8619. var width = meta.presentWidth,
  8620. height = meta.presentHeight;
  8621. return MP4.box(MP4.types.tkhd, new Uint8Array([0x00, 0x00, 0x00, 0x07, // version(0) + flags
  8622. 0x00, 0x00, 0x00, 0x00, // creation_time
  8623. 0x00, 0x00, 0x00, 0x00, // modification_time
  8624. trackId >>> 24 & 0xFF, // track_ID: 4 bytes
  8625. trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF, 0x00, 0x00, 0x00, 0x00, // reserved: 4 bytes
  8626. duration >>> 24 & 0xFF, // duration: 4 bytes
  8627. duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes
  8628. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // layer(2bytes) + alternate_group(2bytes)
  8629. 0x00, 0x00, 0x00, 0x00, // volume(2bytes) + reserved(2bytes)
  8630. 0x00, 0x01, 0x00, 0x00, // ----begin composition matrix----
  8631. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // ----end composition matrix----
  8632. width >>> 8 & 0xFF, // width and height
  8633. width & 0xFF, 0x00, 0x00, height >>> 8 & 0xFF, height & 0xFF, 0x00, 0x00]));
  8634. }
  8635. // Media Box
  8636. }, {
  8637. key: 'mdia',
  8638. value: function mdia(meta) {
  8639. return MP4.box(MP4.types.mdia, MP4.mdhd(meta), MP4.hdlr(meta), MP4.minf(meta));
  8640. }
  8641. // Media header box
  8642. }, {
  8643. key: 'mdhd',
  8644. value: function mdhd(meta) {
  8645. var timescale = meta.timescale;
  8646. var duration = meta.duration;
  8647. return MP4.box(MP4.types.mdhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8648. 0x00, 0x00, 0x00, 0x00, // creation_time
  8649. 0x00, 0x00, 0x00, 0x00, // modification_time
  8650. timescale >>> 24 & 0xFF, // timescale: 4 bytes
  8651. timescale >>> 16 & 0xFF, timescale >>> 8 & 0xFF, timescale & 0xFF, duration >>> 24 & 0xFF, // duration: 4 bytes
  8652. duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x55, 0xC4, // language: und (undetermined)
  8653. 0x00, 0x00 // pre_defined = 0
  8654. ]));
  8655. }
  8656. // Media handler reference box
  8657. }, {
  8658. key: 'hdlr',
  8659. value: function hdlr(meta) {
  8660. var data = null;
  8661. if (meta.type === 'audio') {
  8662. data = MP4.constants.HDLR_AUDIO;
  8663. } else {
  8664. data = MP4.constants.HDLR_VIDEO;
  8665. }
  8666. return MP4.box(MP4.types.hdlr, data);
  8667. }
  8668. // Media infomation box
  8669. }, {
  8670. key: 'minf',
  8671. value: function minf(meta) {
  8672. var xmhd = null;
  8673. if (meta.type === 'audio') {
  8674. xmhd = MP4.box(MP4.types.smhd, MP4.constants.SMHD);
  8675. } else {
  8676. xmhd = MP4.box(MP4.types.vmhd, MP4.constants.VMHD);
  8677. }
  8678. return MP4.box(MP4.types.minf, xmhd, MP4.dinf(), MP4.stbl(meta));
  8679. }
  8680. // Data infomation box
  8681. }, {
  8682. key: 'dinf',
  8683. value: function dinf() {
  8684. var result = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, MP4.constants.DREF));
  8685. return result;
  8686. }
  8687. // Sample table box
  8688. }, {
  8689. key: 'stbl',
  8690. value: function stbl(meta) {
  8691. var result = MP4.box(MP4.types.stbl, // type: stbl
  8692. MP4.stsd(meta), // Sample Description Table
  8693. MP4.box(MP4.types.stts, MP4.constants.STTS), // Time-To-Sample
  8694. MP4.box(MP4.types.stsc, MP4.constants.STSC), // Sample-To-Chunk
  8695. MP4.box(MP4.types.stsz, MP4.constants.STSZ), // Sample size
  8696. MP4.box(MP4.types.stco, MP4.constants.STCO // Chunk offset
  8697. ));
  8698. return result;
  8699. }
  8700. // Sample description box
  8701. }, {
  8702. key: 'stsd',
  8703. value: function stsd(meta) {
  8704. if (meta.type === 'audio') {
  8705. if (meta.codec === 'mp3') {
  8706. return MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.mp3(meta));
  8707. }
  8708. // else: aac -> mp4a
  8709. return MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.mp4a(meta));
  8710. } else {
  8711. return MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.avc1(meta));
  8712. }
  8713. }
  8714. }, {
  8715. key: 'mp3',
  8716. value: function mp3(meta) {
  8717. var channelCount = meta.channelCount;
  8718. var sampleRate = meta.audioSampleRate;
  8719. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // reserved(4)
  8720. 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2)
  8721. 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes
  8722. 0x00, 0x00, 0x00, 0x00, 0x00, channelCount, // channelCount(2)
  8723. 0x00, 0x10, // sampleSize(2)
  8724. 0x00, 0x00, 0x00, 0x00, // reserved(4)
  8725. sampleRate >>> 8 & 0xFF, // Audio sample rate
  8726. sampleRate & 0xFF, 0x00, 0x00]);
  8727. return MP4.box(MP4.types['.mp3'], data);
  8728. }
  8729. }, {
  8730. key: 'mp4a',
  8731. value: function mp4a(meta) {
  8732. var channelCount = meta.channelCount;
  8733. var sampleRate = meta.audioSampleRate;
  8734. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // reserved(4)
  8735. 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2)
  8736. 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes
  8737. 0x00, 0x00, 0x00, 0x00, 0x00, channelCount, // channelCount(2)
  8738. 0x00, 0x10, // sampleSize(2)
  8739. 0x00, 0x00, 0x00, 0x00, // reserved(4)
  8740. sampleRate >>> 8 & 0xFF, // Audio sample rate
  8741. sampleRate & 0xFF, 0x00, 0x00]);
  8742. return MP4.box(MP4.types.mp4a, data, MP4.esds(meta));
  8743. }
  8744. }, {
  8745. key: 'esds',
  8746. value: function esds(meta) {
  8747. var config = meta.config || [];
  8748. var configSize = config.length;
  8749. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version 0 + flags
  8750. 0x03, // descriptor_type
  8751. 0x17 + configSize, // length3
  8752. 0x00, 0x01, // es_id
  8753. 0x00, // stream_priority
  8754. 0x04, // descriptor_type
  8755. 0x0F + configSize, // length
  8756. 0x40, // codec: mpeg4_audio
  8757. 0x15, // stream_type: Audio
  8758. 0x00, 0x00, 0x00, // buffer_size
  8759. 0x00, 0x00, 0x00, 0x00, // maxBitrate
  8760. 0x00, 0x00, 0x00, 0x00, // avgBitrate
  8761. 0x05 // descriptor_type
  8762. ].concat([configSize]).concat(config).concat([0x06, 0x01, 0x02 // GASpecificConfig
  8763. ]));
  8764. return MP4.box(MP4.types.esds, data);
  8765. }
  8766. }, {
  8767. key: 'avc1',
  8768. value: function avc1(meta) {
  8769. var avcc = meta.avcc;
  8770. var width = meta.codecWidth,
  8771. height = meta.codecHeight;
  8772. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // reserved(4)
  8773. 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2)
  8774. 0x00, 0x00, 0x00, 0x00, // pre_defined(2) + reserved(2)
  8775. 0x00, 0x00, 0x00, 0x00, // pre_defined: 3 * 4 bytes
  8776. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, width >>> 8 & 0xFF, // width: 2 bytes
  8777. width & 0xFF, height >>> 8 & 0xFF, // height: 2 bytes
  8778. height & 0xFF, 0x00, 0x48, 0x00, 0x00, // horizresolution: 4 bytes
  8779. 0x00, 0x48, 0x00, 0x00, // vertresolution: 4 bytes
  8780. 0x00, 0x00, 0x00, 0x00, // reserved: 4 bytes
  8781. 0x00, 0x01, // frame_count
  8782. 0x0A, // strlen
  8783. 0x78, 0x71, 0x71, 0x2F, // compressorname: 32 bytes
  8784. 0x66, 0x6C, 0x76, 0x2E, 0x6A, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, // depth
  8785. 0xFF, 0xFF // pre_defined = -1
  8786. ]);
  8787. return MP4.box(MP4.types.avc1, data, MP4.box(MP4.types.avcC, avcc));
  8788. }
  8789. // Movie Extends box
  8790. }, {
  8791. key: 'mvex',
  8792. value: function mvex(meta) {
  8793. return MP4.box(MP4.types.mvex, MP4.trex(meta));
  8794. }
  8795. // Track Extends box
  8796. }, {
  8797. key: 'trex',
  8798. value: function trex(meta) {
  8799. var trackId = meta.id;
  8800. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8801. trackId >>> 24 & 0xFF, // track_ID
  8802. trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF, 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  8803. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  8804. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  8805. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  8806. ]);
  8807. return MP4.box(MP4.types.trex, data);
  8808. }
  8809. // Movie fragment box
  8810. }, {
  8811. key: 'moof',
  8812. value: function moof(track, baseMediaDecodeTime) {
  8813. return MP4.box(MP4.types.moof, MP4.mfhd(track.sequenceNumber), MP4.traf(track, baseMediaDecodeTime));
  8814. }
  8815. }, {
  8816. key: 'mfhd',
  8817. value: function mfhd(sequenceNumber) {
  8818. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, sequenceNumber >>> 24 & 0xFF, // sequence_number: int32
  8819. sequenceNumber >>> 16 & 0xFF, sequenceNumber >>> 8 & 0xFF, sequenceNumber & 0xFF]);
  8820. return MP4.box(MP4.types.mfhd, data);
  8821. }
  8822. // Track fragment box
  8823. }, {
  8824. key: 'traf',
  8825. value: function traf(track, baseMediaDecodeTime) {
  8826. var trackId = track.id;
  8827. // Track fragment header box
  8828. var tfhd = MP4.box(MP4.types.tfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) & flags
  8829. trackId >>> 24 & 0xFF, // track_ID
  8830. trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF]));
  8831. // Track Fragment Decode Time
  8832. var tfdt = MP4.box(MP4.types.tfdt, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) & flags
  8833. baseMediaDecodeTime >>> 24 & 0xFF, // baseMediaDecodeTime: int32
  8834. baseMediaDecodeTime >>> 16 & 0xFF, baseMediaDecodeTime >>> 8 & 0xFF, baseMediaDecodeTime & 0xFF]));
  8835. var sdtp = MP4.sdtp(track);
  8836. var trun = MP4.trun(track, sdtp.byteLength + 16 + 16 + 8 + 16 + 8 + 8);
  8837. return MP4.box(MP4.types.traf, tfhd, tfdt, trun, sdtp);
  8838. }
  8839. // Sample Dependency Type box
  8840. }, {
  8841. key: 'sdtp',
  8842. value: function sdtp(track) {
  8843. var samples = track.samples || [];
  8844. var sampleCount = samples.length;
  8845. var data = new Uint8Array(4 + sampleCount);
  8846. // 0~4 bytes: version(0) & flags
  8847. for (var i = 0; i < sampleCount; i++) {
  8848. var flags = samples[i].flags;
  8849. data[i + 4] = flags.isLeading << 6 | // is_leading: 2 (bit)
  8850. flags.dependsOn << 4 // sample_depends_on
  8851. | flags.isDependedOn << 2 // sample_is_depended_on
  8852. | flags.hasRedundancy; // sample_has_redundancy
  8853. }
  8854. return MP4.box(MP4.types.sdtp, data);
  8855. }
  8856. // Track fragment run box
  8857. }, {
  8858. key: 'trun',
  8859. value: function trun(track, offset) {
  8860. var samples = track.samples || [];
  8861. var sampleCount = samples.length;
  8862. var dataSize = 12 + 16 * sampleCount;
  8863. var data = new Uint8Array(dataSize);
  8864. offset += 8 + dataSize;
  8865. data.set([0x00, 0x00, 0x0F, 0x01, // version(0) & flags
  8866. sampleCount >>> 24 & 0xFF, // sample_count
  8867. sampleCount >>> 16 & 0xFF, sampleCount >>> 8 & 0xFF, sampleCount & 0xFF, offset >>> 24 & 0xFF, // data_offset
  8868. offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF], 0);
  8869. for (var i = 0; i < sampleCount; i++) {
  8870. var duration = samples[i].duration;
  8871. var size = samples[i].size;
  8872. var flags = samples[i].flags;
  8873. var cts = samples[i].cts;
  8874. data.set([duration >>> 24 & 0xFF, // sample_duration
  8875. duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, size >>> 24 & 0xFF, // sample_size
  8876. size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, flags.isLeading << 2 | flags.dependsOn, // sample_flags
  8877. flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.isNonSync, 0x00, 0x00, // sample_degradation_priority
  8878. cts >>> 24 & 0xFF, // sample_composition_time_offset
  8879. cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF], 12 + 16 * i);
  8880. }
  8881. return MP4.box(MP4.types.trun, data);
  8882. }
  8883. }, {
  8884. key: 'mdat',
  8885. value: function mdat(data) {
  8886. return MP4.box(MP4.types.mdat, data);
  8887. }
  8888. }]);
  8889. return MP4;
  8890. }();
  8891. MP4.init();
  8892. exports.default = MP4;
  8893. },{}],38:[function(_dereq_,module,exports){
  8894. 'use strict';
  8895. Object.defineProperty(exports, "__esModule", {
  8896. value: true
  8897. });
  8898. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  8899. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  8900. *
  8901. * @author zheng qian <xqq@xqq.im>
  8902. *
  8903. * Licensed under the Apache License, Version 2.0 (the "License");
  8904. * you may not use this file except in compliance with the License.
  8905. * You may obtain a copy of the License at
  8906. *
  8907. * http://www.apache.org/licenses/LICENSE-2.0
  8908. *
  8909. * Unless required by applicable law or agreed to in writing, software
  8910. * distributed under the License is distributed on an "AS IS" BASIS,
  8911. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8912. * See the License for the specific language governing permissions and
  8913. * limitations under the License.
  8914. */
  8915. var _logger = _dereq_('../utils/logger.js');
  8916. var _logger2 = _interopRequireDefault(_logger);
  8917. var _mp4Generator = _dereq_('./mp4-generator.js');
  8918. var _mp4Generator2 = _interopRequireDefault(_mp4Generator);
  8919. var _aacSilent = _dereq_('./aac-silent.js');
  8920. var _aacSilent2 = _interopRequireDefault(_aacSilent);
  8921. var _browser = _dereq_('../utils/browser.js');
  8922. var _browser2 = _interopRequireDefault(_browser);
  8923. var _mediaSegmentInfo = _dereq_('../core/media-segment-info.js');
  8924. var _exception = _dereq_('../utils/exception.js');
  8925. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8926. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8927. // Fragmented mp4 remuxer
  8928. var MP4Remuxer = function () {
  8929. function MP4Remuxer(config) {
  8930. _classCallCheck(this, MP4Remuxer);
  8931. this.TAG = 'MP4Remuxer';
  8932. this._config = config;
  8933. this._isLive = config.isLive === true ? true : false;
  8934. this._dtsBase = -1;
  8935. this._dtsBaseInited = false;
  8936. this._audioDtsBase = Infinity;
  8937. this._videoDtsBase = Infinity;
  8938. this._audioNextDts = undefined;
  8939. this._videoNextDts = undefined;
  8940. this._audioStashedLastSample = null;
  8941. this._videoStashedLastSample = null;
  8942. this._audioMeta = null;
  8943. this._videoMeta = null;
  8944. this._audioSegmentInfoList = new _mediaSegmentInfo.MediaSegmentInfoList('audio');
  8945. this._videoSegmentInfoList = new _mediaSegmentInfo.MediaSegmentInfoList('video');
  8946. this._onInitSegment = null;
  8947. this._onMediaSegment = null;
  8948. // Workaround for chrome < 50: Always force first sample as a Random Access Point in media segment
  8949. // see https://bugs.chromium.org/p/chromium/issues/detail?id=229412
  8950. this._forceFirstIDR = _browser2.default.chrome && (_browser2.default.version.major < 50 || _browser2.default.version.major === 50 && _browser2.default.version.build < 2661) ? true : false;
  8951. // Workaround for IE11/Edge: Fill silent aac frame after keyframe-seeking
  8952. // Make audio beginDts equals with video beginDts, in order to fix seek freeze
  8953. this._fillSilentAfterSeek = _browser2.default.msedge || _browser2.default.msie;
  8954. // While only FireFox supports 'audio/mp4, codecs="mp3"', use 'audio/mpeg' for chrome, safari, ...
  8955. this._mp3UseMpegAudio = !_browser2.default.firefox;
  8956. this._fillAudioTimestampGap = this._config.fixAudioTimestampGap;
  8957. }
  8958. _createClass(MP4Remuxer, [{
  8959. key: 'destroy',
  8960. value: function destroy() {
  8961. this._dtsBase = -1;
  8962. this._dtsBaseInited = false;
  8963. this._audioMeta = null;
  8964. this._videoMeta = null;
  8965. this._audioSegmentInfoList.clear();
  8966. this._audioSegmentInfoList = null;
  8967. this._videoSegmentInfoList.clear();
  8968. this._videoSegmentInfoList = null;
  8969. this._onInitSegment = null;
  8970. this._onMediaSegment = null;
  8971. }
  8972. }, {
  8973. key: 'bindDataSource',
  8974. value: function bindDataSource(producer) {
  8975. producer.onDataAvailable = this.remux.bind(this);
  8976. producer.onTrackMetadata = this._onTrackMetadataReceived.bind(this);
  8977. return this;
  8978. }
  8979. /* prototype: function onInitSegment(type: string, initSegment: ArrayBuffer): void
  8980. InitSegment: {
  8981. type: string,
  8982. data: ArrayBuffer,
  8983. codec: string,
  8984. container: string
  8985. }
  8986. */
  8987. }, {
  8988. key: 'insertDiscontinuity',
  8989. value: function insertDiscontinuity() {
  8990. this._audioNextDts = this._videoNextDts = undefined;
  8991. }
  8992. }, {
  8993. key: 'seek',
  8994. value: function seek(originalDts) {
  8995. this._audioStashedLastSample = null;
  8996. this._videoStashedLastSample = null;
  8997. this._videoSegmentInfoList.clear();
  8998. this._audioSegmentInfoList.clear();
  8999. }
  9000. }, {
  9001. key: 'remux',
  9002. value: function remux(audioTrack, videoTrack) {
  9003. if (!this._onMediaSegment) {
  9004. throw new _exception.IllegalStateException('MP4Remuxer: onMediaSegment callback must be specificed!');
  9005. }
  9006. if (!this._dtsBaseInited) {
  9007. this._calculateDtsBase(audioTrack, videoTrack);
  9008. }
  9009. this._remuxVideo(videoTrack);
  9010. this._remuxAudio(audioTrack);
  9011. }
  9012. }, {
  9013. key: '_onTrackMetadataReceived',
  9014. value: function _onTrackMetadataReceived(type, metadata) {
  9015. var metabox = null;
  9016. var container = 'mp4';
  9017. var codec = metadata.codec;
  9018. if (type === 'audio') {
  9019. this._audioMeta = metadata;
  9020. if (metadata.codec === 'mp3' && this._mp3UseMpegAudio) {
  9021. // 'audio/mpeg' for MP3 audio track
  9022. container = 'mpeg';
  9023. codec = '';
  9024. metabox = new Uint8Array();
  9025. } else {
  9026. // 'audio/mp4, codecs="codec"'
  9027. metabox = _mp4Generator2.default.generateInitSegment(metadata);
  9028. }
  9029. } else if (type === 'video') {
  9030. this._videoMeta = metadata;
  9031. metabox = _mp4Generator2.default.generateInitSegment(metadata);
  9032. } else {
  9033. return;
  9034. }
  9035. // dispatch metabox (Initialization Segment)
  9036. if (!this._onInitSegment) {
  9037. throw new _exception.IllegalStateException('MP4Remuxer: onInitSegment callback must be specified!');
  9038. }
  9039. this._onInitSegment(type, {
  9040. type: type,
  9041. data: metabox.buffer,
  9042. codec: codec,
  9043. container: type + '/' + container,
  9044. mediaDuration: metadata.duration // in timescale 1000 (milliseconds)
  9045. });
  9046. }
  9047. }, {
  9048. key: '_calculateDtsBase',
  9049. value: function _calculateDtsBase(audioTrack, videoTrack) {
  9050. if (this._dtsBaseInited) {
  9051. return;
  9052. }
  9053. if (audioTrack.samples && audioTrack.samples.length) {
  9054. this._audioDtsBase = audioTrack.samples[0].dts;
  9055. }
  9056. if (videoTrack.samples && videoTrack.samples.length) {
  9057. this._videoDtsBase = videoTrack.samples[0].dts;
  9058. }
  9059. this._dtsBase = Math.min(this._audioDtsBase, this._videoDtsBase);
  9060. this._dtsBaseInited = true;
  9061. }
  9062. }, {
  9063. key: 'flushStashedSamples',
  9064. value: function flushStashedSamples() {
  9065. var videoSample = this._videoStashedLastSample;
  9066. var audioSample = this._audioStashedLastSample;
  9067. var videoTrack = {
  9068. type: 'video',
  9069. id: 1,
  9070. sequenceNumber: 0,
  9071. samples: [],
  9072. length: 0
  9073. };
  9074. if (videoSample != null) {
  9075. videoTrack.samples.push(videoSample);
  9076. videoTrack.length = videoSample.length;
  9077. }
  9078. var audioTrack = {
  9079. type: 'audio',
  9080. id: 2,
  9081. sequenceNumber: 0,
  9082. samples: [],
  9083. length: 0
  9084. };
  9085. if (audioSample != null) {
  9086. audioTrack.samples.push(audioSample);
  9087. audioTrack.length = audioSample.length;
  9088. }
  9089. this._videoStashedLastSample = null;
  9090. this._audioStashedLastSample = null;
  9091. this._remuxVideo(videoTrack, true);
  9092. this._remuxAudio(audioTrack, true);
  9093. }
  9094. }, {
  9095. key: '_remuxAudio',
  9096. value: function _remuxAudio(audioTrack, force) {
  9097. if (this._audioMeta == null) {
  9098. return;
  9099. }
  9100. var track = audioTrack;
  9101. var samples = track.samples;
  9102. var dtsCorrection = undefined;
  9103. var firstDts = -1,
  9104. lastDts = -1,
  9105. lastPts = -1;
  9106. var refSampleDuration = this._audioMeta.refSampleDuration;
  9107. var mpegRawTrack = this._audioMeta.codec === 'mp3' && this._mp3UseMpegAudio;
  9108. var firstSegmentAfterSeek = this._dtsBaseInited && this._audioNextDts === undefined;
  9109. var insertPrefixSilentFrame = false;
  9110. if (!samples || samples.length === 0) {
  9111. return;
  9112. }
  9113. if (samples.length === 1 && !force) {
  9114. // If [sample count in current batch] === 1 && (force != true)
  9115. // Ignore and keep in demuxer's queue
  9116. return;
  9117. } // else if (force === true) do remux
  9118. var offset = 0;
  9119. var mdatbox = null;
  9120. var mdatBytes = 0;
  9121. // calculate initial mdat size
  9122. if (mpegRawTrack) {
  9123. // for raw mpeg buffer
  9124. offset = 0;
  9125. mdatBytes = track.length;
  9126. } else {
  9127. // for fmp4 mdat box
  9128. offset = 8; // size + type
  9129. mdatBytes = 8 + track.length;
  9130. }
  9131. var lastSample = null;
  9132. // Pop the lastSample and waiting for stash
  9133. if (samples.length > 1) {
  9134. lastSample = samples.pop();
  9135. mdatBytes -= lastSample.length;
  9136. }
  9137. // Insert [stashed lastSample in the previous batch] to the front
  9138. if (this._audioStashedLastSample != null) {
  9139. var sample = this._audioStashedLastSample;
  9140. this._audioStashedLastSample = null;
  9141. samples.unshift(sample);
  9142. mdatBytes += sample.length;
  9143. }
  9144. // Stash the lastSample of current batch, waiting for next batch
  9145. if (lastSample != null) {
  9146. this._audioStashedLastSample = lastSample;
  9147. }
  9148. var firstSampleOriginalDts = samples[0].dts - this._dtsBase;
  9149. // calculate dtsCorrection
  9150. if (this._audioNextDts) {
  9151. dtsCorrection = firstSampleOriginalDts - this._audioNextDts;
  9152. } else {
  9153. // this._audioNextDts == undefined
  9154. if (this._audioSegmentInfoList.isEmpty()) {
  9155. dtsCorrection = 0;
  9156. if (this._fillSilentAfterSeek && !this._videoSegmentInfoList.isEmpty()) {
  9157. if (this._audioMeta.originalCodec !== 'mp3') {
  9158. insertPrefixSilentFrame = true;
  9159. }
  9160. }
  9161. } else {
  9162. var _lastSample = this._audioSegmentInfoList.getLastSampleBefore(firstSampleOriginalDts);
  9163. if (_lastSample != null) {
  9164. var distance = firstSampleOriginalDts - (_lastSample.originalDts + _lastSample.duration);
  9165. if (distance <= 3) {
  9166. distance = 0;
  9167. }
  9168. var expectedDts = _lastSample.dts + _lastSample.duration + distance;
  9169. dtsCorrection = firstSampleOriginalDts - expectedDts;
  9170. } else {
  9171. // lastSample == null, cannot found
  9172. dtsCorrection = 0;
  9173. }
  9174. }
  9175. }
  9176. if (insertPrefixSilentFrame) {
  9177. // align audio segment beginDts to match with current video segment's beginDts
  9178. var firstSampleDts = firstSampleOriginalDts - dtsCorrection;
  9179. var videoSegment = this._videoSegmentInfoList.getLastSegmentBefore(firstSampleOriginalDts);
  9180. if (videoSegment != null && videoSegment.beginDts < firstSampleDts) {
  9181. var silentUnit = _aacSilent2.default.getSilentFrame(this._audioMeta.originalCodec, this._audioMeta.channelCount);
  9182. if (silentUnit) {
  9183. var dts = videoSegment.beginDts;
  9184. var silentFrameDuration = firstSampleDts - videoSegment.beginDts;
  9185. _logger2.default.v(this.TAG, 'InsertPrefixSilentAudio: dts: ' + dts + ', duration: ' + silentFrameDuration);
  9186. samples.unshift({ unit: silentUnit, dts: dts, pts: dts });
  9187. mdatBytes += silentUnit.byteLength;
  9188. } // silentUnit == null: Cannot generate, skip
  9189. } else {
  9190. insertPrefixSilentFrame = false;
  9191. }
  9192. }
  9193. var mp4Samples = [];
  9194. // Correct dts for each sample, and calculate sample duration. Then output to mp4Samples
  9195. for (var i = 0; i < samples.length; i++) {
  9196. var _sample = samples[i];
  9197. var unit = _sample.unit;
  9198. var originalDts = _sample.dts - this._dtsBase;
  9199. var _dts = originalDts - dtsCorrection;
  9200. if (firstDts === -1) {
  9201. firstDts = _dts;
  9202. }
  9203. var sampleDuration = 0;
  9204. if (i !== samples.length - 1) {
  9205. var nextDts = samples[i + 1].dts - this._dtsBase - dtsCorrection;
  9206. sampleDuration = nextDts - _dts;
  9207. } else {
  9208. // the last sample
  9209. if (lastSample != null) {
  9210. // use stashed sample's dts to calculate sample duration
  9211. var _nextDts = lastSample.dts - this._dtsBase - dtsCorrection;
  9212. sampleDuration = _nextDts - _dts;
  9213. } else if (mp4Samples.length >= 1) {
  9214. // use second last sample duration
  9215. sampleDuration = mp4Samples[mp4Samples.length - 1].duration;
  9216. } else {
  9217. // the only one sample, use reference sample duration
  9218. sampleDuration = Math.floor(refSampleDuration);
  9219. }
  9220. }
  9221. var needFillSilentFrames = false;
  9222. var silentFrames = null;
  9223. // Silent frame generation, if large timestamp gap detected && config.fixAudioTimestampGap
  9224. if (sampleDuration > refSampleDuration * 1.5 && this._audioMeta.codec !== 'mp3' && this._fillAudioTimestampGap && !_browser2.default.safari) {
  9225. // We need to insert silent frames to fill timestamp gap
  9226. needFillSilentFrames = true;
  9227. var delta = Math.abs(sampleDuration - refSampleDuration);
  9228. var frameCount = Math.ceil(delta / refSampleDuration);
  9229. var currentDts = _dts + refSampleDuration; // Notice: in float
  9230. _logger2.default.w(this.TAG, 'Large audio timestamp gap detected, may cause AV sync to drift. ' + 'Silent frames will be generated to avoid unsync.\n' + ('dts: ' + (_dts + sampleDuration) + ' ms, expected: ' + (_dts + Math.round(refSampleDuration)) + ' ms, ') + ('delta: ' + Math.round(delta) + ' ms, generate: ' + frameCount + ' frames'));
  9231. var _silentUnit = _aacSilent2.default.getSilentFrame(this._audioMeta.originalCodec, this._audioMeta.channelCount);
  9232. if (_silentUnit == null) {
  9233. _logger2.default.w(this.TAG, 'Unable to generate silent frame for ' + (this._audioMeta.originalCodec + ' with ' + this._audioMeta.channelCount + ' channels, repeat last frame'));
  9234. // Repeat last frame
  9235. _silentUnit = unit;
  9236. }
  9237. silentFrames = [];
  9238. for (var j = 0; j < frameCount; j++) {
  9239. var intDts = Math.round(currentDts); // round to integer
  9240. if (silentFrames.length > 0) {
  9241. // Set previous frame sample duration
  9242. var previousFrame = silentFrames[silentFrames.length - 1];
  9243. previousFrame.duration = intDts - previousFrame.dts;
  9244. }
  9245. var frame = {
  9246. dts: intDts,
  9247. pts: intDts,
  9248. cts: 0,
  9249. unit: _silentUnit,
  9250. size: _silentUnit.byteLength,
  9251. duration: 0, // wait for next sample
  9252. originalDts: originalDts,
  9253. flags: {
  9254. isLeading: 0,
  9255. dependsOn: 1,
  9256. isDependedOn: 0,
  9257. hasRedundancy: 0
  9258. }
  9259. };
  9260. silentFrames.push(frame);
  9261. mdatBytes += unit.byteLength;
  9262. currentDts += refSampleDuration;
  9263. }
  9264. // last frame: align end time to next frame dts
  9265. var lastFrame = silentFrames[silentFrames.length - 1];
  9266. lastFrame.duration = _dts + sampleDuration - lastFrame.dts;
  9267. // silentFrames.forEach((frame) => {
  9268. // Log.w(this.TAG, `SilentAudio: dts: ${frame.dts}, duration: ${frame.duration}`);
  9269. // });
  9270. // Set correct sample duration for current frame
  9271. sampleDuration = Math.round(refSampleDuration);
  9272. }
  9273. mp4Samples.push({
  9274. dts: _dts,
  9275. pts: _dts,
  9276. cts: 0,
  9277. unit: _sample.unit,
  9278. size: _sample.unit.byteLength,
  9279. duration: sampleDuration,
  9280. originalDts: originalDts,
  9281. flags: {
  9282. isLeading: 0,
  9283. dependsOn: 1,
  9284. isDependedOn: 0,
  9285. hasRedundancy: 0
  9286. }
  9287. });
  9288. if (needFillSilentFrames) {
  9289. // Silent frames should be inserted after wrong-duration frame
  9290. mp4Samples.push.apply(mp4Samples, silentFrames);
  9291. }
  9292. }
  9293. // allocate mdatbox
  9294. if (mpegRawTrack) {
  9295. // allocate for raw mpeg buffer
  9296. mdatbox = new Uint8Array(mdatBytes);
  9297. } else {
  9298. // allocate for fmp4 mdat box
  9299. mdatbox = new Uint8Array(mdatBytes);
  9300. // size field
  9301. mdatbox[0] = mdatBytes >>> 24 & 0xFF;
  9302. mdatbox[1] = mdatBytes >>> 16 & 0xFF;
  9303. mdatbox[2] = mdatBytes >>> 8 & 0xFF;
  9304. mdatbox[3] = mdatBytes & 0xFF;
  9305. // type field (fourCC)
  9306. mdatbox.set(_mp4Generator2.default.types.mdat, 4);
  9307. }
  9308. // Write samples into mdatbox
  9309. for (var _i = 0; _i < mp4Samples.length; _i++) {
  9310. var _unit = mp4Samples[_i].unit;
  9311. mdatbox.set(_unit, offset);
  9312. offset += _unit.byteLength;
  9313. }
  9314. var latest = mp4Samples[mp4Samples.length - 1];
  9315. lastDts = latest.dts + latest.duration;
  9316. this._audioNextDts = lastDts;
  9317. // fill media segment info & add to info list
  9318. var info = new _mediaSegmentInfo.MediaSegmentInfo();
  9319. info.beginDts = firstDts;
  9320. info.endDts = lastDts;
  9321. info.beginPts = firstDts;
  9322. info.endPts = lastDts;
  9323. info.originalBeginDts = mp4Samples[0].originalDts;
  9324. info.originalEndDts = latest.originalDts + latest.duration;
  9325. info.firstSample = new _mediaSegmentInfo.SampleInfo(mp4Samples[0].dts, mp4Samples[0].pts, mp4Samples[0].duration, mp4Samples[0].originalDts, false);
  9326. info.lastSample = new _mediaSegmentInfo.SampleInfo(latest.dts, latest.pts, latest.duration, latest.originalDts, false);
  9327. if (!this._isLive) {
  9328. this._audioSegmentInfoList.append(info);
  9329. }
  9330. track.samples = mp4Samples;
  9331. track.sequenceNumber++;
  9332. var moofbox = null;
  9333. if (mpegRawTrack) {
  9334. // Generate empty buffer, because useless for raw mpeg
  9335. moofbox = new Uint8Array();
  9336. } else {
  9337. // Generate moof for fmp4 segment
  9338. moofbox = _mp4Generator2.default.moof(track, firstDts);
  9339. }
  9340. track.samples = [];
  9341. track.length = 0;
  9342. var segment = {
  9343. type: 'audio',
  9344. data: this._mergeBoxes(moofbox, mdatbox).buffer,
  9345. sampleCount: mp4Samples.length,
  9346. info: info
  9347. };
  9348. if (mpegRawTrack && firstSegmentAfterSeek) {
  9349. // For MPEG audio stream in MSE, if seeking occurred, before appending new buffer
  9350. // We need explicitly set timestampOffset to the desired point in timeline for mpeg SourceBuffer.
  9351. segment.timestampOffset = firstDts;
  9352. }
  9353. this._onMediaSegment('audio', segment);
  9354. }
  9355. }, {
  9356. key: '_remuxVideo',
  9357. value: function _remuxVideo(videoTrack, force) {
  9358. if (this._videoMeta == null) {
  9359. return;
  9360. }
  9361. var track = videoTrack;
  9362. var samples = track.samples;
  9363. var dtsCorrection = undefined;
  9364. var firstDts = -1,
  9365. lastDts = -1;
  9366. var firstPts = -1,
  9367. lastPts = -1;
  9368. if (!samples || samples.length === 0) {
  9369. return;
  9370. }
  9371. if (samples.length === 1 && !force) {
  9372. // If [sample count in current batch] === 1 && (force != true)
  9373. // Ignore and keep in demuxer's queue
  9374. return;
  9375. } // else if (force === true) do remux
  9376. var offset = 8;
  9377. var mdatbox = null;
  9378. var mdatBytes = 8 + videoTrack.length;
  9379. var lastSample = null;
  9380. // Pop the lastSample and waiting for stash
  9381. if (samples.length > 1) {
  9382. lastSample = samples.pop();
  9383. mdatBytes -= lastSample.length;
  9384. }
  9385. // Insert [stashed lastSample in the previous batch] to the front
  9386. if (this._videoStashedLastSample != null) {
  9387. var sample = this._videoStashedLastSample;
  9388. this._videoStashedLastSample = null;
  9389. samples.unshift(sample);
  9390. mdatBytes += sample.length;
  9391. }
  9392. // Stash the lastSample of current batch, waiting for next batch
  9393. if (lastSample != null) {
  9394. this._videoStashedLastSample = lastSample;
  9395. }
  9396. var firstSampleOriginalDts = samples[0].dts - this._dtsBase;
  9397. // calculate dtsCorrection
  9398. if (this._videoNextDts) {
  9399. dtsCorrection = firstSampleOriginalDts - this._videoNextDts;
  9400. } else {
  9401. // this._videoNextDts == undefined
  9402. if (this._videoSegmentInfoList.isEmpty()) {
  9403. dtsCorrection = 0;
  9404. } else {
  9405. var _lastSample2 = this._videoSegmentInfoList.getLastSampleBefore(firstSampleOriginalDts);
  9406. if (_lastSample2 != null) {
  9407. var distance = firstSampleOriginalDts - (_lastSample2.originalDts + _lastSample2.duration);
  9408. if (distance <= 3) {
  9409. distance = 0;
  9410. }
  9411. var expectedDts = _lastSample2.dts + _lastSample2.duration + distance;
  9412. dtsCorrection = firstSampleOriginalDts - expectedDts;
  9413. } else {
  9414. // lastSample == null, cannot found
  9415. dtsCorrection = 0;
  9416. }
  9417. }
  9418. }
  9419. var info = new _mediaSegmentInfo.MediaSegmentInfo();
  9420. var mp4Samples = [];
  9421. // Correct dts for each sample, and calculate sample duration. Then output to mp4Samples
  9422. for (var i = 0; i < samples.length; i++) {
  9423. var _sample2 = samples[i];
  9424. var originalDts = _sample2.dts - this._dtsBase;
  9425. var isKeyframe = _sample2.isKeyframe;
  9426. var dts = originalDts - dtsCorrection;
  9427. var cts = _sample2.cts;
  9428. var pts = dts + cts;
  9429. if (firstDts === -1) {
  9430. firstDts = dts;
  9431. firstPts = pts;
  9432. }
  9433. var sampleDuration = 0;
  9434. if (i !== samples.length - 1) {
  9435. var nextDts = samples[i + 1].dts - this._dtsBase - dtsCorrection;
  9436. sampleDuration = nextDts - dts;
  9437. } else {
  9438. // the last sample
  9439. if (lastSample != null) {
  9440. // use stashed sample's dts to calculate sample duration
  9441. var _nextDts2 = lastSample.dts - this._dtsBase - dtsCorrection;
  9442. sampleDuration = _nextDts2 - dts;
  9443. } else if (mp4Samples.length >= 1) {
  9444. // use second last sample duration
  9445. sampleDuration = mp4Samples[mp4Samples.length - 1].duration;
  9446. } else {
  9447. // the only one sample, use reference sample duration
  9448. sampleDuration = Math.floor(this._videoMeta.refSampleDuration);
  9449. }
  9450. }
  9451. if (isKeyframe) {
  9452. var syncPoint = new _mediaSegmentInfo.SampleInfo(dts, pts, sampleDuration, _sample2.dts, true);
  9453. syncPoint.fileposition = _sample2.fileposition;
  9454. info.appendSyncPoint(syncPoint);
  9455. }
  9456. mp4Samples.push({
  9457. dts: dts,
  9458. pts: pts,
  9459. cts: cts,
  9460. units: _sample2.units,
  9461. size: _sample2.length,
  9462. isKeyframe: isKeyframe,
  9463. duration: sampleDuration,
  9464. originalDts: originalDts,
  9465. flags: {
  9466. isLeading: 0,
  9467. dependsOn: isKeyframe ? 2 : 1,
  9468. isDependedOn: isKeyframe ? 1 : 0,
  9469. hasRedundancy: 0,
  9470. isNonSync: isKeyframe ? 0 : 1
  9471. }
  9472. });
  9473. }
  9474. // allocate mdatbox
  9475. mdatbox = new Uint8Array(mdatBytes);
  9476. mdatbox[0] = mdatBytes >>> 24 & 0xFF;
  9477. mdatbox[1] = mdatBytes >>> 16 & 0xFF;
  9478. mdatbox[2] = mdatBytes >>> 8 & 0xFF;
  9479. mdatbox[3] = mdatBytes & 0xFF;
  9480. mdatbox.set(_mp4Generator2.default.types.mdat, 4);
  9481. // Write samples into mdatbox
  9482. for (var _i2 = 0; _i2 < mp4Samples.length; _i2++) {
  9483. var units = mp4Samples[_i2].units;
  9484. while (units.length) {
  9485. var unit = units.shift();
  9486. var data = unit.data;
  9487. mdatbox.set(data, offset);
  9488. offset += data.byteLength;
  9489. }
  9490. }
  9491. var latest = mp4Samples[mp4Samples.length - 1];
  9492. lastDts = latest.dts + latest.duration;
  9493. lastPts = latest.pts + latest.duration;
  9494. this._videoNextDts = lastDts;
  9495. // fill media segment info & add to info list
  9496. info.beginDts = firstDts;
  9497. info.endDts = lastDts;
  9498. info.beginPts = firstPts;
  9499. info.endPts = lastPts;
  9500. info.originalBeginDts = mp4Samples[0].originalDts;
  9501. info.originalEndDts = latest.originalDts + latest.duration;
  9502. info.firstSample = new _mediaSegmentInfo.SampleInfo(mp4Samples[0].dts, mp4Samples[0].pts, mp4Samples[0].duration, mp4Samples[0].originalDts, mp4Samples[0].isKeyframe);
  9503. info.lastSample = new _mediaSegmentInfo.SampleInfo(latest.dts, latest.pts, latest.duration, latest.originalDts, latest.isKeyframe);
  9504. if (!this._isLive) {
  9505. this._videoSegmentInfoList.append(info);
  9506. }
  9507. track.samples = mp4Samples;
  9508. track.sequenceNumber++;
  9509. // workaround for chrome < 50: force first sample as a random access point
  9510. // see https://bugs.chromium.org/p/chromium/issues/detail?id=229412
  9511. if (this._forceFirstIDR) {
  9512. var flags = mp4Samples[0].flags;
  9513. flags.dependsOn = 2;
  9514. flags.isNonSync = 0;
  9515. }
  9516. var moofbox = _mp4Generator2.default.moof(track, firstDts);
  9517. track.samples = [];
  9518. track.length = 0;
  9519. this._onMediaSegment('video', {
  9520. type: 'video',
  9521. data: this._mergeBoxes(moofbox, mdatbox).buffer,
  9522. sampleCount: mp4Samples.length,
  9523. info: info
  9524. });
  9525. }
  9526. }, {
  9527. key: '_mergeBoxes',
  9528. value: function _mergeBoxes(moof, mdat) {
  9529. var result = new Uint8Array(moof.byteLength + mdat.byteLength);
  9530. result.set(moof, 0);
  9531. result.set(mdat, moof.byteLength);
  9532. return result;
  9533. }
  9534. }, {
  9535. key: 'onInitSegment',
  9536. get: function get() {
  9537. return this._onInitSegment;
  9538. },
  9539. set: function set(callback) {
  9540. this._onInitSegment = callback;
  9541. }
  9542. /* prototype: function onMediaSegment(type: string, mediaSegment: MediaSegment): void
  9543. MediaSegment: {
  9544. type: string,
  9545. data: ArrayBuffer,
  9546. sampleCount: int32
  9547. info: MediaSegmentInfo
  9548. }
  9549. */
  9550. }, {
  9551. key: 'onMediaSegment',
  9552. get: function get() {
  9553. return this._onMediaSegment;
  9554. },
  9555. set: function set(callback) {
  9556. this._onMediaSegment = callback;
  9557. }
  9558. }]);
  9559. return MP4Remuxer;
  9560. }();
  9561. exports.default = MP4Remuxer;
  9562. },{"../core/media-segment-info.js":8,"../utils/browser.js":39,"../utils/exception.js":40,"../utils/logger.js":41,"./aac-silent.js":36,"./mp4-generator.js":37}],39:[function(_dereq_,module,exports){
  9563. 'use strict';
  9564. Object.defineProperty(exports, "__esModule", {
  9565. value: true
  9566. });
  9567. /*
  9568. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  9569. *
  9570. * @author zheng qian <xqq@xqq.im>
  9571. *
  9572. * Licensed under the Apache License, Version 2.0 (the "License");
  9573. * you may not use this file except in compliance with the License.
  9574. * You may obtain a copy of the License at
  9575. *
  9576. * http://www.apache.org/licenses/LICENSE-2.0
  9577. *
  9578. * Unless required by applicable law or agreed to in writing, software
  9579. * distributed under the License is distributed on an "AS IS" BASIS,
  9580. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9581. * See the License for the specific language governing permissions and
  9582. * limitations under the License.
  9583. */
  9584. var Browser = {};
  9585. function detect() {
  9586. // modified from jquery-browser-plugin
  9587. var ua = self.navigator.userAgent.toLowerCase();
  9588. var match = /(edge)\/([\w.]+)/.exec(ua) || /(opr)[\/]([\w.]+)/.exec(ua) || /(chrome)[ \/]([\w.]+)/.exec(ua) || /(iemobile)[\/]([\w.]+)/.exec(ua) || /(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf('trident') >= 0 && /(rv)(?::| )([\w.]+)/.exec(ua) || ua.indexOf('compatible') < 0 && /(firefox)[ \/]([\w.]+)/.exec(ua) || [];
  9589. var platform_match = /(ipad)/.exec(ua) || /(ipod)/.exec(ua) || /(windows phone)/.exec(ua) || /(iphone)/.exec(ua) || /(kindle)/.exec(ua) || /(android)/.exec(ua) || /(windows)/.exec(ua) || /(mac)/.exec(ua) || /(linux)/.exec(ua) || /(cros)/.exec(ua) || [];
  9590. var matched = {
  9591. browser: match[5] || match[3] || match[1] || '',
  9592. version: match[2] || match[4] || '0',
  9593. majorVersion: match[4] || match[2] || '0',
  9594. platform: platform_match[0] || ''
  9595. };
  9596. var browser = {};
  9597. if (matched.browser) {
  9598. browser[matched.browser] = true;
  9599. var versionArray = matched.majorVersion.split('.');
  9600. browser.version = {
  9601. major: parseInt(matched.majorVersion, 10),
  9602. string: matched.version
  9603. };
  9604. if (versionArray.length > 1) {
  9605. browser.version.minor = parseInt(versionArray[1], 10);
  9606. }
  9607. if (versionArray.length > 2) {
  9608. browser.version.build = parseInt(versionArray[2], 10);
  9609. }
  9610. }
  9611. if (matched.platform) {
  9612. browser[matched.platform] = true;
  9613. }
  9614. if (browser.chrome || browser.opr || browser.safari) {
  9615. browser.webkit = true;
  9616. }
  9617. // MSIE. IE11 has 'rv' identifer
  9618. if (browser.rv || browser.iemobile) {
  9619. if (browser.rv) {
  9620. delete browser.rv;
  9621. }
  9622. var msie = 'msie';
  9623. matched.browser = msie;
  9624. browser[msie] = true;
  9625. }
  9626. // Microsoft Edge
  9627. if (browser.edge) {
  9628. delete browser.edge;
  9629. var msedge = 'msedge';
  9630. matched.browser = msedge;
  9631. browser[msedge] = true;
  9632. }
  9633. // Opera 15+
  9634. if (browser.opr) {
  9635. var opera = 'opera';
  9636. matched.browser = opera;
  9637. browser[opera] = true;
  9638. }
  9639. // Stock android browsers are marked as Safari
  9640. if (browser.safari && browser.android) {
  9641. var android = 'android';
  9642. matched.browser = android;
  9643. browser[android] = true;
  9644. }
  9645. browser.name = matched.browser;
  9646. browser.platform = matched.platform;
  9647. for (var key in Browser) {
  9648. if (Browser.hasOwnProperty(key)) {
  9649. delete Browser[key];
  9650. }
  9651. }
  9652. Object.assign(Browser, browser);
  9653. }
  9654. detect();
  9655. exports.default = Browser;
  9656. },{}],40:[function(_dereq_,module,exports){
  9657. 'use strict';
  9658. Object.defineProperty(exports, "__esModule", {
  9659. value: true
  9660. });
  9661. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  9662. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  9663. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  9664. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9665. /*
  9666. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  9667. *
  9668. * @author zheng qian <xqq@xqq.im>
  9669. *
  9670. * Licensed under the Apache License, Version 2.0 (the "License");
  9671. * you may not use this file except in compliance with the License.
  9672. * You may obtain a copy of the License at
  9673. *
  9674. * http://www.apache.org/licenses/LICENSE-2.0
  9675. *
  9676. * Unless required by applicable law or agreed to in writing, software
  9677. * distributed under the License is distributed on an "AS IS" BASIS,
  9678. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9679. * See the License for the specific language governing permissions and
  9680. * limitations under the License.
  9681. */
  9682. var RuntimeException = exports.RuntimeException = function () {
  9683. function RuntimeException(message) {
  9684. _classCallCheck(this, RuntimeException);
  9685. this._message = message;
  9686. }
  9687. _createClass(RuntimeException, [{
  9688. key: 'toString',
  9689. value: function toString() {
  9690. return this.name + ': ' + this.message;
  9691. }
  9692. }, {
  9693. key: 'name',
  9694. get: function get() {
  9695. return 'RuntimeException';
  9696. }
  9697. }, {
  9698. key: 'message',
  9699. get: function get() {
  9700. return this._message;
  9701. }
  9702. }]);
  9703. return RuntimeException;
  9704. }();
  9705. var IllegalStateException = exports.IllegalStateException = function (_RuntimeException) {
  9706. _inherits(IllegalStateException, _RuntimeException);
  9707. function IllegalStateException(message) {
  9708. _classCallCheck(this, IllegalStateException);
  9709. return _possibleConstructorReturn(this, (IllegalStateException.__proto__ || Object.getPrototypeOf(IllegalStateException)).call(this, message));
  9710. }
  9711. _createClass(IllegalStateException, [{
  9712. key: 'name',
  9713. get: function get() {
  9714. return 'IllegalStateException';
  9715. }
  9716. }]);
  9717. return IllegalStateException;
  9718. }(RuntimeException);
  9719. var InvalidArgumentException = exports.InvalidArgumentException = function (_RuntimeException2) {
  9720. _inherits(InvalidArgumentException, _RuntimeException2);
  9721. function InvalidArgumentException(message) {
  9722. _classCallCheck(this, InvalidArgumentException);
  9723. return _possibleConstructorReturn(this, (InvalidArgumentException.__proto__ || Object.getPrototypeOf(InvalidArgumentException)).call(this, message));
  9724. }
  9725. _createClass(InvalidArgumentException, [{
  9726. key: 'name',
  9727. get: function get() {
  9728. return 'InvalidArgumentException';
  9729. }
  9730. }]);
  9731. return InvalidArgumentException;
  9732. }(RuntimeException);
  9733. var NotImplementedException = exports.NotImplementedException = function (_RuntimeException3) {
  9734. _inherits(NotImplementedException, _RuntimeException3);
  9735. function NotImplementedException(message) {
  9736. _classCallCheck(this, NotImplementedException);
  9737. return _possibleConstructorReturn(this, (NotImplementedException.__proto__ || Object.getPrototypeOf(NotImplementedException)).call(this, message));
  9738. }
  9739. _createClass(NotImplementedException, [{
  9740. key: 'name',
  9741. get: function get() {
  9742. return 'NotImplementedException';
  9743. }
  9744. }]);
  9745. return NotImplementedException;
  9746. }(RuntimeException);
  9747. },{}],41:[function(_dereq_,module,exports){
  9748. 'use strict';
  9749. Object.defineProperty(exports, "__esModule", {
  9750. value: true
  9751. });
  9752. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  9753. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  9754. *
  9755. * @author zheng qian <xqq@xqq.im>
  9756. *
  9757. * Licensed under the Apache License, Version 2.0 (the "License");
  9758. * you may not use this file except in compliance with the License.
  9759. * You may obtain a copy of the License at
  9760. *
  9761. * http://www.apache.org/licenses/LICENSE-2.0
  9762. *
  9763. * Unless required by applicable law or agreed to in writing, software
  9764. * distributed under the License is distributed on an "AS IS" BASIS,
  9765. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9766. * See the License for the specific language governing permissions and
  9767. * limitations under the License.
  9768. */
  9769. var _events = _dereq_('events');
  9770. var _events2 = _interopRequireDefault(_events);
  9771. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9772. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9773. var Log = function () {
  9774. function Log() {
  9775. _classCallCheck(this, Log);
  9776. }
  9777. _createClass(Log, null, [{
  9778. key: 'e',
  9779. value: function e(tag, msg) {
  9780. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  9781. var str = '[' + tag + '] > ' + msg;
  9782. if (Log.ENABLE_CALLBACK) {
  9783. Log.emitter.emit('log', 'error', str);
  9784. }
  9785. if (!Log.ENABLE_ERROR) {
  9786. return;
  9787. }
  9788. if (console.error) {
  9789. console.error(str);
  9790. } else if (console.warn) {
  9791. console.warn(str);
  9792. } else {
  9793. console.log(str);
  9794. }
  9795. }
  9796. }, {
  9797. key: 'i',
  9798. value: function i(tag, msg) {
  9799. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  9800. var str = '[' + tag + '] > ' + msg;
  9801. if (Log.ENABLE_CALLBACK) {
  9802. Log.emitter.emit('log', 'info', str);
  9803. }
  9804. if (!Log.ENABLE_INFO) {
  9805. return;
  9806. }
  9807. if (console.info) {
  9808. console.info(str);
  9809. } else {
  9810. console.log(str);
  9811. }
  9812. }
  9813. }, {
  9814. key: 'w',
  9815. value: function w(tag, msg) {
  9816. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  9817. var str = '[' + tag + '] > ' + msg;
  9818. if (Log.ENABLE_CALLBACK) {
  9819. Log.emitter.emit('log', 'warn', str);
  9820. }
  9821. if (!Log.ENABLE_WARN) {
  9822. return;
  9823. }
  9824. if (console.warn) {
  9825. console.warn(str);
  9826. } else {
  9827. console.log(str);
  9828. }
  9829. }
  9830. }, {
  9831. key: 'd',
  9832. value: function d(tag, msg) {
  9833. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  9834. var str = '[' + tag + '] > ' + msg;
  9835. if (Log.ENABLE_CALLBACK) {
  9836. Log.emitter.emit('log', 'debug', str);
  9837. }
  9838. if (!Log.ENABLE_DEBUG) {
  9839. return;
  9840. }
  9841. if (console.debug) {
  9842. console.debug(str);
  9843. } else {
  9844. console.log(str);
  9845. }
  9846. }
  9847. }, {
  9848. key: 'v',
  9849. value: function v(tag, msg) {
  9850. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  9851. var str = '[' + tag + '] > ' + msg;
  9852. if (Log.ENABLE_CALLBACK) {
  9853. Log.emitter.emit('log', 'verbose', str);
  9854. }
  9855. if (!Log.ENABLE_VERBOSE) {
  9856. return;
  9857. }
  9858. console.log(str);
  9859. }
  9860. }]);
  9861. return Log;
  9862. }();
  9863. Log.GLOBAL_TAG = 'flv.js';
  9864. Log.FORCE_GLOBAL_TAG = false;
  9865. Log.ENABLE_ERROR = true;
  9866. Log.ENABLE_INFO = true;
  9867. Log.ENABLE_WARN = true;
  9868. Log.ENABLE_DEBUG = true;
  9869. Log.ENABLE_VERBOSE = true;
  9870. Log.ENABLE_CALLBACK = false;
  9871. Log.emitter = new _events2.default();
  9872. exports.default = Log;
  9873. },{"events":2}],42:[function(_dereq_,module,exports){
  9874. 'use strict';
  9875. Object.defineProperty(exports, "__esModule", {
  9876. value: true
  9877. });
  9878. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  9879. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  9880. *
  9881. * @author zheng qian <xqq@xqq.im>
  9882. *
  9883. * Licensed under the Apache License, Version 2.0 (the "License");
  9884. * you may not use this file except in compliance with the License.
  9885. * You may obtain a copy of the License at
  9886. *
  9887. * http://www.apache.org/licenses/LICENSE-2.0
  9888. *
  9889. * Unless required by applicable law or agreed to in writing, software
  9890. * distributed under the License is distributed on an "AS IS" BASIS,
  9891. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9892. * See the License for the specific language governing permissions and
  9893. * limitations under the License.
  9894. */
  9895. var _events = _dereq_('events');
  9896. var _events2 = _interopRequireDefault(_events);
  9897. var _logger = _dereq_('./logger.js');
  9898. var _logger2 = _interopRequireDefault(_logger);
  9899. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9900. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9901. var LoggingControl = function () {
  9902. function LoggingControl() {
  9903. _classCallCheck(this, LoggingControl);
  9904. }
  9905. _createClass(LoggingControl, null, [{
  9906. key: 'getConfig',
  9907. value: function getConfig() {
  9908. return {
  9909. globalTag: _logger2.default.GLOBAL_TAG,
  9910. forceGlobalTag: _logger2.default.FORCE_GLOBAL_TAG,
  9911. enableVerbose: _logger2.default.ENABLE_VERBOSE,
  9912. enableDebug: _logger2.default.ENABLE_DEBUG,
  9913. enableInfo: _logger2.default.ENABLE_INFO,
  9914. enableWarn: _logger2.default.ENABLE_WARN,
  9915. enableError: _logger2.default.ENABLE_ERROR,
  9916. enableCallback: _logger2.default.ENABLE_CALLBACK
  9917. };
  9918. }
  9919. }, {
  9920. key: 'applyConfig',
  9921. value: function applyConfig(config) {
  9922. _logger2.default.GLOBAL_TAG = config.globalTag;
  9923. _logger2.default.FORCE_GLOBAL_TAG = config.forceGlobalTag;
  9924. _logger2.default.ENABLE_VERBOSE = config.enableVerbose;
  9925. _logger2.default.ENABLE_DEBUG = config.enableDebug;
  9926. _logger2.default.ENABLE_INFO = config.enableInfo;
  9927. _logger2.default.ENABLE_WARN = config.enableWarn;
  9928. _logger2.default.ENABLE_ERROR = config.enableError;
  9929. _logger2.default.ENABLE_CALLBACK = config.enableCallback;
  9930. }
  9931. }, {
  9932. key: '_notifyChange',
  9933. value: function _notifyChange() {
  9934. var emitter = LoggingControl.emitter;
  9935. if (emitter.listenerCount('change') > 0) {
  9936. var config = LoggingControl.getConfig();
  9937. emitter.emit('change', config);
  9938. }
  9939. }
  9940. }, {
  9941. key: 'registerListener',
  9942. value: function registerListener(listener) {
  9943. LoggingControl.emitter.addListener('change', listener);
  9944. }
  9945. }, {
  9946. key: 'removeListener',
  9947. value: function removeListener(listener) {
  9948. LoggingControl.emitter.removeListener('change', listener);
  9949. }
  9950. }, {
  9951. key: 'addLogListener',
  9952. value: function addLogListener(listener) {
  9953. _logger2.default.emitter.addListener('log', listener);
  9954. if (_logger2.default.emitter.listenerCount('log') > 0) {
  9955. _logger2.default.ENABLE_CALLBACK = true;
  9956. LoggingControl._notifyChange();
  9957. }
  9958. }
  9959. }, {
  9960. key: 'removeLogListener',
  9961. value: function removeLogListener(listener) {
  9962. _logger2.default.emitter.removeListener('log', listener);
  9963. if (_logger2.default.emitter.listenerCount('log') === 0) {
  9964. _logger2.default.ENABLE_CALLBACK = false;
  9965. LoggingControl._notifyChange();
  9966. }
  9967. }
  9968. }, {
  9969. key: 'forceGlobalTag',
  9970. get: function get() {
  9971. return _logger2.default.FORCE_GLOBAL_TAG;
  9972. },
  9973. set: function set(enable) {
  9974. _logger2.default.FORCE_GLOBAL_TAG = enable;
  9975. LoggingControl._notifyChange();
  9976. }
  9977. }, {
  9978. key: 'globalTag',
  9979. get: function get() {
  9980. return _logger2.default.GLOBAL_TAG;
  9981. },
  9982. set: function set(tag) {
  9983. _logger2.default.GLOBAL_TAG = tag;
  9984. LoggingControl._notifyChange();
  9985. }
  9986. }, {
  9987. key: 'enableAll',
  9988. get: function get() {
  9989. return _logger2.default.ENABLE_VERBOSE && _logger2.default.ENABLE_DEBUG && _logger2.default.ENABLE_INFO && _logger2.default.ENABLE_WARN && _logger2.default.ENABLE_ERROR;
  9990. },
  9991. set: function set(enable) {
  9992. _logger2.default.ENABLE_VERBOSE = enable;
  9993. _logger2.default.ENABLE_DEBUG = enable;
  9994. _logger2.default.ENABLE_INFO = enable;
  9995. _logger2.default.ENABLE_WARN = enable;
  9996. _logger2.default.ENABLE_ERROR = enable;
  9997. LoggingControl._notifyChange();
  9998. }
  9999. }, {
  10000. key: 'enableDebug',
  10001. get: function get() {
  10002. return _logger2.default.ENABLE_DEBUG;
  10003. },
  10004. set: function set(enable) {
  10005. _logger2.default.ENABLE_DEBUG = enable;
  10006. LoggingControl._notifyChange();
  10007. }
  10008. }, {
  10009. key: 'enableVerbose',
  10010. get: function get() {
  10011. return _logger2.default.ENABLE_VERBOSE;
  10012. },
  10013. set: function set(enable) {
  10014. _logger2.default.ENABLE_VERBOSE = enable;
  10015. LoggingControl._notifyChange();
  10016. }
  10017. }, {
  10018. key: 'enableInfo',
  10019. get: function get() {
  10020. return _logger2.default.ENABLE_INFO;
  10021. },
  10022. set: function set(enable) {
  10023. _logger2.default.ENABLE_INFO = enable;
  10024. LoggingControl._notifyChange();
  10025. }
  10026. }, {
  10027. key: 'enableWarn',
  10028. get: function get() {
  10029. return _logger2.default.ENABLE_WARN;
  10030. },
  10031. set: function set(enable) {
  10032. _logger2.default.ENABLE_WARN = enable;
  10033. LoggingControl._notifyChange();
  10034. }
  10035. }, {
  10036. key: 'enableError',
  10037. get: function get() {
  10038. return _logger2.default.ENABLE_ERROR;
  10039. },
  10040. set: function set(enable) {
  10041. _logger2.default.ENABLE_ERROR = enable;
  10042. LoggingControl._notifyChange();
  10043. }
  10044. }]);
  10045. return LoggingControl;
  10046. }();
  10047. LoggingControl.emitter = new _events2.default();
  10048. exports.default = LoggingControl;
  10049. },{"./logger.js":41,"events":2}],43:[function(_dereq_,module,exports){
  10050. 'use strict';
  10051. Object.defineProperty(exports, "__esModule", {
  10052. value: true
  10053. });
  10054. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  10055. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10056. /*
  10057. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  10058. *
  10059. * @author zheng qian <xqq@xqq.im>
  10060. *
  10061. * Licensed under the Apache License, Version 2.0 (the "License");
  10062. * you may not use this file except in compliance with the License.
  10063. * You may obtain a copy of the License at
  10064. *
  10065. * http://www.apache.org/licenses/LICENSE-2.0
  10066. *
  10067. * Unless required by applicable law or agreed to in writing, software
  10068. * distributed under the License is distributed on an "AS IS" BASIS,
  10069. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10070. * See the License for the specific language governing permissions and
  10071. * limitations under the License.
  10072. */
  10073. var Polyfill = function () {
  10074. function Polyfill() {
  10075. _classCallCheck(this, Polyfill);
  10076. }
  10077. _createClass(Polyfill, null, [{
  10078. key: 'install',
  10079. value: function install() {
  10080. // ES6 Object.setPrototypeOf
  10081. Object.setPrototypeOf = Object.setPrototypeOf || function (obj, proto) {
  10082. obj.__proto__ = proto;
  10083. return obj;
  10084. };
  10085. // ES6 Object.assign
  10086. Object.assign = Object.assign || function (target) {
  10087. if (target === undefined || target === null) {
  10088. throw new TypeError('Cannot convert undefined or null to object');
  10089. }
  10090. var output = Object(target);
  10091. for (var i = 1; i < arguments.length; i++) {
  10092. var source = arguments[i];
  10093. if (source !== undefined && source !== null) {
  10094. for (var key in source) {
  10095. if (source.hasOwnProperty(key)) {
  10096. output[key] = source[key];
  10097. }
  10098. }
  10099. }
  10100. }
  10101. return output;
  10102. };
  10103. // ES6 Promise (missing support in IE11)
  10104. if (typeof self.Promise !== 'function') {
  10105. _dereq_('es6-promise').polyfill();
  10106. }
  10107. }
  10108. }]);
  10109. return Polyfill;
  10110. }();
  10111. Polyfill.install();
  10112. exports.default = Polyfill;
  10113. },{"es6-promise":1}],44:[function(_dereq_,module,exports){
  10114. 'use strict';
  10115. Object.defineProperty(exports, "__esModule", {
  10116. value: true
  10117. });
  10118. /*
  10119. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  10120. *
  10121. * This file is derived from C++ project libWinTF8 (https://github.com/m13253/libWinTF8)
  10122. * @author zheng qian <xqq@xqq.im>
  10123. *
  10124. * Licensed under the Apache License, Version 2.0 (the "License");
  10125. * you may not use this file except in compliance with the License.
  10126. * You may obtain a copy of the License at
  10127. *
  10128. * http://www.apache.org/licenses/LICENSE-2.0
  10129. *
  10130. * Unless required by applicable law or agreed to in writing, software
  10131. * distributed under the License is distributed on an "AS IS" BASIS,
  10132. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10133. * See the License for the specific language governing permissions and
  10134. * limitations under the License.
  10135. */
  10136. function checkContinuation(uint8array, start, checkLength) {
  10137. var array = uint8array;
  10138. if (start + checkLength < array.length) {
  10139. while (checkLength--) {
  10140. if ((array[++start] & 0xC0) !== 0x80) return false;
  10141. }
  10142. return true;
  10143. } else {
  10144. return false;
  10145. }
  10146. }
  10147. function decodeUTF8(uint8array) {
  10148. var out = [];
  10149. var input = uint8array;
  10150. var i = 0;
  10151. var length = uint8array.length;
  10152. while (i < length) {
  10153. if (input[i] < 0x80) {
  10154. out.push(String.fromCharCode(input[i]));
  10155. ++i;
  10156. continue;
  10157. } else if (input[i] < 0xC0) {
  10158. // fallthrough
  10159. } else if (input[i] < 0xE0) {
  10160. if (checkContinuation(input, i, 1)) {
  10161. var ucs4 = (input[i] & 0x1F) << 6 | input[i + 1] & 0x3F;
  10162. if (ucs4 >= 0x80) {
  10163. out.push(String.fromCharCode(ucs4 & 0xFFFF));
  10164. i += 2;
  10165. continue;
  10166. }
  10167. }
  10168. } else if (input[i] < 0xF0) {
  10169. if (checkContinuation(input, i, 2)) {
  10170. var _ucs = (input[i] & 0xF) << 12 | (input[i + 1] & 0x3F) << 6 | input[i + 2] & 0x3F;
  10171. if (_ucs >= 0x800 && (_ucs & 0xF800) !== 0xD800) {
  10172. out.push(String.fromCharCode(_ucs & 0xFFFF));
  10173. i += 3;
  10174. continue;
  10175. }
  10176. }
  10177. } else if (input[i] < 0xF8) {
  10178. if (checkContinuation(input, i, 3)) {
  10179. var _ucs2 = (input[i] & 0x7) << 18 | (input[i + 1] & 0x3F) << 12 | (input[i + 2] & 0x3F) << 6 | input[i + 3] & 0x3F;
  10180. if (_ucs2 > 0x10000 && _ucs2 < 0x110000) {
  10181. _ucs2 -= 0x10000;
  10182. out.push(String.fromCharCode(_ucs2 >>> 10 | 0xD800));
  10183. out.push(String.fromCharCode(_ucs2 & 0x3FF | 0xDC00));
  10184. i += 4;
  10185. continue;
  10186. }
  10187. }
  10188. }
  10189. out.push(String.fromCharCode(0xFFFD));
  10190. ++i;
  10191. }
  10192. return out.join('');
  10193. }
  10194. exports.default = decodeUTF8;
  10195. },{}]},{},[21])(21)
  10196. });
  10197. //# sourceMappingURL=flv.js.map