flv.js 611 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903
  1. (function(f){
  2. if(typeof exports==="object"&&typeof module!=="undefined"){
  3. module.exports=f()
  4. }else if(typeof define==="function"&&define.amd){
  5. define([],f)
  6. }else{
  7. var g;
  8. if(typeof window!=="undefined"){
  9. g=window
  10. }else if(typeof global!=="undefined"){
  11. g=global
  12. }else if(typeof self!=="undefined"){
  13. g=self
  14. }else{
  15. g=this
  16. }
  17. g.flvjs = f()
  18. }
  19. })(function(){
  20. var define,module,exports;
  21. return (function e(t,n,r){
  22. function s(o,u){
  23. if(!n[o]){
  24. if(!t[o]){
  25. var a=typeof require=="function"&&require;
  26. if(!u&&a) return a(o,!0);
  27. if(i) return i(o,!0);
  28. var f=new Error("Cannot find module '"+o+"'");
  29. throw f.code="MODULE_NOT_FOUND",f
  30. }var l=n[o]={exports:{}};
  31. t[o][0].call(l.exports,function(e){
  32. var n=t[o][1][e];return s(n?n:e)
  33. },l,l.exports,e,t,n,r)}return n[o].exports}
  34. var i=typeof require=="function"&&require;
  35. for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  36. (function (process,global){
  37. /*!
  38. * @overview es6-promise - a tiny implementation of Promises/A+.
  39. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  40. * @license Licensed under MIT license
  41. * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
  42. * @version 4.1.0
  43. */
  44. (function (global, factory) {
  45. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  46. typeof define === 'function' && define.amd ? define(factory) :
  47. (global.ES6Promise = factory());
  48. }(this, (function () { 'use strict';
  49. function objectOrFunction(x) {
  50. return typeof x === 'function' || typeof x === 'object' && x !== null;
  51. }
  52. function isFunction(x) {
  53. return typeof x === 'function';
  54. }
  55. var _isArray = undefined;
  56. if (!Array.isArray) {
  57. _isArray = function (x) {
  58. return Object.prototype.toString.call(x) === '[object Array]';
  59. };
  60. } else {
  61. _isArray = Array.isArray;
  62. }
  63. var isArray = _isArray;
  64. var len = 0;
  65. var vertxNext = undefined;
  66. var customSchedulerFn = undefined;
  67. var asap = function asap(callback, arg) {
  68. queue[len] = callback;
  69. queue[len + 1] = arg;
  70. len += 2;
  71. if (len === 2) {
  72. // If len is 2, that means that we need to schedule an async flush.
  73. // If additional callbacks are queued before the queue is flushed, they
  74. // will be processed by this flush that we are scheduling.
  75. if (customSchedulerFn) {
  76. customSchedulerFn(flush);
  77. } else {
  78. scheduleFlush();
  79. }
  80. }
  81. };
  82. function setScheduler(scheduleFn) {
  83. customSchedulerFn = scheduleFn;
  84. }
  85. function setAsap(asapFn) {
  86. asap = asapFn;
  87. }
  88. var browserWindow = typeof window !== 'undefined' ? window : undefined;
  89. var browserGlobal = browserWindow || {};
  90. var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
  91. var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
  92. // test for web worker but not in IE10
  93. var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
  94. // node
  95. function useNextTick() {
  96. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  97. // see https://github.com/cujojs/when/issues/410 for details
  98. return function () {
  99. return process.nextTick(flush);
  100. };
  101. }
  102. // vertx
  103. function useVertxTimer() {
  104. if (typeof vertxNext !== 'undefined') {
  105. return function () {
  106. vertxNext(flush);
  107. };
  108. }
  109. return useSetTimeout();
  110. }
  111. function useMutationObserver() {
  112. var iterations = 0;
  113. var observer = new BrowserMutationObserver(flush);
  114. var node = document.createTextNode('');
  115. observer.observe(node, { characterData: true });
  116. return function () {
  117. node.data = iterations = ++iterations % 2;
  118. };
  119. }
  120. // web worker
  121. function useMessageChannel() {
  122. var channel = new MessageChannel();
  123. channel.port1.onmessage = flush;
  124. return function () {
  125. return channel.port2.postMessage(0);
  126. };
  127. }
  128. function useSetTimeout() {
  129. // Store setTimeout reference so es6-promise will be unaffected by
  130. // other code modifying setTimeout (like sinon.useFakeTimers())
  131. var globalSetTimeout = setTimeout;
  132. return function () {
  133. return globalSetTimeout(flush, 1);
  134. };
  135. }
  136. var queue = new Array(1000);
  137. function flush() {
  138. for (var i = 0; i < len; i += 2) {
  139. var callback = queue[i];
  140. var arg = queue[i + 1];
  141. callback(arg);
  142. queue[i] = undefined;
  143. queue[i + 1] = undefined;
  144. }
  145. len = 0;
  146. }
  147. function attemptVertx() {
  148. try {
  149. var r = _dereq_;
  150. var vertx = r('vertx');
  151. vertxNext = vertx.runOnLoop || vertx.runOnContext;
  152. return useVertxTimer();
  153. } catch (e) {
  154. return useSetTimeout();
  155. }
  156. }
  157. var scheduleFlush = undefined;
  158. // Decide what async method to use to triggering processing of queued callbacks:
  159. if (isNode) {
  160. scheduleFlush = useNextTick();
  161. } else if (BrowserMutationObserver) {
  162. scheduleFlush = useMutationObserver();
  163. } else if (isWorker) {
  164. scheduleFlush = useMessageChannel();
  165. } else if (browserWindow === undefined && typeof _dereq_ === 'function') {
  166. scheduleFlush = attemptVertx();
  167. } else {
  168. scheduleFlush = useSetTimeout();
  169. }
  170. function then(onFulfillment, onRejection) {
  171. var _arguments = arguments;
  172. var parent = this;
  173. var child = new this.constructor(noop);
  174. if (child[PROMISE_ID] === undefined) {
  175. makePromise(child);
  176. }
  177. var _state = parent._state;
  178. if (_state) {
  179. (function () {
  180. var callback = _arguments[_state - 1];
  181. asap(function () {
  182. return invokeCallback(_state, child, callback, parent._result);
  183. });
  184. })();
  185. } else {
  186. subscribe(parent, child, onFulfillment, onRejection);
  187. }
  188. return child;
  189. }
  190. /**
  191. `Promise.resolve` returns a promise that will become resolved with the
  192. passed `value`. It is shorthand for the following:
  193. ```javascript
  194. let promise = new Promise(function(resolve, reject){
  195. resolve(1);
  196. });
  197. promise.then(function(value){
  198. // value === 1
  199. });
  200. ```
  201. Instead of writing the above, your code now simply becomes the following:
  202. ```javascript
  203. let promise = Promise.resolve(1);
  204. promise.then(function(value){
  205. // value === 1
  206. });
  207. ```
  208. @method resolve
  209. @static
  210. @param {Any} value value that the returned promise will be resolved with
  211. Useful for tooling.
  212. @return {Promise} a promise that will become fulfilled with the given
  213. `value`
  214. */
  215. function resolve(object) {
  216. /*jshint validthis:true */
  217. var Constructor = this;
  218. if (object && typeof object === 'object' && object.constructor === Constructor) {
  219. return object;
  220. }
  221. var promise = new Constructor(noop);
  222. _resolve(promise, object);
  223. return promise;
  224. }
  225. var PROMISE_ID = Math.random().toString(36).substring(16);
  226. function noop() {}
  227. var PENDING = void 0;
  228. var FULFILLED = 1;
  229. var REJECTED = 2;
  230. var GET_THEN_ERROR = new ErrorObject();
  231. function selfFulfillment() {
  232. return new TypeError("You cannot resolve a promise with itself");
  233. }
  234. function cannotReturnOwn() {
  235. return new TypeError('A promises callback cannot return that same promise.');
  236. }
  237. function getThen(promise) {
  238. try {
  239. return promise.then;
  240. } catch (error) {
  241. GET_THEN_ERROR.error = error;
  242. return GET_THEN_ERROR;
  243. }
  244. }
  245. function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  246. try {
  247. then.call(value, fulfillmentHandler, rejectionHandler);
  248. } catch (e) {
  249. return e;
  250. }
  251. }
  252. function handleForeignThenable(promise, thenable, then) {
  253. asap(function (promise) {
  254. var sealed = false;
  255. var error = tryThen(then, thenable, function (value) {
  256. if (sealed) {
  257. return;
  258. }
  259. sealed = true;
  260. if (thenable !== value) {
  261. _resolve(promise, value);
  262. } else {
  263. fulfill(promise, value);
  264. }
  265. }, function (reason) {
  266. if (sealed) {
  267. return;
  268. }
  269. sealed = true;
  270. _reject(promise, reason);
  271. }, 'Settle: ' + (promise._label || ' unknown promise'));
  272. if (!sealed && error) {
  273. sealed = true;
  274. _reject(promise, error);
  275. }
  276. }, promise);
  277. }
  278. function handleOwnThenable(promise, thenable) {
  279. if (thenable._state === FULFILLED) {
  280. fulfill(promise, thenable._result);
  281. } else if (thenable._state === REJECTED) {
  282. _reject(promise, thenable._result);
  283. } else {
  284. subscribe(thenable, undefined, function (value) {
  285. return _resolve(promise, value);
  286. }, function (reason) {
  287. return _reject(promise, reason);
  288. });
  289. }
  290. }
  291. function handleMaybeThenable(promise, maybeThenable, then$$) {
  292. if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {
  293. handleOwnThenable(promise, maybeThenable);
  294. } else {
  295. if (then$$ === GET_THEN_ERROR) {
  296. _reject(promise, GET_THEN_ERROR.error);
  297. GET_THEN_ERROR.error = null;
  298. } else if (then$$ === undefined) {
  299. fulfill(promise, maybeThenable);
  300. } else if (isFunction(then$$)) {
  301. handleForeignThenable(promise, maybeThenable, then$$);
  302. } else {
  303. fulfill(promise, maybeThenable);
  304. }
  305. }
  306. }
  307. function _resolve(promise, value) {
  308. if (promise === value) {
  309. _reject(promise, selfFulfillment());
  310. } else if (objectOrFunction(value)) {
  311. handleMaybeThenable(promise, value, getThen(value));
  312. } else {
  313. fulfill(promise, value);
  314. }
  315. }
  316. function publishRejection(promise) {
  317. if (promise._onerror) {
  318. promise._onerror(promise._result);
  319. }
  320. publish(promise);
  321. }
  322. function fulfill(promise, value) {
  323. if (promise._state !== PENDING) {
  324. return;
  325. }
  326. promise._result = value;
  327. promise._state = FULFILLED;
  328. if (promise._subscribers.length !== 0) {
  329. asap(publish, promise);
  330. }
  331. }
  332. function _reject(promise, reason) {
  333. if (promise._state !== PENDING) {
  334. return;
  335. }
  336. promise._state = REJECTED;
  337. promise._result = reason;
  338. asap(publishRejection, promise);
  339. }
  340. function subscribe(parent, child, onFulfillment, onRejection) {
  341. var _subscribers = parent._subscribers;
  342. var length = _subscribers.length;
  343. parent._onerror = null;
  344. _subscribers[length] = child;
  345. _subscribers[length + FULFILLED] = onFulfillment;
  346. _subscribers[length + REJECTED] = onRejection;
  347. if (length === 0 && parent._state) {
  348. asap(publish, parent);
  349. }
  350. }
  351. function publish(promise) {
  352. var subscribers = promise._subscribers;
  353. var settled = promise._state;
  354. if (subscribers.length === 0) {
  355. return;
  356. }
  357. var child = undefined,
  358. callback = undefined,
  359. detail = promise._result;
  360. for (var i = 0; i < subscribers.length; i += 3) {
  361. child = subscribers[i];
  362. callback = subscribers[i + settled];
  363. if (child) {
  364. invokeCallback(settled, child, callback, detail);
  365. } else {
  366. callback(detail);
  367. }
  368. }
  369. promise._subscribers.length = 0;
  370. }
  371. function ErrorObject() {
  372. this.error = null;
  373. }
  374. var TRY_CATCH_ERROR = new ErrorObject();
  375. function tryCatch(callback, detail) {
  376. try {
  377. return callback(detail);
  378. } catch (e) {
  379. TRY_CATCH_ERROR.error = e;
  380. return TRY_CATCH_ERROR;
  381. }
  382. }
  383. function invokeCallback(settled, promise, callback, detail) {
  384. var hasCallback = isFunction(callback),
  385. value = undefined,
  386. error = undefined,
  387. succeeded = undefined,
  388. failed = undefined;
  389. if (hasCallback) {
  390. value = tryCatch(callback, detail);
  391. if (value === TRY_CATCH_ERROR) {
  392. failed = true;
  393. error = value.error;
  394. value.error = null;
  395. } else {
  396. succeeded = true;
  397. }
  398. if (promise === value) {
  399. _reject(promise, cannotReturnOwn());
  400. return;
  401. }
  402. } else {
  403. value = detail;
  404. succeeded = true;
  405. }
  406. if (promise._state !== PENDING) {
  407. // noop
  408. } else if (hasCallback && succeeded) {
  409. _resolve(promise, value);
  410. } else if (failed) {
  411. _reject(promise, error);
  412. } else if (settled === FULFILLED) {
  413. fulfill(promise, value);
  414. } else if (settled === REJECTED) {
  415. _reject(promise, value);
  416. }
  417. }
  418. function initializePromise(promise, resolver) {
  419. try {
  420. resolver(function resolvePromise(value) {
  421. _resolve(promise, value);
  422. }, function rejectPromise(reason) {
  423. _reject(promise, reason);
  424. });
  425. } catch (e) {
  426. _reject(promise, e);
  427. }
  428. }
  429. var id = 0;
  430. function nextId() {
  431. return id++;
  432. }
  433. function makePromise(promise) {
  434. promise[PROMISE_ID] = id++;
  435. promise._state = undefined;
  436. promise._result = undefined;
  437. promise._subscribers = [];
  438. }
  439. function Enumerator(Constructor, input) {
  440. this._instanceConstructor = Constructor;
  441. this.promise = new Constructor(noop);
  442. if (!this.promise[PROMISE_ID]) {
  443. makePromise(this.promise);
  444. }
  445. if (isArray(input)) {
  446. this._input = input;
  447. this.length = input.length;
  448. this._remaining = input.length;
  449. this._result = new Array(this.length);
  450. if (this.length === 0) {
  451. fulfill(this.promise, this._result);
  452. } else {
  453. this.length = this.length || 0;
  454. this._enumerate();
  455. if (this._remaining === 0) {
  456. fulfill(this.promise, this._result);
  457. }
  458. }
  459. } else {
  460. _reject(this.promise, validationError());
  461. }
  462. }
  463. function validationError() {
  464. return new Error('Array Methods must be provided an Array');
  465. };
  466. Enumerator.prototype._enumerate = function () {
  467. var length = this.length;
  468. var _input = this._input;
  469. for (var i = 0; this._state === PENDING && i < length; i++) {
  470. this._eachEntry(_input[i], i);
  471. }
  472. };
  473. Enumerator.prototype._eachEntry = function (entry, i) {
  474. var c = this._instanceConstructor;
  475. var resolve$$ = c.resolve;
  476. if (resolve$$ === resolve) {
  477. var _then = getThen(entry);
  478. if (_then === then && entry._state !== PENDING) {
  479. this._settledAt(entry._state, i, entry._result);
  480. } else if (typeof _then !== 'function') {
  481. this._remaining--;
  482. this._result[i] = entry;
  483. } else if (c === Promise) {
  484. var promise = new c(noop);
  485. handleMaybeThenable(promise, entry, _then);
  486. this._willSettleAt(promise, i);
  487. } else {
  488. this._willSettleAt(new c(function (resolve$$) {
  489. return resolve$$(entry);
  490. }), i);
  491. }
  492. } else {
  493. this._willSettleAt(resolve$$(entry), i);
  494. }
  495. };
  496. Enumerator.prototype._settledAt = function (state, i, value) {
  497. var promise = this.promise;
  498. if (promise._state === PENDING) {
  499. this._remaining--;
  500. if (state === REJECTED) {
  501. _reject(promise, value);
  502. } else {
  503. this._result[i] = value;
  504. }
  505. }
  506. if (this._remaining === 0) {
  507. fulfill(promise, this._result);
  508. }
  509. };
  510. Enumerator.prototype._willSettleAt = function (promise, i) {
  511. var enumerator = this;
  512. subscribe(promise, undefined, function (value) {
  513. return enumerator._settledAt(FULFILLED, i, value);
  514. }, function (reason) {
  515. return enumerator._settledAt(REJECTED, i, reason);
  516. });
  517. };
  518. /**
  519. `Promise.all` accepts an array of promises, and returns a new promise which
  520. is fulfilled with an array of fulfillment values for the passed promises, or
  521. rejected with the reason of the first passed promise to be rejected. It casts all
  522. elements of the passed iterable to promises as it runs this algorithm.
  523. Example:
  524. ```javascript
  525. let promise1 = resolve(1);
  526. let promise2 = resolve(2);
  527. let promise3 = resolve(3);
  528. let promises = [ promise1, promise2, promise3 ];
  529. Promise.all(promises).then(function(array){
  530. // The array here would be [ 1, 2, 3 ];
  531. });
  532. ```
  533. If any of the `promises` given to `all` are rejected, the first promise
  534. that is rejected will be given as an argument to the returned promises's
  535. rejection handler. For example:
  536. Example:
  537. ```javascript
  538. let promise1 = resolve(1);
  539. let promise2 = reject(new Error("2"));
  540. let promise3 = reject(new Error("3"));
  541. let promises = [ promise1, promise2, promise3 ];
  542. Promise.all(promises).then(function(array){
  543. // Code here never runs because there are rejected promises!
  544. }, function(error) {
  545. // error.message === "2"
  546. });
  547. ```
  548. @method all
  549. @static
  550. @param {Array} entries array of promises
  551. @param {String} label optional string for labeling the promise.
  552. Useful for tooling.
  553. @return {Promise} promise that is fulfilled when all `promises` have been
  554. fulfilled, or rejected if any of them become rejected.
  555. @static
  556. */
  557. function all(entries) {
  558. return new Enumerator(this, entries).promise;
  559. }
  560. /**
  561. `Promise.race` returns a new promise which is settled in the same way as the
  562. first passed promise to settle.
  563. Example:
  564. ```javascript
  565. let promise1 = new Promise(function(resolve, reject){
  566. setTimeout(function(){
  567. resolve('promise 1');
  568. }, 200);
  569. });
  570. let promise2 = new Promise(function(resolve, reject){
  571. setTimeout(function(){
  572. resolve('promise 2');
  573. }, 100);
  574. });
  575. Promise.race([promise1, promise2]).then(function(result){
  576. // result === 'promise 2' because it was resolved before promise1
  577. // was resolved.
  578. });
  579. ```
  580. `Promise.race` is deterministic in that only the state of the first
  581. settled promise matters. For example, even if other promises given to the
  582. `promises` array argument are resolved, but the first settled promise has
  583. become rejected before the other promises became fulfilled, the returned
  584. promise will become rejected:
  585. ```javascript
  586. let promise1 = new Promise(function(resolve, reject){
  587. setTimeout(function(){
  588. resolve('promise 1');
  589. }, 200);
  590. });
  591. let promise2 = new Promise(function(resolve, reject){
  592. setTimeout(function(){
  593. reject(new Error('promise 2'));
  594. }, 100);
  595. });
  596. Promise.race([promise1, promise2]).then(function(result){
  597. // Code here never runs
  598. }, function(reason){
  599. // reason.message === 'promise 2' because promise 2 became rejected before
  600. // promise 1 became fulfilled
  601. });
  602. ```
  603. An example real-world use case is implementing timeouts:
  604. ```javascript
  605. Promise.race([ajax('foo.json'), timeout(5000)])
  606. ```
  607. @method race
  608. @static
  609. @param {Array} promises array of promises to observe
  610. Useful for tooling.
  611. @return {Promise} a promise which settles in the same way as the first passed
  612. promise to settle.
  613. */
  614. function race(entries) {
  615. /*jshint validthis:true */
  616. var Constructor = this;
  617. if (!isArray(entries)) {
  618. return new Constructor(function (_, reject) {
  619. return reject(new TypeError('You must pass an array to race.'));
  620. });
  621. } else {
  622. return new Constructor(function (resolve, reject) {
  623. var length = entries.length;
  624. for (var i = 0; i < length; i++) {
  625. Constructor.resolve(entries[i]).then(resolve, reject);
  626. }
  627. });
  628. }
  629. }
  630. /**
  631. `Promise.reject` returns a promise rejected with the passed `reason`.
  632. It is shorthand for the following:
  633. ```javascript
  634. let promise = new Promise(function(resolve, reject){
  635. reject(new Error('WHOOPS'));
  636. });
  637. promise.then(function(value){
  638. // Code here doesn't run because the promise is rejected!
  639. }, function(reason){
  640. // reason.message === 'WHOOPS'
  641. });
  642. ```
  643. Instead of writing the above, your code now simply becomes the following:
  644. ```javascript
  645. let promise = Promise.reject(new Error('WHOOPS'));
  646. promise.then(function(value){
  647. // Code here doesn't run because the promise is rejected!
  648. }, function(reason){
  649. // reason.message === 'WHOOPS'
  650. });
  651. ```
  652. @method reject
  653. @static
  654. @param {Any} reason value that the returned promise will be rejected with.
  655. Useful for tooling.
  656. @return {Promise} a promise rejected with the given `reason`.
  657. */
  658. function reject(reason) {
  659. /*jshint validthis:true */
  660. var Constructor = this;
  661. var promise = new Constructor(noop);
  662. _reject(promise, reason);
  663. return promise;
  664. }
  665. function needsResolver() {
  666. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  667. }
  668. function needsNew() {
  669. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  670. }
  671. /**
  672. Promise objects represent the eventual result of an asynchronous operation. The
  673. primary way of interacting with a promise is through its `then` method, which
  674. registers callbacks to receive either a promise's eventual value or the reason
  675. why the promise cannot be fulfilled.
  676. Terminology
  677. -----------
  678. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  679. - `thenable` is an object or function that defines a `then` method.
  680. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  681. - `exception` is a value that is thrown using the throw statement.
  682. - `reason` is a value that indicates why a promise was rejected.
  683. - `settled` the final resting state of a promise, fulfilled or rejected.
  684. A promise can be in one of three states: pending, fulfilled, or rejected.
  685. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  686. state. Promises that are rejected have a rejection reason and are in the
  687. rejected state. A fulfillment value is never a thenable.
  688. Promises can also be said to *resolve* a value. If this value is also a
  689. promise, then the original promise's settled state will match the value's
  690. settled state. So a promise that *resolves* a promise that rejects will
  691. itself reject, and a promise that *resolves* a promise that fulfills will
  692. itself fulfill.
  693. Basic Usage:
  694. ------------
  695. ```js
  696. let promise = new Promise(function(resolve, reject) {
  697. // on success
  698. resolve(value);
  699. // on failure
  700. reject(reason);
  701. });
  702. promise.then(function(value) {
  703. // on fulfillment
  704. }, function(reason) {
  705. // on rejection
  706. });
  707. ```
  708. Advanced Usage:
  709. ---------------
  710. Promises shine when abstracting away asynchronous interactions such as
  711. `XMLHttpRequest`s.
  712. ```js
  713. function getJSON(url) {
  714. return new Promise(function(resolve, reject){
  715. let xhr = new XMLHttpRequest();
  716. xhr.open('GET', url);
  717. xhr.onreadystatechange = handler;
  718. xhr.responseType = 'json';
  719. xhr.setRequestHeader('Accept', 'application/json');
  720. xhr.send();
  721. function handler() {
  722. if (this.readyState === this.DONE) {
  723. if (this.status === 200) {
  724. resolve(this.response);
  725. } else {
  726. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  727. }
  728. }
  729. };
  730. });
  731. }
  732. getJSON('/posts.json').then(function(json) {
  733. // on fulfillment
  734. }, function(reason) {
  735. // on rejection
  736. });
  737. ```
  738. Unlike callbacks, promises are great composable primitives.
  739. ```js
  740. Promise.all([
  741. getJSON('/posts'),
  742. getJSON('/comments')
  743. ]).then(function(values){
  744. values[0] // => postsJSON
  745. values[1] // => commentsJSON
  746. return values;
  747. });
  748. ```
  749. @class Promise
  750. @param {function} resolver
  751. Useful for tooling.
  752. @constructor
  753. */
  754. function Promise(resolver) {
  755. this[PROMISE_ID] = nextId();
  756. this._result = this._state = undefined;
  757. this._subscribers = [];
  758. if (noop !== resolver) {
  759. typeof resolver !== 'function' && needsResolver();
  760. this instanceof Promise ? initializePromise(this, resolver) : needsNew();
  761. }
  762. }
  763. Promise.all = all;
  764. Promise.race = race;
  765. Promise.resolve = resolve;
  766. Promise.reject = reject;
  767. Promise._setScheduler = setScheduler;
  768. Promise._setAsap = setAsap;
  769. Promise._asap = asap;
  770. Promise.prototype = {
  771. constructor: Promise,
  772. /**
  773. The primary way of interacting with a promise is through its `then` method,
  774. which registers callbacks to receive either a promise's eventual value or the
  775. reason why the promise cannot be fulfilled.
  776. ```js
  777. findUser().then(function(user){
  778. // user is available
  779. }, function(reason){
  780. // user is unavailable, and you are given the reason why
  781. });
  782. ```
  783. Chaining
  784. --------
  785. The return value of `then` is itself a promise. This second, 'downstream'
  786. promise is resolved with the return value of the first promise's fulfillment
  787. or rejection handler, or rejected if the handler throws an exception.
  788. ```js
  789. findUser().then(function (user) {
  790. return user.name;
  791. }, function (reason) {
  792. return 'default name';
  793. }).then(function (userName) {
  794. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  795. // will be `'default name'`
  796. });
  797. findUser().then(function (user) {
  798. throw new Error('Found user, but still unhappy');
  799. }, function (reason) {
  800. throw new Error('`findUser` rejected and we're unhappy');
  801. }).then(function (value) {
  802. // never reached
  803. }, function (reason) {
  804. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  805. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  806. });
  807. ```
  808. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  809. ```js
  810. findUser().then(function (user) {
  811. throw new PedagogicalException('Upstream error');
  812. }).then(function (value) {
  813. // never reached
  814. }).then(function (value) {
  815. // never reached
  816. }, function (reason) {
  817. // The `PedgagocialException` is propagated all the way down to here
  818. });
  819. ```
  820. Assimilation
  821. ------------
  822. Sometimes the value you want to propagate to a downstream promise can only be
  823. retrieved asynchronously. This can be achieved by returning a promise in the
  824. fulfillment or rejection handler. The downstream promise will then be pending
  825. until the returned promise is settled. This is called *assimilation*.
  826. ```js
  827. findUser().then(function (user) {
  828. return findCommentsByAuthor(user);
  829. }).then(function (comments) {
  830. // The user's comments are now available
  831. });
  832. ```
  833. If the assimliated promise rejects, then the downstream promise will also reject.
  834. ```js
  835. findUser().then(function (user) {
  836. return findCommentsByAuthor(user);
  837. }).then(function (comments) {
  838. // If `findCommentsByAuthor` fulfills, we'll have the value here
  839. }, function (reason) {
  840. // If `findCommentsByAuthor` rejects, we'll have the reason here
  841. });
  842. ```
  843. Simple Example
  844. --------------
  845. Synchronous Example
  846. ```javascript
  847. let result;
  848. try {
  849. result = findResult();
  850. // success
  851. } catch(reason) {
  852. // failure
  853. }
  854. ```
  855. Errback Example
  856. ```js
  857. findResult(function(result, err){
  858. if (err) {
  859. // failure
  860. } else {
  861. // success
  862. }
  863. });
  864. ```
  865. Promise Example;
  866. ```javascript
  867. findResult().then(function(result){
  868. // success
  869. }, function(reason){
  870. // failure
  871. });
  872. ```
  873. Advanced Example
  874. --------------
  875. Synchronous Example
  876. ```javascript
  877. let author, books;
  878. try {
  879. author = findAuthor();
  880. books = findBooksByAuthor(author);
  881. // success
  882. } catch(reason) {
  883. // failure
  884. }
  885. ```
  886. Errback Example
  887. ```js
  888. function foundBooks(books) {
  889. }
  890. function failure(reason) {
  891. }
  892. findAuthor(function(author, err){
  893. if (err) {
  894. failure(err);
  895. // failure
  896. } else {
  897. try {
  898. findBoooksByAuthor(author, function(books, err) {
  899. if (err) {
  900. failure(err);
  901. } else {
  902. try {
  903. foundBooks(books);
  904. } catch(reason) {
  905. failure(reason);
  906. }
  907. }
  908. });
  909. } catch(error) {
  910. failure(err);
  911. }
  912. // success
  913. }
  914. });
  915. ```
  916. Promise Example;
  917. ```javascript
  918. findAuthor().
  919. then(findBooksByAuthor).
  920. then(function(books){
  921. // found books
  922. }).catch(function(reason){
  923. // something went wrong
  924. });
  925. ```
  926. @method then
  927. @param {Function} onFulfilled
  928. @param {Function} onRejected
  929. Useful for tooling.
  930. @return {Promise}
  931. */
  932. then: then,
  933. /**
  934. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  935. as the catch block of a try/catch statement.
  936. ```js
  937. function findAuthor(){
  938. throw new Error('couldn't find that author');
  939. }
  940. // synchronous
  941. try {
  942. findAuthor();
  943. } catch(reason) {
  944. // something went wrong
  945. }
  946. // async with promises
  947. findAuthor().catch(function(reason){
  948. // something went wrong
  949. });
  950. ```
  951. @method catch
  952. @param {Function} onRejection
  953. Useful for tooling.
  954. @return {Promise}
  955. */
  956. 'catch': function _catch(onRejection) {
  957. return this.then(null, onRejection);
  958. }
  959. };
  960. function polyfill() {
  961. var local = undefined;
  962. if (typeof global !== 'undefined') {
  963. local = global;
  964. } else if (typeof self !== 'undefined') {
  965. local = self;
  966. } else {
  967. try {
  968. local = Function('return this')();
  969. } catch (e) {
  970. throw new Error('polyfill failed because global object is unavailable in this environment');
  971. }
  972. }
  973. var P = local.Promise;
  974. if (P) {
  975. var promiseToString = null;
  976. try {
  977. promiseToString = Object.prototype.toString.call(P.resolve());
  978. } catch (e) {
  979. // silently ignored
  980. }
  981. if (promiseToString === '[object Promise]' && !P.cast) {
  982. return;
  983. }
  984. }
  985. local.Promise = Promise;
  986. }
  987. // Strange compat..
  988. Promise.polyfill = polyfill;
  989. Promise.Promise = Promise;
  990. return Promise;
  991. })));
  992. }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  993. },{"_process":3}],2:[function(_dereq_,module,exports){
  994. // Copyright Joyent, Inc. and other Node contributors.
  995. //
  996. // Permission is hereby granted, free of charge, to any person obtaining a
  997. // copy of this software and associated documentation files (the
  998. // "Software"), to deal in the Software without restriction, including
  999. // without limitation the rights to use, copy, modify, merge, publish,
  1000. // distribute, sublicense, and/or sell copies of the Software, and to permit
  1001. // persons to whom the Software is furnished to do so, subject to the
  1002. // following conditions:
  1003. //
  1004. // The above copyright notice and this permission notice shall be included
  1005. // in all copies or substantial portions of the Software.
  1006. //
  1007. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  1008. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  1009. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  1010. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  1011. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  1012. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  1013. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  1014. function EventEmitter() {
  1015. this._events = this._events || {};
  1016. this._maxListeners = this._maxListeners || undefined;
  1017. }
  1018. module.exports = EventEmitter;
  1019. // Backwards-compat with node 0.10.x
  1020. EventEmitter.EventEmitter = EventEmitter;
  1021. EventEmitter.prototype._events = undefined;
  1022. EventEmitter.prototype._maxListeners = undefined;
  1023. // By default EventEmitters will print a warning if more than 10 listeners are
  1024. // added to it. This is a useful default which helps finding memory leaks.
  1025. EventEmitter.defaultMaxListeners = 10;
  1026. // Obviously not all Emitters should be limited to 10. This function allows
  1027. // that to be increased. Set to zero for unlimited.
  1028. EventEmitter.prototype.setMaxListeners = function(n) {
  1029. if (!isNumber(n) || n < 0 || isNaN(n))
  1030. throw TypeError('n must be a positive number');
  1031. this._maxListeners = n;
  1032. return this;
  1033. };
  1034. EventEmitter.prototype.emit = function(type) {
  1035. var er, handler, len, args, i, listeners;
  1036. if (!this._events)
  1037. this._events = {};
  1038. // If there is no 'error' event listener then throw.
  1039. if (type === 'error') {
  1040. if (!this._events.error ||
  1041. (isObject(this._events.error) && !this._events.error.length)) {
  1042. er = arguments[1];
  1043. if (er instanceof Error) {
  1044. throw er; // Unhandled 'error' event
  1045. } else {
  1046. // At least give some kind of context to the user
  1047. var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
  1048. err.context = er;
  1049. throw err;
  1050. }
  1051. }
  1052. }
  1053. handler = this._events[type];
  1054. if (isUndefined(handler))
  1055. return false;
  1056. if (isFunction(handler)) {
  1057. switch (arguments.length) {
  1058. // fast cases
  1059. case 1:
  1060. handler.call(this);
  1061. break;
  1062. case 2:
  1063. handler.call(this, arguments[1]);
  1064. break;
  1065. case 3:
  1066. handler.call(this, arguments[1], arguments[2]);
  1067. break;
  1068. // slower
  1069. default:
  1070. args = Array.prototype.slice.call(arguments, 1);
  1071. handler.apply(this, args);
  1072. }
  1073. } else if (isObject(handler)) {
  1074. args = Array.prototype.slice.call(arguments, 1);
  1075. listeners = handler.slice();
  1076. len = listeners.length;
  1077. for (i = 0; i < len; i++)
  1078. listeners[i].apply(this, args);
  1079. }
  1080. return true;
  1081. };
  1082. EventEmitter.prototype.addListener = function(type, listener) {
  1083. var m;
  1084. if (!isFunction(listener))
  1085. throw TypeError('listener must be a function');
  1086. if (!this._events)
  1087. this._events = {};
  1088. // To avoid recursion in the case that type === "newListener"! Before
  1089. // adding it to the listeners, first emit "newListener".
  1090. if (this._events.newListener)
  1091. this.emit('newListener', type,
  1092. isFunction(listener.listener) ?
  1093. listener.listener : listener);
  1094. if (!this._events[type])
  1095. // Optimize the case of one listener. Don't need the extra array object.
  1096. this._events[type] = listener;
  1097. else if (isObject(this._events[type]))
  1098. // If we've already got an array, just append.
  1099. this._events[type].push(listener);
  1100. else
  1101. // Adding the second element, need to change to array.
  1102. this._events[type] = [this._events[type], listener];
  1103. // Check for listener leak
  1104. if (isObject(this._events[type]) && !this._events[type].warned) {
  1105. if (!isUndefined(this._maxListeners)) {
  1106. m = this._maxListeners;
  1107. } else {
  1108. m = EventEmitter.defaultMaxListeners;
  1109. }
  1110. if (m && m > 0 && this._events[type].length > m) {
  1111. this._events[type].warned = true;
  1112. console.error('(node) warning: possible EventEmitter memory ' +
  1113. 'leak detected. %d listeners added. ' +
  1114. 'Use emitter.setMaxListeners() to increase limit.',
  1115. this._events[type].length);
  1116. if (typeof console.trace === 'function') {
  1117. // not supported in IE 10
  1118. console.trace();
  1119. }
  1120. }
  1121. }
  1122. return this;
  1123. };
  1124. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  1125. EventEmitter.prototype.once = function(type, listener) {
  1126. if (!isFunction(listener))
  1127. throw TypeError('listener must be a function');
  1128. var fired = false;
  1129. function g() {
  1130. this.removeListener(type, g);
  1131. if (!fired) {
  1132. fired = true;
  1133. listener.apply(this, arguments);
  1134. }
  1135. }
  1136. g.listener = listener;
  1137. this.on(type, g);
  1138. return this;
  1139. };
  1140. // emits a 'removeListener' event iff the listener was removed
  1141. EventEmitter.prototype.removeListener = function(type, listener) {
  1142. var list, position, length, i;
  1143. if (!isFunction(listener))
  1144. throw TypeError('listener must be a function');
  1145. if (!this._events || !this._events[type])
  1146. return this;
  1147. list = this._events[type];
  1148. length = list.length;
  1149. position = -1;
  1150. if (list === listener ||
  1151. (isFunction(list.listener) && list.listener === listener)) {
  1152. delete this._events[type];
  1153. if (this._events.removeListener)
  1154. this.emit('removeListener', type, listener);
  1155. } else if (isObject(list)) {
  1156. for (i = length; i-- > 0;) {
  1157. if (list[i] === listener ||
  1158. (list[i].listener && list[i].listener === listener)) {
  1159. position = i;
  1160. break;
  1161. }
  1162. }
  1163. if (position < 0)
  1164. return this;
  1165. if (list.length === 1) {
  1166. list.length = 0;
  1167. delete this._events[type];
  1168. } else {
  1169. list.splice(position, 1);
  1170. }
  1171. if (this._events.removeListener)
  1172. this.emit('removeListener', type, listener);
  1173. }
  1174. return this;
  1175. };
  1176. EventEmitter.prototype.removeAllListeners = function(type) {
  1177. var key, listeners;
  1178. if (!this._events)
  1179. return this;
  1180. // not listening for removeListener, no need to emit
  1181. if (!this._events.removeListener) {
  1182. if (arguments.length === 0)
  1183. this._events = {};
  1184. else if (this._events[type])
  1185. delete this._events[type];
  1186. return this;
  1187. }
  1188. // emit removeListener for all listeners on all events
  1189. if (arguments.length === 0) {
  1190. for (key in this._events) {
  1191. if (key === 'removeListener') continue;
  1192. this.removeAllListeners(key);
  1193. }
  1194. this.removeAllListeners('removeListener');
  1195. this._events = {};
  1196. return this;
  1197. }
  1198. listeners = this._events[type];
  1199. if (isFunction(listeners)) {
  1200. this.removeListener(type, listeners);
  1201. } else if (listeners) {
  1202. // LIFO order
  1203. while (listeners.length)
  1204. this.removeListener(type, listeners[listeners.length - 1]);
  1205. }
  1206. delete this._events[type];
  1207. return this;
  1208. };
  1209. EventEmitter.prototype.listeners = function(type) {
  1210. var ret;
  1211. if (!this._events || !this._events[type])
  1212. ret = [];
  1213. else if (isFunction(this._events[type]))
  1214. ret = [this._events[type]];
  1215. else
  1216. ret = this._events[type].slice();
  1217. return ret;
  1218. };
  1219. EventEmitter.prototype.listenerCount = function(type) {
  1220. if (this._events) {
  1221. var evlistener = this._events[type];
  1222. if (isFunction(evlistener))
  1223. return 1;
  1224. else if (evlistener)
  1225. return evlistener.length;
  1226. }
  1227. return 0;
  1228. };
  1229. EventEmitter.listenerCount = function(emitter, type) {
  1230. return emitter.listenerCount(type);
  1231. };
  1232. function isFunction(arg) {
  1233. return typeof arg === 'function';
  1234. }
  1235. function isNumber(arg) {
  1236. return typeof arg === 'number';
  1237. }
  1238. function isObject(arg) {
  1239. return typeof arg === 'object' && arg !== null;
  1240. }
  1241. function isUndefined(arg) {
  1242. return arg === void 0;
  1243. }
  1244. },{}],3:[function(_dereq_,module,exports){
  1245. // shim for using process in browser
  1246. var process = module.exports = {};
  1247. // cached from whatever global is present so that test runners that stub it
  1248. // don't break things. But we need to wrap it in a try catch in case it is
  1249. // wrapped in strict mode code which doesn't define any globals. It's inside a
  1250. // function because try/catches deoptimize in certain engines.
  1251. var cachedSetTimeout;
  1252. var cachedClearTimeout;
  1253. function defaultSetTimout() {
  1254. throw new Error('setTimeout has not been defined');
  1255. }
  1256. function defaultClearTimeout () {
  1257. throw new Error('clearTimeout has not been defined');
  1258. }
  1259. (function () {
  1260. try {
  1261. if (typeof setTimeout === 'function') {
  1262. cachedSetTimeout = setTimeout;
  1263. } else {
  1264. cachedSetTimeout = defaultSetTimout;
  1265. }
  1266. } catch (e) {
  1267. cachedSetTimeout = defaultSetTimout;
  1268. }
  1269. try {
  1270. if (typeof clearTimeout === 'function') {
  1271. cachedClearTimeout = clearTimeout;
  1272. } else {
  1273. cachedClearTimeout = defaultClearTimeout;
  1274. }
  1275. } catch (e) {
  1276. cachedClearTimeout = defaultClearTimeout;
  1277. }
  1278. } ())
  1279. function runTimeout(fun) {
  1280. if (cachedSetTimeout === setTimeout) {
  1281. //normal enviroments in sane situations
  1282. return setTimeout(fun, 0);
  1283. }
  1284. // if setTimeout wasn't available but was latter defined
  1285. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  1286. cachedSetTimeout = setTimeout;
  1287. return setTimeout(fun, 0);
  1288. }
  1289. try {
  1290. // when when somebody has screwed with setTimeout but no I.E. maddness
  1291. return cachedSetTimeout(fun, 0);
  1292. } catch(e){
  1293. try {
  1294. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  1295. return cachedSetTimeout.call(null, fun, 0);
  1296. } catch(e){
  1297. // 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
  1298. return cachedSetTimeout.call(this, fun, 0);
  1299. }
  1300. }
  1301. }
  1302. function runClearTimeout(marker) {
  1303. if (cachedClearTimeout === clearTimeout) {
  1304. //normal enviroments in sane situations
  1305. return clearTimeout(marker);
  1306. }
  1307. // if clearTimeout wasn't available but was latter defined
  1308. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  1309. cachedClearTimeout = clearTimeout;
  1310. return clearTimeout(marker);
  1311. }
  1312. try {
  1313. // when when somebody has screwed with setTimeout but no I.E. maddness
  1314. return cachedClearTimeout(marker);
  1315. } catch (e){
  1316. try {
  1317. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  1318. return cachedClearTimeout.call(null, marker);
  1319. } catch (e){
  1320. // 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.
  1321. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  1322. return cachedClearTimeout.call(this, marker);
  1323. }
  1324. }
  1325. }
  1326. var queue = [];
  1327. var draining = false;
  1328. var currentQueue;
  1329. var queueIndex = -1;
  1330. function cleanUpNextTick() {
  1331. if (!draining || !currentQueue) {
  1332. return;
  1333. }
  1334. draining = false;
  1335. if (currentQueue.length) {
  1336. queue = currentQueue.concat(queue);
  1337. } else {
  1338. queueIndex = -1;
  1339. }
  1340. if (queue.length) {
  1341. drainQueue();
  1342. }
  1343. }
  1344. function drainQueue() {
  1345. if (draining) {
  1346. return;
  1347. }
  1348. var timeout = runTimeout(cleanUpNextTick);
  1349. draining = true;
  1350. var len = queue.length;
  1351. while(len) {
  1352. currentQueue = queue;
  1353. queue = [];
  1354. while (++queueIndex < len) {
  1355. if (currentQueue) {
  1356. currentQueue[queueIndex].run();
  1357. }
  1358. }
  1359. queueIndex = -1;
  1360. len = queue.length;
  1361. }
  1362. currentQueue = null;
  1363. draining = false;
  1364. runClearTimeout(timeout);
  1365. }
  1366. process.nextTick = function (fun) {
  1367. var args = new Array(arguments.length - 1);
  1368. if (arguments.length > 1) {
  1369. for (var i = 1; i < arguments.length; i++) {
  1370. args[i - 1] = arguments[i];
  1371. }
  1372. }
  1373. queue.push(new Item(fun, args));
  1374. if (queue.length === 1 && !draining) {
  1375. runTimeout(drainQueue);
  1376. }
  1377. };
  1378. // v8 likes predictible objects
  1379. function Item(fun, array) {
  1380. this.fun = fun;
  1381. this.array = array;
  1382. }
  1383. Item.prototype.run = function () {
  1384. this.fun.apply(null, this.array);
  1385. };
  1386. process.title = 'browser';
  1387. process.browser = true;
  1388. process.env = {};
  1389. process.argv = [];
  1390. process.version = ''; // empty string to avoid regexp issues
  1391. process.versions = {};
  1392. function noop() {}
  1393. process.on = noop;
  1394. process.addListener = noop;
  1395. process.once = noop;
  1396. process.off = noop;
  1397. process.removeListener = noop;
  1398. process.removeAllListeners = noop;
  1399. process.emit = noop;
  1400. process.prependListener = noop;
  1401. process.prependOnceListener = noop;
  1402. process.listeners = function (name) { return [] }
  1403. process.binding = function (name) {
  1404. throw new Error('process.binding is not supported');
  1405. };
  1406. process.cwd = function () { return '/' };
  1407. process.chdir = function (dir) {
  1408. throw new Error('process.chdir is not supported');
  1409. };
  1410. process.umask = function() { return 0; };
  1411. },{}],4:[function(_dereq_,module,exports){
  1412. var bundleFn = arguments[3];
  1413. var sources = arguments[4];
  1414. var cache = arguments[5];
  1415. var stringify = JSON.stringify;
  1416. module.exports = function (fn, options) {
  1417. var wkey;
  1418. var cacheKeys = Object.keys(cache);
  1419. for (var i = 0, l = cacheKeys.length; i < l; i++) {
  1420. var key = cacheKeys[i];
  1421. var exp = cache[key].exports;
  1422. // Using babel as a transpiler to use esmodule, the export will always
  1423. // be an object with the default export as a property of it. To ensure
  1424. // the existing api and babel esmodule exports are both supported we
  1425. // check for both
  1426. if (exp === fn || exp && exp.default === fn) {
  1427. wkey = key;
  1428. break;
  1429. }
  1430. }
  1431. if (!wkey) {
  1432. wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
  1433. var wcache = {};
  1434. for (var i = 0, l = cacheKeys.length; i < l; i++) {
  1435. var key = cacheKeys[i];
  1436. wcache[key] = key;
  1437. }
  1438. sources[wkey] = [
  1439. Function(['require','module','exports'], '(' + fn + ')(self)'),
  1440. wcache
  1441. ];
  1442. }
  1443. var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
  1444. var scache = {}; scache[wkey] = wkey;
  1445. sources[skey] = [
  1446. Function(['require'], (
  1447. // try to call default if defined to also support babel esmodule
  1448. // exports
  1449. 'var f = require(' + stringify(wkey) + ');' +
  1450. '(f.default ? f.default : f)(self);'
  1451. )),
  1452. scache
  1453. ];
  1454. var workerSources = {};
  1455. resolveSources(skey);
  1456. function resolveSources(key) {
  1457. workerSources[key] = true;
  1458. for (var depPath in sources[key][1]) {
  1459. var depKey = sources[key][1][depPath];
  1460. if (!workerSources[depKey]) {
  1461. resolveSources(depKey);
  1462. }
  1463. }
  1464. }
  1465. var src = '(' + bundleFn + ')({'
  1466. + Object.keys(workerSources).map(function (key) {
  1467. return stringify(key) + ':['
  1468. + sources[key][0]
  1469. + ',' + stringify(sources[key][1]) + ']'
  1470. ;
  1471. }).join(',')
  1472. + '},{},[' + stringify(skey) + '])'
  1473. ;
  1474. var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  1475. var blob = new Blob([src], { type: 'text/javascript' });
  1476. if (options && options.bare) { return blob; }
  1477. var workerUrl = URL.createObjectURL(blob);
  1478. var worker = new Worker(workerUrl);
  1479. worker.objectURL = workerUrl;
  1480. return worker;
  1481. };
  1482. },{}],5:[function(_dereq_,module,exports){
  1483. 'use strict';
  1484. Object.defineProperty(exports, "__esModule", {
  1485. value: true
  1486. });
  1487. exports.createDefaultConfig = createDefaultConfig;
  1488. /*
  1489. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  1490. *
  1491. * @author zheng qian <xqq@xqq.im>
  1492. *
  1493. * Licensed under the Apache License, Version 2.0 (the "License");
  1494. * you may not use this file except in compliance with the License.
  1495. * You may obtain a copy of the License at
  1496. *
  1497. * http://www.apache.org/licenses/LICENSE-2.0
  1498. *
  1499. * Unless required by applicable law or agreed to in writing, software
  1500. * distributed under the License is distributed on an "AS IS" BASIS,
  1501. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1502. * See the License for the specific language governing permissions and
  1503. * limitations under the License.
  1504. */
  1505. var defaultConfig = exports.defaultConfig = {
  1506. enableWorker: false,
  1507. enableStashBuffer: true,
  1508. stashInitialSize: undefined,
  1509. isLive: false,
  1510. lazyLoad: true,
  1511. lazyLoadMaxDuration: 3 * 60,
  1512. lazyLoadRecoverDuration: 30,
  1513. deferLoadAfterSourceOpen: true,
  1514. // autoCleanupSourceBuffer: default as false, leave unspecified
  1515. autoCleanupMaxBackwardDuration: 3 * 60,
  1516. autoCleanupMinBackwardDuration: 2 * 60,
  1517. statisticsInfoReportInterval: 600,
  1518. fixAudioTimestampGap: true,
  1519. accurateSeek: false,
  1520. seekType: 'range', // [range, param, custom]
  1521. seekParamStart: 'bstart',
  1522. seekParamEnd: 'bend',
  1523. rangeLoadZeroStart: false,
  1524. customSeekHandler: undefined,
  1525. reuseRedirectedURL: false
  1526. // referrerPolicy: leave as unspecified
  1527. };
  1528. function createDefaultConfig() {
  1529. return Object.assign({}, defaultConfig);
  1530. }
  1531. },{}],6:[function(_dereq_,module,exports){
  1532. 'use strict';
  1533. Object.defineProperty(exports, "__esModule", {
  1534. value: true
  1535. });
  1536. 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; }; }(); /*
  1537. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  1538. *
  1539. * @author zheng qian <xqq@xqq.im>
  1540. *
  1541. * Licensed under the Apache License, Version 2.0 (the "License");
  1542. * you may not use this file except in compliance with the License.
  1543. * You may obtain a copy of the License at
  1544. *
  1545. * http://www.apache.org/licenses/LICENSE-2.0
  1546. *
  1547. * Unless required by applicable law or agreed to in writing, software
  1548. * distributed under the License is distributed on an "AS IS" BASIS,
  1549. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1550. * See the License for the specific language governing permissions and
  1551. * limitations under the License.
  1552. */
  1553. var _ioController = _dereq_('../io/io-controller.js');
  1554. var _ioController2 = _interopRequireDefault(_ioController);
  1555. var _config = _dereq_('../config.js');
  1556. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1557. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1558. var Features = function () {
  1559. function Features() {
  1560. _classCallCheck(this, Features);
  1561. }
  1562. _createClass(Features, null, [{
  1563. key: 'supportMSEH264Playback',
  1564. value: function supportMSEH264Playback() {
  1565. return window.MediaSource && window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
  1566. }
  1567. }, {
  1568. key: 'supportNetworkStreamIO',
  1569. value: function supportNetworkStreamIO() {
  1570. var ioctl = new _ioController2.default({}, (0, _config.createDefaultConfig)());
  1571. var loaderType = ioctl.loaderType;
  1572. ioctl.destroy();
  1573. return loaderType == 'fetch-stream-loader' || loaderType == 'xhr-moz-chunked-loader';
  1574. }
  1575. }, {
  1576. key: 'getNetworkLoaderTypeName',
  1577. value: function getNetworkLoaderTypeName() {
  1578. var ioctl = new _ioController2.default({}, (0, _config.createDefaultConfig)());
  1579. var loaderType = ioctl.loaderType;
  1580. ioctl.destroy();
  1581. return loaderType;
  1582. }
  1583. }, {
  1584. key: 'supportNativeMediaPlayback',
  1585. value: function supportNativeMediaPlayback(mimeType) {
  1586. if (Features.videoElement == undefined) {
  1587. Features.videoElement = window.document.createElement('video');
  1588. }
  1589. var canPlay = Features.videoElement.canPlayType(mimeType);
  1590. return canPlay === 'probably' || canPlay == 'maybe';
  1591. }
  1592. }, {
  1593. key: 'getFeatureList',
  1594. value: function getFeatureList() {
  1595. var features = {
  1596. mseFlvPlayback: false,
  1597. mseLiveFlvPlayback: false,
  1598. networkStreamIO: false,
  1599. networkLoaderName: '',
  1600. nativeMP4H264Playback: false,
  1601. nativeWebmVP8Playback: false,
  1602. nativeWebmVP9Playback: false
  1603. };
  1604. features.mseFlvPlayback = Features.supportMSEH264Playback();
  1605. features.networkStreamIO = Features.supportNetworkStreamIO();
  1606. features.networkLoaderName = Features.getNetworkLoaderTypeName();
  1607. features.mseLiveFlvPlayback = features.mseFlvPlayback && features.networkStreamIO;
  1608. features.nativeMP4H264Playback = Features.supportNativeMediaPlayback('video/mp4; codecs="avc1.42001E, mp4a.40.2"');
  1609. features.nativeWebmVP8Playback = Features.supportNativeMediaPlayback('video/webm; codecs="vp8.0, vorbis"');
  1610. features.nativeWebmVP9Playback = Features.supportNativeMediaPlayback('video/webm; codecs="vp9"');
  1611. return features;
  1612. }
  1613. }]);
  1614. return Features;
  1615. }();
  1616. exports.default = Features;
  1617. },{"../config.js":5,"../io/io-controller.js":23}],7:[function(_dereq_,module,exports){
  1618. "use strict";
  1619. Object.defineProperty(exports, "__esModule", {
  1620. value: true
  1621. });
  1622. 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; }; }();
  1623. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1624. /*
  1625. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  1626. *
  1627. * @author zheng qian <xqq@xqq.im>
  1628. *
  1629. * Licensed under the Apache License, Version 2.0 (the "License");
  1630. * you may not use this file except in compliance with the License.
  1631. * You may obtain a copy of the License at
  1632. *
  1633. * http://www.apache.org/licenses/LICENSE-2.0
  1634. *
  1635. * Unless required by applicable law or agreed to in writing, software
  1636. * distributed under the License is distributed on an "AS IS" BASIS,
  1637. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1638. * See the License for the specific language governing permissions and
  1639. * limitations under the License.
  1640. */
  1641. var MediaInfo = function () {
  1642. function MediaInfo() {
  1643. _classCallCheck(this, MediaInfo);
  1644. this.mimeType = null;
  1645. this.duration = null;
  1646. this.hasAudio = null;
  1647. this.hasVideo = null;
  1648. this.audioCodec = null;
  1649. this.videoCodec = null;
  1650. this.audioDataRate = null;
  1651. this.videoDataRate = null;
  1652. this.audioSampleRate = null;
  1653. this.audioChannelCount = null;
  1654. this.width = null;
  1655. this.height = null;
  1656. this.fps = null;
  1657. this.profile = null;
  1658. this.level = null;
  1659. this.refFrames = null;
  1660. this.chromaFormat = null;
  1661. this.sarNum = null;
  1662. this.sarDen = null;
  1663. this.metadata = null;
  1664. this.segments = null; // MediaInfo[]
  1665. this.segmentCount = null;
  1666. this.hasKeyframesIndex = null;
  1667. this.keyframesIndex = null;
  1668. }
  1669. _createClass(MediaInfo, [{
  1670. key: "isComplete",
  1671. value: function isComplete() {
  1672. var audioInfoComplete = this.hasAudio === false || this.hasAudio === true && this.audioCodec != null && this.audioSampleRate != null && this.audioChannelCount != null;
  1673. 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;
  1674. // keyframesIndex may not be present
  1675. return this.mimeType != null && this.duration != null && this.metadata != null && this.hasKeyframesIndex != null && audioInfoComplete && videoInfoComplete;
  1676. }
  1677. }, {
  1678. key: "isSeekable",
  1679. value: function isSeekable() {
  1680. return this.hasKeyframesIndex === true;
  1681. }
  1682. }, {
  1683. key: "getNearestKeyframe",
  1684. value: function getNearestKeyframe(milliseconds) {
  1685. if (this.keyframesIndex == null) {
  1686. return null;
  1687. }
  1688. var table = this.keyframesIndex;
  1689. var keyframeIdx = this._search(table.times, milliseconds);
  1690. return {
  1691. index: keyframeIdx,
  1692. milliseconds: table.times[keyframeIdx],
  1693. fileposition: table.filepositions[keyframeIdx]
  1694. };
  1695. }
  1696. }, {
  1697. key: "_search",
  1698. value: function _search(list, value) {
  1699. var idx = 0;
  1700. var last = list.length - 1;
  1701. var mid = 0;
  1702. var lbound = 0;
  1703. var ubound = last;
  1704. if (value < list[0]) {
  1705. idx = 0;
  1706. lbound = ubound + 1; // skip search
  1707. }
  1708. while (lbound <= ubound) {
  1709. mid = lbound + Math.floor((ubound - lbound) / 2);
  1710. if (mid === last || value >= list[mid] && value < list[mid + 1]) {
  1711. idx = mid;
  1712. break;
  1713. } else if (list[mid] < value) {
  1714. lbound = mid + 1;
  1715. } else {
  1716. ubound = mid - 1;
  1717. }
  1718. }
  1719. return idx;
  1720. }
  1721. }]);
  1722. return MediaInfo;
  1723. }();
  1724. exports.default = MediaInfo;
  1725. },{}],8:[function(_dereq_,module,exports){
  1726. "use strict";
  1727. Object.defineProperty(exports, "__esModule", {
  1728. value: true
  1729. });
  1730. 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; }; }();
  1731. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1732. /*
  1733. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  1734. *
  1735. * @author zheng qian <xqq@xqq.im>
  1736. *
  1737. * Licensed under the Apache License, Version 2.0 (the "License");
  1738. * you may not use this file except in compliance with the License.
  1739. * You may obtain a copy of the License at
  1740. *
  1741. * http://www.apache.org/licenses/LICENSE-2.0
  1742. *
  1743. * Unless required by applicable law or agreed to in writing, software
  1744. * distributed under the License is distributed on an "AS IS" BASIS,
  1745. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1746. * See the License for the specific language governing permissions and
  1747. * limitations under the License.
  1748. */
  1749. // Represents an media sample (audio / video)
  1750. var SampleInfo = exports.SampleInfo = function SampleInfo(dts, pts, duration, originalDts, isSync) {
  1751. _classCallCheck(this, SampleInfo);
  1752. this.dts = dts;
  1753. this.pts = pts;
  1754. this.duration = duration;
  1755. this.originalDts = originalDts;
  1756. this.isSyncPoint = isSync;
  1757. this.fileposition = null;
  1758. };
  1759. // Media Segment concept is defined in Media Source Extensions spec.
  1760. // Particularly in ISO BMFF format, an Media Segment contains a moof box followed by a mdat box.
  1761. var MediaSegmentInfo = exports.MediaSegmentInfo = function () {
  1762. function MediaSegmentInfo() {
  1763. _classCallCheck(this, MediaSegmentInfo);
  1764. this.beginDts = 0;
  1765. this.endDts = 0;
  1766. this.beginPts = 0;
  1767. this.endPts = 0;
  1768. this.originalBeginDts = 0;
  1769. this.originalEndDts = 0;
  1770. this.syncPoints = []; // SampleInfo[n], for video IDR frames only
  1771. this.firstSample = null; // SampleInfo
  1772. this.lastSample = null; // SampleInfo
  1773. }
  1774. _createClass(MediaSegmentInfo, [{
  1775. key: "appendSyncPoint",
  1776. value: function appendSyncPoint(sampleInfo) {
  1777. // also called Random Access Point
  1778. sampleInfo.isSyncPoint = true;
  1779. this.syncPoints.push(sampleInfo);
  1780. }
  1781. }]);
  1782. return MediaSegmentInfo;
  1783. }();
  1784. // Ordered list for recording video IDR frames, sorted by originalDts
  1785. var IDRSampleList = exports.IDRSampleList = function () {
  1786. function IDRSampleList() {
  1787. _classCallCheck(this, IDRSampleList);
  1788. this._list = [];
  1789. }
  1790. _createClass(IDRSampleList, [{
  1791. key: "clear",
  1792. value: function clear() {
  1793. this._list = [];
  1794. }
  1795. }, {
  1796. key: "appendArray",
  1797. value: function appendArray(syncPoints) {
  1798. var list = this._list;
  1799. if (syncPoints.length === 0) {
  1800. return;
  1801. }
  1802. if (list.length > 0 && syncPoints[0].originalDts < list[list.length - 1].originalDts) {
  1803. this.clear();
  1804. }
  1805. Array.prototype.push.apply(list, syncPoints);
  1806. }
  1807. }, {
  1808. key: "getLastSyncPointBeforeDts",
  1809. value: function getLastSyncPointBeforeDts(dts) {
  1810. if (this._list.length == 0) {
  1811. return null;
  1812. }
  1813. var list = this._list;
  1814. var idx = 0;
  1815. var last = list.length - 1;
  1816. var mid = 0;
  1817. var lbound = 0;
  1818. var ubound = last;
  1819. if (dts < list[0].dts) {
  1820. idx = 0;
  1821. lbound = ubound + 1;
  1822. }
  1823. while (lbound <= ubound) {
  1824. mid = lbound + Math.floor((ubound - lbound) / 2);
  1825. if (mid === last || dts >= list[mid].dts && dts < list[mid + 1].dts) {
  1826. idx = mid;
  1827. break;
  1828. } else if (list[mid].dts < dts) {
  1829. lbound = mid + 1;
  1830. } else {
  1831. ubound = mid - 1;
  1832. }
  1833. }
  1834. return this._list[idx];
  1835. }
  1836. }]);
  1837. return IDRSampleList;
  1838. }();
  1839. // Data structure for recording information of media segments in single track.
  1840. var MediaSegmentInfoList = exports.MediaSegmentInfoList = function () {
  1841. function MediaSegmentInfoList(type) {
  1842. _classCallCheck(this, MediaSegmentInfoList);
  1843. this._type = type;
  1844. this._list = [];
  1845. this._lastAppendLocation = -1; // cached last insert location
  1846. }
  1847. _createClass(MediaSegmentInfoList, [{
  1848. key: "isEmpty",
  1849. value: function isEmpty() {
  1850. return this._list.length === 0;
  1851. }
  1852. }, {
  1853. key: "clear",
  1854. value: function clear() {
  1855. this._list = [];
  1856. this._lastAppendLocation = -1;
  1857. }
  1858. }, {
  1859. key: "_searchNearestSegmentBefore",
  1860. value: function _searchNearestSegmentBefore(originalBeginDts) {
  1861. var list = this._list;
  1862. if (list.length === 0) {
  1863. return -2;
  1864. }
  1865. var last = list.length - 1;
  1866. var mid = 0;
  1867. var lbound = 0;
  1868. var ubound = last;
  1869. var idx = 0;
  1870. if (originalBeginDts < list[0].originalBeginDts) {
  1871. idx = -1;
  1872. return idx;
  1873. }
  1874. while (lbound <= ubound) {
  1875. mid = lbound + Math.floor((ubound - lbound) / 2);
  1876. if (mid === last || originalBeginDts > list[mid].lastSample.originalDts && originalBeginDts < list[mid + 1].originalBeginDts) {
  1877. idx = mid;
  1878. break;
  1879. } else if (list[mid].originalBeginDts < originalBeginDts) {
  1880. lbound = mid + 1;
  1881. } else {
  1882. ubound = mid - 1;
  1883. }
  1884. }
  1885. return idx;
  1886. }
  1887. }, {
  1888. key: "_searchNearestSegmentAfter",
  1889. value: function _searchNearestSegmentAfter(originalBeginDts) {
  1890. return this._searchNearestSegmentBefore(originalBeginDts) + 1;
  1891. }
  1892. }, {
  1893. key: "append",
  1894. value: function append(mediaSegmentInfo) {
  1895. var list = this._list;
  1896. var msi = mediaSegmentInfo;
  1897. var lastAppendIdx = this._lastAppendLocation;
  1898. var insertIdx = 0;
  1899. 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)) {
  1900. insertIdx = lastAppendIdx + 1; // use cached location idx
  1901. } else {
  1902. if (list.length > 0) {
  1903. insertIdx = this._searchNearestSegmentBefore(msi.originalBeginDts) + 1;
  1904. }
  1905. }
  1906. this._lastAppendLocation = insertIdx;
  1907. this._list.splice(insertIdx, 0, msi);
  1908. }
  1909. }, {
  1910. key: "getLastSegmentBefore",
  1911. value: function getLastSegmentBefore(originalBeginDts) {
  1912. var idx = this._searchNearestSegmentBefore(originalBeginDts);
  1913. if (idx >= 0) {
  1914. return this._list[idx];
  1915. } else {
  1916. // -1
  1917. return null;
  1918. }
  1919. }
  1920. }, {
  1921. key: "getLastSampleBefore",
  1922. value: function getLastSampleBefore(originalBeginDts) {
  1923. var segment = this.getLastSegmentBefore(originalBeginDts);
  1924. if (segment != null) {
  1925. return segment.lastSample;
  1926. } else {
  1927. return null;
  1928. }
  1929. }
  1930. }, {
  1931. key: "getLastSyncPointBefore",
  1932. value: function getLastSyncPointBefore(originalBeginDts) {
  1933. var segmentIdx = this._searchNearestSegmentBefore(originalBeginDts);
  1934. var syncPoints = this._list[segmentIdx].syncPoints;
  1935. while (syncPoints.length === 0 && segmentIdx > 0) {
  1936. segmentIdx--;
  1937. syncPoints = this._list[segmentIdx].syncPoints;
  1938. }
  1939. if (syncPoints.length > 0) {
  1940. return syncPoints[syncPoints.length - 1];
  1941. } else {
  1942. return null;
  1943. }
  1944. }
  1945. }, {
  1946. key: "type",
  1947. get: function get() {
  1948. return this._type;
  1949. }
  1950. }, {
  1951. key: "length",
  1952. get: function get() {
  1953. return this._list.length;
  1954. }
  1955. }]);
  1956. return MediaSegmentInfoList;
  1957. }();
  1958. },{}],9:[function(_dereq_,module,exports){
  1959. 'use strict';
  1960. Object.defineProperty(exports, "__esModule", {
  1961. value: true
  1962. });
  1963. 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; }; }(); /*
  1964. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  1965. *
  1966. * @author zheng qian <xqq@xqq.im>
  1967. *
  1968. * Licensed under the Apache License, Version 2.0 (the "License");
  1969. * you may not use this file except in compliance with the License.
  1970. * You may obtain a copy of the License at
  1971. *
  1972. * http://www.apache.org/licenses/LICENSE-2.0
  1973. *
  1974. * Unless required by applicable law or agreed to in writing, software
  1975. * distributed under the License is distributed on an "AS IS" BASIS,
  1976. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1977. * See the License for the specific language governing permissions and
  1978. * limitations under the License.
  1979. */
  1980. var _events = _dereq_('events');
  1981. var _events2 = _interopRequireDefault(_events);
  1982. var _logger = _dereq_('../utils/logger.js');
  1983. var _logger2 = _interopRequireDefault(_logger);
  1984. var _browser = _dereq_('../utils/browser.js');
  1985. var _browser2 = _interopRequireDefault(_browser);
  1986. var _mseEvents = _dereq_('./mse-events.js');
  1987. var _mseEvents2 = _interopRequireDefault(_mseEvents);
  1988. var _mediaSegmentInfo = _dereq_('./media-segment-info.js');
  1989. var _exception = _dereq_('../utils/exception.js');
  1990. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1991. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1992. // Media Source Extensions controller
  1993. var MSEController = function () {
  1994. function MSEController(config) {
  1995. _classCallCheck(this, MSEController);
  1996. this.TAG = 'MSEController';
  1997. this._config = config;
  1998. this._emitter = new _events2.default();
  1999. if (this._config.isLive && this._config.autoCleanupSourceBuffer == undefined) {
  2000. // For live stream, do auto cleanup by default
  2001. this._config.autoCleanupSourceBuffer = true;
  2002. }
  2003. this.e = {
  2004. onSourceOpen: this._onSourceOpen.bind(this),
  2005. onSourceEnded: this._onSourceEnded.bind(this),
  2006. onSourceClose: this._onSourceClose.bind(this),
  2007. onSourceBufferError: this._onSourceBufferError.bind(this),
  2008. onSourceBufferUpdateEnd: this._onSourceBufferUpdateEnd.bind(this)
  2009. };
  2010. this._mediaSource = null;
  2011. this._mediaSourceObjectURL = null;
  2012. this._mediaElement = null;
  2013. this._isBufferFull = false;
  2014. this._hasPendingEos = false;
  2015. this._requireSetMediaDuration = false;
  2016. this._pendingMediaDuration = 0;
  2017. this._pendingSourceBufferInit = [];
  2018. this._mimeTypes = {
  2019. video: null,
  2020. audio: null
  2021. };
  2022. this._sourceBuffers = {
  2023. video: null,
  2024. audio: null
  2025. };
  2026. this._lastInitSegments = {
  2027. video: null,
  2028. audio: null
  2029. };
  2030. this._pendingSegments = {
  2031. video: [],
  2032. audio: []
  2033. };
  2034. this._pendingRemoveRanges = {
  2035. video: [],
  2036. audio: []
  2037. };
  2038. this._idrList = new _mediaSegmentInfo.IDRSampleList();
  2039. }
  2040. _createClass(MSEController, [{
  2041. key: 'destroy',
  2042. value: function destroy() {
  2043. if (this._mediaElement || this._mediaSource) {
  2044. this.detachMediaElement();
  2045. }
  2046. this.e = null;
  2047. this._emitter.removeAllListeners();
  2048. this._emitter = null;
  2049. }
  2050. }, {
  2051. key: 'on',
  2052. value: function on(event, listener) {
  2053. this._emitter.addListener(event, listener);
  2054. }
  2055. }, {
  2056. key: 'off',
  2057. value: function off(event, listener) {
  2058. this._emitter.removeListener(event, listener);
  2059. }
  2060. }, {
  2061. key: 'attachMediaElement',
  2062. value: function attachMediaElement(mediaElement) {
  2063. if (this._mediaSource) {
  2064. throw new _exception.IllegalStateException('MediaSource has been attached to an HTMLMediaElement!');
  2065. }
  2066. var ms = this._mediaSource = new window.MediaSource();
  2067. ms.addEventListener('sourceopen', this.e.onSourceOpen);
  2068. ms.addEventListener('sourceended', this.e.onSourceEnded);
  2069. ms.addEventListener('sourceclose', this.e.onSourceClose);
  2070. this._mediaElement = mediaElement;
  2071. this._mediaSourceObjectURL = window.URL.createObjectURL(this._mediaSource);
  2072. mediaElement.src = this._mediaSourceObjectURL;
  2073. }
  2074. }, {
  2075. key: 'detachMediaElement',
  2076. value: function detachMediaElement() {
  2077. if (this._mediaSource) {
  2078. var ms = this._mediaSource;
  2079. for (var type in this._sourceBuffers) {
  2080. // pending segments should be discard
  2081. var ps = this._pendingSegments[type];
  2082. ps.splice(0, ps.length);
  2083. this._pendingSegments[type] = null;
  2084. this._pendingRemoveRanges[type] = null;
  2085. this._lastInitSegments[type] = null;
  2086. // remove all sourcebuffers
  2087. var sb = this._sourceBuffers[type];
  2088. if (sb) {
  2089. if (ms.readyState !== 'closed') {
  2090. ms.removeSourceBuffer(sb);
  2091. sb.removeEventListener('error', this.e.onSourceBufferError);
  2092. sb.removeEventListener('updateend', this.e.onSourceBufferUpdateEnd);
  2093. }
  2094. this._mimeTypes[type] = null;
  2095. this._sourceBuffers[type] = null;
  2096. }
  2097. }
  2098. if (ms.readyState === 'open') {
  2099. try {
  2100. ms.endOfStream();
  2101. } catch (error) {
  2102. _logger2.default.e(this.TAG, error.message);
  2103. }
  2104. }
  2105. ms.removeEventListener('sourceopen', this.e.onSourceOpen);
  2106. ms.removeEventListener('sourceended', this.e.onSourceEnded);
  2107. ms.removeEventListener('sourceclose', this.e.onSourceClose);
  2108. this._pendingSourceBufferInit = [];
  2109. this._isBufferFull = false;
  2110. this._idrList.clear();
  2111. this._mediaSource = null;
  2112. }
  2113. if (this._mediaElement) {
  2114. this._mediaElement.src = '';
  2115. this._mediaElement.removeAttribute('src');
  2116. this._mediaElement = null;
  2117. }
  2118. if (this._mediaSourceObjectURL) {
  2119. window.URL.revokeObjectURL(this._mediaSourceObjectURL);
  2120. this._mediaSourceObjectURL = null;
  2121. }
  2122. }
  2123. }, {
  2124. key: 'appendInitSegment',
  2125. value: function appendInitSegment(initSegment, deferred) {
  2126. if (!this._mediaSource || this._mediaSource.readyState !== 'open') {
  2127. // sourcebuffer creation requires mediaSource.readyState === 'open'
  2128. // so we defer the sourcebuffer creation, until sourceopen event triggered
  2129. this._pendingSourceBufferInit.push(initSegment);
  2130. // make sure that this InitSegment is in the front of pending segments queue
  2131. this._pendingSegments[initSegment.type].push(initSegment);
  2132. return;
  2133. }
  2134. var is = initSegment;
  2135. var mimeType = '' + is.container;
  2136. if (is.codec && is.codec.length > 0) {
  2137. mimeType += ';codecs=' + is.codec;
  2138. }
  2139. var firstInitSegment = false;
  2140. _logger2.default.v(this.TAG, 'Received Initialization Segment, mimeType: ' + mimeType);
  2141. this._lastInitSegments[is.type] = is;
  2142. if (mimeType !== this._mimeTypes[is.type]) {
  2143. if (!this._mimeTypes[is.type]) {
  2144. // empty, first chance create sourcebuffer
  2145. firstInitSegment = true;
  2146. try {
  2147. var sb = this._sourceBuffers[is.type] = this._mediaSource.addSourceBuffer(mimeType);
  2148. sb.addEventListener('error', this.e.onSourceBufferError);
  2149. sb.addEventListener('updateend', this.e.onSourceBufferUpdateEnd);
  2150. } catch (error) {
  2151. _logger2.default.e(this.TAG, error.message);
  2152. this._emitter.emit(_mseEvents2.default.ERROR, { code: error.code, msg: error.message });
  2153. return;
  2154. }
  2155. } else {
  2156. _logger2.default.v(this.TAG, 'Notice: ' + is.type + ' mimeType changed, origin: ' + this._mimeTypes[is.type] + ', target: ' + mimeType);
  2157. }
  2158. this._mimeTypes[is.type] = mimeType;
  2159. }
  2160. if (!deferred) {
  2161. // deferred means this InitSegment has been pushed to pendingSegments queue
  2162. this._pendingSegments[is.type].push(is);
  2163. }
  2164. if (!firstInitSegment) {
  2165. // append immediately only if init segment in subsequence
  2166. if (this._sourceBuffers[is.type] && !this._sourceBuffers[is.type].updating) {
  2167. this._doAppendSegments();
  2168. }
  2169. }
  2170. if (_browser2.default.safari && is.container === 'audio/mpeg' && is.mediaDuration > 0) {
  2171. // 'audio/mpeg' track under Safari may cause MediaElement's duration to be NaN
  2172. // Manually correct MediaSource.duration to make progress bar seekable, and report right duration
  2173. this._requireSetMediaDuration = true;
  2174. this._pendingMediaDuration = is.mediaDuration / 1000; // in seconds
  2175. this._updateMediaSourceDuration();
  2176. }
  2177. }
  2178. }, {
  2179. key: 'appendMediaSegment',
  2180. value: function appendMediaSegment(mediaSegment) {
  2181. var ms = mediaSegment;
  2182. this._pendingSegments[ms.type].push(ms);
  2183. if (this._config.autoCleanupSourceBuffer && this._needCleanupSourceBuffer()) {
  2184. this._doCleanupSourceBuffer();
  2185. }
  2186. var sb = this._sourceBuffers[ms.type];
  2187. if (sb && !sb.updating && !this._hasPendingRemoveRanges()) {
  2188. this._doAppendSegments();
  2189. }
  2190. }
  2191. }, {
  2192. key: 'seek',
  2193. value: function seek(seconds) {
  2194. // remove all appended buffers
  2195. for (var type in this._sourceBuffers) {
  2196. if (!this._sourceBuffers[type]) {
  2197. continue;
  2198. }
  2199. // abort current buffer append algorithm
  2200. var sb = this._sourceBuffers[type];
  2201. if (this._mediaSource.readyState === 'open') {
  2202. try {
  2203. // If range removal algorithm is running, InvalidStateError will be throwed
  2204. // Ignore it.
  2205. sb.abort();
  2206. } catch (error) {
  2207. _logger2.default.e(this.TAG, error.message);
  2208. }
  2209. }
  2210. // IDRList should be clear
  2211. this._idrList.clear();
  2212. // pending segments should be discard
  2213. var ps = this._pendingSegments[type];
  2214. ps.splice(0, ps.length);
  2215. if (this._mediaSource.readyState === 'closed') {
  2216. // Parent MediaSource object has been detached from HTMLMediaElement
  2217. continue;
  2218. }
  2219. // record ranges to be remove from SourceBuffer
  2220. for (var i = 0; i < sb.buffered.length; i++) {
  2221. var start = sb.buffered.start(i);
  2222. var end = sb.buffered.end(i);
  2223. this._pendingRemoveRanges[type].push({ start: start, end: end });
  2224. }
  2225. // if sb is not updating, let's remove ranges now!
  2226. if (!sb.updating) {
  2227. this._doRemoveRanges();
  2228. }
  2229. // Safari 10 may get InvalidStateError in the later appendBuffer() after SourceBuffer.remove() call
  2230. // Internal parser's state may be invalid at this time. Re-append last InitSegment to workaround.
  2231. // Related issue: https://bugs.webkit.org/show_bug.cgi?id=159230
  2232. if (_browser2.default.safari) {
  2233. var lastInitSegment = this._lastInitSegments[type];
  2234. if (lastInitSegment) {
  2235. this._pendingSegments[type].push(lastInitSegment);
  2236. if (!sb.updating) {
  2237. this._doAppendSegments();
  2238. }
  2239. }
  2240. }
  2241. }
  2242. }
  2243. }, {
  2244. key: 'endOfStream',
  2245. value: function endOfStream() {
  2246. var ms = this._mediaSource;
  2247. var sb = this._sourceBuffers;
  2248. if (!ms || ms.readyState !== 'open') {
  2249. if (ms && ms.readyState === 'closed' && this._hasPendingSegments()) {
  2250. // If MediaSource hasn't turned into open state, and there're pending segments
  2251. // Mark pending endOfStream, defer call until all pending segments appended complete
  2252. this._hasPendingEos = true;
  2253. }
  2254. return;
  2255. }
  2256. if (sb.video && sb.video.updating || sb.audio && sb.audio.updating) {
  2257. // If any sourcebuffer is updating, defer endOfStream operation
  2258. // See _onSourceBufferUpdateEnd()
  2259. this._hasPendingEos = true;
  2260. } else {
  2261. this._hasPendingEos = false;
  2262. // Notify media data loading complete
  2263. // This is helpful for correcting total duration to match last media segment
  2264. // Otherwise MediaElement's ended event may not be triggered
  2265. ms.endOfStream();
  2266. }
  2267. }
  2268. }, {
  2269. key: 'getNearestKeyframe',
  2270. value: function getNearestKeyframe(dts) {
  2271. return this._idrList.getLastSyncPointBeforeDts(dts);
  2272. }
  2273. }, {
  2274. key: '_needCleanupSourceBuffer',
  2275. value: function _needCleanupSourceBuffer() {
  2276. if (!this._config.autoCleanupSourceBuffer) {
  2277. return false;
  2278. }
  2279. var currentTime = this._mediaElement.currentTime;
  2280. for (var type in this._sourceBuffers) {
  2281. var sb = this._sourceBuffers[type];
  2282. if (sb) {
  2283. var buffered = sb.buffered;
  2284. if (buffered.length >= 1) {
  2285. if (currentTime - buffered.start(0) >= this._config.autoCleanupMaxBackwardDuration) {
  2286. return true;
  2287. }
  2288. }
  2289. }
  2290. }
  2291. return false;
  2292. }
  2293. }, {
  2294. key: '_doCleanupSourceBuffer',
  2295. value: function _doCleanupSourceBuffer() {
  2296. var currentTime = this._mediaElement.currentTime;
  2297. for (var type in this._sourceBuffers) {
  2298. var sb = this._sourceBuffers[type];
  2299. if (sb) {
  2300. var buffered = sb.buffered;
  2301. var doRemove = false;
  2302. for (var i = 0; i < buffered.length; i++) {
  2303. var start = buffered.start(i);
  2304. var end = buffered.end(i);
  2305. if (start <= currentTime && currentTime < end + 3) {
  2306. // padding 3 seconds
  2307. if (currentTime - start >= this._config.autoCleanupMaxBackwardDuration) {
  2308. doRemove = true;
  2309. var removeEnd = currentTime - this._config.autoCleanupMinBackwardDuration;
  2310. this._pendingRemoveRanges[type].push({ start: start, end: removeEnd });
  2311. }
  2312. } else if (end < currentTime) {
  2313. doRemove = true;
  2314. this._pendingRemoveRanges[type].push({ start: start, end: end });
  2315. }
  2316. }
  2317. if (doRemove && !sb.updating) {
  2318. this._doRemoveRanges();
  2319. }
  2320. }
  2321. }
  2322. }
  2323. }, {
  2324. key: '_updateMediaSourceDuration',
  2325. value: function _updateMediaSourceDuration() {
  2326. var sb = this._sourceBuffers;
  2327. if (this._mediaElement.readyState === 0 || this._mediaSource.readyState !== 'open') {
  2328. return;
  2329. }
  2330. if (sb.video && sb.video.updating || sb.audio && sb.audio.updating) {
  2331. return;
  2332. }
  2333. var current = this._mediaSource.duration;
  2334. var target = this._pendingMediaDuration;
  2335. if (target > 0 && (isNaN(current) || target > current)) {
  2336. _logger2.default.v(this.TAG, 'Update MediaSource duration from ' + current + ' to ' + target);
  2337. this._mediaSource.duration = target;
  2338. }
  2339. this._requireSetMediaDuration = false;
  2340. this._pendingMediaDuration = 0;
  2341. }
  2342. }, {
  2343. key: '_doRemoveRanges',
  2344. value: function _doRemoveRanges() {
  2345. for (var type in this._pendingRemoveRanges) {
  2346. if (!this._sourceBuffers[type] || this._sourceBuffers[type].updating) {
  2347. continue;
  2348. }
  2349. var sb = this._sourceBuffers[type];
  2350. var ranges = this._pendingRemoveRanges[type];
  2351. while (ranges.length && !sb.updating) {
  2352. var range = ranges.shift();
  2353. sb.remove(range.start, range.end);
  2354. }
  2355. }
  2356. }
  2357. }, {
  2358. key: '_doAppendSegments',
  2359. value: function _doAppendSegments() {
  2360. var pendingSegments = this._pendingSegments;
  2361. for (var type in pendingSegments) {
  2362. if (!this._sourceBuffers[type] || this._sourceBuffers[type].updating) {
  2363. continue;
  2364. }
  2365. if (pendingSegments[type].length > 0) {
  2366. var segment = pendingSegments[type].shift();
  2367. if (segment.timestampOffset) {
  2368. // For MPEG audio stream in MSE, if unbuffered-seeking occurred
  2369. // We need explicitly set timestampOffset to the desired point in timeline for mpeg SourceBuffer.
  2370. var currentOffset = this._sourceBuffers[type].timestampOffset;
  2371. var targetOffset = segment.timestampOffset / 1000; // in seconds
  2372. var delta = Math.abs(currentOffset - targetOffset);
  2373. if (delta > 0.1) {
  2374. // If time delta > 100ms
  2375. _logger2.default.v(this.TAG, 'Update MPEG audio timestampOffset from ' + currentOffset + ' to ' + targetOffset);
  2376. this._sourceBuffers[type].timestampOffset = targetOffset;
  2377. }
  2378. delete segment.timestampOffset;
  2379. }
  2380. if (!segment.data || segment.data.byteLength === 0) {
  2381. // Ignore empty buffer
  2382. continue;
  2383. }
  2384. try {
  2385. this._sourceBuffers[type].appendBuffer(segment.data);
  2386. this._isBufferFull = false;
  2387. if (type === 'video' && segment.hasOwnProperty('info')) {
  2388. this._idrList.appendArray(segment.info.syncPoints);
  2389. }
  2390. } catch (error) {
  2391. this._pendingSegments[type].unshift(segment);
  2392. if (error.code === 22) {
  2393. // QuotaExceededError
  2394. /* Notice that FireFox may not throw QuotaExceededError if SourceBuffer is full
  2395. * Currently we can only do lazy-load to avoid SourceBuffer become scattered.
  2396. * SourceBuffer eviction policy may be changed in future version of FireFox.
  2397. *
  2398. * Related issues:
  2399. * https://bugzilla.mozilla.org/show_bug.cgi?id=1279885
  2400. * https://bugzilla.mozilla.org/show_bug.cgi?id=1280023
  2401. */
  2402. // report buffer full, abort network IO
  2403. if (!this._isBufferFull) {
  2404. this._emitter.emit(_mseEvents2.default.BUFFER_FULL);
  2405. }
  2406. this._isBufferFull = true;
  2407. } else {
  2408. _logger2.default.e(this.TAG, error.message);
  2409. this._emitter.emit(_mseEvents2.default.ERROR, { code: error.code, msg: error.message });
  2410. }
  2411. }
  2412. }
  2413. }
  2414. }
  2415. }, {
  2416. key: '_onSourceOpen',
  2417. value: function _onSourceOpen() {
  2418. _logger2.default.v(this.TAG, 'MediaSource onSourceOpen');
  2419. this._mediaSource.removeEventListener('sourceopen', this.e.onSourceOpen);
  2420. // deferred sourcebuffer creation / initialization
  2421. if (this._pendingSourceBufferInit.length > 0) {
  2422. var pendings = this._pendingSourceBufferInit;
  2423. while (pendings.length) {
  2424. var segment = pendings.shift();
  2425. this.appendInitSegment(segment, true);
  2426. }
  2427. }
  2428. // there may be some pending media segments, append them
  2429. if (this._hasPendingSegments()) {
  2430. this._doAppendSegments();
  2431. }
  2432. this._emitter.emit(_mseEvents2.default.SOURCE_OPEN);
  2433. }
  2434. }, {
  2435. key: '_onSourceEnded',
  2436. value: function _onSourceEnded() {
  2437. // fired on endOfStream
  2438. _logger2.default.v(this.TAG, 'MediaSource onSourceEnded');
  2439. }
  2440. }, {
  2441. key: '_onSourceClose',
  2442. value: function _onSourceClose() {
  2443. // fired on detaching from media element
  2444. _logger2.default.v(this.TAG, 'MediaSource onSourceClose');
  2445. if (this._mediaSource && this.e != null) {
  2446. this._mediaSource.removeEventListener('sourceopen', this.e.onSourceOpen);
  2447. this._mediaSource.removeEventListener('sourceended', this.e.onSourceEnded);
  2448. this._mediaSource.removeEventListener('sourceclose', this.e.onSourceClose);
  2449. }
  2450. }
  2451. }, {
  2452. key: '_hasPendingSegments',
  2453. value: function _hasPendingSegments() {
  2454. var ps = this._pendingSegments;
  2455. return ps.video.length > 0 || ps.audio.length > 0;
  2456. }
  2457. }, {
  2458. key: '_hasPendingRemoveRanges',
  2459. value: function _hasPendingRemoveRanges() {
  2460. var prr = this._pendingRemoveRanges;
  2461. return prr.video.length > 0 || prr.audio.length > 0;
  2462. }
  2463. }, {
  2464. key: '_onSourceBufferUpdateEnd',
  2465. value: function _onSourceBufferUpdateEnd() {
  2466. if (this._requireSetMediaDuration) {
  2467. this._updateMediaSourceDuration();
  2468. } else if (this._hasPendingRemoveRanges()) {
  2469. this._doRemoveRanges();
  2470. } else if (this._hasPendingSegments()) {
  2471. this._doAppendSegments();
  2472. } else if (this._hasPendingEos) {
  2473. this.endOfStream();
  2474. }
  2475. this._emitter.emit(_mseEvents2.default.UPDATE_END);
  2476. }
  2477. }, {
  2478. key: '_onSourceBufferError',
  2479. value: function _onSourceBufferError(e) {
  2480. _logger2.default.e(this.TAG, 'SourceBuffer Error: ' + e);
  2481. // this error might not always be fatal, just ignore it
  2482. }
  2483. }]);
  2484. return MSEController;
  2485. }();
  2486. exports.default = MSEController;
  2487. },{"../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){
  2488. 'use strict';
  2489. Object.defineProperty(exports, "__esModule", {
  2490. value: true
  2491. });
  2492. /*
  2493. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  2494. *
  2495. * @author zheng qian <xqq@xqq.im>
  2496. *
  2497. * Licensed under the Apache License, Version 2.0 (the "License");
  2498. * you may not use this file except in compliance with the License.
  2499. * You may obtain a copy of the License at
  2500. *
  2501. * http://www.apache.org/licenses/LICENSE-2.0
  2502. *
  2503. * Unless required by applicable law or agreed to in writing, software
  2504. * distributed under the License is distributed on an "AS IS" BASIS,
  2505. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2506. * See the License for the specific language governing permissions and
  2507. * limitations under the License.
  2508. */
  2509. var MSEEvents = {
  2510. ERROR: 'error',
  2511. SOURCE_OPEN: 'source_open',
  2512. UPDATE_END: 'update_end',
  2513. BUFFER_FULL: 'buffer_full'
  2514. };
  2515. exports.default = MSEEvents;
  2516. },{}],11:[function(_dereq_,module,exports){
  2517. 'use strict';
  2518. Object.defineProperty(exports, "__esModule", {
  2519. value: true
  2520. });
  2521. 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; }; }(); /*
  2522. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  2523. *
  2524. * @author zheng qian <xqq@xqq.im>
  2525. *
  2526. * Licensed under the Apache License, Version 2.0 (the "License");
  2527. * you may not use this file except in compliance with the License.
  2528. * You may obtain a copy of the License at
  2529. *
  2530. * http://www.apache.org/licenses/LICENSE-2.0
  2531. *
  2532. * Unless required by applicable law or agreed to in writing, software
  2533. * distributed under the License is distributed on an "AS IS" BASIS,
  2534. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2535. * See the License for the specific language governing permissions and
  2536. * limitations under the License.
  2537. */
  2538. var _events = _dereq_('events');
  2539. var _events2 = _interopRequireDefault(_events);
  2540. var _logger = _dereq_('../utils/logger.js');
  2541. var _logger2 = _interopRequireDefault(_logger);
  2542. var _loggingControl = _dereq_('../utils/logging-control.js');
  2543. var _loggingControl2 = _interopRequireDefault(_loggingControl);
  2544. var _transmuxingController = _dereq_('./transmuxing-controller.js');
  2545. var _transmuxingController2 = _interopRequireDefault(_transmuxingController);
  2546. var _transmuxingEvents = _dereq_('./transmuxing-events.js');
  2547. var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
  2548. var _transmuxingWorker = _dereq_('./transmuxing-worker.js');
  2549. var _transmuxingWorker2 = _interopRequireDefault(_transmuxingWorker);
  2550. var _mediaInfo = _dereq_('./media-info.js');
  2551. var _mediaInfo2 = _interopRequireDefault(_mediaInfo);
  2552. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2553. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2554. var Transmuxer = function () {
  2555. function Transmuxer(mediaDataSource, config) {
  2556. _classCallCheck(this, Transmuxer);
  2557. this.TAG = 'Transmuxer';
  2558. this._emitter = new _events2.default();
  2559. if (config.enableWorker && typeof Worker !== 'undefined') {
  2560. try {
  2561. var work = _dereq_('webworkify');
  2562. this._worker = work(_transmuxingWorker2.default);
  2563. this._workerDestroying = false;
  2564. this._worker.addEventListener('message', this._onWorkerMessage.bind(this));
  2565. this._worker.postMessage({ cmd: 'init', param: [mediaDataSource, config] });
  2566. this.e = {
  2567. onLoggingConfigChanged: this._onLoggingConfigChanged.bind(this)
  2568. };
  2569. _loggingControl2.default.registerListener(this.e.onLoggingConfigChanged);
  2570. this._worker.postMessage({ cmd: 'logging_config', param: _loggingControl2.default.getConfig() });
  2571. } catch (error) {
  2572. _logger2.default.e(this.TAG, 'Error while initialize transmuxing worker, fallback to inline transmuxing');
  2573. this._worker = null;
  2574. this._controller = new _transmuxingController2.default(mediaDataSource, config);
  2575. }
  2576. } else {
  2577. this._controller = new _transmuxingController2.default(mediaDataSource, config);
  2578. }
  2579. if (this._controller) {
  2580. var ctl = this._controller;
  2581. ctl.on(_transmuxingEvents2.default.IO_ERROR, this._onIOError.bind(this));
  2582. ctl.on(_transmuxingEvents2.default.DEMUX_ERROR, this._onDemuxError.bind(this));
  2583. ctl.on(_transmuxingEvents2.default.INIT_SEGMENT, this._onInitSegment.bind(this));
  2584. ctl.on(_transmuxingEvents2.default.MEDIA_SEGMENT, this._onMediaSegment.bind(this));
  2585. ctl.on(_transmuxingEvents2.default.LOADING_COMPLETE, this._onLoadingComplete.bind(this));
  2586. ctl.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF, this._onRecoveredEarlyEof.bind(this));
  2587. ctl.on(_transmuxingEvents2.default.MEDIA_INFO, this._onMediaInfo.bind(this));
  2588. ctl.on(_transmuxingEvents2.default.STATISTICS_INFO, this._onStatisticsInfo.bind(this));
  2589. ctl.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, this._onRecommendSeekpoint.bind(this));
  2590. }
  2591. }
  2592. _createClass(Transmuxer, [{
  2593. key: 'destroy',
  2594. value: function destroy() {
  2595. if (this._worker) {
  2596. if (!this._workerDestroying) {
  2597. this._workerDestroying = true;
  2598. this._worker.postMessage({ cmd: 'destroy' });
  2599. _loggingControl2.default.removeListener(this.e.onLoggingConfigChanged);
  2600. this.e = null;
  2601. }
  2602. } else {
  2603. this._controller.destroy();
  2604. this._controller = null;
  2605. }
  2606. this._emitter.removeAllListeners();
  2607. this._emitter = null;
  2608. }
  2609. }, {
  2610. key: 'on',
  2611. value: function on(event, listener) {
  2612. this._emitter.addListener(event, listener);
  2613. }
  2614. }, {
  2615. key: 'off',
  2616. value: function off(event, listener) {
  2617. this._emitter.removeListener(event, listener);
  2618. }
  2619. }, {
  2620. key: 'hasWorker',
  2621. value: function hasWorker() {
  2622. return this._worker != null;
  2623. }
  2624. }, {
  2625. key: 'open',
  2626. value: function open() {
  2627. if (this._worker) {
  2628. this._worker.postMessage({ cmd: 'start' });
  2629. } else {
  2630. this._controller.start();
  2631. }
  2632. }
  2633. }, {
  2634. key: 'close',
  2635. value: function close() {
  2636. if (this._worker) {
  2637. this._worker.postMessage({ cmd: 'stop' });
  2638. } else {
  2639. this._controller.stop();
  2640. }
  2641. }
  2642. }, {
  2643. key: 'seek',
  2644. value: function seek(milliseconds) {
  2645. if (this._worker) {
  2646. this._worker.postMessage({ cmd: 'seek', param: milliseconds });
  2647. } else {
  2648. this._controller.seek(milliseconds);
  2649. }
  2650. }
  2651. }, {
  2652. key: 'pause',
  2653. value: function pause() {
  2654. if (this._worker) {
  2655. this._worker.postMessage({ cmd: 'pause' });
  2656. } else {
  2657. this._controller.pause();
  2658. }
  2659. }
  2660. }, {
  2661. key: 'resume',
  2662. value: function resume() {
  2663. if (this._worker) {
  2664. this._worker.postMessage({ cmd: 'resume' });
  2665. } else {
  2666. this._controller.resume();
  2667. }
  2668. }
  2669. }, {
  2670. key: '_onInitSegment',
  2671. value: function _onInitSegment(type, initSegment) {
  2672. var _this = this;
  2673. // do async invoke
  2674. Promise.resolve().then(function () {
  2675. _this._emitter.emit(_transmuxingEvents2.default.INIT_SEGMENT, type, initSegment);
  2676. });
  2677. }
  2678. }, {
  2679. key: '_onMediaSegment',
  2680. value: function _onMediaSegment(type, mediaSegment) {
  2681. var _this2 = this;
  2682. Promise.resolve().then(function () {
  2683. _this2._emitter.emit(_transmuxingEvents2.default.MEDIA_SEGMENT, type, mediaSegment);
  2684. });
  2685. }
  2686. }, {
  2687. key: '_onLoadingComplete',
  2688. value: function _onLoadingComplete() {
  2689. var _this3 = this;
  2690. Promise.resolve().then(function () {
  2691. _this3._emitter.emit(_transmuxingEvents2.default.LOADING_COMPLETE);
  2692. });
  2693. }
  2694. }, {
  2695. key: '_onRecoveredEarlyEof',
  2696. value: function _onRecoveredEarlyEof() {
  2697. var _this4 = this;
  2698. Promise.resolve().then(function () {
  2699. _this4._emitter.emit(_transmuxingEvents2.default.RECOVERED_EARLY_EOF);
  2700. });
  2701. }
  2702. }, {
  2703. key: '_onMediaInfo',
  2704. value: function _onMediaInfo(mediaInfo) {
  2705. var _this5 = this;
  2706. Promise.resolve().then(function () {
  2707. _this5._emitter.emit(_transmuxingEvents2.default.MEDIA_INFO, mediaInfo);
  2708. });
  2709. }
  2710. }, {
  2711. key: '_onStatisticsInfo',
  2712. value: function _onStatisticsInfo(statisticsInfo) {
  2713. var _this6 = this;
  2714. Promise.resolve().then(function () {
  2715. _this6._emitter.emit(_transmuxingEvents2.default.STATISTICS_INFO, statisticsInfo);
  2716. });
  2717. }
  2718. }, {
  2719. key: '_onIOError',
  2720. value: function _onIOError(type, info) {
  2721. var _this7 = this;
  2722. Promise.resolve().then(function () {
  2723. _this7._emitter.emit(_transmuxingEvents2.default.IO_ERROR, type, info);
  2724. });
  2725. }
  2726. }, {
  2727. key: '_onDemuxError',
  2728. value: function _onDemuxError(type, info) {
  2729. var _this8 = this;
  2730. Promise.resolve().then(function () {
  2731. _this8._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR, type, info);
  2732. });
  2733. }
  2734. }, {
  2735. key: '_onRecommendSeekpoint',
  2736. value: function _onRecommendSeekpoint(milliseconds) {
  2737. var _this9 = this;
  2738. Promise.resolve().then(function () {
  2739. _this9._emitter.emit(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, milliseconds);
  2740. });
  2741. }
  2742. }, {
  2743. key: '_onLoggingConfigChanged',
  2744. value: function _onLoggingConfigChanged(config) {
  2745. if (this._worker) {
  2746. this._worker.postMessage({ cmd: 'logging_config', param: config });
  2747. }
  2748. }
  2749. }, {
  2750. key: '_onWorkerMessage',
  2751. value: function _onWorkerMessage(e) {
  2752. var message = e.data;
  2753. var data = message.data;
  2754. if (message.msg === 'destroyed' || this._workerDestroying) {
  2755. this._workerDestroying = false;
  2756. this._worker.terminate();
  2757. this._worker = null;
  2758. return;
  2759. }
  2760. switch (message.msg) {
  2761. case _transmuxingEvents2.default.INIT_SEGMENT:
  2762. case _transmuxingEvents2.default.MEDIA_SEGMENT:
  2763. this._emitter.emit(message.msg, data.type, data.data);
  2764. break;
  2765. case _transmuxingEvents2.default.LOADING_COMPLETE:
  2766. case _transmuxingEvents2.default.RECOVERED_EARLY_EOF:
  2767. this._emitter.emit(message.msg);
  2768. break;
  2769. case _transmuxingEvents2.default.MEDIA_INFO:
  2770. Object.setPrototypeOf(data, _mediaInfo2.default.prototype);
  2771. this._emitter.emit(message.msg, data);
  2772. break;
  2773. case _transmuxingEvents2.default.STATISTICS_INFO:
  2774. this._emitter.emit(message.msg, data);
  2775. break;
  2776. case _transmuxingEvents2.default.IO_ERROR:
  2777. case _transmuxingEvents2.default.DEMUX_ERROR:
  2778. this._emitter.emit(message.msg, data.type, data.info);
  2779. break;
  2780. case _transmuxingEvents2.default.RECOMMEND_SEEKPOINT:
  2781. this._emitter.emit(message.msg, data);
  2782. break;
  2783. case 'logcat_callback':
  2784. _logger2.default.emitter.emit('log', data.type, data.logcat);
  2785. break;
  2786. default:
  2787. break;
  2788. }
  2789. }
  2790. }]);
  2791. return Transmuxer;
  2792. }();
  2793. exports.default = Transmuxer;
  2794. },{"../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){
  2795. 'use strict';
  2796. Object.defineProperty(exports, "__esModule", {
  2797. value: true
  2798. });
  2799. 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; }; }(); /*
  2800. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  2801. *
  2802. * @author zheng qian <xqq@xqq.im>
  2803. *
  2804. * Licensed under the Apache License, Version 2.0 (the "License");
  2805. * you may not use this file except in compliance with the License.
  2806. * You may obtain a copy of the License at
  2807. *
  2808. * http://www.apache.org/licenses/LICENSE-2.0
  2809. *
  2810. * Unless required by applicable law or agreed to in writing, software
  2811. * distributed under the License is distributed on an "AS IS" BASIS,
  2812. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2813. * See the License for the specific language governing permissions and
  2814. * limitations under the License.
  2815. */
  2816. var _events = _dereq_('events');
  2817. var _events2 = _interopRequireDefault(_events);
  2818. var _logger = _dereq_('../utils/logger.js');
  2819. var _logger2 = _interopRequireDefault(_logger);
  2820. var _browser = _dereq_('../utils/browser.js');
  2821. var _browser2 = _interopRequireDefault(_browser);
  2822. var _mediaInfo = _dereq_('./media-info.js');
  2823. var _mediaInfo2 = _interopRequireDefault(_mediaInfo);
  2824. var _flvDemuxer = _dereq_('../demux/flv-demuxer.js');
  2825. var _flvDemuxer2 = _interopRequireDefault(_flvDemuxer);
  2826. var _mp4Remuxer = _dereq_('../remux/mp4-remuxer.js');
  2827. var _mp4Remuxer2 = _interopRequireDefault(_mp4Remuxer);
  2828. var _demuxErrors = _dereq_('../demux/demux-errors.js');
  2829. var _demuxErrors2 = _interopRequireDefault(_demuxErrors);
  2830. var _ioController = _dereq_('../io/io-controller.js');
  2831. var _ioController2 = _interopRequireDefault(_ioController);
  2832. var _transmuxingEvents = _dereq_('./transmuxing-events.js');
  2833. var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
  2834. var _loader = _dereq_('../io/loader.js');
  2835. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2836. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2837. // Transmuxing (IO, Demuxing, Remuxing) controller, with multipart support
  2838. var TransmuxingController = function () {
  2839. function TransmuxingController(mediaDataSource, config) {
  2840. _classCallCheck(this, TransmuxingController);
  2841. this.TAG = 'TransmuxingController';
  2842. this._emitter = new _events2.default();
  2843. this._config = config;
  2844. // treat single part media as multipart media, which has only one segment
  2845. if (!mediaDataSource.segments) {
  2846. mediaDataSource.segments = [{
  2847. duration: mediaDataSource.duration,
  2848. filesize: mediaDataSource.filesize,
  2849. url: mediaDataSource.url
  2850. }];
  2851. }
  2852. // fill in default IO params if not exists
  2853. if (typeof mediaDataSource.cors !== 'boolean') {
  2854. mediaDataSource.cors = true;
  2855. }
  2856. if (typeof mediaDataSource.withCredentials !== 'boolean') {
  2857. mediaDataSource.withCredentials = false;
  2858. }
  2859. this._mediaDataSource = mediaDataSource;
  2860. this._currentSegmentIndex = 0;
  2861. var totalDuration = 0;
  2862. this._mediaDataSource.segments.forEach(function (segment) {
  2863. // timestampBase for each segment, and calculate total duration
  2864. segment.timestampBase = totalDuration;
  2865. totalDuration += segment.duration;
  2866. // params needed by IOController
  2867. segment.cors = mediaDataSource.cors;
  2868. segment.withCredentials = mediaDataSource.withCredentials;
  2869. // referrer policy control, if exist
  2870. if (config.referrerPolicy) {
  2871. segment.referrerPolicy = config.referrerPolicy;
  2872. }
  2873. });
  2874. if (!isNaN(totalDuration) && this._mediaDataSource.duration !== totalDuration) {
  2875. this._mediaDataSource.duration = totalDuration;
  2876. }
  2877. this._mediaInfo = null;
  2878. this._demuxer = null;
  2879. this._remuxer = null;
  2880. this._ioctl = null;
  2881. this._pendingSeekTime = null;
  2882. this._pendingResolveSeekPoint = null;
  2883. this._statisticsReporter = null;
  2884. }
  2885. _createClass(TransmuxingController, [{
  2886. key: 'destroy',
  2887. value: function destroy() {
  2888. this._mediaInfo = null;
  2889. this._mediaDataSource = null;
  2890. if (this._statisticsReporter) {
  2891. this._disableStatisticsReporter();
  2892. }
  2893. if (this._ioctl) {
  2894. this._ioctl.destroy();
  2895. this._ioctl = null;
  2896. }
  2897. if (this._demuxer) {
  2898. this._demuxer.destroy();
  2899. this._demuxer = null;
  2900. }
  2901. if (this._remuxer) {
  2902. this._remuxer.destroy();
  2903. this._remuxer = null;
  2904. }
  2905. this._emitter.removeAllListeners();
  2906. this._emitter = null;
  2907. }
  2908. }, {
  2909. key: 'on',
  2910. value: function on(event, listener) {
  2911. this._emitter.addListener(event, listener);
  2912. }
  2913. }, {
  2914. key: 'off',
  2915. value: function off(event, listener) {
  2916. this._emitter.removeListener(event, listener);
  2917. }
  2918. }, {
  2919. key: 'start',
  2920. value: function start() {
  2921. this._loadSegment(0);
  2922. this._enableStatisticsReporter();
  2923. }
  2924. }, {
  2925. key: '_loadSegment',
  2926. value: function _loadSegment(segmentIndex, optionalFrom) {
  2927. this._currentSegmentIndex = segmentIndex;
  2928. var dataSource = this._mediaDataSource.segments[segmentIndex];
  2929. var ioctl = this._ioctl = new _ioController2.default(dataSource, this._config, segmentIndex);
  2930. ioctl.onError = this._onIOException.bind(this);
  2931. ioctl.onSeeked = this._onIOSeeked.bind(this);
  2932. ioctl.onComplete = this._onIOComplete.bind(this);
  2933. ioctl.onRedirect = this._onIORedirect.bind(this);
  2934. ioctl.onRecoveredEarlyEof = this._onIORecoveredEarlyEof.bind(this);
  2935. if (optionalFrom) {
  2936. this._demuxer.bindDataSource(this._ioctl);
  2937. } else {
  2938. ioctl.onDataArrival = this._onInitChunkArrival.bind(this);
  2939. }
  2940. ioctl.open(optionalFrom);
  2941. }
  2942. }, {
  2943. key: 'stop',
  2944. value: function stop() {
  2945. this._internalAbort();
  2946. this._disableStatisticsReporter();
  2947. }
  2948. }, {
  2949. key: '_internalAbort',
  2950. value: function _internalAbort() {
  2951. if (this._ioctl) {
  2952. this._ioctl.destroy();
  2953. this._ioctl = null;
  2954. }
  2955. }
  2956. }, {
  2957. key: 'pause',
  2958. value: function pause() {
  2959. // take a rest
  2960. if (this._ioctl && this._ioctl.isWorking()) {
  2961. this._ioctl.pause();
  2962. this._disableStatisticsReporter();
  2963. }
  2964. }
  2965. }, {
  2966. key: 'resume',
  2967. value: function resume() {
  2968. if (this._ioctl && this._ioctl.isPaused()) {
  2969. this._ioctl.resume();
  2970. this._enableStatisticsReporter();
  2971. }
  2972. }
  2973. }, {
  2974. key: 'seek',
  2975. value: function seek(milliseconds) {
  2976. if (this._mediaInfo == null || !this._mediaInfo.isSeekable()) {
  2977. return;
  2978. }
  2979. var targetSegmentIndex = this._searchSegmentIndexContains(milliseconds);
  2980. if (targetSegmentIndex === this._currentSegmentIndex) {
  2981. // intra-segment seeking
  2982. var segmentInfo = this._mediaInfo.segments[targetSegmentIndex];
  2983. if (segmentInfo == undefined) {
  2984. // current segment loading started, but mediainfo hasn't received yet
  2985. // wait for the metadata loaded, then seek to expected position
  2986. this._pendingSeekTime = milliseconds;
  2987. } else {
  2988. var keyframe = segmentInfo.getNearestKeyframe(milliseconds);
  2989. this._remuxer.seek(keyframe.milliseconds);
  2990. this._ioctl.seek(keyframe.fileposition);
  2991. // Will be resolved in _onRemuxerMediaSegmentArrival()
  2992. this._pendingResolveSeekPoint = keyframe.milliseconds;
  2993. }
  2994. } else {
  2995. // cross-segment seeking
  2996. var targetSegmentInfo = this._mediaInfo.segments[targetSegmentIndex];
  2997. if (targetSegmentInfo == undefined) {
  2998. // target segment hasn't been loaded. We need metadata then seek to expected time
  2999. this._pendingSeekTime = milliseconds;
  3000. this._internalAbort();
  3001. this._remuxer.seek();
  3002. this._remuxer.insertDiscontinuity();
  3003. this._loadSegment(targetSegmentIndex);
  3004. // Here we wait for the metadata loaded, then seek to expected position
  3005. } else {
  3006. // We have target segment's metadata, direct seek to target position
  3007. var _keyframe = targetSegmentInfo.getNearestKeyframe(milliseconds);
  3008. this._internalAbort();
  3009. this._remuxer.seek(milliseconds);
  3010. this._remuxer.insertDiscontinuity();
  3011. this._demuxer.resetMediaInfo();
  3012. this._demuxer.timestampBase = this._mediaDataSource.segments[targetSegmentIndex].timestampBase;
  3013. this._loadSegment(targetSegmentIndex, _keyframe.fileposition);
  3014. this._pendingResolveSeekPoint = _keyframe.milliseconds;
  3015. this._reportSegmentMediaInfo(targetSegmentIndex);
  3016. }
  3017. }
  3018. this._enableStatisticsReporter();
  3019. }
  3020. }, {
  3021. key: '_searchSegmentIndexContains',
  3022. value: function _searchSegmentIndexContains(milliseconds) {
  3023. var segments = this._mediaDataSource.segments;
  3024. var idx = segments.length - 1;
  3025. for (var i = 0; i < segments.length; i++) {
  3026. if (milliseconds < segments[i].timestampBase) {
  3027. idx = i - 1;
  3028. break;
  3029. }
  3030. }
  3031. return idx;
  3032. }
  3033. }, {
  3034. key: '_onInitChunkArrival',
  3035. value: function _onInitChunkArrival(data, byteStart) {
  3036. var _this = this;
  3037. var probeData = null;
  3038. var consumed = 0;
  3039. if (byteStart > 0) {
  3040. // IOController seeked immediately after opened, byteStart > 0 callback may received
  3041. this._demuxer.bindDataSource(this._ioctl);
  3042. this._demuxer.timestampBase = this._mediaDataSource.segments[this._currentSegmentIndex].timestampBase;
  3043. consumed = this._demuxer.parseChunks(data, byteStart);
  3044. } else if ((probeData = _flvDemuxer2.default.probe(data)).match) {
  3045. // Always create new FLVDemuxer
  3046. this._demuxer = new _flvDemuxer2.default(probeData, this._config);
  3047. if (!this._remuxer) {
  3048. this._remuxer = new _mp4Remuxer2.default(this._config);
  3049. }
  3050. var mds = this._mediaDataSource;
  3051. if (mds.duration != undefined && !isNaN(mds.duration)) {
  3052. this._demuxer.overridedDuration = mds.duration;
  3053. }
  3054. if (typeof mds.hasAudio === 'boolean') {
  3055. this._demuxer.overridedHasAudio = mds.hasAudio;
  3056. }
  3057. if (typeof mds.hasVideo === 'boolean') {
  3058. this._demuxer.overridedHasVideo = mds.hasVideo;
  3059. }
  3060. this._demuxer.timestampBase = mds.segments[this._currentSegmentIndex].timestampBase;
  3061. this._demuxer.onError = this._onDemuxException.bind(this);
  3062. this._demuxer.onMediaInfo = this._onMediaInfo.bind(this);
  3063. this._remuxer.bindDataSource(this._demuxer.bindDataSource(this._ioctl));
  3064. this._remuxer.onInitSegment = this._onRemuxerInitSegmentArrival.bind(this);
  3065. this._remuxer.onMediaSegment = this._onRemuxerMediaSegmentArrival.bind(this);
  3066. consumed = this._demuxer.parseChunks(data, byteStart);
  3067. } else {
  3068. probeData = null;
  3069. _logger2.default.e(this.TAG, 'Non-FLV, Unsupported media type!');
  3070. Promise.resolve().then(function () {
  3071. _this._internalAbort();
  3072. });
  3073. this._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR, _demuxErrors2.default.FORMAT_UNSUPPORTED, 'Non-FLV, Unsupported media type');
  3074. consumed = 0;
  3075. }
  3076. return consumed;
  3077. }
  3078. }, {
  3079. key: '_onMediaInfo',
  3080. value: function _onMediaInfo(mediaInfo) {
  3081. var _this2 = this;
  3082. if (this._mediaInfo == null) {
  3083. // Store first segment's mediainfo as global mediaInfo
  3084. this._mediaInfo = Object.assign({}, mediaInfo);
  3085. this._mediaInfo.keyframesIndex = null;
  3086. this._mediaInfo.segments = [];
  3087. this._mediaInfo.segmentCount = this._mediaDataSource.segments.length;
  3088. Object.setPrototypeOf(this._mediaInfo, _mediaInfo2.default.prototype);
  3089. }
  3090. var segmentInfo = Object.assign({}, mediaInfo);
  3091. Object.setPrototypeOf(segmentInfo, _mediaInfo2.default.prototype);
  3092. this._mediaInfo.segments[this._currentSegmentIndex] = segmentInfo;
  3093. // notify mediaInfo update
  3094. this._reportSegmentMediaInfo(this._currentSegmentIndex);
  3095. if (this._pendingSeekTime != null) {
  3096. Promise.resolve().then(function () {
  3097. var target = _this2._pendingSeekTime;
  3098. _this2._pendingSeekTime = null;
  3099. _this2.seek(target);
  3100. });
  3101. }
  3102. }
  3103. }, {
  3104. key: '_onIOSeeked',
  3105. value: function _onIOSeeked() {
  3106. this._remuxer.insertDiscontinuity();
  3107. }
  3108. }, {
  3109. key: '_onIOComplete',
  3110. value: function _onIOComplete(extraData) {
  3111. var segmentIndex = extraData;
  3112. var nextSegmentIndex = segmentIndex + 1;
  3113. if (nextSegmentIndex < this._mediaDataSource.segments.length) {
  3114. this._internalAbort();
  3115. this._loadSegment(nextSegmentIndex);
  3116. } else {
  3117. this._remuxer.flushStashedSamples();
  3118. this._emitter.emit(_transmuxingEvents2.default.LOADING_COMPLETE);
  3119. this._disableStatisticsReporter();
  3120. }
  3121. }
  3122. }, {
  3123. key: '_onIORedirect',
  3124. value: function _onIORedirect(redirectedURL) {
  3125. var segmentIndex = this._ioctl.extraData;
  3126. this._mediaDataSource.segments[segmentIndex].redirectedURL = redirectedURL;
  3127. }
  3128. }, {
  3129. key: '_onIORecoveredEarlyEof',
  3130. value: function _onIORecoveredEarlyEof() {
  3131. this._emitter.emit(_transmuxingEvents2.default.RECOVERED_EARLY_EOF);
  3132. }
  3133. }, {
  3134. key: '_onIOException',
  3135. value: function _onIOException(type, info) {
  3136. _logger2.default.e(this.TAG, 'IOException: type = ' + type + ', code = ' + info.code + ', msg = ' + info.msg);
  3137. this._emitter.emit(_transmuxingEvents2.default.IO_ERROR, type, info);
  3138. this._disableStatisticsReporter();
  3139. }
  3140. }, {
  3141. key: '_onDemuxException',
  3142. value: function _onDemuxException(type, info) {
  3143. _logger2.default.e(this.TAG, 'DemuxException: type = ' + type + ', info = ' + info);
  3144. this._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR, type, info);
  3145. }
  3146. }, {
  3147. key: '_onRemuxerInitSegmentArrival',
  3148. value: function _onRemuxerInitSegmentArrival(type, initSegment) {
  3149. this._emitter.emit(_transmuxingEvents2.default.INIT_SEGMENT, type, initSegment);
  3150. }
  3151. }, {
  3152. key: '_onRemuxerMediaSegmentArrival',
  3153. value: function _onRemuxerMediaSegmentArrival(type, mediaSegment) {
  3154. if (this._pendingSeekTime != null) {
  3155. // Media segments after new-segment cross-seeking should be dropped.
  3156. return;
  3157. }
  3158. this._emitter.emit(_transmuxingEvents2.default.MEDIA_SEGMENT, type, mediaSegment);
  3159. // Resolve pending seekPoint
  3160. if (this._pendingResolveSeekPoint != null && type === 'video') {
  3161. var syncPoints = mediaSegment.info.syncPoints;
  3162. var seekpoint = this._pendingResolveSeekPoint;
  3163. this._pendingResolveSeekPoint = null;
  3164. // Safari: Pass PTS for recommend_seekpoint
  3165. if (_browser2.default.safari && syncPoints.length > 0 && syncPoints[0].originalDts === seekpoint) {
  3166. seekpoint = syncPoints[0].pts;
  3167. }
  3168. // else: use original DTS (keyframe.milliseconds)
  3169. this._emitter.emit(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, seekpoint);
  3170. }
  3171. }
  3172. }, {
  3173. key: '_enableStatisticsReporter',
  3174. value: function _enableStatisticsReporter() {
  3175. if (this._statisticsReporter == null) {
  3176. this._statisticsReporter = self.setInterval(this._reportStatisticsInfo.bind(this), this._config.statisticsInfoReportInterval);
  3177. }
  3178. }
  3179. }, {
  3180. key: '_disableStatisticsReporter',
  3181. value: function _disableStatisticsReporter() {
  3182. if (this._statisticsReporter) {
  3183. self.clearInterval(this._statisticsReporter);
  3184. this._statisticsReporter = null;
  3185. }
  3186. }
  3187. }, {
  3188. key: '_reportSegmentMediaInfo',
  3189. value: function _reportSegmentMediaInfo(segmentIndex) {
  3190. var segmentInfo = this._mediaInfo.segments[segmentIndex];
  3191. var exportInfo = Object.assign({}, segmentInfo);
  3192. exportInfo.duration = this._mediaInfo.duration;
  3193. exportInfo.segmentCount = this._mediaInfo.segmentCount;
  3194. delete exportInfo.segments;
  3195. delete exportInfo.keyframesIndex;
  3196. this._emitter.emit(_transmuxingEvents2.default.MEDIA_INFO, exportInfo);
  3197. }
  3198. }, {
  3199. key: '_reportStatisticsInfo',
  3200. value: function _reportStatisticsInfo() {
  3201. var info = {};
  3202. info.url = this._ioctl.currentURL;
  3203. info.hasRedirect = this._ioctl.hasRedirect;
  3204. if (info.hasRedirect) {
  3205. info.redirectedURL = this._ioctl.currentRedirectedURL;
  3206. }
  3207. info.speed = this._ioctl.currentSpeed;
  3208. info.loaderType = this._ioctl.loaderType;
  3209. info.currentSegmentIndex = this._currentSegmentIndex;
  3210. info.totalSegmentCount = this._mediaDataSource.segments.length;
  3211. this._emitter.emit(_transmuxingEvents2.default.STATISTICS_INFO, info);
  3212. }
  3213. }]);
  3214. return TransmuxingController;
  3215. }();
  3216. exports.default = TransmuxingController;
  3217. },{"../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){
  3218. 'use strict';
  3219. Object.defineProperty(exports, "__esModule", {
  3220. value: true
  3221. });
  3222. /*
  3223. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  3224. *
  3225. * @author zheng qian <xqq@xqq.im>
  3226. *
  3227. * Licensed under the Apache License, Version 2.0 (the "License");
  3228. * you may not use this file except in compliance with the License.
  3229. * You may obtain a copy of the License at
  3230. *
  3231. * http://www.apache.org/licenses/LICENSE-2.0
  3232. *
  3233. * Unless required by applicable law or agreed to in writing, software
  3234. * distributed under the License is distributed on an "AS IS" BASIS,
  3235. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3236. * See the License for the specific language governing permissions and
  3237. * limitations under the License.
  3238. */
  3239. var TransmuxingEvents = {
  3240. IO_ERROR: 'io_error',
  3241. DEMUX_ERROR: 'demux_error',
  3242. INIT_SEGMENT: 'init_segment',
  3243. MEDIA_SEGMENT: 'media_segment',
  3244. LOADING_COMPLETE: 'loading_complete',
  3245. RECOVERED_EARLY_EOF: 'recovered_early_eof',
  3246. MEDIA_INFO: 'media_info',
  3247. STATISTICS_INFO: 'statistics_info',
  3248. RECOMMEND_SEEKPOINT: 'recommend_seekpoint'
  3249. };
  3250. exports.default = TransmuxingEvents;
  3251. },{}],14:[function(_dereq_,module,exports){
  3252. 'use strict';
  3253. Object.defineProperty(exports, "__esModule", {
  3254. value: true
  3255. });
  3256. var _logger = _dereq_('../utils/logger.js');
  3257. var _logger2 = _interopRequireDefault(_logger);
  3258. var _loggingControl = _dereq_('../utils/logging-control.js');
  3259. var _loggingControl2 = _interopRequireDefault(_loggingControl);
  3260. var _polyfill = _dereq_('../utils/polyfill.js');
  3261. var _polyfill2 = _interopRequireDefault(_polyfill);
  3262. var _transmuxingController = _dereq_('./transmuxing-controller.js');
  3263. var _transmuxingController2 = _interopRequireDefault(_transmuxingController);
  3264. var _transmuxingEvents = _dereq_('./transmuxing-events.js');
  3265. var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
  3266. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  3267. /* post message to worker:
  3268. data: {
  3269. cmd: string
  3270. param: any
  3271. }
  3272. receive message from worker:
  3273. data: {
  3274. msg: string,
  3275. data: any
  3276. }
  3277. */
  3278. var TransmuxingWorker = function TransmuxingWorker(self) {
  3279. var TAG = 'TransmuxingWorker';
  3280. var controller = null;
  3281. var logcatListener = onLogcatCallback.bind(this);
  3282. _polyfill2.default.install();
  3283. self.addEventListener('message', function (e) {
  3284. switch (e.data.cmd) {
  3285. case 'init':
  3286. controller = new _transmuxingController2.default(e.data.param[0], e.data.param[1]);
  3287. controller.on(_transmuxingEvents2.default.IO_ERROR, onIOError.bind(this));
  3288. controller.on(_transmuxingEvents2.default.DEMUX_ERROR, onDemuxError.bind(this));
  3289. controller.on(_transmuxingEvents2.default.INIT_SEGMENT, onInitSegment.bind(this));
  3290. controller.on(_transmuxingEvents2.default.MEDIA_SEGMENT, onMediaSegment.bind(this));
  3291. controller.on(_transmuxingEvents2.default.LOADING_COMPLETE, onLoadingComplete.bind(this));
  3292. controller.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF, onRecoveredEarlyEof.bind(this));
  3293. controller.on(_transmuxingEvents2.default.MEDIA_INFO, onMediaInfo.bind(this));
  3294. controller.on(_transmuxingEvents2.default.STATISTICS_INFO, onStatisticsInfo.bind(this));
  3295. controller.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, onRecommendSeekpoint.bind(this));
  3296. break;
  3297. case 'destroy':
  3298. if (controller) {
  3299. controller.destroy();
  3300. controller = null;
  3301. }
  3302. self.postMessage({ msg: 'destroyed' });
  3303. break;
  3304. case 'start':
  3305. controller.start();
  3306. break;
  3307. case 'stop':
  3308. controller.stop();
  3309. break;
  3310. case 'seek':
  3311. controller.seek(e.data.param);
  3312. break;
  3313. case 'pause':
  3314. controller.pause();
  3315. break;
  3316. case 'resume':
  3317. controller.resume();
  3318. break;
  3319. case 'logging_config':
  3320. {
  3321. var config = e.data.param;
  3322. _loggingControl2.default.applyConfig(config);
  3323. if (config.enableCallback === true) {
  3324. _loggingControl2.default.addLogListener(logcatListener);
  3325. } else {
  3326. _loggingControl2.default.removeLogListener(logcatListener);
  3327. }
  3328. break;
  3329. }
  3330. }
  3331. });
  3332. function onInitSegment(type, initSegment) {
  3333. var obj = {
  3334. msg: _transmuxingEvents2.default.INIT_SEGMENT,
  3335. data: {
  3336. type: type,
  3337. data: initSegment
  3338. }
  3339. };
  3340. self.postMessage(obj, [initSegment.data]); // data: ArrayBuffer
  3341. }
  3342. function onMediaSegment(type, mediaSegment) {
  3343. var obj = {
  3344. msg: _transmuxingEvents2.default.MEDIA_SEGMENT,
  3345. data: {
  3346. type: type,
  3347. data: mediaSegment
  3348. }
  3349. };
  3350. self.postMessage(obj, [mediaSegment.data]); // data: ArrayBuffer
  3351. }
  3352. function onLoadingComplete() {
  3353. var obj = {
  3354. msg: _transmuxingEvents2.default.LOADING_COMPLETE
  3355. };
  3356. self.postMessage(obj);
  3357. }
  3358. function onRecoveredEarlyEof() {
  3359. var obj = {
  3360. msg: _transmuxingEvents2.default.RECOVERED_EARLY_EOF
  3361. };
  3362. self.postMessage(obj);
  3363. }
  3364. function onMediaInfo(mediaInfo) {
  3365. var obj = {
  3366. msg: _transmuxingEvents2.default.MEDIA_INFO,
  3367. data: mediaInfo
  3368. };
  3369. self.postMessage(obj);
  3370. }
  3371. function onStatisticsInfo(statInfo) {
  3372. var obj = {
  3373. msg: _transmuxingEvents2.default.STATISTICS_INFO,
  3374. data: statInfo
  3375. };
  3376. self.postMessage(obj);
  3377. }
  3378. function onIOError(type, info) {
  3379. self.postMessage({
  3380. msg: _transmuxingEvents2.default.IO_ERROR,
  3381. data: {
  3382. type: type,
  3383. info: info
  3384. }
  3385. });
  3386. }
  3387. function onDemuxError(type, info) {
  3388. self.postMessage({
  3389. msg: _transmuxingEvents2.default.DEMUX_ERROR,
  3390. data: {
  3391. type: type,
  3392. info: info
  3393. }
  3394. });
  3395. }
  3396. function onRecommendSeekpoint(milliseconds) {
  3397. self.postMessage({
  3398. msg: _transmuxingEvents2.default.RECOMMEND_SEEKPOINT,
  3399. data: milliseconds
  3400. });
  3401. }
  3402. function onLogcatCallback(type, str) {
  3403. self.postMessage({
  3404. msg: 'logcat_callback',
  3405. data: {
  3406. type: type,
  3407. logcat: str
  3408. }
  3409. });
  3410. }
  3411. }; /*
  3412. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  3413. *
  3414. * @author zheng qian <xqq@xqq.im>
  3415. *
  3416. * Licensed under the Apache License, Version 2.0 (the "License");
  3417. * you may not use this file except in compliance with the License.
  3418. * You may obtain a copy of the License at
  3419. *
  3420. * http://www.apache.org/licenses/LICENSE-2.0
  3421. *
  3422. * Unless required by applicable law or agreed to in writing, software
  3423. * distributed under the License is distributed on an "AS IS" BASIS,
  3424. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3425. * See the License for the specific language governing permissions and
  3426. * limitations under the License.
  3427. */
  3428. exports.default = TransmuxingWorker;
  3429. },{"../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){
  3430. 'use strict';
  3431. Object.defineProperty(exports, "__esModule", {
  3432. value: true
  3433. });
  3434. 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; }; }(); /*
  3435. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  3436. *
  3437. * @author zheng qian <xqq@xqq.im>
  3438. *
  3439. * Licensed under the Apache License, Version 2.0 (the "License");
  3440. * you may not use this file except in compliance with the License.
  3441. * You may obtain a copy of the License at
  3442. *
  3443. * http://www.apache.org/licenses/LICENSE-2.0
  3444. *
  3445. * Unless required by applicable law or agreed to in writing, software
  3446. * distributed under the License is distributed on an "AS IS" BASIS,
  3447. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3448. * See the License for the specific language governing permissions and
  3449. * limitations under the License.
  3450. */
  3451. var _logger = _dereq_('../utils/logger.js');
  3452. var _logger2 = _interopRequireDefault(_logger);
  3453. var _utf8Conv = _dereq_('../utils/utf8-conv.js');
  3454. var _utf8Conv2 = _interopRequireDefault(_utf8Conv);
  3455. var _exception = _dereq_('../utils/exception.js');
  3456. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  3457. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3458. var le = function () {
  3459. var buf = new ArrayBuffer(2);
  3460. new DataView(buf).setInt16(0, 256, true); // little-endian write
  3461. return new Int16Array(buf)[0] === 256; // platform-spec read, if equal then LE
  3462. }();
  3463. var AMF = function () {
  3464. function AMF() {
  3465. _classCallCheck(this, AMF);
  3466. }
  3467. _createClass(AMF, null, [{
  3468. key: 'parseScriptData',
  3469. value: function parseScriptData(arrayBuffer, dataOffset, dataSize) {
  3470. var data = {};
  3471. try {
  3472. var name = AMF.parseValue(arrayBuffer, dataOffset, dataSize);
  3473. var value = AMF.parseValue(arrayBuffer, dataOffset + name.size, dataSize - name.size);
  3474. data[name.data] = value.data;
  3475. } catch (e) {
  3476. _logger2.default.e('AMF', e.toString());
  3477. }
  3478. return data;
  3479. }
  3480. }, {
  3481. key: 'parseObject',
  3482. value: function parseObject(arrayBuffer, dataOffset, dataSize) {
  3483. if (dataSize < 3) {
  3484. throw new _exception.IllegalStateException('Data not enough when parse ScriptDataObject');
  3485. }
  3486. var name = AMF.parseString(arrayBuffer, dataOffset, dataSize);
  3487. var value = AMF.parseValue(arrayBuffer, dataOffset + name.size, dataSize - name.size);
  3488. var isObjectEnd = value.objectEnd;
  3489. return {
  3490. data: {
  3491. name: name.data,
  3492. value: value.data
  3493. },
  3494. size: name.size + value.size,
  3495. objectEnd: isObjectEnd
  3496. };
  3497. }
  3498. }, {
  3499. key: 'parseVariable',
  3500. value: function parseVariable(arrayBuffer, dataOffset, dataSize) {
  3501. return AMF.parseObject(arrayBuffer, dataOffset, dataSize);
  3502. }
  3503. }, {
  3504. key: 'parseString',
  3505. value: function parseString(arrayBuffer, dataOffset, dataSize) {
  3506. if (dataSize < 2) {
  3507. throw new _exception.IllegalStateException('Data not enough when parse String');
  3508. }
  3509. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  3510. var length = v.getUint16(0, !le);
  3511. var str = void 0;
  3512. if (length > 0) {
  3513. str = (0, _utf8Conv2.default)(new Uint8Array(arrayBuffer, dataOffset + 2, length));
  3514. } else {
  3515. str = '';
  3516. }
  3517. return {
  3518. data: str,
  3519. size: 2 + length
  3520. };
  3521. }
  3522. }, {
  3523. key: 'parseLongString',
  3524. value: function parseLongString(arrayBuffer, dataOffset, dataSize) {
  3525. if (dataSize < 4) {
  3526. throw new _exception.IllegalStateException('Data not enough when parse LongString');
  3527. }
  3528. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  3529. var length = v.getUint32(0, !le);
  3530. var str = void 0;
  3531. if (length > 0) {
  3532. str = (0, _utf8Conv2.default)(new Uint8Array(arrayBuffer, dataOffset + 4, length));
  3533. } else {
  3534. str = '';
  3535. }
  3536. return {
  3537. data: str,
  3538. size: 4 + length
  3539. };
  3540. }
  3541. }, {
  3542. key: 'parseDate',
  3543. value: function parseDate(arrayBuffer, dataOffset, dataSize) {
  3544. if (dataSize < 10) {
  3545. throw new _exception.IllegalStateException('Data size invalid when parse Date');
  3546. }
  3547. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  3548. var timestamp = v.getFloat64(0, !le);
  3549. var localTimeOffset = v.getInt16(8, !le);
  3550. timestamp += localTimeOffset * 60 * 1000; // get UTC time
  3551. return {
  3552. data: new Date(timestamp),
  3553. size: 8 + 2
  3554. };
  3555. }
  3556. }, {
  3557. key: 'parseValue',
  3558. value: function parseValue(arrayBuffer, dataOffset, dataSize) {
  3559. if (dataSize < 1) {
  3560. throw new _exception.IllegalStateException('Data not enough when parse Value');
  3561. }
  3562. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  3563. var offset = 1;
  3564. var type = v.getUint8(0);
  3565. var value = void 0;
  3566. var objectEnd = false;
  3567. try {
  3568. switch (type) {
  3569. case 0:
  3570. // Number(Double) type
  3571. value = v.getFloat64(1, !le);
  3572. offset += 8;
  3573. break;
  3574. case 1:
  3575. {
  3576. // Boolean type
  3577. var b = v.getUint8(1);
  3578. value = b ? true : false;
  3579. offset += 1;
  3580. break;
  3581. }
  3582. case 2:
  3583. {
  3584. // String type
  3585. var amfstr = AMF.parseString(arrayBuffer, dataOffset + 1, dataSize - 1);
  3586. value = amfstr.data;
  3587. offset += amfstr.size;
  3588. break;
  3589. }
  3590. case 3:
  3591. {
  3592. // Object(s) type
  3593. value = {};
  3594. var terminal = 0; // workaround for malformed Objects which has missing ScriptDataObjectEnd
  3595. if ((v.getUint32(dataSize - 4, !le) & 0x00FFFFFF) === 9) {
  3596. terminal = 3;
  3597. }
  3598. while (offset < dataSize - 4) {
  3599. // 4 === type(UI8) + ScriptDataObjectEnd(UI24)
  3600. var amfobj = AMF.parseObject(arrayBuffer, dataOffset + offset, dataSize - offset - terminal);
  3601. if (amfobj.objectEnd) break;
  3602. value[amfobj.data.name] = amfobj.data.value;
  3603. offset += amfobj.size;
  3604. }
  3605. if (offset <= dataSize - 3) {
  3606. var marker = v.getUint32(offset - 1, !le) & 0x00FFFFFF;
  3607. if (marker === 9) {
  3608. offset += 3;
  3609. }
  3610. }
  3611. break;
  3612. }
  3613. case 8:
  3614. {
  3615. // ECMA array type (Mixed array)
  3616. value = {};
  3617. offset += 4; // ECMAArrayLength(UI32)
  3618. var _terminal = 0; // workaround for malformed MixedArrays which has missing ScriptDataObjectEnd
  3619. if ((v.getUint32(dataSize - 4, !le) & 0x00FFFFFF) === 9) {
  3620. _terminal = 3;
  3621. }
  3622. while (offset < dataSize - 8) {
  3623. // 8 === type(UI8) + ECMAArrayLength(UI32) + ScriptDataVariableEnd(UI24)
  3624. var amfvar = AMF.parseVariable(arrayBuffer, dataOffset + offset, dataSize - offset - _terminal);
  3625. if (amfvar.objectEnd) break;
  3626. value[amfvar.data.name] = amfvar.data.value;
  3627. offset += amfvar.size;
  3628. }
  3629. if (offset <= dataSize - 3) {
  3630. var _marker = v.getUint32(offset - 1, !le) & 0x00FFFFFF;
  3631. if (_marker === 9) {
  3632. offset += 3;
  3633. }
  3634. }
  3635. break;
  3636. }
  3637. case 9:
  3638. // ScriptDataObjectEnd
  3639. value = undefined;
  3640. offset = 1;
  3641. objectEnd = true;
  3642. break;
  3643. case 10:
  3644. {
  3645. // Strict array type
  3646. // ScriptDataValue[n]. NOTE: according to video_file_format_spec_v10_1.pdf
  3647. value = [];
  3648. var strictArrayLength = v.getUint32(1, !le);
  3649. offset += 4;
  3650. for (var i = 0; i < strictArrayLength; i++) {
  3651. var val = AMF.parseValue(arrayBuffer, dataOffset + offset, dataSize - offset);
  3652. value.push(val.data);
  3653. offset += val.size;
  3654. }
  3655. break;
  3656. }
  3657. case 11:
  3658. {
  3659. // Date type
  3660. var date = AMF.parseDate(arrayBuffer, dataOffset + 1, dataSize - 1);
  3661. value = date.data;
  3662. offset += date.size;
  3663. break;
  3664. }
  3665. case 12:
  3666. {
  3667. // Long string type
  3668. var amfLongStr = AMF.parseString(arrayBuffer, dataOffset + 1, dataSize - 1);
  3669. value = amfLongStr.data;
  3670. offset += amfLongStr.size;
  3671. break;
  3672. }
  3673. default:
  3674. // ignore and skip
  3675. offset = dataSize;
  3676. _logger2.default.w('AMF', 'Unsupported AMF value type ' + type);
  3677. }
  3678. } catch (e) {
  3679. _logger2.default.e('AMF', e.toString());
  3680. }
  3681. return {
  3682. data: value,
  3683. size: offset,
  3684. objectEnd: objectEnd
  3685. };
  3686. }
  3687. }]);
  3688. return AMF;
  3689. }();
  3690. exports.default = AMF;
  3691. },{"../utils/exception.js":40,"../utils/logger.js":41,"../utils/utf8-conv.js":44}],16:[function(_dereq_,module,exports){
  3692. 'use strict';
  3693. Object.defineProperty(exports, "__esModule", {
  3694. value: true
  3695. });
  3696. /*
  3697. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  3698. *
  3699. * @author zheng qian <xqq@xqq.im>
  3700. *
  3701. * Licensed under the Apache License, Version 2.0 (the "License");
  3702. * you may not use this file except in compliance with the License.
  3703. * You may obtain a copy of the License at
  3704. *
  3705. * http://www.apache.org/licenses/LICENSE-2.0
  3706. *
  3707. * Unless required by applicable law or agreed to in writing, software
  3708. * distributed under the License is distributed on an "AS IS" BASIS,
  3709. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3710. * See the License for the specific language governing permissions and
  3711. * limitations under the License.
  3712. */
  3713. var DemuxErrors = {
  3714. OK: 'OK',
  3715. FORMAT_ERROR: 'FormatError',
  3716. FORMAT_UNSUPPORTED: 'FormatUnsupported',
  3717. CODEC_UNSUPPORTED: 'CodecUnsupported'
  3718. };
  3719. exports.default = DemuxErrors;
  3720. },{}],17:[function(_dereq_,module,exports){
  3721. 'use strict';
  3722. Object.defineProperty(exports, "__esModule", {
  3723. value: true
  3724. });
  3725. 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; }; }(); /*
  3726. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  3727. *
  3728. * @author zheng qian <xqq@xqq.im>
  3729. *
  3730. * Licensed under the Apache License, Version 2.0 (the "License");
  3731. * you may not use this file except in compliance with the License.
  3732. * You may obtain a copy of the License at
  3733. *
  3734. * http://www.apache.org/licenses/LICENSE-2.0
  3735. *
  3736. * Unless required by applicable law or agreed to in writing, software
  3737. * distributed under the License is distributed on an "AS IS" BASIS,
  3738. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3739. * See the License for the specific language governing permissions and
  3740. * limitations under the License.
  3741. */
  3742. var _exception = _dereq_('../utils/exception.js');
  3743. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3744. // Exponential-Golomb buffer decoder
  3745. var ExpGolomb = function () {
  3746. function ExpGolomb(uint8array) {
  3747. _classCallCheck(this, ExpGolomb);
  3748. this.TAG = 'ExpGolomb';
  3749. this._buffer = uint8array;
  3750. this._buffer_index = 0;
  3751. this._total_bytes = uint8array.byteLength;
  3752. this._total_bits = uint8array.byteLength * 8;
  3753. this._current_word = 0;
  3754. this._current_word_bits_left = 0;
  3755. }
  3756. _createClass(ExpGolomb, [{
  3757. key: 'destroy',
  3758. value: function destroy() {
  3759. this._buffer = null;
  3760. }
  3761. }, {
  3762. key: '_fillCurrentWord',
  3763. value: function _fillCurrentWord() {
  3764. var buffer_bytes_left = this._total_bytes - this._buffer_index;
  3765. if (buffer_bytes_left <= 0) throw new _exception.IllegalStateException('ExpGolomb: _fillCurrentWord() but no bytes available');
  3766. var bytes_read = Math.min(4, buffer_bytes_left);
  3767. var word = new Uint8Array(4);
  3768. word.set(this._buffer.subarray(this._buffer_index, this._buffer_index + bytes_read));
  3769. this._current_word = new DataView(word.buffer).getUint32(0, false);
  3770. this._buffer_index += bytes_read;
  3771. this._current_word_bits_left = bytes_read * 8;
  3772. }
  3773. }, {
  3774. key: 'readBits',
  3775. value: function readBits(bits) {
  3776. if (bits > 32) throw new _exception.InvalidArgumentException('ExpGolomb: readBits() bits exceeded max 32bits!');
  3777. if (bits <= this._current_word_bits_left) {
  3778. var _result = this._current_word >>> 32 - bits;
  3779. this._current_word <<= bits;
  3780. this._current_word_bits_left -= bits;
  3781. return _result;
  3782. }
  3783. var result = this._current_word_bits_left ? this._current_word : 0;
  3784. result = result >>> 32 - this._current_word_bits_left;
  3785. var bits_need_left = bits - this._current_word_bits_left;
  3786. this._fillCurrentWord();
  3787. var bits_read_next = Math.min(bits_need_left, this._current_word_bits_left);
  3788. var result2 = this._current_word >>> 32 - bits_read_next;
  3789. this._current_word <<= bits_read_next;
  3790. this._current_word_bits_left -= bits_read_next;
  3791. result = result << bits_read_next | result2;
  3792. return result;
  3793. }
  3794. }, {
  3795. key: 'readBool',
  3796. value: function readBool() {
  3797. return this.readBits(1) === 1;
  3798. }
  3799. }, {
  3800. key: 'readByte',
  3801. value: function readByte() {
  3802. return this.readBits(8);
  3803. }
  3804. }, {
  3805. key: '_skipLeadingZero',
  3806. value: function _skipLeadingZero() {
  3807. var zero_count = void 0;
  3808. for (zero_count = 0; zero_count < this._current_word_bits_left; zero_count++) {
  3809. if (0 !== (this._current_word & 0x80000000 >>> zero_count)) {
  3810. this._current_word <<= zero_count;
  3811. this._current_word_bits_left -= zero_count;
  3812. return zero_count;
  3813. }
  3814. }
  3815. this._fillCurrentWord();
  3816. return zero_count + this._skipLeadingZero();
  3817. }
  3818. }, {
  3819. key: 'readUEG',
  3820. value: function readUEG() {
  3821. // unsigned exponential golomb
  3822. var leading_zeros = this._skipLeadingZero();
  3823. return this.readBits(leading_zeros + 1) - 1;
  3824. }
  3825. }, {
  3826. key: 'readSEG',
  3827. value: function readSEG() {
  3828. // signed exponential golomb
  3829. var value = this.readUEG();
  3830. if (value & 0x01) {
  3831. return value + 1 >>> 1;
  3832. } else {
  3833. return -1 * (value >>> 1);
  3834. }
  3835. }
  3836. }]);
  3837. return ExpGolomb;
  3838. }();
  3839. exports.default = ExpGolomb;
  3840. },{"../utils/exception.js":40}],18:[function(_dereq_,module,exports){
  3841. 'use strict';
  3842. Object.defineProperty(exports, "__esModule", {
  3843. value: true
  3844. });
  3845. 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; };
  3846. 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; }; }(); /*
  3847. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  3848. *
  3849. * @author zheng qian <xqq@xqq.im>
  3850. *
  3851. * Licensed under the Apache License, Version 2.0 (the "License");
  3852. * you may not use this file except in compliance with the License.
  3853. * You may obtain a copy of the License at
  3854. *
  3855. * http://www.apache.org/licenses/LICENSE-2.0
  3856. *
  3857. * Unless required by applicable law or agreed to in writing, software
  3858. * distributed under the License is distributed on an "AS IS" BASIS,
  3859. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3860. * See the License for the specific language governing permissions and
  3861. * limitations under the License.
  3862. */
  3863. var _logger = _dereq_('../utils/logger.js');
  3864. var _logger2 = _interopRequireDefault(_logger);
  3865. var _amfParser = _dereq_('./amf-parser.js');
  3866. var _amfParser2 = _interopRequireDefault(_amfParser);
  3867. var _spsParser = _dereq_('./sps-parser.js');
  3868. var _spsParser2 = _interopRequireDefault(_spsParser);
  3869. var _demuxErrors = _dereq_('./demux-errors.js');
  3870. var _demuxErrors2 = _interopRequireDefault(_demuxErrors);
  3871. var _mediaInfo = _dereq_('../core/media-info.js');
  3872. var _mediaInfo2 = _interopRequireDefault(_mediaInfo);
  3873. var _exception = _dereq_('../utils/exception.js');
  3874. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  3875. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3876. function Swap16(src) {
  3877. return src >>> 8 & 0xFF | (src & 0xFF) << 8;
  3878. }
  3879. function Swap32(src) {
  3880. return (src & 0xFF000000) >>> 24 | (src & 0x00FF0000) >>> 8 | (src & 0x0000FF00) << 8 | (src & 0x000000FF) << 24;
  3881. }
  3882. function ReadBig32(array, index) {
  3883. return array[index] << 24 | array[index + 1] << 16 | array[index + 2] << 8 | array[index + 3];
  3884. }
  3885. var FLVDemuxer = function () {
  3886. function FLVDemuxer(probeData, config) {
  3887. _classCallCheck(this, FLVDemuxer);
  3888. this.TAG = 'FLVDemuxer';
  3889. this._config = config;
  3890. this._onError = null;
  3891. this._onMediaInfo = null;
  3892. this._onTrackMetadata = null;
  3893. this._onDataAvailable = null;
  3894. this._dataOffset = probeData.dataOffset;
  3895. this._firstParse = true;
  3896. this._dispatch = false;
  3897. this._hasAudio = probeData.hasAudioTrack;
  3898. this._hasVideo = probeData.hasVideoTrack;
  3899. this._hasAudioFlagOverrided = false;
  3900. this._hasVideoFlagOverrided = false;
  3901. this._audioInitialMetadataDispatched = false;
  3902. this._videoInitialMetadataDispatched = false;
  3903. this._mediaInfo = new _mediaInfo2.default();
  3904. this._mediaInfo.hasAudio = this._hasAudio;
  3905. this._mediaInfo.hasVideo = this._hasVideo;
  3906. this._metadata = null;
  3907. this._audioMetadata = null;
  3908. this._videoMetadata = null;
  3909. this._naluLengthSize = 4;
  3910. this._timestampBase = 0; // int32, in milliseconds
  3911. this._timescale = 1000;
  3912. this._duration = 0; // int32, in milliseconds
  3913. this._durationOverrided = false;
  3914. this._referenceFrameRate = {
  3915. fixed: true,
  3916. fps: 23.976,
  3917. fps_num: 23976,
  3918. fps_den: 1000
  3919. };
  3920. this._flvSoundRateTable = [5500, 11025, 22050, 44100, 48000];
  3921. this._mpegSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  3922. this._mpegAudioV10SampleRateTable = [44100, 48000, 32000, 0];
  3923. this._mpegAudioV20SampleRateTable = [22050, 24000, 16000, 0];
  3924. this._mpegAudioV25SampleRateTable = [11025, 12000, 8000, 0];
  3925. this._mpegAudioL1BitRateTable = [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, -1];
  3926. this._mpegAudioL2BitRateTable = [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, -1];
  3927. this._mpegAudioL3BitRateTable = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1];
  3928. this._videoTrack = { type: 'video', id: 1, sequenceNumber: 0, samples: [], length: 0 };
  3929. this._audioTrack = { type: 'audio', id: 2, sequenceNumber: 0, samples: [], length: 0 };
  3930. this._littleEndian = function () {
  3931. var buf = new ArrayBuffer(2);
  3932. new DataView(buf).setInt16(0, 256, true); // little-endian write
  3933. return new Int16Array(buf)[0] === 256; // platform-spec read, if equal then LE
  3934. }();
  3935. }
  3936. _createClass(FLVDemuxer, [{
  3937. key: 'destroy',
  3938. value: function destroy() {
  3939. this._mediaInfo = null;
  3940. this._metadata = null;
  3941. this._audioMetadata = null;
  3942. this._videoMetadata = null;
  3943. this._videoTrack = null;
  3944. this._audioTrack = null;
  3945. this._onError = null;
  3946. this._onMediaInfo = null;
  3947. this._onTrackMetadata = null;
  3948. this._onDataAvailable = null;
  3949. }
  3950. }, {
  3951. key: 'bindDataSource',
  3952. value: function bindDataSource(loader) {
  3953. loader.onDataArrival = this.parseChunks.bind(this);
  3954. return this;
  3955. }
  3956. // prototype: function(type: string, metadata: any): void
  3957. }, {
  3958. key: 'resetMediaInfo',
  3959. value: function resetMediaInfo() {
  3960. this._mediaInfo = new _mediaInfo2.default();
  3961. }
  3962. }, {
  3963. key: '_isInitialMetadataDispatched',
  3964. value: function _isInitialMetadataDispatched() {
  3965. if (this._hasAudio && this._hasVideo) {
  3966. // both audio & video
  3967. return this._audioInitialMetadataDispatched && this._videoInitialMetadataDispatched;
  3968. }
  3969. if (this._hasAudio && !this._hasVideo) {
  3970. // audio only
  3971. return this._audioInitialMetadataDispatched;
  3972. }
  3973. if (!this._hasAudio && this._hasVideo) {
  3974. // video only
  3975. return this._videoInitialMetadataDispatched;
  3976. }
  3977. return false;
  3978. }
  3979. // function parseChunks(chunk: ArrayBuffer, byteStart: number): number;
  3980. }, {
  3981. key: 'parseChunks',
  3982. value: function parseChunks(chunk, byteStart) {
  3983. if (!this._onError || !this._onMediaInfo || !this._onTrackMetadata || !this._onDataAvailable) {
  3984. throw new _exception.IllegalStateException('Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified');
  3985. }
  3986. var offset = 0;
  3987. var le = this._littleEndian;
  3988. if (byteStart === 0) {
  3989. // buffer with FLV header
  3990. if (chunk.byteLength > 13) {
  3991. var probeData = FLVDemuxer.probe(chunk);
  3992. offset = probeData.dataOffset;
  3993. } else {
  3994. return 0;
  3995. }
  3996. }
  3997. if (this._firstParse) {
  3998. // handle PreviousTagSize0 before Tag1
  3999. this._firstParse = false;
  4000. if (byteStart + offset !== this._dataOffset) {
  4001. _logger2.default.w(this.TAG, 'First time parsing but chunk byteStart invalid!');
  4002. }
  4003. var v = new DataView(chunk, offset);
  4004. var prevTagSize0 = v.getUint32(0, !le);
  4005. if (prevTagSize0 !== 0) {
  4006. _logger2.default.w(this.TAG, 'PrevTagSize0 !== 0 !!!');
  4007. }
  4008. offset += 4;
  4009. }
  4010. while (offset < chunk.byteLength) {
  4011. this._dispatch = true;
  4012. var _v = new DataView(chunk, offset);
  4013. if (offset + 11 + 4 > chunk.byteLength) {
  4014. // data not enough for parsing an flv tag
  4015. break;
  4016. }
  4017. var tagType = _v.getUint8(0);
  4018. var dataSize = _v.getUint32(0, !le) & 0x00FFFFFF;
  4019. if (offset + 11 + dataSize + 4 > chunk.byteLength) {
  4020. // data not enough for parsing actual data body
  4021. break;
  4022. }
  4023. if (tagType !== 8 && tagType !== 9 && tagType !== 18) {
  4024. _logger2.default.w(this.TAG, 'Unsupported tag type ' + tagType + ', skipped');
  4025. // consume the whole tag (skip it)
  4026. offset += 11 + dataSize + 4;
  4027. continue;
  4028. }
  4029. var ts2 = _v.getUint8(4);
  4030. var ts1 = _v.getUint8(5);
  4031. var ts0 = _v.getUint8(6);
  4032. var ts3 = _v.getUint8(7);
  4033. var timestamp = ts0 | ts1 << 8 | ts2 << 16 | ts3 << 24;
  4034. var streamId = _v.getUint32(7, !le) & 0x00FFFFFF;
  4035. if (streamId !== 0) {
  4036. _logger2.default.w(this.TAG, 'Meet tag which has StreamID != 0!');
  4037. }
  4038. var dataOffset = offset + 11;
  4039. switch (tagType) {
  4040. case 8:
  4041. // Audio
  4042. this._parseAudioData(chunk, dataOffset, dataSize, timestamp);
  4043. break;
  4044. case 9:
  4045. // Video
  4046. this._parseVideoData(chunk, dataOffset, dataSize, timestamp, byteStart + offset);
  4047. break;
  4048. case 18:
  4049. // ScriptDataObject
  4050. this._parseScriptData(chunk, dataOffset, dataSize);
  4051. break;
  4052. }
  4053. var prevTagSize = _v.getUint32(11 + dataSize, !le);
  4054. if (prevTagSize !== 11 + dataSize) {
  4055. _logger2.default.w(this.TAG, 'Invalid PrevTagSize ' + prevTagSize);
  4056. }
  4057. offset += 11 + dataSize + 4; // tagBody + dataSize + prevTagSize
  4058. }
  4059. // dispatch parsed frames to consumer (typically, the remuxer)
  4060. if (this._isInitialMetadataDispatched()) {
  4061. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  4062. this._onDataAvailable(this._audioTrack, this._videoTrack);
  4063. }
  4064. }
  4065. return offset; // consumed bytes, just equals latest offset index
  4066. }
  4067. }, {
  4068. key: '_parseScriptData',
  4069. value: function _parseScriptData(arrayBuffer, dataOffset, dataSize) {
  4070. var scriptData = _amfParser2.default.parseScriptData(arrayBuffer, dataOffset, dataSize);
  4071. if (scriptData.hasOwnProperty('onMetaData')) {
  4072. if (scriptData.onMetaData == null || _typeof(scriptData.onMetaData) !== 'object') {
  4073. _logger2.default.w(this.TAG, 'Invalid onMetaData structure!');
  4074. return;
  4075. }
  4076. if (this._metadata) {
  4077. _logger2.default.w(this.TAG, 'Found another onMetaData tag!');
  4078. }
  4079. this._metadata = scriptData;
  4080. var onMetaData = this._metadata.onMetaData;
  4081. if (typeof onMetaData.hasAudio === 'boolean') {
  4082. // hasAudio
  4083. if (this._hasAudioFlagOverrided === false) {
  4084. this._hasAudio = onMetaData.hasAudio;
  4085. this._mediaInfo.hasAudio = this._hasAudio;
  4086. }
  4087. }
  4088. if (typeof onMetaData.hasVideo === 'boolean') {
  4089. // hasVideo
  4090. if (this._hasVideoFlagOverrided === false) {
  4091. this._hasVideo = onMetaData.hasVideo;
  4092. this._mediaInfo.hasVideo = this._hasVideo;
  4093. }
  4094. }
  4095. if (typeof onMetaData.audiodatarate === 'number') {
  4096. // audiodatarate
  4097. this._mediaInfo.audioDataRate = onMetaData.audiodatarate;
  4098. }
  4099. if (typeof onMetaData.videodatarate === 'number') {
  4100. // videodatarate
  4101. this._mediaInfo.videoDataRate = onMetaData.videodatarate;
  4102. }
  4103. if (typeof onMetaData.width === 'number') {
  4104. // width
  4105. this._mediaInfo.width = onMetaData.width;
  4106. }
  4107. if (typeof onMetaData.height === 'number') {
  4108. // height
  4109. this._mediaInfo.height = onMetaData.height;
  4110. }
  4111. if (typeof onMetaData.duration === 'number') {
  4112. // duration
  4113. if (!this._durationOverrided) {
  4114. var duration = Math.floor(onMetaData.duration * this._timescale);
  4115. this._duration = duration;
  4116. this._mediaInfo.duration = duration;
  4117. }
  4118. } else {
  4119. this._mediaInfo.duration = 0;
  4120. }
  4121. if (typeof onMetaData.framerate === 'number') {
  4122. // framerate
  4123. var fps_num = Math.floor(onMetaData.framerate * 1000);
  4124. if (fps_num > 0) {
  4125. var fps = fps_num / 1000;
  4126. this._referenceFrameRate.fixed = true;
  4127. this._referenceFrameRate.fps = fps;
  4128. this._referenceFrameRate.fps_num = fps_num;
  4129. this._referenceFrameRate.fps_den = 1000;
  4130. this._mediaInfo.fps = fps;
  4131. }
  4132. }
  4133. if (_typeof(onMetaData.keyframes) === 'object') {
  4134. // keyframes
  4135. this._mediaInfo.hasKeyframesIndex = true;
  4136. var keyframes = onMetaData.keyframes;
  4137. this._mediaInfo.keyframesIndex = this._parseKeyframesIndex(keyframes);
  4138. onMetaData.keyframes = null; // keyframes has been extracted, remove it
  4139. } else {
  4140. this._mediaInfo.hasKeyframesIndex = false;
  4141. }
  4142. this._dispatch = false;
  4143. this._mediaInfo.metadata = onMetaData;
  4144. _logger2.default.v(this.TAG, 'Parsed onMetaData');
  4145. if (this._mediaInfo.isComplete()) {
  4146. this._onMediaInfo(this._mediaInfo);
  4147. }
  4148. }
  4149. }
  4150. }, {
  4151. key: '_parseKeyframesIndex',
  4152. value: function _parseKeyframesIndex(keyframes) {
  4153. var times = [];
  4154. var filepositions = [];
  4155. // ignore first keyframe which is actually AVC Sequence Header (AVCDecoderConfigurationRecord)
  4156. for (var i = 1; i < keyframes.times.length; i++) {
  4157. var time = this._timestampBase + Math.floor(keyframes.times[i] * 1000);
  4158. times.push(time);
  4159. filepositions.push(keyframes.filepositions[i]);
  4160. }
  4161. return {
  4162. times: times,
  4163. filepositions: filepositions
  4164. };
  4165. }
  4166. }, {
  4167. key: '_parseAudioData',
  4168. value: function _parseAudioData(arrayBuffer, dataOffset, dataSize, tagTimestamp) {
  4169. if (dataSize <= 1) {
  4170. _logger2.default.w(this.TAG, 'Flv: Invalid audio packet, missing SoundData payload!');
  4171. return;
  4172. }
  4173. if (this._hasAudioFlagOverrided === true && this._hasAudio === false) {
  4174. // If hasAudio: false indicated explicitly in MediaDataSource,
  4175. // Ignore all the audio packets
  4176. return;
  4177. }
  4178. var le = this._littleEndian;
  4179. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  4180. var soundSpec = v.getUint8(0);
  4181. var soundFormat = soundSpec >>> 4;
  4182. if (soundFormat !== 2 && soundFormat !== 10) {
  4183. // MP3 or AAC
  4184. this._onError(_demuxErrors2.default.CODEC_UNSUPPORTED, 'Flv: Unsupported audio codec idx: ' + soundFormat);
  4185. return;
  4186. }
  4187. var soundRate = 0;
  4188. var soundRateIndex = (soundSpec & 12) >>> 2;
  4189. if (soundRateIndex >= 0 && soundRateIndex <= 4) {
  4190. soundRate = this._flvSoundRateTable[soundRateIndex];
  4191. } else {
  4192. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid audio sample rate idx: ' + soundRateIndex);
  4193. return;
  4194. }
  4195. var soundSize = (soundSpec & 2) >>> 1; // unused
  4196. var soundType = soundSpec & 1;
  4197. var meta = this._audioMetadata;
  4198. var track = this._audioTrack;
  4199. if (!meta) {
  4200. if (this._hasAudio === false && this._hasAudioFlagOverrided === false) {
  4201. this._hasAudio = true;
  4202. this._mediaInfo.hasAudio = true;
  4203. }
  4204. // initial metadata
  4205. meta = this._audioMetadata = {};
  4206. meta.type = 'audio';
  4207. meta.id = track.id;
  4208. meta.timescale = this._timescale;
  4209. meta.duration = this._duration;
  4210. meta.audioSampleRate = soundRate;
  4211. meta.channelCount = soundType === 0 ? 1 : 2;
  4212. }
  4213. if (soundFormat === 10) {
  4214. // AAC
  4215. var aacData = this._parseAACAudioData(arrayBuffer, dataOffset + 1, dataSize - 1);
  4216. if (aacData == undefined) {
  4217. return;
  4218. }
  4219. if (aacData.packetType === 0) {
  4220. // AAC sequence header (AudioSpecificConfig)
  4221. if (meta.config) {
  4222. _logger2.default.w(this.TAG, 'Found another AudioSpecificConfig!');
  4223. }
  4224. var misc = aacData.data;
  4225. meta.audioSampleRate = misc.samplingRate;
  4226. meta.channelCount = misc.channelCount;
  4227. meta.codec = misc.codec;
  4228. meta.originalCodec = misc.originalCodec;
  4229. meta.config = misc.config;
  4230. // The decode result of an aac sample is 1024 PCM samples
  4231. meta.refSampleDuration = 1024 / meta.audioSampleRate * meta.timescale;
  4232. _logger2.default.v(this.TAG, 'Parsed AudioSpecificConfig');
  4233. if (this._isInitialMetadataDispatched()) {
  4234. // Non-initial metadata, force dispatch (or flush) parsed frames to remuxer
  4235. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  4236. this._onDataAvailable(this._audioTrack, this._videoTrack);
  4237. }
  4238. } else {
  4239. this._audioInitialMetadataDispatched = true;
  4240. }
  4241. // then notify new metadata
  4242. this._dispatch = false;
  4243. this._onTrackMetadata('audio', meta);
  4244. var mi = this._mediaInfo;
  4245. mi.audioCodec = meta.originalCodec;
  4246. mi.audioSampleRate = meta.audioSampleRate;
  4247. mi.audioChannelCount = meta.channelCount;
  4248. if (mi.hasVideo) {
  4249. if (mi.videoCodec != null) {
  4250. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
  4251. }
  4252. } else {
  4253. mi.mimeType = 'video/x-flv; codecs="' + mi.audioCodec + '"';
  4254. }
  4255. if (mi.isComplete()) {
  4256. this._onMediaInfo(mi);
  4257. }
  4258. } else if (aacData.packetType === 1) {
  4259. // AAC raw frame data
  4260. var dts = this._timestampBase + tagTimestamp;
  4261. var aacSample = { unit: aacData.data, length: aacData.data.byteLength, dts: dts, pts: dts };
  4262. track.samples.push(aacSample);
  4263. track.length += aacData.data.length;
  4264. } else {
  4265. _logger2.default.e(this.TAG, 'Flv: Unsupported AAC data type ' + aacData.packetType);
  4266. }
  4267. } else if (soundFormat === 2) {
  4268. // MP3
  4269. if (!meta.codec) {
  4270. // We need metadata for mp3 audio track, extract info from frame header
  4271. var _misc = this._parseMP3AudioData(arrayBuffer, dataOffset + 1, dataSize - 1, true);
  4272. if (_misc == undefined) {
  4273. return;
  4274. }
  4275. meta.audioSampleRate = _misc.samplingRate;
  4276. meta.channelCount = _misc.channelCount;
  4277. meta.codec = _misc.codec;
  4278. meta.originalCodec = _misc.originalCodec;
  4279. // The decode result of an mp3 sample is 1152 PCM samples
  4280. meta.refSampleDuration = 1152 / meta.audioSampleRate * meta.timescale;
  4281. _logger2.default.v(this.TAG, 'Parsed MPEG Audio Frame Header');
  4282. this._audioInitialMetadataDispatched = true;
  4283. this._onTrackMetadata('audio', meta);
  4284. var _mi = this._mediaInfo;
  4285. _mi.audioCodec = meta.codec;
  4286. _mi.audioSampleRate = meta.audioSampleRate;
  4287. _mi.audioChannelCount = meta.channelCount;
  4288. _mi.audioDataRate = _misc.bitRate;
  4289. if (_mi.hasVideo) {
  4290. if (_mi.videoCodec != null) {
  4291. _mi.mimeType = 'video/x-flv; codecs="' + _mi.videoCodec + ',' + _mi.audioCodec + '"';
  4292. }
  4293. } else {
  4294. _mi.mimeType = 'video/x-flv; codecs="' + _mi.audioCodec + '"';
  4295. }
  4296. if (_mi.isComplete()) {
  4297. this._onMediaInfo(_mi);
  4298. }
  4299. }
  4300. // This packet is always a valid audio packet, extract it
  4301. var data = this._parseMP3AudioData(arrayBuffer, dataOffset + 1, dataSize - 1, false);
  4302. if (data == undefined) {
  4303. return;
  4304. }
  4305. var _dts = this._timestampBase + tagTimestamp;
  4306. var mp3Sample = { unit: data, length: data.byteLength, dts: _dts, pts: _dts };
  4307. track.samples.push(mp3Sample);
  4308. track.length += data.length;
  4309. }
  4310. }
  4311. }, {
  4312. key: '_parseAACAudioData',
  4313. value: function _parseAACAudioData(arrayBuffer, dataOffset, dataSize) {
  4314. if (dataSize <= 1) {
  4315. _logger2.default.w(this.TAG, 'Flv: Invalid AAC packet, missing AACPacketType or/and Data!');
  4316. return;
  4317. }
  4318. var result = {};
  4319. var array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  4320. result.packetType = array[0];
  4321. if (array[0] === 0) {
  4322. result.data = this._parseAACAudioSpecificConfig(arrayBuffer, dataOffset + 1, dataSize - 1);
  4323. } else {
  4324. result.data = array.subarray(1);
  4325. }
  4326. return result;
  4327. }
  4328. }, {
  4329. key: '_parseAACAudioSpecificConfig',
  4330. value: function _parseAACAudioSpecificConfig(arrayBuffer, dataOffset, dataSize) {
  4331. var array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  4332. var config = null;
  4333. /* Audio Object Type:
  4334. 0: Null
  4335. 1: AAC Main
  4336. 2: AAC LC
  4337. 3: AAC SSR (Scalable Sample Rate)
  4338. 4: AAC LTP (Long Term Prediction)
  4339. 5: HE-AAC / SBR (Spectral Band Replication)
  4340. 6: AAC Scalable
  4341. */
  4342. var audioObjectType = 0;
  4343. var originalAudioObjectType = 0;
  4344. var audioExtensionObjectType = null;
  4345. var samplingIndex = 0;
  4346. var extensionSamplingIndex = null;
  4347. // 5 bits
  4348. audioObjectType = originalAudioObjectType = array[0] >>> 3;
  4349. // 4 bits
  4350. samplingIndex = (array[0] & 0x07) << 1 | array[1] >>> 7;
  4351. if (samplingIndex < 0 || samplingIndex >= this._mpegSamplingRates.length) {
  4352. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: AAC invalid sampling frequency index!');
  4353. return;
  4354. }
  4355. var samplingFrequence = this._mpegSamplingRates[samplingIndex];
  4356. // 4 bits
  4357. var channelConfig = (array[1] & 0x78) >>> 3;
  4358. if (channelConfig < 0 || channelConfig >= 8) {
  4359. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: AAC invalid channel configuration');
  4360. return;
  4361. }
  4362. if (audioObjectType === 5) {
  4363. // HE-AAC?
  4364. // 4 bits
  4365. extensionSamplingIndex = (array[1] & 0x07) << 1 | array[2] >>> 7;
  4366. // 5 bits
  4367. audioExtensionObjectType = (array[2] & 0x7C) >>> 2;
  4368. }
  4369. // workarounds for various browsers
  4370. var userAgent = self.navigator.userAgent.toLowerCase();
  4371. if (userAgent.indexOf('firefox') !== -1) {
  4372. // firefox: use SBR (HE-AAC) if freq less than 24kHz
  4373. if (samplingIndex >= 6) {
  4374. audioObjectType = 5;
  4375. config = new Array(4);
  4376. extensionSamplingIndex = samplingIndex - 3;
  4377. } else {
  4378. // use LC-AAC
  4379. audioObjectType = 2;
  4380. config = new Array(2);
  4381. extensionSamplingIndex = samplingIndex;
  4382. }
  4383. } else if (userAgent.indexOf('android') !== -1) {
  4384. // android: always use LC-AAC
  4385. audioObjectType = 2;
  4386. config = new Array(2);
  4387. extensionSamplingIndex = samplingIndex;
  4388. } else {
  4389. // for other browsers, e.g. chrome...
  4390. // Always use HE-AAC to make it easier to switch aac codec profile
  4391. audioObjectType = 5;
  4392. extensionSamplingIndex = samplingIndex;
  4393. config = new Array(4);
  4394. if (samplingIndex >= 6) {
  4395. extensionSamplingIndex = samplingIndex - 3;
  4396. } else if (channelConfig === 1) {
  4397. // Mono channel
  4398. audioObjectType = 2;
  4399. config = new Array(2);
  4400. extensionSamplingIndex = samplingIndex;
  4401. }
  4402. }
  4403. config[0] = audioObjectType << 3;
  4404. config[0] |= (samplingIndex & 0x0F) >>> 1;
  4405. config[1] = (samplingIndex & 0x0F) << 7;
  4406. config[1] |= (channelConfig & 0x0F) << 3;
  4407. if (audioObjectType === 5) {
  4408. config[1] |= (extensionSamplingIndex & 0x0F) >>> 1;
  4409. config[2] = (extensionSamplingIndex & 0x01) << 7;
  4410. // extended audio object type: force to 2 (LC-AAC)
  4411. config[2] |= 2 << 2;
  4412. config[3] = 0;
  4413. }
  4414. return {
  4415. config: config,
  4416. samplingRate: samplingFrequence,
  4417. channelCount: channelConfig,
  4418. codec: 'mp4a.40.' + audioObjectType,
  4419. originalCodec: 'mp4a.40.' + originalAudioObjectType
  4420. };
  4421. }
  4422. }, {
  4423. key: '_parseMP3AudioData',
  4424. value: function _parseMP3AudioData(arrayBuffer, dataOffset, dataSize, requestHeader) {
  4425. if (dataSize < 4) {
  4426. _logger2.default.w(this.TAG, 'Flv: Invalid MP3 packet, header missing!');
  4427. return;
  4428. }
  4429. var le = this._littleEndian;
  4430. var array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  4431. var result = null;
  4432. if (requestHeader) {
  4433. if (array[0] !== 0xFF) {
  4434. return;
  4435. }
  4436. var ver = array[1] >>> 3 & 0x03;
  4437. var layer = (array[1] & 0x06) >> 1;
  4438. var bitrate_index = (array[2] & 0xF0) >>> 4;
  4439. var sampling_freq_index = (array[2] & 0x0C) >>> 2;
  4440. var channel_mode = array[3] >>> 6 & 0x03;
  4441. var channel_count = channel_mode !== 3 ? 2 : 1;
  4442. var sample_rate = 0;
  4443. var bit_rate = 0;
  4444. var object_type = 34; // Layer-3, listed in MPEG-4 Audio Object Types
  4445. var codec = 'mp3';
  4446. switch (ver) {
  4447. case 0:
  4448. // MPEG 2.5
  4449. sample_rate = this._mpegAudioV25SampleRateTable[sampling_freq_index];
  4450. break;
  4451. case 2:
  4452. // MPEG 2
  4453. sample_rate = this._mpegAudioV20SampleRateTable[sampling_freq_index];
  4454. break;
  4455. case 3:
  4456. // MPEG 1
  4457. sample_rate = this._mpegAudioV10SampleRateTable[sampling_freq_index];
  4458. break;
  4459. }
  4460. switch (layer) {
  4461. case 1:
  4462. // Layer 3
  4463. object_type = 34;
  4464. if (bitrate_index < this._mpegAudioL3BitRateTable.length) {
  4465. bit_rate = this._mpegAudioL3BitRateTable[bitrate_index];
  4466. }
  4467. break;
  4468. case 2:
  4469. // Layer 2
  4470. object_type = 33;
  4471. if (bitrate_index < this._mpegAudioL2BitRateTable.length) {
  4472. bit_rate = this._mpegAudioL2BitRateTable[bitrate_index];
  4473. }
  4474. break;
  4475. case 3:
  4476. // Layer 1
  4477. object_type = 32;
  4478. if (bitrate_index < this._mpegAudioL1BitRateTable.length) {
  4479. bit_rate = this._mpegAudioL1BitRateTable[bitrate_index];
  4480. }
  4481. break;
  4482. }
  4483. result = {
  4484. bitRate: bit_rate,
  4485. samplingRate: sample_rate,
  4486. channelCount: channel_count,
  4487. codec: codec,
  4488. originalCodec: codec
  4489. };
  4490. } else {
  4491. result = array;
  4492. }
  4493. return result;
  4494. }
  4495. }, {
  4496. key: '_parseVideoData',
  4497. value: function _parseVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition) {
  4498. if (dataSize <= 1) {
  4499. _logger2.default.w(this.TAG, 'Flv: Invalid video packet, missing VideoData payload!');
  4500. return;
  4501. }
  4502. if (this._hasVideoFlagOverrided === true && this._hasVideo === false) {
  4503. // If hasVideo: false indicated explicitly in MediaDataSource,
  4504. // Ignore all the video packets
  4505. return;
  4506. }
  4507. var spec = new Uint8Array(arrayBuffer, dataOffset, dataSize)[0];
  4508. var frameType = (spec & 240) >>> 4;
  4509. var codecId = spec & 15;
  4510. if (codecId !== 7) {
  4511. this._onError(_demuxErrors2.default.CODEC_UNSUPPORTED, 'Flv: Unsupported codec in video frame: ' + codecId);
  4512. return;
  4513. }
  4514. this._parseAVCVideoPacket(arrayBuffer, dataOffset + 1, dataSize - 1, tagTimestamp, tagPosition, frameType);
  4515. }
  4516. }, {
  4517. key: '_parseAVCVideoPacket',
  4518. value: function _parseAVCVideoPacket(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType) {
  4519. if (dataSize < 4) {
  4520. _logger2.default.w(this.TAG, 'Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime');
  4521. return;
  4522. }
  4523. var le = this._littleEndian;
  4524. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  4525. var packetType = v.getUint8(0);
  4526. var cts_unsigned = v.getUint32(0, !le) & 0x00FFFFFF;
  4527. var cts = cts_unsigned << 8 >> 8; // convert to 24-bit signed int
  4528. if (packetType === 0) {
  4529. // AVCDecoderConfigurationRecord
  4530. this._parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset + 4, dataSize - 4);
  4531. } else if (packetType === 1) {
  4532. // One or more Nalus
  4533. this._parseAVCVideoData(arrayBuffer, dataOffset + 4, dataSize - 4, tagTimestamp, tagPosition, frameType, cts);
  4534. } else if (packetType === 2) {
  4535. // empty, AVC end of sequence
  4536. } else {
  4537. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid video packet type ' + packetType);
  4538. return;
  4539. }
  4540. }
  4541. }, {
  4542. key: '_parseAVCDecoderConfigurationRecord',
  4543. value: function _parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset, dataSize) {
  4544. if (dataSize < 7) {
  4545. _logger2.default.w(this.TAG, 'Flv: Invalid AVCDecoderConfigurationRecord, lack of data!');
  4546. return;
  4547. }
  4548. var meta = this._videoMetadata;
  4549. var track = this._videoTrack;
  4550. var le = this._littleEndian;
  4551. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  4552. if (!meta) {
  4553. if (this._hasVideo === false && this._hasVideoFlagOverrided === false) {
  4554. this._hasVideo = true;
  4555. this._mediaInfo.hasVideo = true;
  4556. }
  4557. meta = this._videoMetadata = {};
  4558. meta.type = 'video';
  4559. meta.id = track.id;
  4560. meta.timescale = this._timescale;
  4561. meta.duration = this._duration;
  4562. } else {
  4563. if (typeof meta.avcc !== 'undefined') {
  4564. _logger2.default.w(this.TAG, 'Found another AVCDecoderConfigurationRecord!');
  4565. }
  4566. }
  4567. var version = v.getUint8(0); // configurationVersion
  4568. var avcProfile = v.getUint8(1); // avcProfileIndication
  4569. var profileCompatibility = v.getUint8(2); // profile_compatibility
  4570. var avcLevel = v.getUint8(3); // AVCLevelIndication
  4571. if (version !== 1 || avcProfile === 0) {
  4572. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord');
  4573. return;
  4574. }
  4575. this._naluLengthSize = (v.getUint8(4) & 3) + 1; // lengthSizeMinusOne
  4576. if (this._naluLengthSize !== 3 && this._naluLengthSize !== 4) {
  4577. // holy shit!!!
  4578. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Strange NaluLengthSizeMinusOne: ' + (this._naluLengthSize - 1));
  4579. return;
  4580. }
  4581. var spsCount = v.getUint8(5) & 31; // numOfSequenceParameterSets
  4582. if (spsCount === 0) {
  4583. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord: No SPS');
  4584. return;
  4585. } else if (spsCount > 1) {
  4586. _logger2.default.w(this.TAG, 'Flv: Strange AVCDecoderConfigurationRecord: SPS Count = ' + spsCount);
  4587. }
  4588. var offset = 6;
  4589. for (var i = 0; i < spsCount; i++) {
  4590. var len = v.getUint16(offset, !le); // sequenceParameterSetLength
  4591. offset += 2;
  4592. if (len === 0) {
  4593. continue;
  4594. }
  4595. // Notice: Nalu without startcode header (00 00 00 01)
  4596. var sps = new Uint8Array(arrayBuffer, dataOffset + offset, len);
  4597. offset += len;
  4598. var config = _spsParser2.default.parseSPS(sps);
  4599. if (i !== 0) {
  4600. // ignore other sps's config
  4601. continue;
  4602. }
  4603. meta.codecWidth = config.codec_size.width;
  4604. meta.codecHeight = config.codec_size.height;
  4605. meta.presentWidth = config.present_size.width;
  4606. meta.presentHeight = config.present_size.height;
  4607. meta.profile = config.profile_string;
  4608. meta.level = config.level_string;
  4609. meta.bitDepth = config.bit_depth;
  4610. meta.chromaFormat = config.chroma_format;
  4611. meta.sarRatio = config.sar_ratio;
  4612. meta.frameRate = config.frame_rate;
  4613. if (config.frame_rate.fixed === false || config.frame_rate.fps_num === 0 || config.frame_rate.fps_den === 0) {
  4614. meta.frameRate = this._referenceFrameRate;
  4615. }
  4616. var fps_den = meta.frameRate.fps_den;
  4617. var fps_num = meta.frameRate.fps_num;
  4618. meta.refSampleDuration = meta.timescale * (fps_den / fps_num);
  4619. var codecArray = sps.subarray(1, 4);
  4620. var codecString = 'avc1.';
  4621. for (var j = 0; j < 3; j++) {
  4622. var h = codecArray[j].toString(16);
  4623. if (h.length < 2) {
  4624. h = '0' + h;
  4625. }
  4626. codecString += h;
  4627. }
  4628. meta.codec = codecString;
  4629. var mi = this._mediaInfo;
  4630. mi.width = meta.codecWidth;
  4631. mi.height = meta.codecHeight;
  4632. mi.fps = meta.frameRate.fps;
  4633. mi.profile = meta.profile;
  4634. mi.level = meta.level;
  4635. mi.refFrames = config.ref_frames;
  4636. mi.chromaFormat = config.chroma_format_string;
  4637. mi.sarNum = meta.sarRatio.width;
  4638. mi.sarDen = meta.sarRatio.height;
  4639. mi.videoCodec = codecString;
  4640. if (mi.hasAudio) {
  4641. if (mi.audioCodec != null) {
  4642. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
  4643. }
  4644. } else {
  4645. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + '"';
  4646. }
  4647. if (mi.isComplete()) {
  4648. this._onMediaInfo(mi);
  4649. }
  4650. }
  4651. var ppsCount = v.getUint8(offset); // numOfPictureParameterSets
  4652. if (ppsCount === 0) {
  4653. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord: No PPS');
  4654. return;
  4655. } else if (ppsCount > 1) {
  4656. _logger2.default.w(this.TAG, 'Flv: Strange AVCDecoderConfigurationRecord: PPS Count = ' + ppsCount);
  4657. }
  4658. offset++;
  4659. for (var _i = 0; _i < ppsCount; _i++) {
  4660. var _len = v.getUint16(offset, !le); // pictureParameterSetLength
  4661. offset += 2;
  4662. if (_len === 0) {
  4663. continue;
  4664. }
  4665. // pps is useless for extracting video information
  4666. offset += _len;
  4667. }
  4668. meta.avcc = new Uint8Array(dataSize);
  4669. meta.avcc.set(new Uint8Array(arrayBuffer, dataOffset, dataSize), 0);
  4670. _logger2.default.v(this.TAG, 'Parsed AVCDecoderConfigurationRecord');
  4671. if (this._isInitialMetadataDispatched()) {
  4672. // flush parsed frames
  4673. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  4674. this._onDataAvailable(this._audioTrack, this._videoTrack);
  4675. }
  4676. } else {
  4677. this._videoInitialMetadataDispatched = true;
  4678. }
  4679. // notify new metadata
  4680. this._dispatch = false;
  4681. this._onTrackMetadata('video', meta);
  4682. }
  4683. }, {
  4684. key: '_parseAVCVideoData',
  4685. value: function _parseAVCVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType, cts) {
  4686. var le = this._littleEndian;
  4687. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  4688. var units = [],
  4689. length = 0;
  4690. var offset = 0;
  4691. var lengthSize = this._naluLengthSize;
  4692. var dts = this._timestampBase + tagTimestamp;
  4693. var keyframe = frameType === 1; // from FLV Frame Type constants
  4694. while (offset < dataSize) {
  4695. if (offset + 4 >= dataSize) {
  4696. _logger2.default.w(this.TAG, 'Malformed Nalu near timestamp ' + dts + ', offset = ' + offset + ', dataSize = ' + dataSize);
  4697. break; // data not enough for next Nalu
  4698. }
  4699. // Nalu with length-header (AVC1)
  4700. var naluSize = v.getUint32(offset, !le); // Big-Endian read
  4701. if (lengthSize === 3) {
  4702. naluSize >>>= 8;
  4703. }
  4704. if (naluSize > dataSize - lengthSize) {
  4705. _logger2.default.w(this.TAG, 'Malformed Nalus near timestamp ' + dts + ', NaluSize > DataSize!');
  4706. return;
  4707. }
  4708. var unitType = v.getUint8(offset + lengthSize) & 0x1F;
  4709. if (unitType === 5) {
  4710. // IDR
  4711. keyframe = true;
  4712. }
  4713. var data = new Uint8Array(arrayBuffer, dataOffset + offset, lengthSize + naluSize);
  4714. var unit = { type: unitType, data: data };
  4715. units.push(unit);
  4716. length += data.byteLength;
  4717. offset += lengthSize + naluSize;
  4718. }
  4719. if (units.length) {
  4720. var track = this._videoTrack;
  4721. var avcSample = {
  4722. units: units,
  4723. length: length,
  4724. isKeyframe: keyframe,
  4725. dts: dts,
  4726. cts: cts,
  4727. pts: dts + cts
  4728. };
  4729. if (keyframe) {
  4730. avcSample.fileposition = tagPosition;
  4731. }
  4732. track.samples.push(avcSample);
  4733. track.length += length;
  4734. }
  4735. }
  4736. }, {
  4737. key: 'onTrackMetadata',
  4738. get: function get() {
  4739. return this._onTrackMetadata;
  4740. },
  4741. set: function set(callback) {
  4742. this._onTrackMetadata = callback;
  4743. }
  4744. // prototype: function(mediaInfo: MediaInfo): void
  4745. }, {
  4746. key: 'onMediaInfo',
  4747. get: function get() {
  4748. return this._onMediaInfo;
  4749. },
  4750. set: function set(callback) {
  4751. this._onMediaInfo = callback;
  4752. }
  4753. // prototype: function(type: number, info: string): void
  4754. }, {
  4755. key: 'onError',
  4756. get: function get() {
  4757. return this._onError;
  4758. },
  4759. set: function set(callback) {
  4760. this._onError = callback;
  4761. }
  4762. // prototype: function(videoTrack: any, audioTrack: any): void
  4763. }, {
  4764. key: 'onDataAvailable',
  4765. get: function get() {
  4766. return this._onDataAvailable;
  4767. },
  4768. set: function set(callback) {
  4769. this._onDataAvailable = callback;
  4770. }
  4771. // timestamp base for output samples, must be in milliseconds
  4772. }, {
  4773. key: 'timestampBase',
  4774. get: function get() {
  4775. return this._timestampBase;
  4776. },
  4777. set: function set(base) {
  4778. this._timestampBase = base;
  4779. }
  4780. }, {
  4781. key: 'overridedDuration',
  4782. get: function get() {
  4783. return this._duration;
  4784. }
  4785. // Force-override media duration. Must be in milliseconds, int32
  4786. ,
  4787. set: function set(duration) {
  4788. this._durationOverrided = true;
  4789. this._duration = duration;
  4790. this._mediaInfo.duration = duration;
  4791. }
  4792. // Force-override audio track present flag, boolean
  4793. }, {
  4794. key: 'overridedHasAudio',
  4795. set: function set(hasAudio) {
  4796. this._hasAudioFlagOverrided = true;
  4797. this._hasAudio = hasAudio;
  4798. this._mediaInfo.hasAudio = hasAudio;
  4799. }
  4800. // Force-override video track present flag, boolean
  4801. }, {
  4802. key: 'overridedHasVideo',
  4803. set: function set(hasVideo) {
  4804. this._hasVideoFlagOverrided = true;
  4805. this._hasVideo = hasVideo;
  4806. this._mediaInfo.hasVideo = hasVideo;
  4807. }
  4808. }], [{
  4809. key: 'probe',
  4810. value: function probe(buffer) {
  4811. var data = new Uint8Array(buffer);
  4812. var mismatch = { match: false };
  4813. if (data[0] !== 0x46 || data[1] !== 0x4C || data[2] !== 0x56 || data[3] !== 0x01) {
  4814. return mismatch;
  4815. }
  4816. var hasAudio = (data[4] & 4) >>> 2 !== 0;
  4817. var hasVideo = (data[4] & 1) !== 0;
  4818. var offset = ReadBig32(data, 5);
  4819. if (offset < 9) {
  4820. return mismatch;
  4821. }
  4822. return {
  4823. match: true,
  4824. consumed: offset,
  4825. dataOffset: offset,
  4826. hasAudioTrack: hasAudio,
  4827. hasVideoTrack: hasVideo
  4828. };
  4829. }
  4830. }]);
  4831. return FLVDemuxer;
  4832. }();
  4833. exports.default = FLVDemuxer;
  4834. },{"../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){
  4835. 'use strict';
  4836. Object.defineProperty(exports, "__esModule", {
  4837. value: true
  4838. });
  4839. 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; }; }(); /*
  4840. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  4841. *
  4842. * @author zheng qian <xqq@xqq.im>
  4843. *
  4844. * Licensed under the Apache License, Version 2.0 (the "License");
  4845. * you may not use this file except in compliance with the License.
  4846. * You may obtain a copy of the License at
  4847. *
  4848. * http://www.apache.org/licenses/LICENSE-2.0
  4849. *
  4850. * Unless required by applicable law or agreed to in writing, software
  4851. * distributed under the License is distributed on an "AS IS" BASIS,
  4852. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4853. * See the License for the specific language governing permissions and
  4854. * limitations under the License.
  4855. */
  4856. var _expGolomb = _dereq_('./exp-golomb.js');
  4857. var _expGolomb2 = _interopRequireDefault(_expGolomb);
  4858. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  4859. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4860. var SPSParser = function () {
  4861. function SPSParser() {
  4862. _classCallCheck(this, SPSParser);
  4863. }
  4864. _createClass(SPSParser, null, [{
  4865. key: '_ebsp2rbsp',
  4866. value: function _ebsp2rbsp(uint8array) {
  4867. var src = uint8array;
  4868. var src_length = src.byteLength;
  4869. var dst = new Uint8Array(src_length);
  4870. var dst_idx = 0;
  4871. for (var i = 0; i < src_length; i++) {
  4872. if (i >= 2) {
  4873. // Unescape: Skip 0x03 after 00 00
  4874. if (src[i] === 0x03 && src[i - 1] === 0x00 && src[i - 2] === 0x00) {
  4875. continue;
  4876. }
  4877. }
  4878. dst[dst_idx] = src[i];
  4879. dst_idx++;
  4880. }
  4881. return new Uint8Array(dst.buffer, 0, dst_idx);
  4882. }
  4883. }, {
  4884. key: 'parseSPS',
  4885. value: function parseSPS(uint8array) {
  4886. var rbsp = SPSParser._ebsp2rbsp(uint8array);
  4887. var gb = new _expGolomb2.default(rbsp);
  4888. gb.readByte();
  4889. var profile_idc = gb.readByte(); // profile_idc
  4890. gb.readByte(); // constraint_set_flags[5] + reserved_zero[3]
  4891. var level_idc = gb.readByte(); // level_idc
  4892. gb.readUEG(); // seq_parameter_set_id
  4893. var profile_string = SPSParser.getProfileString(profile_idc);
  4894. var level_string = SPSParser.getLevelString(level_idc);
  4895. var chroma_format_idc = 1;
  4896. var chroma_format = 420;
  4897. var chroma_format_table = [0, 420, 422, 444];
  4898. var bit_depth = 8;
  4899. 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) {
  4900. chroma_format_idc = gb.readUEG();
  4901. if (chroma_format_idc === 3) {
  4902. gb.readBits(1); // separate_colour_plane_flag
  4903. }
  4904. if (chroma_format_idc <= 3) {
  4905. chroma_format = chroma_format_table[chroma_format_idc];
  4906. }
  4907. bit_depth = gb.readUEG() + 8; // bit_depth_luma_minus8
  4908. gb.readUEG(); // bit_depth_chroma_minus8
  4909. gb.readBits(1); // qpprime_y_zero_transform_bypass_flag
  4910. if (gb.readBool()) {
  4911. // seq_scaling_matrix_present_flag
  4912. var scaling_list_count = chroma_format_idc !== 3 ? 8 : 12;
  4913. for (var i = 0; i < scaling_list_count; i++) {
  4914. if (gb.readBool()) {
  4915. // seq_scaling_list_present_flag
  4916. if (i < 6) {
  4917. SPSParser._skipScalingList(gb, 16);
  4918. } else {
  4919. SPSParser._skipScalingList(gb, 64);
  4920. }
  4921. }
  4922. }
  4923. }
  4924. }
  4925. gb.readUEG(); // log2_max_frame_num_minus4
  4926. var pic_order_cnt_type = gb.readUEG();
  4927. if (pic_order_cnt_type === 0) {
  4928. gb.readUEG(); // log2_max_pic_order_cnt_lsb_minus_4
  4929. } else if (pic_order_cnt_type === 1) {
  4930. gb.readBits(1); // delta_pic_order_always_zero_flag
  4931. gb.readSEG(); // offset_for_non_ref_pic
  4932. gb.readSEG(); // offset_for_top_to_bottom_field
  4933. var num_ref_frames_in_pic_order_cnt_cycle = gb.readUEG();
  4934. for (var _i = 0; _i < num_ref_frames_in_pic_order_cnt_cycle; _i++) {
  4935. gb.readSEG(); // offset_for_ref_frame
  4936. }
  4937. }
  4938. var ref_frames = gb.readUEG(); // max_num_ref_frames
  4939. gb.readBits(1); // gaps_in_frame_num_value_allowed_flag
  4940. var pic_width_in_mbs_minus1 = gb.readUEG();
  4941. var pic_height_in_map_units_minus1 = gb.readUEG();
  4942. var frame_mbs_only_flag = gb.readBits(1);
  4943. if (frame_mbs_only_flag === 0) {
  4944. gb.readBits(1); // mb_adaptive_frame_field_flag
  4945. }
  4946. gb.readBits(1); // direct_8x8_inference_flag
  4947. var frame_crop_left_offset = 0;
  4948. var frame_crop_right_offset = 0;
  4949. var frame_crop_top_offset = 0;
  4950. var frame_crop_bottom_offset = 0;
  4951. var frame_cropping_flag = gb.readBool();
  4952. if (frame_cropping_flag) {
  4953. frame_crop_left_offset = gb.readUEG();
  4954. frame_crop_right_offset = gb.readUEG();
  4955. frame_crop_top_offset = gb.readUEG();
  4956. frame_crop_bottom_offset = gb.readUEG();
  4957. }
  4958. var sar_width = 1,
  4959. sar_height = 1;
  4960. var fps = 0,
  4961. fps_fixed = true,
  4962. fps_num = 0,
  4963. fps_den = 0;
  4964. var vui_parameters_present_flag = gb.readBool();
  4965. if (vui_parameters_present_flag) {
  4966. if (gb.readBool()) {
  4967. // aspect_ratio_info_present_flag
  4968. var aspect_ratio_idc = gb.readByte();
  4969. var sar_w_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2];
  4970. var sar_h_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
  4971. if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) {
  4972. sar_width = sar_w_table[aspect_ratio_idc - 1];
  4973. sar_height = sar_h_table[aspect_ratio_idc - 1];
  4974. } else if (aspect_ratio_idc === 255) {
  4975. sar_width = gb.readByte() << 8 | gb.readByte();
  4976. sar_height = gb.readByte() << 8 | gb.readByte();
  4977. }
  4978. }
  4979. if (gb.readBool()) {
  4980. // overscan_info_present_flag
  4981. gb.readBool(); // overscan_appropriate_flag
  4982. }
  4983. if (gb.readBool()) {
  4984. // video_signal_type_present_flag
  4985. gb.readBits(4); // video_format & video_full_range_flag
  4986. if (gb.readBool()) {
  4987. // colour_description_present_flag
  4988. gb.readBits(24); // colour_primaries & transfer_characteristics & matrix_coefficients
  4989. }
  4990. }
  4991. if (gb.readBool()) {
  4992. // chroma_loc_info_present_flag
  4993. gb.readUEG(); // chroma_sample_loc_type_top_field
  4994. gb.readUEG(); // chroma_sample_loc_type_bottom_field
  4995. }
  4996. if (gb.readBool()) {
  4997. // timing_info_present_flag
  4998. var num_units_in_tick = gb.readBits(32);
  4999. var time_scale = gb.readBits(32);
  5000. fps_fixed = gb.readBool(); // fixed_frame_rate_flag
  5001. fps_num = time_scale;
  5002. fps_den = num_units_in_tick * 2;
  5003. fps = fps_num / fps_den;
  5004. }
  5005. }
  5006. var sarScale = 1;
  5007. if (sar_width !== 1 || sar_height !== 1) {
  5008. sarScale = sar_width / sar_height;
  5009. }
  5010. var crop_unit_x = 0,
  5011. crop_unit_y = 0;
  5012. if (chroma_format_idc === 0) {
  5013. crop_unit_x = 1;
  5014. crop_unit_y = 2 - frame_mbs_only_flag;
  5015. } else {
  5016. var sub_wc = chroma_format_idc === 3 ? 1 : 2;
  5017. var sub_hc = chroma_format_idc === 1 ? 2 : 1;
  5018. crop_unit_x = sub_wc;
  5019. crop_unit_y = sub_hc * (2 - frame_mbs_only_flag);
  5020. }
  5021. var codec_width = (pic_width_in_mbs_minus1 + 1) * 16;
  5022. var codec_height = (2 - frame_mbs_only_flag) * ((pic_height_in_map_units_minus1 + 1) * 16);
  5023. codec_width -= (frame_crop_left_offset + frame_crop_right_offset) * crop_unit_x;
  5024. codec_height -= (frame_crop_top_offset + frame_crop_bottom_offset) * crop_unit_y;
  5025. var present_width = Math.ceil(codec_width * sarScale);
  5026. gb.destroy();
  5027. gb = null;
  5028. return {
  5029. profile_string: profile_string, // baseline, high, high10, ...
  5030. level_string: level_string, // 3, 3.1, 4, 4.1, 5, 5.1, ...
  5031. bit_depth: bit_depth, // 8bit, 10bit, ...
  5032. ref_frames: ref_frames,
  5033. chroma_format: chroma_format, // 4:2:0, 4:2:2, ...
  5034. chroma_format_string: SPSParser.getChromaFormatString(chroma_format),
  5035. frame_rate: {
  5036. fixed: fps_fixed,
  5037. fps: fps,
  5038. fps_den: fps_den,
  5039. fps_num: fps_num
  5040. },
  5041. sar_ratio: {
  5042. width: sar_width,
  5043. height: sar_height
  5044. },
  5045. codec_size: {
  5046. width: codec_width,
  5047. height: codec_height
  5048. },
  5049. present_size: {
  5050. width: present_width,
  5051. height: codec_height
  5052. }
  5053. };
  5054. }
  5055. }, {
  5056. key: '_skipScalingList',
  5057. value: function _skipScalingList(gb, count) {
  5058. var last_scale = 8,
  5059. next_scale = 8;
  5060. var delta_scale = 0;
  5061. for (var i = 0; i < count; i++) {
  5062. if (next_scale !== 0) {
  5063. delta_scale = gb.readSEG();
  5064. next_scale = (last_scale + delta_scale + 256) % 256;
  5065. }
  5066. last_scale = next_scale === 0 ? last_scale : next_scale;
  5067. }
  5068. }
  5069. }, {
  5070. key: 'getProfileString',
  5071. value: function getProfileString(profile_idc) {
  5072. switch (profile_idc) {
  5073. case 66:
  5074. return 'Baseline';
  5075. case 77:
  5076. return 'Main';
  5077. case 88:
  5078. return 'Extended';
  5079. case 100:
  5080. return 'High';
  5081. case 110:
  5082. return 'High10';
  5083. case 122:
  5084. return 'High422';
  5085. case 244:
  5086. return 'High444';
  5087. default:
  5088. return 'Unknown';
  5089. }
  5090. }
  5091. }, {
  5092. key: 'getLevelString',
  5093. value: function getLevelString(level_idc) {
  5094. return (level_idc / 10).toFixed(1);
  5095. }
  5096. }, {
  5097. key: 'getChromaFormatString',
  5098. value: function getChromaFormatString(chroma) {
  5099. switch (chroma) {
  5100. case 420:
  5101. return '4:2:0';
  5102. case 422:
  5103. return '4:2:2';
  5104. case 444:
  5105. return '4:4:4';
  5106. default:
  5107. return 'Unknown';
  5108. }
  5109. }
  5110. }]);
  5111. return SPSParser;
  5112. }();
  5113. exports.default = SPSParser;
  5114. },{"./exp-golomb.js":17}],20:[function(_dereq_,module,exports){
  5115. 'use strict';
  5116. Object.defineProperty(exports, "__esModule", {
  5117. value: true
  5118. });
  5119. 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; }; /*
  5120. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  5121. *
  5122. * @author zheng qian <xqq@xqq.im>
  5123. *
  5124. * Licensed under the Apache License, Version 2.0 (the "License");
  5125. * you may not use this file except in compliance with the License.
  5126. * You may obtain a copy of the License at
  5127. *
  5128. * http://www.apache.org/licenses/LICENSE-2.0
  5129. *
  5130. * Unless required by applicable law or agreed to in writing, software
  5131. * distributed under the License is distributed on an "AS IS" BASIS,
  5132. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5133. * See the License for the specific language governing permissions and
  5134. * limitations under the License.
  5135. */
  5136. var _polyfill = _dereq_('./utils/polyfill.js');
  5137. var _polyfill2 = _interopRequireDefault(_polyfill);
  5138. var _features = _dereq_('./core/features.js');
  5139. var _features2 = _interopRequireDefault(_features);
  5140. var _flvPlayer = _dereq_('./player/flv-player.js');
  5141. var _flvPlayer2 = _interopRequireDefault(_flvPlayer);
  5142. var _nativePlayer = _dereq_('./player/native-player.js');
  5143. var _nativePlayer2 = _interopRequireDefault(_nativePlayer);
  5144. var _playerEvents = _dereq_('./player/player-events.js');
  5145. var _playerEvents2 = _interopRequireDefault(_playerEvents);
  5146. var _playerErrors = _dereq_('./player/player-errors.js');
  5147. var _loggingControl = _dereq_('./utils/logging-control.js');
  5148. var _loggingControl2 = _interopRequireDefault(_loggingControl);
  5149. var _exception = _dereq_('./utils/exception.js');
  5150. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5151. // here are all the interfaces
  5152. // install polyfills
  5153. _polyfill2.default.install();
  5154. // factory method
  5155. function createPlayer(mediaDataSource, optionalConfig) {
  5156. var mds = mediaDataSource;
  5157. if (mds == null || (typeof mds === 'undefined' ? 'undefined' : _typeof(mds)) !== 'object') {
  5158. throw new _exception.InvalidArgumentException('MediaDataSource must be an javascript object!');
  5159. }
  5160. if (!mds.hasOwnProperty('type')) {
  5161. throw new _exception.InvalidArgumentException('MediaDataSource must has type field to indicate video file type!');
  5162. }
  5163. switch (mds.type) {
  5164. case 'flv':
  5165. return new _flvPlayer2.default(mds, optionalConfig);
  5166. default:
  5167. return new _nativePlayer2.default(mds, optionalConfig);
  5168. }
  5169. }
  5170. // feature detection
  5171. function isSupported() {
  5172. return _features2.default.supportMSEH264Playback();
  5173. }
  5174. function getFeatureList() {
  5175. return _features2.default.getFeatureList();
  5176. }
  5177. // interfaces
  5178. var flvjs = {};
  5179. flvjs.createPlayer = createPlayer;
  5180. flvjs.isSupported = isSupported;
  5181. flvjs.getFeatureList = getFeatureList;
  5182. flvjs.Events = _playerEvents2.default;
  5183. flvjs.ErrorTypes = _playerErrors.ErrorTypes;
  5184. flvjs.ErrorDetails = _playerErrors.ErrorDetails;
  5185. flvjs.FlvPlayer = _flvPlayer2.default;
  5186. flvjs.NativePlayer = _nativePlayer2.default;
  5187. flvjs.LoggingControl = _loggingControl2.default;
  5188. Object.defineProperty(flvjs, 'version', {
  5189. enumerable: true,
  5190. get: function get() {
  5191. // replaced by browserify-versionify transform
  5192. return '1.4.0';
  5193. }
  5194. });
  5195. exports.default = flvjs;
  5196. },{"./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){
  5197. 'use strict';
  5198. // entry/index file
  5199. // make it compatible with browserify's umd wrapper
  5200. module.exports = _dereq_('./flv.js').default;
  5201. },{"./flv.js":20}],22:[function(_dereq_,module,exports){
  5202. 'use strict';
  5203. Object.defineProperty(exports, "__esModule", {
  5204. value: true
  5205. });
  5206. 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; };
  5207. 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); } };
  5208. 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; }; }();
  5209. var _logger = _dereq_('../utils/logger.js');
  5210. var _logger2 = _interopRequireDefault(_logger);
  5211. var _browser = _dereq_('../utils/browser.js');
  5212. var _browser2 = _interopRequireDefault(_browser);
  5213. var _loader = _dereq_('./loader.js');
  5214. var _exception = _dereq_('../utils/exception.js');
  5215. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5216. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5217. 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; }
  5218. 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; } /*
  5219. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  5220. *
  5221. * @author zheng qian <xqq@xqq.im>
  5222. *
  5223. * Licensed under the Apache License, Version 2.0 (the "License");
  5224. * you may not use this file except in compliance with the License.
  5225. * You may obtain a copy of the License at
  5226. *
  5227. * http://www.apache.org/licenses/LICENSE-2.0
  5228. *
  5229. * Unless required by applicable law or agreed to in writing, software
  5230. * distributed under the License is distributed on an "AS IS" BASIS,
  5231. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5232. * See the License for the specific language governing permissions and
  5233. * limitations under the License.
  5234. */
  5235. /* fetch + stream IO loader. Currently working on chrome 43+.
  5236. * fetch provides a better alternative http API to XMLHttpRequest
  5237. *
  5238. * fetch spec https://fetch.spec.whatwg.org/
  5239. * stream spec https://streams.spec.whatwg.org/
  5240. */
  5241. var FetchStreamLoader = function (_BaseLoader) {
  5242. _inherits(FetchStreamLoader, _BaseLoader);
  5243. _createClass(FetchStreamLoader, null, [{
  5244. key: 'isSupported',
  5245. value: function isSupported() {
  5246. try {
  5247. // fetch + stream is broken on Microsoft Edge. Disable before build 15048.
  5248. // see https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8196907/
  5249. // Fixed in Jan 10, 2017. Build 15048+ removed from blacklist.
  5250. var isWorkWellEdge = _browser2.default.msedge && _browser2.default.version.minor >= 15048;
  5251. var browserNotBlacklisted = _browser2.default.msedge ? isWorkWellEdge : true;
  5252. return self.fetch && self.ReadableStream && browserNotBlacklisted;
  5253. } catch (e) {
  5254. return false;
  5255. }
  5256. }
  5257. }]);
  5258. function FetchStreamLoader(seekHandler, config) {
  5259. _classCallCheck(this, FetchStreamLoader);
  5260. var _this = _possibleConstructorReturn(this, (FetchStreamLoader.__proto__ || Object.getPrototypeOf(FetchStreamLoader)).call(this, 'fetch-stream-loader'));
  5261. _this.TAG = 'FetchStreamLoader';
  5262. _this._seekHandler = seekHandler;
  5263. _this._config = config;
  5264. _this._needStash = true;
  5265. _this._requestAbort = false;
  5266. _this._contentLength = null;
  5267. _this._receivedLength = 0;
  5268. return _this;
  5269. }
  5270. _createClass(FetchStreamLoader, [{
  5271. key: 'destroy',
  5272. value: function destroy() {
  5273. if (this.isWorking()) {
  5274. this.abort();
  5275. }
  5276. _get(FetchStreamLoader.prototype.__proto__ || Object.getPrototypeOf(FetchStreamLoader.prototype), 'destroy', this).call(this);
  5277. }
  5278. }, {
  5279. key: 'open',
  5280. value: function open(dataSource, range) {
  5281. var _this2 = this;
  5282. this._dataSource = dataSource;
  5283. this._range = range;
  5284. var sourceURL = dataSource.url;
  5285. if (this._config.reuseRedirectedURL && dataSource.redirectedURL != undefined) {
  5286. sourceURL = dataSource.redirectedURL;
  5287. }
  5288. var seekConfig = this._seekHandler.getConfig(sourceURL, range);
  5289. var headers = new self.Headers();
  5290. if (_typeof(seekConfig.headers) === 'object') {
  5291. var configHeaders = seekConfig.headers;
  5292. for (var key in configHeaders) {
  5293. if (configHeaders.hasOwnProperty(key)) {
  5294. headers.append(key, configHeaders[key]);
  5295. }
  5296. }
  5297. }
  5298. var params = {
  5299. method: 'GET',
  5300. headers: headers,
  5301. mode: 'cors',
  5302. cache: 'default',
  5303. // The default policy of Fetch API in the whatwg standard
  5304. // Safari incorrectly indicates 'no-referrer' as default policy, fuck it
  5305. referrerPolicy: 'no-referrer-when-downgrade'
  5306. };
  5307. // cors is enabled by default
  5308. if (dataSource.cors === false) {
  5309. // no-cors means 'disregard cors policy', which can only be used in ServiceWorker
  5310. params.mode = 'same-origin';
  5311. }
  5312. // withCredentials is disabled by default
  5313. if (dataSource.withCredentials) {
  5314. params.credentials = 'include';
  5315. }
  5316. // referrerPolicy from config
  5317. if (dataSource.referrerPolicy) {
  5318. params.referrerPolicy = dataSource.referrerPolicy;
  5319. }
  5320. this._status = _loader.LoaderStatus.kConnecting;
  5321. self.fetch(seekConfig.url, params).then(function (res) {
  5322. if (_this2._requestAbort) {
  5323. _this2._requestAbort = false;
  5324. _this2._status = _loader.LoaderStatus.kIdle;
  5325. return;
  5326. }
  5327. if (res.ok && res.status >= 200 && res.status <= 299) {
  5328. if (res.url !== seekConfig.url) {
  5329. if (_this2._onURLRedirect) {
  5330. var redirectedURL = _this2._seekHandler.removeURLParameters(res.url);
  5331. _this2._onURLRedirect(redirectedURL);
  5332. }
  5333. }
  5334. var lengthHeader = res.headers.get('Content-Length');
  5335. if (lengthHeader != null) {
  5336. _this2._contentLength = parseInt(lengthHeader);
  5337. if (_this2._contentLength !== 0) {
  5338. if (_this2._onContentLengthKnown) {
  5339. _this2._onContentLengthKnown(_this2._contentLength);
  5340. }
  5341. }
  5342. }
  5343. return _this2._pump.call(_this2, res.body.getReader());
  5344. } else {
  5345. _this2._status = _loader.LoaderStatus.kError;
  5346. if (_this2._onError) {
  5347. _this2._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: res.status, msg: res.statusText });
  5348. } else {
  5349. throw new _exception.RuntimeException('FetchStreamLoader: Http code invalid, ' + res.status + ' ' + res.statusText);
  5350. }
  5351. }
  5352. }).catch(function (e) {
  5353. _this2._status = _loader.LoaderStatus.kError;
  5354. if (_this2._onError) {
  5355. _this2._onError(_loader.LoaderErrors.EXCEPTION, { code: -1, msg: e.message });
  5356. } else {
  5357. throw e;
  5358. }
  5359. });
  5360. }
  5361. }, {
  5362. key: 'abort',
  5363. value: function abort() {
  5364. this._requestAbort = true;
  5365. }
  5366. }, {
  5367. key: '_pump',
  5368. value: function _pump(reader) {
  5369. var _this3 = this;
  5370. // ReadableStreamReader
  5371. return reader.read().then(function (result) {
  5372. if (result.done) {
  5373. _this3._status = _loader.LoaderStatus.kComplete;
  5374. if (_this3._onComplete) {
  5375. _this3._onComplete(_this3._range.from, _this3._range.from + _this3._receivedLength - 1);
  5376. }
  5377. } else {
  5378. if (_this3._requestAbort === true) {
  5379. _this3._requestAbort = false;
  5380. _this3._status = _loader.LoaderStatus.kComplete;
  5381. return reader.cancel();
  5382. }
  5383. _this3._status = _loader.LoaderStatus.kBuffering;
  5384. var chunk = result.value.buffer;
  5385. var byteStart = _this3._range.from + _this3._receivedLength;
  5386. _this3._receivedLength += chunk.byteLength;
  5387. if (_this3._onDataArrival) {
  5388. _this3._onDataArrival(chunk, byteStart, _this3._receivedLength);
  5389. }
  5390. _this3._pump(reader);
  5391. }
  5392. }).catch(function (e) {
  5393. if (e.code === 11 && _browser2.default.msedge) {
  5394. // InvalidStateError on Microsoft Edge
  5395. // Workaround: Edge may throw InvalidStateError after ReadableStreamReader.cancel() call
  5396. // Ignore the unknown exception.
  5397. // Related issue: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/11265202/
  5398. return;
  5399. }
  5400. _this3._status = _loader.LoaderStatus.kError;
  5401. var type = 0;
  5402. var info = null;
  5403. if ((e.code === 19 || e.message === 'network error') && ( // NETWORK_ERR
  5404. _this3._contentLength === null || _this3._contentLength !== null && _this3._receivedLength < _this3._contentLength)) {
  5405. type = _loader.LoaderErrors.EARLY_EOF;
  5406. info = { code: e.code, msg: 'Fetch stream meet Early-EOF' };
  5407. } else {
  5408. type = _loader.LoaderErrors.EXCEPTION;
  5409. info = { code: e.code, msg: e.message };
  5410. }
  5411. if (_this3._onError) {
  5412. _this3._onError(type, info);
  5413. } else {
  5414. throw new _exception.RuntimeException(info.msg);
  5415. }
  5416. });
  5417. }
  5418. }]);
  5419. return FetchStreamLoader;
  5420. }(_loader.BaseLoader);
  5421. exports.default = FetchStreamLoader;
  5422. },{"../utils/browser.js":39,"../utils/exception.js":40,"../utils/logger.js":41,"./loader.js":24}],23:[function(_dereq_,module,exports){
  5423. 'use strict';
  5424. Object.defineProperty(exports, "__esModule", {
  5425. value: true
  5426. });
  5427. 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; }; }(); /*
  5428. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  5429. *
  5430. * @author zheng qian <xqq@xqq.im>
  5431. *
  5432. * Licensed under the Apache License, Version 2.0 (the "License");
  5433. * you may not use this file except in compliance with the License.
  5434. * You may obtain a copy of the License at
  5435. *
  5436. * http://www.apache.org/licenses/LICENSE-2.0
  5437. *
  5438. * Unless required by applicable law or agreed to in writing, software
  5439. * distributed under the License is distributed on an "AS IS" BASIS,
  5440. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5441. * See the License for the specific language governing permissions and
  5442. * limitations under the License.
  5443. */
  5444. var _logger = _dereq_('../utils/logger.js');
  5445. var _logger2 = _interopRequireDefault(_logger);
  5446. var _speedSampler = _dereq_('./speed-sampler.js');
  5447. var _speedSampler2 = _interopRequireDefault(_speedSampler);
  5448. var _loader = _dereq_('./loader.js');
  5449. var _fetchStreamLoader = _dereq_('./fetch-stream-loader.js');
  5450. var _fetchStreamLoader2 = _interopRequireDefault(_fetchStreamLoader);
  5451. var _xhrMozChunkedLoader = _dereq_('./xhr-moz-chunked-loader.js');
  5452. var _xhrMozChunkedLoader2 = _interopRequireDefault(_xhrMozChunkedLoader);
  5453. var _xhrMsstreamLoader = _dereq_('./xhr-msstream-loader.js');
  5454. var _xhrMsstreamLoader2 = _interopRequireDefault(_xhrMsstreamLoader);
  5455. var _xhrRangeLoader = _dereq_('./xhr-range-loader.js');
  5456. var _xhrRangeLoader2 = _interopRequireDefault(_xhrRangeLoader);
  5457. var _websocketLoader = _dereq_('./websocket-loader.js');
  5458. var _websocketLoader2 = _interopRequireDefault(_websocketLoader);
  5459. var _rangeSeekHandler = _dereq_('./range-seek-handler.js');
  5460. var _rangeSeekHandler2 = _interopRequireDefault(_rangeSeekHandler);
  5461. var _paramSeekHandler = _dereq_('./param-seek-handler.js');
  5462. var _paramSeekHandler2 = _interopRequireDefault(_paramSeekHandler);
  5463. var _exception = _dereq_('../utils/exception.js');
  5464. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5465. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5466. /**
  5467. * DataSource: {
  5468. * url: string,
  5469. * filesize: number,
  5470. * cors: boolean,
  5471. * withCredentials: boolean
  5472. * }
  5473. *
  5474. */
  5475. // Manage IO Loaders
  5476. var IOController = function () {
  5477. function IOController(dataSource, config, extraData) {
  5478. _classCallCheck(this, IOController);
  5479. this.TAG = 'IOController';
  5480. this._config = config;
  5481. this._extraData = extraData;
  5482. this._stashInitialSize = 1024 * 384; // default initial size: 384KB
  5483. if (config.stashInitialSize != undefined && config.stashInitialSize > 0) {
  5484. // apply from config
  5485. this._stashInitialSize = config.stashInitialSize;
  5486. }
  5487. this._stashUsed = 0;
  5488. this._stashSize = this._stashInitialSize;
  5489. this._bufferSize = 1024 * 1024 * 3; // initial size: 3MB
  5490. this._stashBuffer = new ArrayBuffer(this._bufferSize);
  5491. this._stashByteStart = 0;
  5492. this._enableStash = true;
  5493. if (config.enableStashBuffer === false) {
  5494. this._enableStash = false;
  5495. }
  5496. this._loader = null;
  5497. this._loaderClass = null;
  5498. this._seekHandler = null;
  5499. this._dataSource = dataSource;
  5500. this._isWebSocketURL = /wss?:\/\/(.+?)/.test(dataSource.url);
  5501. this._refTotalLength = dataSource.filesize ? dataSource.filesize : null;
  5502. this._totalLength = this._refTotalLength;
  5503. this._fullRequestFlag = false;
  5504. this._currentRange = null;
  5505. this._redirectedURL = null;
  5506. this._speedNormalized = 0;
  5507. this._speedSampler = new _speedSampler2.default();
  5508. this._speedNormalizeList = [64, 128, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096];
  5509. this._isEarlyEofReconnecting = false;
  5510. this._paused = false;
  5511. this._resumeFrom = 0;
  5512. this._onDataArrival = null;
  5513. this._onSeeked = null;
  5514. this._onError = null;
  5515. this._onComplete = null;
  5516. this._onRedirect = null;
  5517. this._onRecoveredEarlyEof = null;
  5518. this._selectSeekHandler();
  5519. this._selectLoader();
  5520. this._createLoader();
  5521. }
  5522. _createClass(IOController, [{
  5523. key: 'destroy',
  5524. value: function destroy() {
  5525. if (this._loader.isWorking()) {
  5526. this._loader.abort();
  5527. }
  5528. this._loader.destroy();
  5529. this._loader = null;
  5530. this._loaderClass = null;
  5531. this._dataSource = null;
  5532. this._stashBuffer = null;
  5533. this._stashUsed = this._stashSize = this._bufferSize = this._stashByteStart = 0;
  5534. this._currentRange = null;
  5535. this._speedSampler = null;
  5536. this._isEarlyEofReconnecting = false;
  5537. this._onDataArrival = null;
  5538. this._onSeeked = null;
  5539. this._onError = null;
  5540. this._onComplete = null;
  5541. this._onRedirect = null;
  5542. this._onRecoveredEarlyEof = null;
  5543. this._extraData = null;
  5544. }
  5545. }, {
  5546. key: 'isWorking',
  5547. value: function isWorking() {
  5548. return this._loader && this._loader.isWorking() && !this._paused;
  5549. }
  5550. }, {
  5551. key: 'isPaused',
  5552. value: function isPaused() {
  5553. return this._paused;
  5554. }
  5555. }, {
  5556. key: '_selectSeekHandler',
  5557. value: function _selectSeekHandler() {
  5558. var config = this._config;
  5559. if (config.seekType === 'range') {
  5560. this._seekHandler = new _rangeSeekHandler2.default(this._config.rangeLoadZeroStart);
  5561. } else if (config.seekType === 'param') {
  5562. var paramStart = config.seekParamStart || 'bstart';
  5563. var paramEnd = config.seekParamEnd || 'bend';
  5564. this._seekHandler = new _paramSeekHandler2.default(paramStart, paramEnd);
  5565. } else if (config.seekType === 'custom') {
  5566. if (typeof config.customSeekHandler !== 'function') {
  5567. throw new _exception.InvalidArgumentException('Custom seekType specified in config but invalid customSeekHandler!');
  5568. }
  5569. this._seekHandler = new config.customSeekHandler();
  5570. } else {
  5571. throw new _exception.InvalidArgumentException('Invalid seekType in config: ' + config.seekType);
  5572. }
  5573. }
  5574. }, {
  5575. key: '_selectLoader',
  5576. value: function _selectLoader() {
  5577. if (this._isWebSocketURL) {
  5578. this._loaderClass = _websocketLoader2.default;
  5579. } else if (_fetchStreamLoader2.default.isSupported()) {
  5580. this._loaderClass = _fetchStreamLoader2.default;
  5581. } else if (_xhrMozChunkedLoader2.default.isSupported()) {
  5582. this._loaderClass = _xhrMozChunkedLoader2.default;
  5583. } else if (_xhrRangeLoader2.default.isSupported()) {
  5584. this._loaderClass = _xhrRangeLoader2.default;
  5585. } else {
  5586. throw new _exception.RuntimeException('Your browser doesn\'t support xhr with arraybuffer responseType!');
  5587. }
  5588. }
  5589. }, {
  5590. key: '_createLoader',
  5591. value: function _createLoader() {
  5592. this._loader = new this._loaderClass(this._seekHandler, this._config);
  5593. if (this._loader.needStashBuffer === false) {
  5594. this._enableStash = false;
  5595. }
  5596. this._loader.onContentLengthKnown = this._onContentLengthKnown.bind(this);
  5597. this._loader.onURLRedirect = this._onURLRedirect.bind(this);
  5598. this._loader.onDataArrival = this._onLoaderChunkArrival.bind(this);
  5599. this._loader.onComplete = this._onLoaderComplete.bind(this);
  5600. this._loader.onError = this._onLoaderError.bind(this);
  5601. }
  5602. }, {
  5603. key: 'open',
  5604. value: function open(optionalFrom) {
  5605. this._currentRange = { from: 0, to: -1 };
  5606. if (optionalFrom) {
  5607. this._currentRange.from = optionalFrom;
  5608. }
  5609. this._speedSampler.reset();
  5610. if (!optionalFrom) {
  5611. this._fullRequestFlag = true;
  5612. }
  5613. this._loader.open(this._dataSource, Object.assign({}, this._currentRange));
  5614. }
  5615. }, {
  5616. key: 'abort',
  5617. value: function abort() {
  5618. this._loader.abort();
  5619. if (this._paused) {
  5620. this._paused = false;
  5621. this._resumeFrom = 0;
  5622. }
  5623. }
  5624. }, {
  5625. key: 'pause',
  5626. value: function pause() {
  5627. if (this.isWorking()) {
  5628. this._loader.abort();
  5629. if (this._stashUsed !== 0) {
  5630. this._resumeFrom = this._stashByteStart;
  5631. this._currentRange.to = this._stashByteStart - 1;
  5632. } else {
  5633. this._resumeFrom = this._currentRange.to + 1;
  5634. }
  5635. this._stashUsed = 0;
  5636. this._stashByteStart = 0;
  5637. this._paused = true;
  5638. }
  5639. }
  5640. }, {
  5641. key: 'resume',
  5642. value: function resume() {
  5643. if (this._paused) {
  5644. this._paused = false;
  5645. var bytes = this._resumeFrom;
  5646. this._resumeFrom = 0;
  5647. this._internalSeek(bytes, true);
  5648. }
  5649. }
  5650. }, {
  5651. key: 'seek',
  5652. value: function seek(bytes) {
  5653. this._paused = false;
  5654. this._stashUsed = 0;
  5655. this._stashByteStart = 0;
  5656. this._internalSeek(bytes, true);
  5657. }
  5658. /**
  5659. * When seeking request is from media seeking, unconsumed stash data should be dropped
  5660. * However, stash data shouldn't be dropped if seeking requested from http reconnection
  5661. *
  5662. * @dropUnconsumed: Ignore and discard all unconsumed data in stash buffer
  5663. */
  5664. }, {
  5665. key: '_internalSeek',
  5666. value: function _internalSeek(bytes, dropUnconsumed) {
  5667. if (this._loader.isWorking()) {
  5668. this._loader.abort();
  5669. }
  5670. // dispatch & flush stash buffer before seek
  5671. this._flushStashBuffer(dropUnconsumed);
  5672. this._loader.destroy();
  5673. this._loader = null;
  5674. var requestRange = { from: bytes, to: -1 };
  5675. this._currentRange = { from: requestRange.from, to: -1 };
  5676. this._speedSampler.reset();
  5677. this._stashSize = this._stashInitialSize;
  5678. this._createLoader();
  5679. this._loader.open(this._dataSource, requestRange);
  5680. if (this._onSeeked) {
  5681. this._onSeeked();
  5682. }
  5683. }
  5684. }, {
  5685. key: 'updateUrl',
  5686. value: function updateUrl(url) {
  5687. if (!url || typeof url !== 'string' || url.length === 0) {
  5688. throw new _exception.InvalidArgumentException('Url must be a non-empty string!');
  5689. }
  5690. this._dataSource.url = url;
  5691. // TODO: replace with new url
  5692. }
  5693. }, {
  5694. key: '_expandBuffer',
  5695. value: function _expandBuffer(expectedBytes) {
  5696. var bufferNewSize = this._stashSize;
  5697. while (bufferNewSize + 1024 * 1024 * 1 < expectedBytes) {
  5698. bufferNewSize *= 2;
  5699. }
  5700. bufferNewSize += 1024 * 1024 * 1; // bufferSize = stashSize + 1MB
  5701. if (bufferNewSize === this._bufferSize) {
  5702. return;
  5703. }
  5704. var newBuffer = new ArrayBuffer(bufferNewSize);
  5705. if (this._stashUsed > 0) {
  5706. // copy existing data into new buffer
  5707. var stashOldArray = new Uint8Array(this._stashBuffer, 0, this._stashUsed);
  5708. var stashNewArray = new Uint8Array(newBuffer, 0, bufferNewSize);
  5709. stashNewArray.set(stashOldArray, 0);
  5710. }
  5711. this._stashBuffer = newBuffer;
  5712. this._bufferSize = bufferNewSize;
  5713. }
  5714. }, {
  5715. key: '_normalizeSpeed',
  5716. value: function _normalizeSpeed(input) {
  5717. var list = this._speedNormalizeList;
  5718. var last = list.length - 1;
  5719. var mid = 0;
  5720. var lbound = 0;
  5721. var ubound = last;
  5722. if (input < list[0]) {
  5723. return list[0];
  5724. }
  5725. // binary search
  5726. while (lbound <= ubound) {
  5727. mid = lbound + Math.floor((ubound - lbound) / 2);
  5728. if (mid === last || input >= list[mid] && input < list[mid + 1]) {
  5729. return list[mid];
  5730. } else if (list[mid] < input) {
  5731. lbound = mid + 1;
  5732. } else {
  5733. ubound = mid - 1;
  5734. }
  5735. }
  5736. }
  5737. }, {
  5738. key: '_adjustStashSize',
  5739. value: function _adjustStashSize(normalized) {
  5740. var stashSizeKB = 0;
  5741. if (this._config.isLive) {
  5742. // live stream: always use single normalized speed for size of stashSizeKB
  5743. stashSizeKB = normalized;
  5744. } else {
  5745. if (normalized < 512) {
  5746. stashSizeKB = normalized;
  5747. } else if (normalized >= 512 && normalized <= 1024) {
  5748. stashSizeKB = Math.floor(normalized * 1.5);
  5749. } else {
  5750. stashSizeKB = normalized * 2;
  5751. }
  5752. }
  5753. if (stashSizeKB > 8192) {
  5754. stashSizeKB = 8192;
  5755. }
  5756. var bufferSize = stashSizeKB * 1024 + 1024 * 1024 * 1; // stashSize + 1MB
  5757. if (this._bufferSize < bufferSize) {
  5758. this._expandBuffer(bufferSize);
  5759. }
  5760. this._stashSize = stashSizeKB * 1024;
  5761. }
  5762. }, {
  5763. key: '_dispatchChunks',
  5764. value: function _dispatchChunks(chunks, byteStart) {
  5765. this._currentRange.to = byteStart + chunks.byteLength - 1;
  5766. return this._onDataArrival(chunks, byteStart);
  5767. }
  5768. }, {
  5769. key: '_onURLRedirect',
  5770. value: function _onURLRedirect(redirectedURL) {
  5771. this._redirectedURL = redirectedURL;
  5772. if (this._onRedirect) {
  5773. this._onRedirect(redirectedURL);
  5774. }
  5775. }
  5776. }, {
  5777. key: '_onContentLengthKnown',
  5778. value: function _onContentLengthKnown(contentLength) {
  5779. if (contentLength && this._fullRequestFlag) {
  5780. this._totalLength = contentLength;
  5781. this._fullRequestFlag = false;
  5782. }
  5783. }
  5784. }, {
  5785. key: '_onLoaderChunkArrival',
  5786. value: function _onLoaderChunkArrival(chunk, byteStart, receivedLength) {
  5787. if (!this._onDataArrival) {
  5788. throw new _exception.IllegalStateException('IOController: No existing consumer (onDataArrival) callback!');
  5789. }
  5790. if (this._paused) {
  5791. return;
  5792. }
  5793. if (this._isEarlyEofReconnecting) {
  5794. // Auto-reconnect for EarlyEof succeed, notify to upper-layer by callback
  5795. this._isEarlyEofReconnecting = false;
  5796. if (this._onRecoveredEarlyEof) {
  5797. this._onRecoveredEarlyEof();
  5798. }
  5799. }
  5800. this._speedSampler.addBytes(chunk.byteLength);
  5801. // adjust stash buffer size according to network speed dynamically
  5802. var KBps = this._speedSampler.lastSecondKBps;
  5803. if (KBps !== 0) {
  5804. var normalized = this._normalizeSpeed(KBps);
  5805. if (this._speedNormalized !== normalized) {
  5806. this._speedNormalized = normalized;
  5807. this._adjustStashSize(normalized);
  5808. }
  5809. }
  5810. if (!this._enableStash) {
  5811. // disable stash
  5812. if (this._stashUsed === 0) {
  5813. // dispatch chunk directly to consumer;
  5814. // check ret value (consumed bytes) and stash unconsumed to stashBuffer
  5815. var consumed = this._dispatchChunks(chunk, byteStart);
  5816. if (consumed < chunk.byteLength) {
  5817. // unconsumed data remain.
  5818. var remain = chunk.byteLength - consumed;
  5819. if (remain > this._bufferSize) {
  5820. this._expandBuffer(remain);
  5821. }
  5822. var stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  5823. stashArray.set(new Uint8Array(chunk, consumed), 0);
  5824. this._stashUsed += remain;
  5825. this._stashByteStart = byteStart + consumed;
  5826. }
  5827. } else {
  5828. // else: Merge chunk into stashBuffer, and dispatch stashBuffer to consumer.
  5829. if (this._stashUsed + chunk.byteLength > this._bufferSize) {
  5830. this._expandBuffer(this._stashUsed + chunk.byteLength);
  5831. }
  5832. var _stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  5833. _stashArray.set(new Uint8Array(chunk), this._stashUsed);
  5834. this._stashUsed += chunk.byteLength;
  5835. var _consumed = this._dispatchChunks(this._stashBuffer.slice(0, this._stashUsed), this._stashByteStart);
  5836. if (_consumed < this._stashUsed && _consumed > 0) {
  5837. // unconsumed data remain
  5838. var remainArray = new Uint8Array(this._stashBuffer, _consumed);
  5839. _stashArray.set(remainArray, 0);
  5840. }
  5841. this._stashUsed -= _consumed;
  5842. this._stashByteStart += _consumed;
  5843. }
  5844. } else {
  5845. // enable stash
  5846. if (this._stashUsed === 0 && this._stashByteStart === 0) {
  5847. // seeked? or init chunk?
  5848. // This is the first chunk after seek action
  5849. this._stashByteStart = byteStart;
  5850. }
  5851. if (this._stashUsed + chunk.byteLength <= this._stashSize) {
  5852. // just stash
  5853. var _stashArray2 = new Uint8Array(this._stashBuffer, 0, this._stashSize);
  5854. _stashArray2.set(new Uint8Array(chunk), this._stashUsed);
  5855. this._stashUsed += chunk.byteLength;
  5856. } else {
  5857. // stashUsed + chunkSize > stashSize, size limit exceeded
  5858. var _stashArray3 = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  5859. if (this._stashUsed > 0) {
  5860. // There're stash datas in buffer
  5861. // dispatch the whole stashBuffer, and stash remain data
  5862. // then append chunk to stashBuffer (stash)
  5863. var buffer = this._stashBuffer.slice(0, this._stashUsed);
  5864. var _consumed2 = this._dispatchChunks(buffer, this._stashByteStart);
  5865. if (_consumed2 < buffer.byteLength) {
  5866. if (_consumed2 > 0) {
  5867. var _remainArray = new Uint8Array(buffer, _consumed2);
  5868. _stashArray3.set(_remainArray, 0);
  5869. this._stashUsed = _remainArray.byteLength;
  5870. this._stashByteStart += _consumed2;
  5871. }
  5872. } else {
  5873. this._stashUsed = 0;
  5874. this._stashByteStart += _consumed2;
  5875. }
  5876. if (this._stashUsed + chunk.byteLength > this._bufferSize) {
  5877. this._expandBuffer(this._stashUsed + chunk.byteLength);
  5878. _stashArray3 = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  5879. }
  5880. _stashArray3.set(new Uint8Array(chunk), this._stashUsed);
  5881. this._stashUsed += chunk.byteLength;
  5882. } else {
  5883. // stash buffer empty, but chunkSize > stashSize (oh, holy shit)
  5884. // dispatch chunk directly and stash remain data
  5885. var _consumed3 = this._dispatchChunks(chunk, byteStart);
  5886. if (_consumed3 < chunk.byteLength) {
  5887. var _remain = chunk.byteLength - _consumed3;
  5888. if (_remain > this._bufferSize) {
  5889. this._expandBuffer(_remain);
  5890. _stashArray3 = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  5891. }
  5892. _stashArray3.set(new Uint8Array(chunk, _consumed3), 0);
  5893. this._stashUsed += _remain;
  5894. this._stashByteStart = byteStart + _consumed3;
  5895. }
  5896. }
  5897. }
  5898. }
  5899. }
  5900. }, {
  5901. key: '_flushStashBuffer',
  5902. value: function _flushStashBuffer(dropUnconsumed) {
  5903. if (this._stashUsed > 0) {
  5904. var buffer = this._stashBuffer.slice(0, this._stashUsed);
  5905. var consumed = this._dispatchChunks(buffer, this._stashByteStart);
  5906. var remain = buffer.byteLength - consumed;
  5907. if (consumed < buffer.byteLength) {
  5908. if (dropUnconsumed) {
  5909. _logger2.default.w(this.TAG, remain + ' bytes unconsumed data remain when flush buffer, dropped');
  5910. } else {
  5911. if (consumed > 0) {
  5912. var stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  5913. var remainArray = new Uint8Array(buffer, consumed);
  5914. stashArray.set(remainArray, 0);
  5915. this._stashUsed = remainArray.byteLength;
  5916. this._stashByteStart += consumed;
  5917. }
  5918. return 0;
  5919. }
  5920. }
  5921. this._stashUsed = 0;
  5922. this._stashByteStart = 0;
  5923. return remain;
  5924. }
  5925. return 0;
  5926. }
  5927. }, {
  5928. key: '_onLoaderComplete',
  5929. value: function _onLoaderComplete(from, to) {
  5930. // Force-flush stash buffer, and drop unconsumed data
  5931. this._flushStashBuffer(true);
  5932. if (this._onComplete) {
  5933. this._onComplete(this._extraData);
  5934. }
  5935. }
  5936. }, {
  5937. key: '_onLoaderError',
  5938. value: function _onLoaderError(type, data) {
  5939. _logger2.default.e(this.TAG, 'Loader error, code = ' + data.code + ', msg = ' + data.msg);
  5940. this._flushStashBuffer(false);
  5941. if (this._isEarlyEofReconnecting) {
  5942. // Auto-reconnect for EarlyEof failed, throw UnrecoverableEarlyEof error to upper-layer
  5943. this._isEarlyEofReconnecting = false;
  5944. type = _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF;
  5945. }
  5946. switch (type) {
  5947. case _loader.LoaderErrors.EARLY_EOF:
  5948. {
  5949. if (!this._config.isLive) {
  5950. // Do internal http reconnect if not live stream
  5951. if (this._totalLength) {
  5952. var nextFrom = this._currentRange.to + 1;
  5953. if (nextFrom < this._totalLength) {
  5954. _logger2.default.w(this.TAG, 'Connection lost, trying reconnect...');
  5955. this._isEarlyEofReconnecting = true;
  5956. this._internalSeek(nextFrom, false);
  5957. }
  5958. return;
  5959. }
  5960. // else: We don't know totalLength, throw UnrecoverableEarlyEof
  5961. }
  5962. // live stream: throw UnrecoverableEarlyEof error to upper-layer
  5963. type = _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF;
  5964. break;
  5965. }
  5966. case _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF:
  5967. case _loader.LoaderErrors.CONNECTING_TIMEOUT:
  5968. case _loader.LoaderErrors.HTTP_STATUS_CODE_INVALID:
  5969. case _loader.LoaderErrors.EXCEPTION:
  5970. break;
  5971. }
  5972. if (this._onError) {
  5973. this._onError(type, data);
  5974. } else {
  5975. throw new _exception.RuntimeException('IOException: ' + data.msg);
  5976. }
  5977. }
  5978. }, {
  5979. key: 'status',
  5980. get: function get() {
  5981. return this._loader.status;
  5982. }
  5983. }, {
  5984. key: 'extraData',
  5985. get: function get() {
  5986. return this._extraData;
  5987. },
  5988. set: function set(data) {
  5989. this._extraData = data;
  5990. }
  5991. // prototype: function onDataArrival(chunks: ArrayBuffer, byteStart: number): number
  5992. }, {
  5993. key: 'onDataArrival',
  5994. get: function get() {
  5995. return this._onDataArrival;
  5996. },
  5997. set: function set(callback) {
  5998. this._onDataArrival = callback;
  5999. }
  6000. }, {
  6001. key: 'onSeeked',
  6002. get: function get() {
  6003. return this._onSeeked;
  6004. },
  6005. set: function set(callback) {
  6006. this._onSeeked = callback;
  6007. }
  6008. // prototype: function onError(type: number, info: {code: number, msg: string}): void
  6009. }, {
  6010. key: 'onError',
  6011. get: function get() {
  6012. return this._onError;
  6013. },
  6014. set: function set(callback) {
  6015. this._onError = callback;
  6016. }
  6017. }, {
  6018. key: 'onComplete',
  6019. get: function get() {
  6020. return this._onComplete;
  6021. },
  6022. set: function set(callback) {
  6023. this._onComplete = callback;
  6024. }
  6025. }, {
  6026. key: 'onRedirect',
  6027. get: function get() {
  6028. return this._onRedirect;
  6029. },
  6030. set: function set(callback) {
  6031. this._onRedirect = callback;
  6032. }
  6033. }, {
  6034. key: 'onRecoveredEarlyEof',
  6035. get: function get() {
  6036. return this._onRecoveredEarlyEof;
  6037. },
  6038. set: function set(callback) {
  6039. this._onRecoveredEarlyEof = callback;
  6040. }
  6041. }, {
  6042. key: 'currentURL',
  6043. get: function get() {
  6044. return this._dataSource.url;
  6045. }
  6046. }, {
  6047. key: 'hasRedirect',
  6048. get: function get() {
  6049. return this._redirectedURL != null || this._dataSource.redirectedURL != undefined;
  6050. }
  6051. }, {
  6052. key: 'currentRedirectedURL',
  6053. get: function get() {
  6054. return this._redirectedURL || this._dataSource.redirectedURL;
  6055. }
  6056. // in KB/s
  6057. }, {
  6058. key: 'currentSpeed',
  6059. get: function get() {
  6060. if (this._loaderClass === _xhrRangeLoader2.default) {
  6061. // SpeedSampler is inaccuracy if loader is RangeLoader
  6062. return this._loader.currentSpeed;
  6063. }
  6064. return this._speedSampler.lastSecondKBps;
  6065. }
  6066. }, {
  6067. key: 'loaderType',
  6068. get: function get() {
  6069. return this._loader.type;
  6070. }
  6071. }]);
  6072. return IOController;
  6073. }();
  6074. exports.default = IOController;
  6075. },{"../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){
  6076. 'use strict';
  6077. Object.defineProperty(exports, "__esModule", {
  6078. value: true
  6079. });
  6080. exports.BaseLoader = exports.LoaderErrors = exports.LoaderStatus = undefined;
  6081. 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; }; }(); /*
  6082. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  6083. *
  6084. * @author zheng qian <xqq@xqq.im>
  6085. *
  6086. * Licensed under the Apache License, Version 2.0 (the "License");
  6087. * you may not use this file except in compliance with the License.
  6088. * You may obtain a copy of the License at
  6089. *
  6090. * http://www.apache.org/licenses/LICENSE-2.0
  6091. *
  6092. * Unless required by applicable law or agreed to in writing, software
  6093. * distributed under the License is distributed on an "AS IS" BASIS,
  6094. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6095. * See the License for the specific language governing permissions and
  6096. * limitations under the License.
  6097. */
  6098. var _exception = _dereq_('../utils/exception.js');
  6099. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6100. var LoaderStatus = exports.LoaderStatus = {
  6101. kIdle: 0,
  6102. kConnecting: 1,
  6103. kBuffering: 2,
  6104. kError: 3,
  6105. kComplete: 4
  6106. };
  6107. var LoaderErrors = exports.LoaderErrors = {
  6108. OK: 'OK',
  6109. EXCEPTION: 'Exception',
  6110. HTTP_STATUS_CODE_INVALID: 'HttpStatusCodeInvalid',
  6111. CONNECTING_TIMEOUT: 'ConnectingTimeout',
  6112. EARLY_EOF: 'EarlyEof',
  6113. UNRECOVERABLE_EARLY_EOF: 'UnrecoverableEarlyEof'
  6114. };
  6115. /* Loader has callbacks which have following prototypes:
  6116. * function onContentLengthKnown(contentLength: number): void
  6117. * function onURLRedirect(url: string): void
  6118. * function onDataArrival(chunk: ArrayBuffer, byteStart: number, receivedLength: number): void
  6119. * function onError(errorType: number, errorInfo: {code: number, msg: string}): void
  6120. * function onComplete(rangeFrom: number, rangeTo: number): void
  6121. */
  6122. var BaseLoader = exports.BaseLoader = function () {
  6123. function BaseLoader(typeName) {
  6124. _classCallCheck(this, BaseLoader);
  6125. this._type = typeName || 'undefined';
  6126. this._status = LoaderStatus.kIdle;
  6127. this._needStash = false;
  6128. // callbacks
  6129. this._onContentLengthKnown = null;
  6130. this._onURLRedirect = null;
  6131. this._onDataArrival = null;
  6132. this._onError = null;
  6133. this._onComplete = null;
  6134. }
  6135. _createClass(BaseLoader, [{
  6136. key: 'destroy',
  6137. value: function destroy() {
  6138. this._status = LoaderStatus.kIdle;
  6139. this._onContentLengthKnown = null;
  6140. this._onURLRedirect = null;
  6141. this._onDataArrival = null;
  6142. this._onError = null;
  6143. this._onComplete = null;
  6144. }
  6145. }, {
  6146. key: 'isWorking',
  6147. value: function isWorking() {
  6148. return this._status === LoaderStatus.kConnecting || this._status === LoaderStatus.kBuffering;
  6149. }
  6150. }, {
  6151. key: 'open',
  6152. // pure virtual
  6153. value: function open(dataSource, range) {
  6154. throw new _exception.NotImplementedException('Unimplemented abstract function!');
  6155. }
  6156. }, {
  6157. key: 'abort',
  6158. value: function abort() {
  6159. throw new _exception.NotImplementedException('Unimplemented abstract function!');
  6160. }
  6161. }, {
  6162. key: 'type',
  6163. get: function get() {
  6164. return this._type;
  6165. }
  6166. }, {
  6167. key: 'status',
  6168. get: function get() {
  6169. return this._status;
  6170. }
  6171. }, {
  6172. key: 'needStashBuffer',
  6173. get: function get() {
  6174. return this._needStash;
  6175. }
  6176. }, {
  6177. key: 'onContentLengthKnown',
  6178. get: function get() {
  6179. return this._onContentLengthKnown;
  6180. },
  6181. set: function set(callback) {
  6182. this._onContentLengthKnown = callback;
  6183. }
  6184. }, {
  6185. key: 'onURLRedirect',
  6186. get: function get() {
  6187. return this._onURLRedirect;
  6188. },
  6189. set: function set(callback) {
  6190. this._onURLRedirect = callback;
  6191. }
  6192. }, {
  6193. key: 'onDataArrival',
  6194. get: function get() {
  6195. return this._onDataArrival;
  6196. },
  6197. set: function set(callback) {
  6198. this._onDataArrival = callback;
  6199. }
  6200. }, {
  6201. key: 'onError',
  6202. get: function get() {
  6203. return this._onError;
  6204. },
  6205. set: function set(callback) {
  6206. this._onError = callback;
  6207. }
  6208. }, {
  6209. key: 'onComplete',
  6210. get: function get() {
  6211. return this._onComplete;
  6212. },
  6213. set: function set(callback) {
  6214. this._onComplete = callback;
  6215. }
  6216. }]);
  6217. return BaseLoader;
  6218. }();
  6219. },{"../utils/exception.js":40}],25:[function(_dereq_,module,exports){
  6220. 'use strict';
  6221. Object.defineProperty(exports, "__esModule", {
  6222. value: true
  6223. });
  6224. 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; }; }();
  6225. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6226. /*
  6227. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  6228. *
  6229. * @author zheng qian <xqq@xqq.im>
  6230. *
  6231. * Licensed under the Apache License, Version 2.0 (the "License");
  6232. * you may not use this file except in compliance with the License.
  6233. * You may obtain a copy of the License at
  6234. *
  6235. * http://www.apache.org/licenses/LICENSE-2.0
  6236. *
  6237. * Unless required by applicable law or agreed to in writing, software
  6238. * distributed under the License is distributed on an "AS IS" BASIS,
  6239. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6240. * See the License for the specific language governing permissions and
  6241. * limitations under the License.
  6242. */
  6243. var ParamSeekHandler = function () {
  6244. function ParamSeekHandler(paramStart, paramEnd) {
  6245. _classCallCheck(this, ParamSeekHandler);
  6246. this._startName = paramStart;
  6247. this._endName = paramEnd;
  6248. }
  6249. _createClass(ParamSeekHandler, [{
  6250. key: 'getConfig',
  6251. value: function getConfig(baseUrl, range) {
  6252. var url = baseUrl;
  6253. if (range.from !== 0 || range.to !== -1) {
  6254. var needAnd = true;
  6255. if (url.indexOf('?') === -1) {
  6256. url += '?';
  6257. needAnd = false;
  6258. }
  6259. if (needAnd) {
  6260. url += '&';
  6261. }
  6262. url += this._startName + '=' + range.from.toString();
  6263. if (range.to !== -1) {
  6264. url += '&' + this._endName + '=' + range.to.toString();
  6265. }
  6266. }
  6267. return {
  6268. url: url,
  6269. headers: {}
  6270. };
  6271. }
  6272. }, {
  6273. key: 'removeURLParameters',
  6274. value: function removeURLParameters(seekedURL) {
  6275. var baseURL = seekedURL.split('?')[0];
  6276. var params = undefined;
  6277. var queryIndex = seekedURL.indexOf('?');
  6278. if (queryIndex !== -1) {
  6279. params = seekedURL.substring(queryIndex + 1);
  6280. }
  6281. var resultParams = '';
  6282. if (params != undefined && params.length > 0) {
  6283. var pairs = params.split('&');
  6284. for (var i = 0; i < pairs.length; i++) {
  6285. var pair = pairs[i].split('=');
  6286. var requireAnd = i > 0;
  6287. if (pair[0] !== this._startName && pair[0] !== this._endName) {
  6288. if (requireAnd) {
  6289. resultParams += '&';
  6290. }
  6291. resultParams += pairs[i];
  6292. }
  6293. }
  6294. }
  6295. return resultParams.length === 0 ? baseURL : baseURL + '?' + resultParams;
  6296. }
  6297. }]);
  6298. return ParamSeekHandler;
  6299. }();
  6300. exports.default = ParamSeekHandler;
  6301. },{}],26:[function(_dereq_,module,exports){
  6302. 'use strict';
  6303. Object.defineProperty(exports, "__esModule", {
  6304. value: true
  6305. });
  6306. 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; }; }();
  6307. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6308. /*
  6309. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  6310. *
  6311. * @author zheng qian <xqq@xqq.im>
  6312. *
  6313. * Licensed under the Apache License, Version 2.0 (the "License");
  6314. * you may not use this file except in compliance with the License.
  6315. * You may obtain a copy of the License at
  6316. *
  6317. * http://www.apache.org/licenses/LICENSE-2.0
  6318. *
  6319. * Unless required by applicable law or agreed to in writing, software
  6320. * distributed under the License is distributed on an "AS IS" BASIS,
  6321. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6322. * See the License for the specific language governing permissions and
  6323. * limitations under the License.
  6324. */
  6325. var RangeSeekHandler = function () {
  6326. function RangeSeekHandler(zeroStart) {
  6327. _classCallCheck(this, RangeSeekHandler);
  6328. this._zeroStart = zeroStart || false;
  6329. }
  6330. _createClass(RangeSeekHandler, [{
  6331. key: 'getConfig',
  6332. value: function getConfig(url, range) {
  6333. var headers = {};
  6334. if (range.from !== 0 || range.to !== -1) {
  6335. var param = void 0;
  6336. if (range.to !== -1) {
  6337. param = 'bytes=' + range.from.toString() + '-' + range.to.toString();
  6338. } else {
  6339. param = 'bytes=' + range.from.toString() + '-';
  6340. }
  6341. headers['Range'] = param;
  6342. } else if (this._zeroStart) {
  6343. headers['Range'] = 'bytes=0-';
  6344. }
  6345. return {
  6346. url: url,
  6347. headers: headers
  6348. };
  6349. }
  6350. }, {
  6351. key: 'removeURLParameters',
  6352. value: function removeURLParameters(seekedURL) {
  6353. return seekedURL;
  6354. }
  6355. }]);
  6356. return RangeSeekHandler;
  6357. }();
  6358. exports.default = RangeSeekHandler;
  6359. },{}],27:[function(_dereq_,module,exports){
  6360. "use strict";
  6361. Object.defineProperty(exports, "__esModule", {
  6362. value: true
  6363. });
  6364. 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; }; }();
  6365. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6366. /*
  6367. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  6368. *
  6369. * @author zheng qian <xqq@xqq.im>
  6370. *
  6371. * Licensed under the Apache License, Version 2.0 (the "License");
  6372. * you may not use this file except in compliance with the License.
  6373. * You may obtain a copy of the License at
  6374. *
  6375. * http://www.apache.org/licenses/LICENSE-2.0
  6376. *
  6377. * Unless required by applicable law or agreed to in writing, software
  6378. * distributed under the License is distributed on an "AS IS" BASIS,
  6379. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6380. * See the License for the specific language governing permissions and
  6381. * limitations under the License.
  6382. */
  6383. // Utility class to calculate realtime network I/O speed
  6384. var SpeedSampler = function () {
  6385. function SpeedSampler() {
  6386. _classCallCheck(this, SpeedSampler);
  6387. // milliseconds
  6388. this._firstCheckpoint = 0;
  6389. this._lastCheckpoint = 0;
  6390. this._intervalBytes = 0;
  6391. this._totalBytes = 0;
  6392. this._lastSecondBytes = 0;
  6393. // compatibility detection
  6394. if (self.performance && self.performance.now) {
  6395. this._now = self.performance.now.bind(self.performance);
  6396. } else {
  6397. this._now = Date.now;
  6398. }
  6399. }
  6400. _createClass(SpeedSampler, [{
  6401. key: "reset",
  6402. value: function reset() {
  6403. this._firstCheckpoint = this._lastCheckpoint = 0;
  6404. this._totalBytes = this._intervalBytes = 0;
  6405. this._lastSecondBytes = 0;
  6406. }
  6407. }, {
  6408. key: "addBytes",
  6409. value: function addBytes(bytes) {
  6410. if (this._firstCheckpoint === 0) {
  6411. this._firstCheckpoint = this._now();
  6412. this._lastCheckpoint = this._firstCheckpoint;
  6413. this._intervalBytes += bytes;
  6414. this._totalBytes += bytes;
  6415. } else if (this._now() - this._lastCheckpoint < 1000) {
  6416. this._intervalBytes += bytes;
  6417. this._totalBytes += bytes;
  6418. } else {
  6419. // duration >= 1000
  6420. this._lastSecondBytes = this._intervalBytes;
  6421. this._intervalBytes = bytes;
  6422. this._totalBytes += bytes;
  6423. this._lastCheckpoint = this._now();
  6424. }
  6425. }
  6426. }, {
  6427. key: "currentKBps",
  6428. get: function get() {
  6429. this.addBytes(0);
  6430. var durationSeconds = (this._now() - this._lastCheckpoint) / 1000;
  6431. if (durationSeconds == 0) durationSeconds = 1;
  6432. return this._intervalBytes / durationSeconds / 1024;
  6433. }
  6434. }, {
  6435. key: "lastSecondKBps",
  6436. get: function get() {
  6437. this.addBytes(0);
  6438. if (this._lastSecondBytes !== 0) {
  6439. return this._lastSecondBytes / 1024;
  6440. } else {
  6441. // lastSecondBytes === 0
  6442. if (this._now() - this._lastCheckpoint >= 500) {
  6443. // if time interval since last checkpoint has exceeded 500ms
  6444. // the speed is nearly accurate
  6445. return this.currentKBps;
  6446. } else {
  6447. // We don't know
  6448. return 0;
  6449. }
  6450. }
  6451. }
  6452. }, {
  6453. key: "averageKBps",
  6454. get: function get() {
  6455. var durationSeconds = (this._now() - this._firstCheckpoint) / 1000;
  6456. return this._totalBytes / durationSeconds / 1024;
  6457. }
  6458. }]);
  6459. return SpeedSampler;
  6460. }();
  6461. exports.default = SpeedSampler;
  6462. },{}],28:[function(_dereq_,module,exports){
  6463. 'use strict';
  6464. Object.defineProperty(exports, "__esModule", {
  6465. value: true
  6466. });
  6467. 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); } };
  6468. 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; }; }();
  6469. var _logger = _dereq_('../utils/logger.js');
  6470. var _logger2 = _interopRequireDefault(_logger);
  6471. var _loader = _dereq_('./loader.js');
  6472. var _exception = _dereq_('../utils/exception.js');
  6473. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6474. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6475. 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; }
  6476. 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; } /*
  6477. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  6478. *
  6479. * @author zheng qian <xqq@xqq.im>
  6480. *
  6481. * Licensed under the Apache License, Version 2.0 (the "License");
  6482. * you may not use this file except in compliance with the License.
  6483. * You may obtain a copy of the License at
  6484. *
  6485. * http://www.apache.org/licenses/LICENSE-2.0
  6486. *
  6487. * Unless required by applicable law or agreed to in writing, software
  6488. * distributed under the License is distributed on an "AS IS" BASIS,
  6489. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6490. * See the License for the specific language governing permissions and
  6491. * limitations under the License.
  6492. */
  6493. // For FLV over WebSocket live stream
  6494. var WebSocketLoader = function (_BaseLoader) {
  6495. _inherits(WebSocketLoader, _BaseLoader);
  6496. _createClass(WebSocketLoader, null, [{
  6497. key: 'isSupported',
  6498. value: function isSupported() {
  6499. try {
  6500. return typeof self.WebSocket !== 'undefined';
  6501. } catch (e) {
  6502. return false;
  6503. }
  6504. }
  6505. }]);
  6506. function WebSocketLoader() {
  6507. _classCallCheck(this, WebSocketLoader);
  6508. var _this = _possibleConstructorReturn(this, (WebSocketLoader.__proto__ || Object.getPrototypeOf(WebSocketLoader)).call(this, 'websocket-loader'));
  6509. _this.TAG = 'WebSocketLoader';
  6510. _this._needStash = true;
  6511. _this._ws = null;
  6512. _this._requestAbort = false;
  6513. _this._receivedLength = 0;
  6514. return _this;
  6515. }
  6516. _createClass(WebSocketLoader, [{
  6517. key: 'destroy',
  6518. value: function destroy() {
  6519. if (this._ws) {
  6520. this.abort();
  6521. }
  6522. _get(WebSocketLoader.prototype.__proto__ || Object.getPrototypeOf(WebSocketLoader.prototype), 'destroy', this).call(this);
  6523. }
  6524. }, {
  6525. key: 'open',
  6526. value: function open(dataSource) {
  6527. try {
  6528. var ws = this._ws = new self.WebSocket(dataSource.url);
  6529. ws.binaryType = 'arraybuffer';
  6530. ws.onopen = this._onWebSocketOpen.bind(this);
  6531. ws.onclose = this._onWebSocketClose.bind(this);
  6532. ws.onmessage = this._onWebSocketMessage.bind(this);
  6533. ws.onerror = this._onWebSocketError.bind(this);
  6534. this._status = _loader.LoaderStatus.kConnecting;
  6535. } catch (e) {
  6536. this._status = _loader.LoaderStatus.kError;
  6537. var info = { code: e.code, msg: e.message };
  6538. if (this._onError) {
  6539. this._onError(_loader.LoaderErrors.EXCEPTION, info);
  6540. } else {
  6541. throw new _exception.RuntimeException(info.msg);
  6542. }
  6543. }
  6544. }
  6545. }, {
  6546. key: 'abort',
  6547. value: function abort() {
  6548. var ws = this._ws;
  6549. if (ws && (ws.readyState === 0 || ws.readyState === 1)) {
  6550. // CONNECTING || OPEN
  6551. this._requestAbort = true;
  6552. ws.close();
  6553. }
  6554. this._ws = null;
  6555. this._status = _loader.LoaderStatus.kComplete;
  6556. }
  6557. }, {
  6558. key: '_onWebSocketOpen',
  6559. value: function _onWebSocketOpen(e) {
  6560. this._status = _loader.LoaderStatus.kBuffering;
  6561. }
  6562. }, {
  6563. key: '_onWebSocketClose',
  6564. value: function _onWebSocketClose(e) {
  6565. if (this._requestAbort === true) {
  6566. this._requestAbort = false;
  6567. return;
  6568. }
  6569. this._status = _loader.LoaderStatus.kComplete;
  6570. if (this._onComplete) {
  6571. this._onComplete(0, this._receivedLength - 1);
  6572. }
  6573. }
  6574. }, {
  6575. key: '_onWebSocketMessage',
  6576. value: function _onWebSocketMessage(e) {
  6577. var _this2 = this;
  6578. if (e.data instanceof ArrayBuffer) {
  6579. this._dispatchArrayBuffer(e.data);
  6580. } else if (e.data instanceof Blob) {
  6581. var reader = new FileReader();
  6582. reader.onload = function () {
  6583. _this2._dispatchArrayBuffer(reader.result);
  6584. };
  6585. reader.readAsArrayBuffer(e.data);
  6586. } else {
  6587. this._status = _loader.LoaderStatus.kError;
  6588. var info = { code: -1, msg: 'Unsupported WebSocket message type: ' + e.data.constructor.name };
  6589. if (this._onError) {
  6590. this._onError(_loader.LoaderErrors.EXCEPTION, info);
  6591. } else {
  6592. throw new _exception.RuntimeException(info.msg);
  6593. }
  6594. }
  6595. }
  6596. }, {
  6597. key: '_dispatchArrayBuffer',
  6598. value: function _dispatchArrayBuffer(arraybuffer) {
  6599. var chunk = arraybuffer;
  6600. var byteStart = this._receivedLength;
  6601. this._receivedLength += chunk.byteLength;
  6602. if (this._onDataArrival) {
  6603. this._onDataArrival(chunk, byteStart, this._receivedLength);
  6604. }
  6605. }
  6606. }, {
  6607. key: '_onWebSocketError',
  6608. value: function _onWebSocketError(e) {
  6609. this._status = _loader.LoaderStatus.kError;
  6610. var info = {
  6611. code: e.code,
  6612. msg: e.message
  6613. };
  6614. if (this._onError) {
  6615. this._onError(_loader.LoaderErrors.EXCEPTION, info);
  6616. } else {
  6617. throw new _exception.RuntimeException(info.msg);
  6618. }
  6619. }
  6620. }]);
  6621. return WebSocketLoader;
  6622. }(_loader.BaseLoader);
  6623. exports.default = WebSocketLoader;
  6624. },{"../utils/exception.js":40,"../utils/logger.js":41,"./loader.js":24}],29:[function(_dereq_,module,exports){
  6625. 'use strict';
  6626. Object.defineProperty(exports, "__esModule", {
  6627. value: true
  6628. });
  6629. 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; };
  6630. 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); } };
  6631. 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; }; }();
  6632. var _logger = _dereq_('../utils/logger.js');
  6633. var _logger2 = _interopRequireDefault(_logger);
  6634. var _loader = _dereq_('./loader.js');
  6635. var _exception = _dereq_('../utils/exception.js');
  6636. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6637. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6638. 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; }
  6639. 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; } /*
  6640. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  6641. *
  6642. * @author zheng qian <xqq@xqq.im>
  6643. *
  6644. * Licensed under the Apache License, Version 2.0 (the "License");
  6645. * you may not use this file except in compliance with the License.
  6646. * You may obtain a copy of the License at
  6647. *
  6648. * http://www.apache.org/licenses/LICENSE-2.0
  6649. *
  6650. * Unless required by applicable law or agreed to in writing, software
  6651. * distributed under the License is distributed on an "AS IS" BASIS,
  6652. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6653. * See the License for the specific language governing permissions and
  6654. * limitations under the License.
  6655. */
  6656. // For FireFox browser which supports `xhr.responseType = 'moz-chunked-arraybuffer'`
  6657. var MozChunkedLoader = function (_BaseLoader) {
  6658. _inherits(MozChunkedLoader, _BaseLoader);
  6659. _createClass(MozChunkedLoader, null, [{
  6660. key: 'isSupported',
  6661. value: function isSupported() {
  6662. try {
  6663. var xhr = new XMLHttpRequest();
  6664. // Firefox 37- requires .open() to be called before setting responseType
  6665. xhr.open('GET', 'https://example.com', true);
  6666. xhr.responseType = 'moz-chunked-arraybuffer';
  6667. return xhr.responseType === 'moz-chunked-arraybuffer';
  6668. } catch (e) {
  6669. _logger2.default.w('MozChunkedLoader', e.message);
  6670. return false;
  6671. }
  6672. }
  6673. }]);
  6674. function MozChunkedLoader(seekHandler, config) {
  6675. _classCallCheck(this, MozChunkedLoader);
  6676. var _this = _possibleConstructorReturn(this, (MozChunkedLoader.__proto__ || Object.getPrototypeOf(MozChunkedLoader)).call(this, 'xhr-moz-chunked-loader'));
  6677. _this.TAG = 'MozChunkedLoader';
  6678. _this._seekHandler = seekHandler;
  6679. _this._config = config;
  6680. _this._needStash = true;
  6681. _this._xhr = null;
  6682. _this._requestAbort = false;
  6683. _this._contentLength = null;
  6684. _this._receivedLength = 0;
  6685. return _this;
  6686. }
  6687. _createClass(MozChunkedLoader, [{
  6688. key: 'destroy',
  6689. value: function destroy() {
  6690. if (this.isWorking()) {
  6691. this.abort();
  6692. }
  6693. if (this._xhr) {
  6694. this._xhr.onreadystatechange = null;
  6695. this._xhr.onprogress = null;
  6696. this._xhr.onloadend = null;
  6697. this._xhr.onerror = null;
  6698. this._xhr = null;
  6699. }
  6700. _get(MozChunkedLoader.prototype.__proto__ || Object.getPrototypeOf(MozChunkedLoader.prototype), 'destroy', this).call(this);
  6701. }
  6702. }, {
  6703. key: 'open',
  6704. value: function open(dataSource, range) {
  6705. this._dataSource = dataSource;
  6706. this._range = range;
  6707. var sourceURL = dataSource.url;
  6708. if (this._config.reuseRedirectedURL && dataSource.redirectedURL != undefined) {
  6709. sourceURL = dataSource.redirectedURL;
  6710. }
  6711. var seekConfig = this._seekHandler.getConfig(sourceURL, range);
  6712. this._requestURL = seekConfig.url;
  6713. var xhr = this._xhr = new XMLHttpRequest();
  6714. xhr.open('GET', seekConfig.url, true);
  6715. xhr.responseType = 'moz-chunked-arraybuffer';
  6716. xhr.onreadystatechange = this._onReadyStateChange.bind(this);
  6717. xhr.onprogress = this._onProgress.bind(this);
  6718. xhr.onloadend = this._onLoadEnd.bind(this);
  6719. xhr.onerror = this._onXhrError.bind(this);
  6720. // cors is auto detected and enabled by xhr
  6721. // withCredentials is disabled by default
  6722. if (dataSource.withCredentials) {
  6723. xhr.withCredentials = true;
  6724. }
  6725. if (_typeof(seekConfig.headers) === 'object') {
  6726. var headers = seekConfig.headers;
  6727. for (var key in headers) {
  6728. if (headers.hasOwnProperty(key)) {
  6729. xhr.setRequestHeader(key, headers[key]);
  6730. }
  6731. }
  6732. }
  6733. this._status = _loader.LoaderStatus.kConnecting;
  6734. xhr.send();
  6735. }
  6736. }, {
  6737. key: 'abort',
  6738. value: function abort() {
  6739. this._requestAbort = true;
  6740. if (this._xhr) {
  6741. this._xhr.abort();
  6742. }
  6743. this._status = _loader.LoaderStatus.kComplete;
  6744. }
  6745. }, {
  6746. key: '_onReadyStateChange',
  6747. value: function _onReadyStateChange(e) {
  6748. var xhr = e.target;
  6749. if (xhr.readyState === 2) {
  6750. // HEADERS_RECEIVED
  6751. if (xhr.responseURL != undefined && xhr.responseURL !== this._requestURL) {
  6752. if (this._onURLRedirect) {
  6753. var redirectedURL = this._seekHandler.removeURLParameters(xhr.responseURL);
  6754. this._onURLRedirect(redirectedURL);
  6755. }
  6756. }
  6757. if (xhr.status !== 0 && (xhr.status < 200 || xhr.status > 299)) {
  6758. this._status = _loader.LoaderStatus.kError;
  6759. if (this._onError) {
  6760. this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: xhr.status, msg: xhr.statusText });
  6761. } else {
  6762. throw new _exception.RuntimeException('MozChunkedLoader: Http code invalid, ' + xhr.status + ' ' + xhr.statusText);
  6763. }
  6764. } else {
  6765. this._status = _loader.LoaderStatus.kBuffering;
  6766. }
  6767. }
  6768. }
  6769. }, {
  6770. key: '_onProgress',
  6771. value: function _onProgress(e) {
  6772. if (this._status === _loader.LoaderStatus.kError) {
  6773. // Ignore error response
  6774. return;
  6775. }
  6776. if (this._contentLength === null) {
  6777. if (e.total !== null && e.total !== 0) {
  6778. this._contentLength = e.total;
  6779. if (this._onContentLengthKnown) {
  6780. this._onContentLengthKnown(this._contentLength);
  6781. }
  6782. }
  6783. }
  6784. var chunk = e.target.response;
  6785. var byteStart = this._range.from + this._receivedLength;
  6786. this._receivedLength += chunk.byteLength;
  6787. if (this._onDataArrival) {
  6788. this._onDataArrival(chunk, byteStart, this._receivedLength);
  6789. }
  6790. }
  6791. }, {
  6792. key: '_onLoadEnd',
  6793. value: function _onLoadEnd(e) {
  6794. if (this._requestAbort === true) {
  6795. this._requestAbort = false;
  6796. return;
  6797. } else if (this._status === _loader.LoaderStatus.kError) {
  6798. return;
  6799. }
  6800. this._status = _loader.LoaderStatus.kComplete;
  6801. if (this._onComplete) {
  6802. this._onComplete(this._range.from, this._range.from + this._receivedLength - 1);
  6803. }
  6804. }
  6805. }, {
  6806. key: '_onXhrError',
  6807. value: function _onXhrError(e) {
  6808. this._status = _loader.LoaderStatus.kError;
  6809. var type = 0;
  6810. var info = null;
  6811. if (this._contentLength && e.loaded < this._contentLength) {
  6812. type = _loader.LoaderErrors.EARLY_EOF;
  6813. info = { code: -1, msg: 'Moz-Chunked stream meet Early-Eof' };
  6814. } else {
  6815. type = _loader.LoaderErrors.EXCEPTION;
  6816. info = { code: -1, msg: e.constructor.name + ' ' + e.type };
  6817. }
  6818. if (this._onError) {
  6819. this._onError(type, info);
  6820. } else {
  6821. throw new _exception.RuntimeException(info.msg);
  6822. }
  6823. }
  6824. }]);
  6825. return MozChunkedLoader;
  6826. }(_loader.BaseLoader);
  6827. exports.default = MozChunkedLoader;
  6828. },{"../utils/exception.js":40,"../utils/logger.js":41,"./loader.js":24}],30:[function(_dereq_,module,exports){
  6829. 'use strict';
  6830. Object.defineProperty(exports, "__esModule", {
  6831. value: true
  6832. });
  6833. 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; };
  6834. 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); } };
  6835. 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; }; }();
  6836. var _logger = _dereq_('../utils/logger.js');
  6837. var _logger2 = _interopRequireDefault(_logger);
  6838. var _loader = _dereq_('./loader.js');
  6839. var _exception = _dereq_('../utils/exception.js');
  6840. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6841. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6842. 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; }
  6843. 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; } /*
  6844. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  6845. *
  6846. * @author zheng qian <xqq@xqq.im>
  6847. *
  6848. * Licensed under the Apache License, Version 2.0 (the "License");
  6849. * you may not use this file except in compliance with the License.
  6850. * You may obtain a copy of the License at
  6851. *
  6852. * http://www.apache.org/licenses/LICENSE-2.0
  6853. *
  6854. * Unless required by applicable law or agreed to in writing, software
  6855. * distributed under the License is distributed on an "AS IS" BASIS,
  6856. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6857. * See the License for the specific language governing permissions and
  6858. * limitations under the License.
  6859. */
  6860. /* Notice: ms-stream may cause IE/Edge browser crash if seek too frequently!!!
  6861. * The browser may crash in wininet.dll. Disable for now.
  6862. *
  6863. * For IE11/Edge browser by microsoft which supports `xhr.responseType = 'ms-stream'`
  6864. * Notice that ms-stream API sucks. The buffer is always expanding along with downloading.
  6865. *
  6866. * We need to abort the xhr if buffer size exceeded limit size (e.g. 16 MiB), then do reconnect.
  6867. * in order to release previous ArrayBuffer to avoid memory leak
  6868. *
  6869. * Otherwise, the ArrayBuffer will increase to a terrible size that equals final file size.
  6870. */
  6871. var MSStreamLoader = function (_BaseLoader) {
  6872. _inherits(MSStreamLoader, _BaseLoader);
  6873. _createClass(MSStreamLoader, null, [{
  6874. key: 'isSupported',
  6875. value: function isSupported() {
  6876. try {
  6877. if (typeof self.MSStream === 'undefined' || typeof self.MSStreamReader === 'undefined') {
  6878. return false;
  6879. }
  6880. var xhr = new XMLHttpRequest();
  6881. xhr.open('GET', 'https://example.com', true);
  6882. xhr.responseType = 'ms-stream';
  6883. return xhr.responseType === 'ms-stream';
  6884. } catch (e) {
  6885. _logger2.default.w('MSStreamLoader', e.message);
  6886. return false;
  6887. }
  6888. }
  6889. }]);
  6890. function MSStreamLoader(seekHandler, config) {
  6891. _classCallCheck(this, MSStreamLoader);
  6892. var _this = _possibleConstructorReturn(this, (MSStreamLoader.__proto__ || Object.getPrototypeOf(MSStreamLoader)).call(this, 'xhr-msstream-loader'));
  6893. _this.TAG = 'MSStreamLoader';
  6894. _this._seekHandler = seekHandler;
  6895. _this._config = config;
  6896. _this._needStash = true;
  6897. _this._xhr = null;
  6898. _this._reader = null; // MSStreamReader
  6899. _this._totalRange = null;
  6900. _this._currentRange = null;
  6901. _this._currentRequestURL = null;
  6902. _this._currentRedirectedURL = null;
  6903. _this._contentLength = null;
  6904. _this._receivedLength = 0;
  6905. _this._bufferLimit = 16 * 1024 * 1024; // 16MB
  6906. _this._lastTimeBufferSize = 0;
  6907. _this._isReconnecting = false;
  6908. return _this;
  6909. }
  6910. _createClass(MSStreamLoader, [{
  6911. key: 'destroy',
  6912. value: function destroy() {
  6913. if (this.isWorking()) {
  6914. this.abort();
  6915. }
  6916. if (this._reader) {
  6917. this._reader.onprogress = null;
  6918. this._reader.onload = null;
  6919. this._reader.onerror = null;
  6920. this._reader = null;
  6921. }
  6922. if (this._xhr) {
  6923. this._xhr.onreadystatechange = null;
  6924. this._xhr = null;
  6925. }
  6926. _get(MSStreamLoader.prototype.__proto__ || Object.getPrototypeOf(MSStreamLoader.prototype), 'destroy', this).call(this);
  6927. }
  6928. }, {
  6929. key: 'open',
  6930. value: function open(dataSource, range) {
  6931. this._internalOpen(dataSource, range, false);
  6932. }
  6933. }, {
  6934. key: '_internalOpen',
  6935. value: function _internalOpen(dataSource, range, isSubrange) {
  6936. this._dataSource = dataSource;
  6937. if (!isSubrange) {
  6938. this._totalRange = range;
  6939. } else {
  6940. this._currentRange = range;
  6941. }
  6942. var sourceURL = dataSource.url;
  6943. if (this._config.reuseRedirectedURL) {
  6944. if (this._currentRedirectedURL != undefined) {
  6945. sourceURL = this._currentRedirectedURL;
  6946. } else if (dataSource.redirectedURL != undefined) {
  6947. sourceURL = dataSource.redirectedURL;
  6948. }
  6949. }
  6950. var seekConfig = this._seekHandler.getConfig(sourceURL, range);
  6951. this._currentRequestURL = seekConfig.url;
  6952. var reader = this._reader = new self.MSStreamReader();
  6953. reader.onprogress = this._msrOnProgress.bind(this);
  6954. reader.onload = this._msrOnLoad.bind(this);
  6955. reader.onerror = this._msrOnError.bind(this);
  6956. var xhr = this._xhr = new XMLHttpRequest();
  6957. xhr.open('GET', seekConfig.url, true);
  6958. xhr.responseType = 'ms-stream';
  6959. xhr.onreadystatechange = this._xhrOnReadyStateChange.bind(this);
  6960. xhr.onerror = this._xhrOnError.bind(this);
  6961. if (dataSource.withCredentials) {
  6962. xhr.withCredentials = true;
  6963. }
  6964. if (_typeof(seekConfig.headers) === 'object') {
  6965. var headers = seekConfig.headers;
  6966. for (var key in headers) {
  6967. if (headers.hasOwnProperty(key)) {
  6968. xhr.setRequestHeader(key, headers[key]);
  6969. }
  6970. }
  6971. }
  6972. if (this._isReconnecting) {
  6973. this._isReconnecting = false;
  6974. } else {
  6975. this._status = _loader.LoaderStatus.kConnecting;
  6976. }
  6977. xhr.send();
  6978. }
  6979. }, {
  6980. key: 'abort',
  6981. value: function abort() {
  6982. this._internalAbort();
  6983. this._status = _loader.LoaderStatus.kComplete;
  6984. }
  6985. }, {
  6986. key: '_internalAbort',
  6987. value: function _internalAbort() {
  6988. if (this._reader) {
  6989. if (this._reader.readyState === 1) {
  6990. // LOADING
  6991. this._reader.abort();
  6992. }
  6993. this._reader.onprogress = null;
  6994. this._reader.onload = null;
  6995. this._reader.onerror = null;
  6996. this._reader = null;
  6997. }
  6998. if (this._xhr) {
  6999. this._xhr.abort();
  7000. this._xhr.onreadystatechange = null;
  7001. this._xhr = null;
  7002. }
  7003. }
  7004. }, {
  7005. key: '_xhrOnReadyStateChange',
  7006. value: function _xhrOnReadyStateChange(e) {
  7007. var xhr = e.target;
  7008. if (xhr.readyState === 2) {
  7009. // HEADERS_RECEIVED
  7010. if (xhr.status >= 200 && xhr.status <= 299) {
  7011. this._status = _loader.LoaderStatus.kBuffering;
  7012. if (xhr.responseURL != undefined) {
  7013. var redirectedURL = this._seekHandler.removeURLParameters(xhr.responseURL);
  7014. if (xhr.responseURL !== this._currentRequestURL && redirectedURL !== this._currentRedirectedURL) {
  7015. this._currentRedirectedURL = redirectedURL;
  7016. if (this._onURLRedirect) {
  7017. this._onURLRedirect(redirectedURL);
  7018. }
  7019. }
  7020. }
  7021. var lengthHeader = xhr.getResponseHeader('Content-Length');
  7022. if (lengthHeader != null && this._contentLength == null) {
  7023. var length = parseInt(lengthHeader);
  7024. if (length > 0) {
  7025. this._contentLength = length;
  7026. if (this._onContentLengthKnown) {
  7027. this._onContentLengthKnown(this._contentLength);
  7028. }
  7029. }
  7030. }
  7031. } else {
  7032. this._status = _loader.LoaderStatus.kError;
  7033. if (this._onError) {
  7034. this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: xhr.status, msg: xhr.statusText });
  7035. } else {
  7036. throw new _exception.RuntimeException('MSStreamLoader: Http code invalid, ' + xhr.status + ' ' + xhr.statusText);
  7037. }
  7038. }
  7039. } else if (xhr.readyState === 3) {
  7040. // LOADING
  7041. if (xhr.status >= 200 && xhr.status <= 299) {
  7042. this._status = _loader.LoaderStatus.kBuffering;
  7043. var msstream = xhr.response;
  7044. this._reader.readAsArrayBuffer(msstream);
  7045. }
  7046. }
  7047. }
  7048. }, {
  7049. key: '_xhrOnError',
  7050. value: function _xhrOnError(e) {
  7051. this._status = _loader.LoaderStatus.kError;
  7052. var type = _loader.LoaderErrors.EXCEPTION;
  7053. var info = { code: -1, msg: e.constructor.name + ' ' + e.type };
  7054. if (this._onError) {
  7055. this._onError(type, info);
  7056. } else {
  7057. throw new _exception.RuntimeException(info.msg);
  7058. }
  7059. }
  7060. }, {
  7061. key: '_msrOnProgress',
  7062. value: function _msrOnProgress(e) {
  7063. var reader = e.target;
  7064. var bigbuffer = reader.result;
  7065. if (bigbuffer == null) {
  7066. // result may be null, workaround for buggy M$
  7067. this._doReconnectIfNeeded();
  7068. return;
  7069. }
  7070. var slice = bigbuffer.slice(this._lastTimeBufferSize);
  7071. this._lastTimeBufferSize = bigbuffer.byteLength;
  7072. var byteStart = this._totalRange.from + this._receivedLength;
  7073. this._receivedLength += slice.byteLength;
  7074. if (this._onDataArrival) {
  7075. this._onDataArrival(slice, byteStart, this._receivedLength);
  7076. }
  7077. if (bigbuffer.byteLength >= this._bufferLimit) {
  7078. _logger2.default.v(this.TAG, 'MSStream buffer exceeded max size near ' + (byteStart + slice.byteLength) + ', reconnecting...');
  7079. this._doReconnectIfNeeded();
  7080. }
  7081. }
  7082. }, {
  7083. key: '_doReconnectIfNeeded',
  7084. value: function _doReconnectIfNeeded() {
  7085. if (this._contentLength == null || this._receivedLength < this._contentLength) {
  7086. this._isReconnecting = true;
  7087. this._lastTimeBufferSize = 0;
  7088. this._internalAbort();
  7089. var range = {
  7090. from: this._totalRange.from + this._receivedLength,
  7091. to: -1
  7092. };
  7093. this._internalOpen(this._dataSource, range, true);
  7094. }
  7095. }
  7096. }, {
  7097. key: '_msrOnLoad',
  7098. value: function _msrOnLoad(e) {
  7099. // actually it is onComplete event
  7100. this._status = _loader.LoaderStatus.kComplete;
  7101. if (this._onComplete) {
  7102. this._onComplete(this._totalRange.from, this._totalRange.from + this._receivedLength - 1);
  7103. }
  7104. }
  7105. }, {
  7106. key: '_msrOnError',
  7107. value: function _msrOnError(e) {
  7108. this._status = _loader.LoaderStatus.kError;
  7109. var type = 0;
  7110. var info = null;
  7111. if (this._contentLength && this._receivedLength < this._contentLength) {
  7112. type = _loader.LoaderErrors.EARLY_EOF;
  7113. info = { code: -1, msg: 'MSStream meet Early-Eof' };
  7114. } else {
  7115. type = _loader.LoaderErrors.EARLY_EOF;
  7116. info = { code: -1, msg: e.constructor.name + ' ' + e.type };
  7117. }
  7118. if (this._onError) {
  7119. this._onError(type, info);
  7120. } else {
  7121. throw new _exception.RuntimeException(info.msg);
  7122. }
  7123. }
  7124. }]);
  7125. return MSStreamLoader;
  7126. }(_loader.BaseLoader);
  7127. exports.default = MSStreamLoader;
  7128. },{"../utils/exception.js":40,"../utils/logger.js":41,"./loader.js":24}],31:[function(_dereq_,module,exports){
  7129. 'use strict';
  7130. Object.defineProperty(exports, "__esModule", {
  7131. value: true
  7132. });
  7133. 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; };
  7134. 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); } };
  7135. 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; }; }();
  7136. var _logger = _dereq_('../utils/logger.js');
  7137. var _logger2 = _interopRequireDefault(_logger);
  7138. var _speedSampler = _dereq_('./speed-sampler.js');
  7139. var _speedSampler2 = _interopRequireDefault(_speedSampler);
  7140. var _loader = _dereq_('./loader.js');
  7141. var _exception = _dereq_('../utils/exception.js');
  7142. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  7143. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7144. 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; }
  7145. 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; } /*
  7146. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  7147. *
  7148. * @author zheng qian <xqq@xqq.im>
  7149. *
  7150. * Licensed under the Apache License, Version 2.0 (the "License");
  7151. * you may not use this file except in compliance with the License.
  7152. * You may obtain a copy of the License at
  7153. *
  7154. * http://www.apache.org/licenses/LICENSE-2.0
  7155. *
  7156. * Unless required by applicable law or agreed to in writing, software
  7157. * distributed under the License is distributed on an "AS IS" BASIS,
  7158. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7159. * See the License for the specific language governing permissions and
  7160. * limitations under the License.
  7161. */
  7162. // Universal IO Loader, implemented by adding Range header in xhr's request header
  7163. var RangeLoader = function (_BaseLoader) {
  7164. _inherits(RangeLoader, _BaseLoader);
  7165. _createClass(RangeLoader, null, [{
  7166. key: 'isSupported',
  7167. value: function isSupported() {
  7168. try {
  7169. var xhr = new XMLHttpRequest();
  7170. xhr.open('GET', 'https://example.com', true);
  7171. xhr.responseType = 'arraybuffer';
  7172. return xhr.responseType === 'arraybuffer';
  7173. } catch (e) {
  7174. _logger2.default.w('RangeLoader', e.message);
  7175. return false;
  7176. }
  7177. }
  7178. }]);
  7179. function RangeLoader(seekHandler, config) {
  7180. _classCallCheck(this, RangeLoader);
  7181. var _this = _possibleConstructorReturn(this, (RangeLoader.__proto__ || Object.getPrototypeOf(RangeLoader)).call(this, 'xhr-range-loader'));
  7182. _this.TAG = 'RangeLoader';
  7183. _this._seekHandler = seekHandler;
  7184. _this._config = config;
  7185. _this._needStash = false;
  7186. _this._chunkSizeKBList = [128, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 5120, 6144, 7168, 8192];
  7187. _this._currentChunkSizeKB = 384;
  7188. _this._currentSpeedNormalized = 0;
  7189. _this._zeroSpeedChunkCount = 0;
  7190. _this._xhr = null;
  7191. _this._speedSampler = new _speedSampler2.default();
  7192. _this._requestAbort = false;
  7193. _this._waitForTotalLength = false;
  7194. _this._totalLengthReceived = false;
  7195. _this._currentRequestURL = null;
  7196. _this._currentRedirectedURL = null;
  7197. _this._currentRequestRange = null;
  7198. _this._totalLength = null; // size of the entire file
  7199. _this._contentLength = null; // Content-Length of entire request range
  7200. _this._receivedLength = 0; // total received bytes
  7201. _this._lastTimeLoaded = 0; // received bytes of current request sub-range
  7202. return _this;
  7203. }
  7204. _createClass(RangeLoader, [{
  7205. key: 'destroy',
  7206. value: function destroy() {
  7207. if (this.isWorking()) {
  7208. this.abort();
  7209. }
  7210. if (this._xhr) {
  7211. this._xhr.onreadystatechange = null;
  7212. this._xhr.onprogress = null;
  7213. this._xhr.onload = null;
  7214. this._xhr.onerror = null;
  7215. this._xhr = null;
  7216. }
  7217. _get(RangeLoader.prototype.__proto__ || Object.getPrototypeOf(RangeLoader.prototype), 'destroy', this).call(this);
  7218. }
  7219. }, {
  7220. key: 'open',
  7221. value: function open(dataSource, range) {
  7222. this._dataSource = dataSource;
  7223. this._range = range;
  7224. this._status = _loader.LoaderStatus.kConnecting;
  7225. var useRefTotalLength = false;
  7226. if (this._dataSource.filesize != undefined && this._dataSource.filesize !== 0) {
  7227. useRefTotalLength = true;
  7228. this._totalLength = this._dataSource.filesize;
  7229. }
  7230. if (!this._totalLengthReceived && !useRefTotalLength) {
  7231. // We need total filesize
  7232. this._waitForTotalLength = true;
  7233. this._internalOpen(this._dataSource, { from: 0, to: -1 });
  7234. } else {
  7235. // We have filesize, start loading
  7236. this._openSubRange();
  7237. }
  7238. }
  7239. }, {
  7240. key: '_openSubRange',
  7241. value: function _openSubRange() {
  7242. var chunkSize = this._currentChunkSizeKB * 1024;
  7243. var from = this._range.from + this._receivedLength;
  7244. var to = from + chunkSize;
  7245. if (this._contentLength != null) {
  7246. if (to - this._range.from >= this._contentLength) {
  7247. to = this._range.from + this._contentLength - 1;
  7248. }
  7249. }
  7250. this._currentRequestRange = { from: from, to: to };
  7251. this._internalOpen(this._dataSource, this._currentRequestRange);
  7252. }
  7253. }, {
  7254. key: '_internalOpen',
  7255. value: function _internalOpen(dataSource, range) {
  7256. this._lastTimeLoaded = 0;
  7257. var sourceURL = dataSource.url;
  7258. if (this._config.reuseRedirectedURL) {
  7259. if (this._currentRedirectedURL != undefined) {
  7260. sourceURL = this._currentRedirectedURL;
  7261. } else if (dataSource.redirectedURL != undefined) {
  7262. sourceURL = dataSource.redirectedURL;
  7263. }
  7264. }
  7265. var seekConfig = this._seekHandler.getConfig(sourceURL, range);
  7266. this._currentRequestURL = seekConfig.url;
  7267. var xhr = this._xhr = new XMLHttpRequest();
  7268. xhr.open('GET', seekConfig.url, true);
  7269. xhr.responseType = 'arraybuffer';
  7270. xhr.onreadystatechange = this._onReadyStateChange.bind(this);
  7271. xhr.onprogress = this._onProgress.bind(this);
  7272. xhr.onload = this._onLoad.bind(this);
  7273. xhr.onerror = this._onXhrError.bind(this);
  7274. if (dataSource.withCredentials) {
  7275. xhr.withCredentials = true;
  7276. }
  7277. if (_typeof(seekConfig.headers) === 'object') {
  7278. var headers = seekConfig.headers;
  7279. for (var key in headers) {
  7280. if (headers.hasOwnProperty(key)) {
  7281. xhr.setRequestHeader(key, headers[key]);
  7282. }
  7283. }
  7284. }
  7285. xhr.send();
  7286. }
  7287. }, {
  7288. key: 'abort',
  7289. value: function abort() {
  7290. this._requestAbort = true;
  7291. this._internalAbort();
  7292. this._status = _loader.LoaderStatus.kComplete;
  7293. }
  7294. }, {
  7295. key: '_internalAbort',
  7296. value: function _internalAbort() {
  7297. if (this._xhr) {
  7298. this._xhr.onreadystatechange = null;
  7299. this._xhr.onprogress = null;
  7300. this._xhr.onload = null;
  7301. this._xhr.onerror = null;
  7302. this._xhr.abort();
  7303. this._xhr = null;
  7304. }
  7305. }
  7306. }, {
  7307. key: '_onReadyStateChange',
  7308. value: function _onReadyStateChange(e) {
  7309. var xhr = e.target;
  7310. if (xhr.readyState === 2) {
  7311. // HEADERS_RECEIVED
  7312. if (xhr.responseURL != undefined) {
  7313. // if the browser support this property
  7314. var redirectedURL = this._seekHandler.removeURLParameters(xhr.responseURL);
  7315. if (xhr.responseURL !== this._currentRequestURL && redirectedURL !== this._currentRedirectedURL) {
  7316. this._currentRedirectedURL = redirectedURL;
  7317. if (this._onURLRedirect) {
  7318. this._onURLRedirect(redirectedURL);
  7319. }
  7320. }
  7321. }
  7322. if (xhr.status >= 200 && xhr.status <= 299) {
  7323. if (this._waitForTotalLength) {
  7324. return;
  7325. }
  7326. this._status = _loader.LoaderStatus.kBuffering;
  7327. } else {
  7328. this._status = _loader.LoaderStatus.kError;
  7329. if (this._onError) {
  7330. this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: xhr.status, msg: xhr.statusText });
  7331. } else {
  7332. throw new _exception.RuntimeException('RangeLoader: Http code invalid, ' + xhr.status + ' ' + xhr.statusText);
  7333. }
  7334. }
  7335. }
  7336. }
  7337. }, {
  7338. key: '_onProgress',
  7339. value: function _onProgress(e) {
  7340. if (this._status === _loader.LoaderStatus.kError) {
  7341. // Ignore error response
  7342. return;
  7343. }
  7344. if (this._contentLength === null) {
  7345. var openNextRange = false;
  7346. if (this._waitForTotalLength) {
  7347. this._waitForTotalLength = false;
  7348. this._totalLengthReceived = true;
  7349. openNextRange = true;
  7350. var total = e.total;
  7351. this._internalAbort();
  7352. if (total != null & total !== 0) {
  7353. this._totalLength = total;
  7354. }
  7355. }
  7356. // calculate currrent request range's contentLength
  7357. if (this._range.to === -1) {
  7358. this._contentLength = this._totalLength - this._range.from;
  7359. } else {
  7360. // to !== -1
  7361. this._contentLength = this._range.to - this._range.from + 1;
  7362. }
  7363. if (openNextRange) {
  7364. this._openSubRange();
  7365. return;
  7366. }
  7367. if (this._onContentLengthKnown) {
  7368. this._onContentLengthKnown(this._contentLength);
  7369. }
  7370. }
  7371. var delta = e.loaded - this._lastTimeLoaded;
  7372. this._lastTimeLoaded = e.loaded;
  7373. this._speedSampler.addBytes(delta);
  7374. }
  7375. }, {
  7376. key: '_normalizeSpeed',
  7377. value: function _normalizeSpeed(input) {
  7378. var list = this._chunkSizeKBList;
  7379. var last = list.length - 1;
  7380. var mid = 0;
  7381. var lbound = 0;
  7382. var ubound = last;
  7383. if (input < list[0]) {
  7384. return list[0];
  7385. }
  7386. while (lbound <= ubound) {
  7387. mid = lbound + Math.floor((ubound - lbound) / 2);
  7388. if (mid === last || input >= list[mid] && input < list[mid + 1]) {
  7389. return list[mid];
  7390. } else if (list[mid] < input) {
  7391. lbound = mid + 1;
  7392. } else {
  7393. ubound = mid - 1;
  7394. }
  7395. }
  7396. }
  7397. }, {
  7398. key: '_onLoad',
  7399. value: function _onLoad(e) {
  7400. if (this._status === _loader.LoaderStatus.kError) {
  7401. // Ignore error response
  7402. return;
  7403. }
  7404. if (this._waitForTotalLength) {
  7405. this._waitForTotalLength = false;
  7406. return;
  7407. }
  7408. this._lastTimeLoaded = 0;
  7409. var KBps = this._speedSampler.lastSecondKBps;
  7410. if (KBps === 0) {
  7411. this._zeroSpeedChunkCount++;
  7412. if (this._zeroSpeedChunkCount >= 3) {
  7413. // Try get currentKBps after 3 chunks
  7414. KBps = this._speedSampler.currentKBps;
  7415. }
  7416. }
  7417. if (KBps !== 0) {
  7418. var normalized = this._normalizeSpeed(KBps);
  7419. if (this._currentSpeedNormalized !== normalized) {
  7420. this._currentSpeedNormalized = normalized;
  7421. this._currentChunkSizeKB = normalized;
  7422. }
  7423. }
  7424. var chunk = e.target.response;
  7425. var byteStart = this._range.from + this._receivedLength;
  7426. this._receivedLength += chunk.byteLength;
  7427. var reportComplete = false;
  7428. if (this._contentLength != null && this._receivedLength < this._contentLength) {
  7429. // continue load next chunk
  7430. this._openSubRange();
  7431. } else {
  7432. reportComplete = true;
  7433. }
  7434. // dispatch received chunk
  7435. if (this._onDataArrival) {
  7436. this._onDataArrival(chunk, byteStart, this._receivedLength);
  7437. }
  7438. if (reportComplete) {
  7439. this._status = _loader.LoaderStatus.kComplete;
  7440. if (this._onComplete) {
  7441. this._onComplete(this._range.from, this._range.from + this._receivedLength - 1);
  7442. }
  7443. }
  7444. }
  7445. }, {
  7446. key: '_onXhrError',
  7447. value: function _onXhrError(e) {
  7448. this._status = _loader.LoaderStatus.kError;
  7449. var type = 0;
  7450. var info = null;
  7451. if (this._contentLength && this._receivedLength > 0 && this._receivedLength < this._contentLength) {
  7452. type = _loader.LoaderErrors.EARLY_EOF;
  7453. info = { code: -1, msg: 'RangeLoader meet Early-Eof' };
  7454. } else {
  7455. type = _loader.LoaderErrors.EXCEPTION;
  7456. info = { code: -1, msg: e.constructor.name + ' ' + e.type };
  7457. }
  7458. if (this._onError) {
  7459. this._onError(type, info);
  7460. } else {
  7461. throw new _exception.RuntimeException(info.msg);
  7462. }
  7463. }
  7464. }, {
  7465. key: 'currentSpeed',
  7466. get: function get() {
  7467. return this._speedSampler.lastSecondKBps;
  7468. }
  7469. }]);
  7470. return RangeLoader;
  7471. }(_loader.BaseLoader);
  7472. exports.default = RangeLoader;
  7473. },{"../utils/exception.js":40,"../utils/logger.js":41,"./loader.js":24,"./speed-sampler.js":27}],32:[function(_dereq_,module,exports){
  7474. 'use strict';
  7475. Object.defineProperty(exports, "__esModule", {
  7476. value: true
  7477. });
  7478. 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; };
  7479. 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; }; }(); /*
  7480. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  7481. *
  7482. * @author zheng qian <xqq@xqq.im>
  7483. *
  7484. * Licensed under the Apache License, Version 2.0 (the "License");
  7485. * you may not use this file except in compliance with the License.
  7486. * You may obtain a copy of the License at
  7487. *
  7488. * http://www.apache.org/licenses/LICENSE-2.0
  7489. *
  7490. * Unless required by applicable law or agreed to in writing, software
  7491. * distributed under the License is distributed on an "AS IS" BASIS,
  7492. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7493. * See the License for the specific language governing permissions and
  7494. * limitations under the License.
  7495. */
  7496. var _events = _dereq_('events');
  7497. var _events2 = _interopRequireDefault(_events);
  7498. var _logger = _dereq_('../utils/logger.js');
  7499. var _logger2 = _interopRequireDefault(_logger);
  7500. var _browser = _dereq_('../utils/browser.js');
  7501. var _browser2 = _interopRequireDefault(_browser);
  7502. var _playerEvents = _dereq_('./player-events.js');
  7503. var _playerEvents2 = _interopRequireDefault(_playerEvents);
  7504. var _transmuxer = _dereq_('../core/transmuxer.js');
  7505. var _transmuxer2 = _interopRequireDefault(_transmuxer);
  7506. var _transmuxingEvents = _dereq_('../core/transmuxing-events.js');
  7507. var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
  7508. var _mseController = _dereq_('../core/mse-controller.js');
  7509. var _mseController2 = _interopRequireDefault(_mseController);
  7510. var _mseEvents = _dereq_('../core/mse-events.js');
  7511. var _mseEvents2 = _interopRequireDefault(_mseEvents);
  7512. var _playerErrors = _dereq_('./player-errors.js');
  7513. var _config = _dereq_('../config.js');
  7514. var _exception = _dereq_('../utils/exception.js');
  7515. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  7516. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7517. var FlvPlayer = function () {
  7518. function FlvPlayer(mediaDataSource, config) {
  7519. _classCallCheck(this, FlvPlayer);
  7520. this.TAG = 'FlvPlayer';
  7521. this._type = 'FlvPlayer';
  7522. this._emitter = new _events2.default();
  7523. this._config = (0, _config.createDefaultConfig)();
  7524. if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object') {
  7525. Object.assign(this._config, config);
  7526. }
  7527. if (mediaDataSource.type.toLowerCase() !== 'flv') {
  7528. throw new _exception.InvalidArgumentException('FlvPlayer requires an flv MediaDataSource input!');
  7529. }
  7530. if (mediaDataSource.isLive === true) {
  7531. this._config.isLive = true;
  7532. }
  7533. this.e = {
  7534. onvLoadedMetadata: this._onvLoadedMetadata.bind(this),
  7535. onvSeeking: this._onvSeeking.bind(this),
  7536. onvCanPlay: this._onvCanPlay.bind(this),
  7537. onvStalled: this._onvStalled.bind(this),
  7538. onvProgress: this._onvProgress.bind(this)
  7539. };
  7540. if (self.performance && self.performance.now) {
  7541. this._now = self.performance.now.bind(self.performance);
  7542. } else {
  7543. this._now = Date.now;
  7544. }
  7545. this._pendingSeekTime = null; // in seconds
  7546. this._requestSetTime = false;
  7547. this._seekpointRecord = null;
  7548. this._progressChecker = null;
  7549. this._mediaDataSource = mediaDataSource;
  7550. this._mediaElement = null;
  7551. this._msectl = null;
  7552. this._transmuxer = null;
  7553. this._mseSourceOpened = false;
  7554. this._hasPendingLoad = false;
  7555. this._receivedCanPlay = false;
  7556. this._mediaInfo = null;
  7557. this._statisticsInfo = null;
  7558. var chromeNeedIDRFix = _browser2.default.chrome && (_browser2.default.version.major < 50 || _browser2.default.version.major === 50 && _browser2.default.version.build < 2661);
  7559. this._alwaysSeekKeyframe = chromeNeedIDRFix || _browser2.default.msedge || _browser2.default.msie ? true : false;
  7560. if (this._alwaysSeekKeyframe) {
  7561. this._config.accurateSeek = false;
  7562. }
  7563. }
  7564. _createClass(FlvPlayer, [{
  7565. key: 'destroy',
  7566. value: function destroy() {
  7567. if (this._progressChecker != null) {
  7568. window.clearInterval(this._progressChecker);
  7569. this._progressChecker = null;
  7570. }
  7571. if (this._transmuxer) {
  7572. this.unload();
  7573. }
  7574. if (this._mediaElement) {
  7575. this.detachMediaElement();
  7576. }
  7577. this.e = null;
  7578. this._mediaDataSource = null;
  7579. this._emitter.removeAllListeners();
  7580. this._emitter = null;
  7581. }
  7582. }, {
  7583. key: 'on',
  7584. value: function on(event, listener) {
  7585. var _this = this;
  7586. if (event === _playerEvents2.default.MEDIA_INFO) {
  7587. if (this._mediaInfo != null) {
  7588. Promise.resolve().then(function () {
  7589. _this._emitter.emit(_playerEvents2.default.MEDIA_INFO, _this.mediaInfo);
  7590. });
  7591. }
  7592. } else if (event === _playerEvents2.default.STATISTICS_INFO) {
  7593. if (this._statisticsInfo != null) {
  7594. Promise.resolve().then(function () {
  7595. _this._emitter.emit(_playerEvents2.default.STATISTICS_INFO, _this.statisticsInfo);
  7596. });
  7597. }
  7598. }
  7599. this._emitter.addListener(event, listener);
  7600. }
  7601. }, {
  7602. key: 'off',
  7603. value: function off(event, listener) {
  7604. this._emitter.removeListener(event, listener);
  7605. }
  7606. }, {
  7607. key: 'attachMediaElement',
  7608. value: function attachMediaElement(mediaElement) {
  7609. var _this2 = this;
  7610. this._mediaElement = mediaElement;
  7611. mediaElement.addEventListener('loadedmetadata', this.e.onvLoadedMetadata);
  7612. mediaElement.addEventListener('seeking', this.e.onvSeeking);
  7613. mediaElement.addEventListener('canplay', this.e.onvCanPlay);
  7614. mediaElement.addEventListener('stalled', this.e.onvStalled);
  7615. mediaElement.addEventListener('progress', this.e.onvProgress);
  7616. this._msectl = new _mseController2.default(this._config);
  7617. this._msectl.on(_mseEvents2.default.UPDATE_END, this._onmseUpdateEnd.bind(this));
  7618. this._msectl.on(_mseEvents2.default.BUFFER_FULL, this._onmseBufferFull.bind(this));
  7619. this._msectl.on(_mseEvents2.default.SOURCE_OPEN, function () {
  7620. _this2._mseSourceOpened = true;
  7621. if (_this2._hasPendingLoad) {
  7622. _this2._hasPendingLoad = false;
  7623. _this2.load();
  7624. }
  7625. });
  7626. this._msectl.on(_mseEvents2.default.ERROR, function (info) {
  7627. _this2._emitter.emit(_playerEvents2.default.ERROR, _playerErrors.ErrorTypes.MEDIA_ERROR, _playerErrors.ErrorDetails.MEDIA_MSE_ERROR, info);
  7628. });
  7629. this._msectl.attachMediaElement(mediaElement);
  7630. if (this._pendingSeekTime != null) {
  7631. try {
  7632. mediaElement.currentTime = this._pendingSeekTime;
  7633. this._pendingSeekTime = null;
  7634. } catch (e) {
  7635. // IE11 may throw InvalidStateError if readyState === 0
  7636. // We can defer set currentTime operation after loadedmetadata
  7637. }
  7638. }
  7639. }
  7640. }, {
  7641. key: 'detachMediaElement',
  7642. value: function detachMediaElement() {
  7643. if (this._mediaElement) {
  7644. this._msectl.detachMediaElement();
  7645. this._mediaElement.removeEventListener('loadedmetadata', this.e.onvLoadedMetadata);
  7646. this._mediaElement.removeEventListener('seeking', this.e.onvSeeking);
  7647. this._mediaElement.removeEventListener('canplay', this.e.onvCanPlay);
  7648. this._mediaElement.removeEventListener('stalled', this.e.onvStalled);
  7649. this._mediaElement.removeEventListener('progress', this.e.onvProgress);
  7650. this._mediaElement = null;
  7651. }
  7652. if (this._msectl) {
  7653. this._msectl.destroy();
  7654. this._msectl = null;
  7655. }
  7656. }
  7657. }, {
  7658. key: 'load',
  7659. value: function load() {
  7660. var _this3 = this;
  7661. if (!this._mediaElement) {
  7662. throw new _exception.IllegalStateException('HTMLMediaElement must be attached before load()!');
  7663. }
  7664. if (this._transmuxer) {
  7665. throw new _exception.IllegalStateException('FlvPlayer.load() has been called, please call unload() first!');
  7666. }
  7667. if (this._hasPendingLoad) {
  7668. return;
  7669. }
  7670. if (this._config.deferLoadAfterSourceOpen && this._mseSourceOpened === false) {
  7671. this._hasPendingLoad = true;
  7672. return;
  7673. }
  7674. if (this._mediaElement.readyState > 0) {
  7675. this._requestSetTime = true;
  7676. // IE11 may throw InvalidStateError if readyState === 0
  7677. this._mediaElement.currentTime = 0;
  7678. }
  7679. this._transmuxer = new _transmuxer2.default(this._mediaDataSource, this._config);
  7680. this._transmuxer.on(_transmuxingEvents2.default.INIT_SEGMENT, function (type, is) {
  7681. _this3._msectl.appendInitSegment(is);
  7682. });
  7683. this._transmuxer.on(_transmuxingEvents2.default.MEDIA_SEGMENT, function (type, ms) {
  7684. _this3._msectl.appendMediaSegment(ms);
  7685. // lazyLoad check
  7686. if (_this3._config.lazyLoad && !_this3._config.isLive) {
  7687. var currentTime = _this3._mediaElement.currentTime;
  7688. if (ms.info.endDts >= (currentTime + _this3._config.lazyLoadMaxDuration) * 1000) {
  7689. if (_this3._progressChecker == null) {
  7690. _logger2.default.v(_this3.TAG, 'Maximum buffering duration exceeded, suspend transmuxing task');
  7691. _this3._suspendTransmuxer();
  7692. }
  7693. }
  7694. }
  7695. });
  7696. this._transmuxer.on(_transmuxingEvents2.default.LOADING_COMPLETE, function () {
  7697. _this3._msectl.endOfStream();
  7698. _this3._emitter.emit(_playerEvents2.default.LOADING_COMPLETE);
  7699. });
  7700. this._transmuxer.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF, function () {
  7701. _this3._emitter.emit(_playerEvents2.default.RECOVERED_EARLY_EOF);
  7702. });
  7703. this._transmuxer.on(_transmuxingEvents2.default.IO_ERROR, function (detail, info) {
  7704. _this3._emitter.emit(_playerEvents2.default.ERROR, _playerErrors.ErrorTypes.NETWORK_ERROR, detail, info);
  7705. });
  7706. this._transmuxer.on(_transmuxingEvents2.default.DEMUX_ERROR, function (detail, info) {
  7707. _this3._emitter.emit(_playerEvents2.default.ERROR, _playerErrors.ErrorTypes.MEDIA_ERROR, detail, { code: -1, msg: info });
  7708. });
  7709. this._transmuxer.on(_transmuxingEvents2.default.MEDIA_INFO, function (mediaInfo) {
  7710. _this3._mediaInfo = mediaInfo;
  7711. _this3._emitter.emit(_playerEvents2.default.MEDIA_INFO, Object.assign({}, mediaInfo));
  7712. });
  7713. this._transmuxer.on(_transmuxingEvents2.default.STATISTICS_INFO, function (statInfo) {
  7714. _this3._statisticsInfo = _this3._fillStatisticsInfo(statInfo);
  7715. _this3._emitter.emit(_playerEvents2.default.STATISTICS_INFO, Object.assign({}, _this3._statisticsInfo));
  7716. });
  7717. this._transmuxer.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, function (milliseconds) {
  7718. if (_this3._mediaElement && !_this3._config.accurateSeek) {
  7719. _this3._requestSetTime = true;
  7720. _this3._mediaElement.currentTime = milliseconds / 1000;
  7721. }
  7722. });
  7723. this._transmuxer.open();
  7724. }
  7725. }, {
  7726. key: 'unload',
  7727. value: function unload() {
  7728. if (this._mediaElement) {
  7729. this._mediaElement.pause();
  7730. }
  7731. if (this._msectl) {
  7732. this._msectl.seek(0);
  7733. }
  7734. if (this._transmuxer) {
  7735. this._transmuxer.close();
  7736. this._transmuxer.destroy();
  7737. this._transmuxer = null;
  7738. }
  7739. }
  7740. }, {
  7741. key: 'play',
  7742. value: function play() {
  7743. return this._mediaElement.play();
  7744. }
  7745. }, {
  7746. key: 'pause',
  7747. value: function pause() {
  7748. this._mediaElement.pause();
  7749. }
  7750. }, {
  7751. key: '_fillStatisticsInfo',
  7752. value: function _fillStatisticsInfo(statInfo) {
  7753. statInfo.playerType = this._type;
  7754. if (!(this._mediaElement instanceof HTMLVideoElement)) {
  7755. return statInfo;
  7756. }
  7757. var hasQualityInfo = true;
  7758. var decoded = 0;
  7759. var dropped = 0;
  7760. if (this._mediaElement.getVideoPlaybackQuality) {
  7761. var quality = this._mediaElement.getVideoPlaybackQuality();
  7762. decoded = quality.totalVideoFrames;
  7763. dropped = quality.droppedVideoFrames;
  7764. } else if (this._mediaElement.webkitDecodedFrameCount != undefined) {
  7765. decoded = this._mediaElement.webkitDecodedFrameCount;
  7766. dropped = this._mediaElement.webkitDroppedFrameCount;
  7767. } else {
  7768. hasQualityInfo = false;
  7769. }
  7770. if (hasQualityInfo) {
  7771. statInfo.decodedFrames = decoded;
  7772. statInfo.droppedFrames = dropped;
  7773. }
  7774. return statInfo;
  7775. }
  7776. }, {
  7777. key: '_onmseUpdateEnd',
  7778. value: function _onmseUpdateEnd() {
  7779. if (!this._config.lazyLoad || this._config.isLive) {
  7780. return;
  7781. }
  7782. var buffered = this._mediaElement.buffered;
  7783. var currentTime = this._mediaElement.currentTime;
  7784. var currentRangeStart = 0;
  7785. var currentRangeEnd = 0;
  7786. for (var i = 0; i < buffered.length; i++) {
  7787. var start = buffered.start(i);
  7788. var end = buffered.end(i);
  7789. if (start <= currentTime && currentTime < end) {
  7790. currentRangeStart = start;
  7791. currentRangeEnd = end;
  7792. break;
  7793. }
  7794. }
  7795. if (currentRangeEnd >= currentTime + this._config.lazyLoadMaxDuration && this._progressChecker == null) {
  7796. _logger2.default.v(this.TAG, 'Maximum buffering duration exceeded, suspend transmuxing task');
  7797. this._suspendTransmuxer();
  7798. }
  7799. }
  7800. }, {
  7801. key: '_onmseBufferFull',
  7802. value: function _onmseBufferFull() {
  7803. _logger2.default.v(this.TAG, 'MSE SourceBuffer is full, suspend transmuxing task');
  7804. if (this._progressChecker == null) {
  7805. this._suspendTransmuxer();
  7806. }
  7807. }
  7808. }, {
  7809. key: '_suspendTransmuxer',
  7810. value: function _suspendTransmuxer() {
  7811. if (this._transmuxer) {
  7812. this._transmuxer.pause();
  7813. if (this._progressChecker == null) {
  7814. this._progressChecker = window.setInterval(this._checkProgressAndResume.bind(this), 1000);
  7815. }
  7816. }
  7817. }
  7818. }, {
  7819. key: '_checkProgressAndResume',
  7820. value: function _checkProgressAndResume() {
  7821. var currentTime = this._mediaElement.currentTime;
  7822. var buffered = this._mediaElement.buffered;
  7823. var needResume = false;
  7824. for (var i = 0; i < buffered.length; i++) {
  7825. var from = buffered.start(i);
  7826. var to = buffered.end(i);
  7827. if (currentTime >= from && currentTime < to) {
  7828. if (currentTime >= to - this._config.lazyLoadRecoverDuration) {
  7829. needResume = true;
  7830. }
  7831. break;
  7832. }
  7833. }
  7834. if (needResume) {
  7835. window.clearInterval(this._progressChecker);
  7836. this._progressChecker = null;
  7837. if (needResume) {
  7838. _logger2.default.v(this.TAG, 'Continue loading from paused position');
  7839. this._transmuxer.resume();
  7840. }
  7841. }
  7842. }
  7843. }, {
  7844. key: '_isTimepointBuffered',
  7845. value: function _isTimepointBuffered(seconds) {
  7846. var buffered = this._mediaElement.buffered;
  7847. for (var i = 0; i < buffered.length; i++) {
  7848. var from = buffered.start(i);
  7849. var to = buffered.end(i);
  7850. if (seconds >= from && seconds < to) {
  7851. return true;
  7852. }
  7853. }
  7854. return false;
  7855. }
  7856. }, {
  7857. key: '_internalSeek',
  7858. value: function _internalSeek(seconds) {
  7859. var directSeek = this._isTimepointBuffered(seconds);
  7860. var directSeekBegin = false;
  7861. var directSeekBeginTime = 0;
  7862. if (seconds < 1.0 && this._mediaElement.buffered.length > 0) {
  7863. var videoBeginTime = this._mediaElement.buffered.start(0);
  7864. if (videoBeginTime < 1.0 && seconds < videoBeginTime || _browser2.default.safari) {
  7865. directSeekBegin = true;
  7866. // also workaround for Safari: Seek to 0 may cause video stuck, use 0.1 to avoid
  7867. directSeekBeginTime = _browser2.default.safari ? 0.1 : videoBeginTime;
  7868. }
  7869. }
  7870. if (directSeekBegin) {
  7871. // seek to video begin, set currentTime directly if beginPTS buffered
  7872. this._requestSetTime = true;
  7873. this._mediaElement.currentTime = directSeekBeginTime;
  7874. } else if (directSeek) {
  7875. // buffered position
  7876. if (!this._alwaysSeekKeyframe) {
  7877. this._requestSetTime = true;
  7878. this._mediaElement.currentTime = seconds;
  7879. } else {
  7880. var idr = this._msectl.getNearestKeyframe(Math.floor(seconds * 1000));
  7881. this._requestSetTime = true;
  7882. if (idr != null) {
  7883. this._mediaElement.currentTime = idr.dts / 1000;
  7884. } else {
  7885. this._mediaElement.currentTime = seconds;
  7886. }
  7887. }
  7888. if (this._progressChecker != null) {
  7889. this._checkProgressAndResume();
  7890. }
  7891. } else {
  7892. if (this._progressChecker != null) {
  7893. window.clearInterval(this._progressChecker);
  7894. this._progressChecker = null;
  7895. }
  7896. this._msectl.seek(seconds);
  7897. this._transmuxer.seek(Math.floor(seconds * 1000)); // in milliseconds
  7898. // no need to set mediaElement.currentTime if non-accurateSeek,
  7899. // just wait for the recommend_seekpoint callback
  7900. if (this._config.accurateSeek) {
  7901. this._requestSetTime = true;
  7902. this._mediaElement.currentTime = seconds;
  7903. }
  7904. }
  7905. }
  7906. }, {
  7907. key: '_checkAndApplyUnbufferedSeekpoint',
  7908. value: function _checkAndApplyUnbufferedSeekpoint() {
  7909. if (this._seekpointRecord) {
  7910. if (this._seekpointRecord.recordTime <= this._now() - 100) {
  7911. var target = this._mediaElement.currentTime;
  7912. this._seekpointRecord = null;
  7913. if (!this._isTimepointBuffered(target)) {
  7914. if (this._progressChecker != null) {
  7915. window.clearTimeout(this._progressChecker);
  7916. this._progressChecker = null;
  7917. }
  7918. // .currentTime is consists with .buffered timestamp
  7919. // Chrome/Edge use DTS, while FireFox/Safari use PTS
  7920. this._msectl.seek(target);
  7921. this._transmuxer.seek(Math.floor(target * 1000));
  7922. // set currentTime if accurateSeek, or wait for recommend_seekpoint callback
  7923. if (this._config.accurateSeek) {
  7924. this._requestSetTime = true;
  7925. this._mediaElement.currentTime = target;
  7926. }
  7927. }
  7928. } else {
  7929. window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this), 50);
  7930. }
  7931. }
  7932. }
  7933. }, {
  7934. key: '_checkAndResumeStuckPlayback',
  7935. value: function _checkAndResumeStuckPlayback(stalled) {
  7936. var media = this._mediaElement;
  7937. if (stalled || !this._receivedCanPlay || media.readyState < 2) {
  7938. // HAVE_CURRENT_DATA
  7939. var buffered = media.buffered;
  7940. if (buffered.length > 0 && media.currentTime < buffered.start(0)) {
  7941. _logger2.default.w(this.TAG, 'Playback seems stuck at ' + media.currentTime + ', seek to ' + buffered.start(0));
  7942. this._requestSetTime = true;
  7943. this._mediaElement.currentTime = buffered.start(0);
  7944. this._mediaElement.removeEventListener('progress', this.e.onvProgress);
  7945. }
  7946. } else {
  7947. // Playback didn't stuck, remove progress event listener
  7948. this._mediaElement.removeEventListener('progress', this.e.onvProgress);
  7949. }
  7950. }
  7951. }, {
  7952. key: '_onvLoadedMetadata',
  7953. value: function _onvLoadedMetadata(e) {
  7954. if (this._pendingSeekTime != null) {
  7955. this._mediaElement.currentTime = this._pendingSeekTime;
  7956. this._pendingSeekTime = null;
  7957. }
  7958. }
  7959. }, {
  7960. key: '_onvSeeking',
  7961. value: function _onvSeeking(e) {
  7962. // handle seeking request from browser's progress bar
  7963. var target = this._mediaElement.currentTime;
  7964. var buffered = this._mediaElement.buffered;
  7965. if (this._requestSetTime) {
  7966. this._requestSetTime = false;
  7967. return;
  7968. }
  7969. if (target < 1.0 && buffered.length > 0) {
  7970. // seek to video begin, set currentTime directly if beginPTS buffered
  7971. var videoBeginTime = buffered.start(0);
  7972. if (videoBeginTime < 1.0 && target < videoBeginTime || _browser2.default.safari) {
  7973. this._requestSetTime = true;
  7974. // also workaround for Safari: Seek to 0 may cause video stuck, use 0.1 to avoid
  7975. this._mediaElement.currentTime = _browser2.default.safari ? 0.1 : videoBeginTime;
  7976. return;
  7977. }
  7978. }
  7979. if (this._isTimepointBuffered(target)) {
  7980. if (this._alwaysSeekKeyframe) {
  7981. var idr = this._msectl.getNearestKeyframe(Math.floor(target * 1000));
  7982. if (idr != null) {
  7983. this._requestSetTime = true;
  7984. this._mediaElement.currentTime = idr.dts / 1000;
  7985. }
  7986. }
  7987. if (this._progressChecker != null) {
  7988. this._checkProgressAndResume();
  7989. }
  7990. return;
  7991. }
  7992. this._seekpointRecord = {
  7993. seekPoint: target,
  7994. recordTime: this._now()
  7995. };
  7996. window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this), 50);
  7997. }
  7998. }, {
  7999. key: '_onvCanPlay',
  8000. value: function _onvCanPlay(e) {
  8001. this._receivedCanPlay = true;
  8002. this._mediaElement.removeEventListener('canplay', this.e.onvCanPlay);
  8003. }
  8004. }, {
  8005. key: '_onvStalled',
  8006. value: function _onvStalled(e) {
  8007. this._checkAndResumeStuckPlayback(true);
  8008. }
  8009. }, {
  8010. key: '_onvProgress',
  8011. value: function _onvProgress(e) {
  8012. this._checkAndResumeStuckPlayback();
  8013. }
  8014. }, {
  8015. key: 'type',
  8016. get: function get() {
  8017. return this._type;
  8018. }
  8019. }, {
  8020. key: 'buffered',
  8021. get: function get() {
  8022. return this._mediaElement.buffered;
  8023. }
  8024. }, {
  8025. key: 'duration',
  8026. get: function get() {
  8027. return this._mediaElement.duration;
  8028. }
  8029. }, {
  8030. key: 'volume',
  8031. get: function get() {
  8032. return this._mediaElement.volume;
  8033. },
  8034. set: function set(value) {
  8035. this._mediaElement.volume = value;
  8036. }
  8037. }, {
  8038. key: 'muted',
  8039. get: function get() {
  8040. return this._mediaElement.muted;
  8041. },
  8042. set: function set(muted) {
  8043. this._mediaElement.muted = muted;
  8044. }
  8045. }, {
  8046. key: 'currentTime',
  8047. get: function get() {
  8048. if (this._mediaElement) {
  8049. return this._mediaElement.currentTime;
  8050. }
  8051. return 0;
  8052. },
  8053. set: function set(seconds) {
  8054. if (this._mediaElement) {
  8055. this._internalSeek(seconds);
  8056. } else {
  8057. this._pendingSeekTime = seconds;
  8058. }
  8059. }
  8060. }, {
  8061. key: 'mediaInfo',
  8062. get: function get() {
  8063. return Object.assign({}, this._mediaInfo);
  8064. }
  8065. }, {
  8066. key: 'statisticsInfo',
  8067. get: function get() {
  8068. if (this._statisticsInfo == null) {
  8069. this._statisticsInfo = {};
  8070. }
  8071. this._statisticsInfo = this._fillStatisticsInfo(this._statisticsInfo);
  8072. return Object.assign({}, this._statisticsInfo);
  8073. }
  8074. }]);
  8075. return FlvPlayer;
  8076. }();
  8077. exports.default = FlvPlayer;
  8078. },{"../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){
  8079. 'use strict';
  8080. Object.defineProperty(exports, "__esModule", {
  8081. value: true
  8082. });
  8083. 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; };
  8084. 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; }; }(); /*
  8085. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  8086. *
  8087. * @author zheng qian <xqq@xqq.im>
  8088. *
  8089. * Licensed under the Apache License, Version 2.0 (the "License");
  8090. * you may not use this file except in compliance with the License.
  8091. * You may obtain a copy of the License at
  8092. *
  8093. * http://www.apache.org/licenses/LICENSE-2.0
  8094. *
  8095. * Unless required by applicable law or agreed to in writing, software
  8096. * distributed under the License is distributed on an "AS IS" BASIS,
  8097. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8098. * See the License for the specific language governing permissions and
  8099. * limitations under the License.
  8100. */
  8101. var _events = _dereq_('events');
  8102. var _events2 = _interopRequireDefault(_events);
  8103. var _playerEvents = _dereq_('./player-events.js');
  8104. var _playerEvents2 = _interopRequireDefault(_playerEvents);
  8105. var _config = _dereq_('../config.js');
  8106. var _exception = _dereq_('../utils/exception.js');
  8107. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8108. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8109. // Player wrapper for browser's native player (HTMLVideoElement) without MediaSource src.
  8110. var NativePlayer = function () {
  8111. function NativePlayer(mediaDataSource, config) {
  8112. _classCallCheck(this, NativePlayer);
  8113. this.TAG = 'NativePlayer';
  8114. this._type = 'NativePlayer';
  8115. this._emitter = new _events2.default();
  8116. this._config = (0, _config.createDefaultConfig)();
  8117. if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object') {
  8118. Object.assign(this._config, config);
  8119. }
  8120. if (mediaDataSource.type.toLowerCase() === 'flv') {
  8121. throw new _exception.InvalidArgumentException('NativePlayer does\'t support flv MediaDataSource input!');
  8122. }
  8123. if (mediaDataSource.hasOwnProperty('segments')) {
  8124. throw new _exception.InvalidArgumentException('NativePlayer(' + mediaDataSource.type + ') doesn\'t support multipart playback!');
  8125. }
  8126. this.e = {
  8127. onvLoadedMetadata: this._onvLoadedMetadata.bind(this)
  8128. };
  8129. this._pendingSeekTime = null;
  8130. this._statisticsReporter = null;
  8131. this._mediaDataSource = mediaDataSource;
  8132. this._mediaElement = null;
  8133. }
  8134. _createClass(NativePlayer, [{
  8135. key: 'destroy',
  8136. value: function destroy() {
  8137. if (this._mediaElement) {
  8138. this.unload();
  8139. this.detachMediaElement();
  8140. }
  8141. this.e = null;
  8142. this._mediaDataSource = null;
  8143. this._emitter.removeAllListeners();
  8144. this._emitter = null;
  8145. }
  8146. }, {
  8147. key: 'on',
  8148. value: function on(event, listener) {
  8149. var _this = this;
  8150. if (event === _playerEvents2.default.MEDIA_INFO) {
  8151. if (this._mediaElement != null && this._mediaElement.readyState !== 0) {
  8152. // HAVE_NOTHING
  8153. Promise.resolve().then(function () {
  8154. _this._emitter.emit(_playerEvents2.default.MEDIA_INFO, _this.mediaInfo);
  8155. });
  8156. }
  8157. } else if (event === _playerEvents2.default.STATISTICS_INFO) {
  8158. if (this._mediaElement != null && this._mediaElement.readyState !== 0) {
  8159. Promise.resolve().then(function () {
  8160. _this._emitter.emit(_playerEvents2.default.STATISTICS_INFO, _this.statisticsInfo);
  8161. });
  8162. }
  8163. }
  8164. this._emitter.addListener(event, listener);
  8165. }
  8166. }, {
  8167. key: 'off',
  8168. value: function off(event, listener) {
  8169. this._emitter.removeListener(event, listener);
  8170. }
  8171. }, {
  8172. key: 'attachMediaElement',
  8173. value: function attachMediaElement(mediaElement) {
  8174. this._mediaElement = mediaElement;
  8175. mediaElement.addEventListener('loadedmetadata', this.e.onvLoadedMetadata);
  8176. if (this._pendingSeekTime != null) {
  8177. try {
  8178. mediaElement.currentTime = this._pendingSeekTime;
  8179. this._pendingSeekTime = null;
  8180. } catch (e) {
  8181. // IE11 may throw InvalidStateError if readyState === 0
  8182. // Defer set currentTime operation after loadedmetadata
  8183. }
  8184. }
  8185. }
  8186. }, {
  8187. key: 'detachMediaElement',
  8188. value: function detachMediaElement() {
  8189. if (this._mediaElement) {
  8190. this._mediaElement.src = '';
  8191. this._mediaElement.removeAttribute('src');
  8192. this._mediaElement.removeEventListener('loadedmetadata', this.e.onvLoadedMetadata);
  8193. this._mediaElement = null;
  8194. }
  8195. if (this._statisticsReporter != null) {
  8196. window.clearInterval(this._statisticsReporter);
  8197. this._statisticsReporter = null;
  8198. }
  8199. }
  8200. }, {
  8201. key: 'load',
  8202. value: function load() {
  8203. if (!this._mediaElement) {
  8204. throw new _exception.IllegalStateException('HTMLMediaElement must be attached before load()!');
  8205. }
  8206. this._mediaElement.src = this._mediaDataSource.url;
  8207. if (this._mediaElement.readyState > 0) {
  8208. this._mediaElement.currentTime = 0;
  8209. }
  8210. this._mediaElement.preload = 'auto';
  8211. this._mediaElement.load();
  8212. this._statisticsReporter = window.setInterval(this._reportStatisticsInfo.bind(this), this._config.statisticsInfoReportInterval);
  8213. }
  8214. }, {
  8215. key: 'unload',
  8216. value: function unload() {
  8217. if (this._mediaElement) {
  8218. this._mediaElement.src = '';
  8219. this._mediaElement.removeAttribute('src');
  8220. }
  8221. if (this._statisticsReporter != null) {
  8222. window.clearInterval(this._statisticsReporter);
  8223. this._statisticsReporter = null;
  8224. }
  8225. }
  8226. }, {
  8227. key: 'play',
  8228. value: function play() {
  8229. return this._mediaElement.play();
  8230. }
  8231. }, {
  8232. key: 'pause',
  8233. value: function pause() {
  8234. this._mediaElement.pause();
  8235. }
  8236. }, {
  8237. key: '_onvLoadedMetadata',
  8238. value: function _onvLoadedMetadata(e) {
  8239. if (this._pendingSeekTime != null) {
  8240. this._mediaElement.currentTime = this._pendingSeekTime;
  8241. this._pendingSeekTime = null;
  8242. }
  8243. this._emitter.emit(_playerEvents2.default.MEDIA_INFO, this.mediaInfo);
  8244. }
  8245. }, {
  8246. key: '_reportStatisticsInfo',
  8247. value: function _reportStatisticsInfo() {
  8248. this._emitter.emit(_playerEvents2.default.STATISTICS_INFO, this.statisticsInfo);
  8249. }
  8250. }, {
  8251. key: 'type',
  8252. get: function get() {
  8253. return this._type;
  8254. }
  8255. }, {
  8256. key: 'buffered',
  8257. get: function get() {
  8258. return this._mediaElement.buffered;
  8259. }
  8260. }, {
  8261. key: 'duration',
  8262. get: function get() {
  8263. return this._mediaElement.duration;
  8264. }
  8265. }, {
  8266. key: 'volume',
  8267. get: function get() {
  8268. return this._mediaElement.volume;
  8269. },
  8270. set: function set(value) {
  8271. this._mediaElement.volume = value;
  8272. }
  8273. }, {
  8274. key: 'muted',
  8275. get: function get() {
  8276. return this._mediaElement.muted;
  8277. },
  8278. set: function set(muted) {
  8279. this._mediaElement.muted = muted;
  8280. }
  8281. }, {
  8282. key: 'currentTime',
  8283. get: function get() {
  8284. if (this._mediaElement) {
  8285. return this._mediaElement.currentTime;
  8286. }
  8287. return 0;
  8288. },
  8289. set: function set(seconds) {
  8290. if (this._mediaElement) {
  8291. this._mediaElement.currentTime = seconds;
  8292. } else {
  8293. this._pendingSeekTime = seconds;
  8294. }
  8295. }
  8296. }, {
  8297. key: 'mediaInfo',
  8298. get: function get() {
  8299. var mediaPrefix = this._mediaElement instanceof HTMLAudioElement ? 'audio/' : 'video/';
  8300. var info = {
  8301. mimeType: mediaPrefix + this._mediaDataSource.type
  8302. };
  8303. if (this._mediaElement) {
  8304. info.duration = Math.floor(this._mediaElement.duration * 1000);
  8305. if (this._mediaElement instanceof HTMLVideoElement) {
  8306. info.width = this._mediaElement.videoWidth;
  8307. info.height = this._mediaElement.videoHeight;
  8308. }
  8309. }
  8310. return info;
  8311. }
  8312. }, {
  8313. key: 'statisticsInfo',
  8314. get: function get() {
  8315. var info = {
  8316. playerType: this._type,
  8317. url: this._mediaDataSource.url
  8318. };
  8319. if (!(this._mediaElement instanceof HTMLVideoElement)) {
  8320. return info;
  8321. }
  8322. var hasQualityInfo = true;
  8323. var decoded = 0;
  8324. var dropped = 0;
  8325. if (this._mediaElement.getVideoPlaybackQuality) {
  8326. var quality = this._mediaElement.getVideoPlaybackQuality();
  8327. decoded = quality.totalVideoFrames;
  8328. dropped = quality.droppedVideoFrames;
  8329. } else if (this._mediaElement.webkitDecodedFrameCount != undefined) {
  8330. decoded = this._mediaElement.webkitDecodedFrameCount;
  8331. dropped = this._mediaElement.webkitDroppedFrameCount;
  8332. } else {
  8333. hasQualityInfo = false;
  8334. }
  8335. if (hasQualityInfo) {
  8336. info.decodedFrames = decoded;
  8337. info.droppedFrames = dropped;
  8338. }
  8339. return info;
  8340. }
  8341. }]);
  8342. return NativePlayer;
  8343. }();
  8344. exports.default = NativePlayer;
  8345. },{"../config.js":5,"../utils/exception.js":40,"./player-events.js":35,"events":2}],34:[function(_dereq_,module,exports){
  8346. 'use strict';
  8347. Object.defineProperty(exports, "__esModule", {
  8348. value: true
  8349. });
  8350. exports.ErrorDetails = exports.ErrorTypes = undefined;
  8351. var _loader = _dereq_('../io/loader.js');
  8352. var _demuxErrors = _dereq_('../demux/demux-errors.js');
  8353. var _demuxErrors2 = _interopRequireDefault(_demuxErrors);
  8354. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8355. /*
  8356. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  8357. *
  8358. * @author zheng qian <xqq@xqq.im>
  8359. *
  8360. * Licensed under the Apache License, Version 2.0 (the "License");
  8361. * you may not use this file except in compliance with the License.
  8362. * You may obtain a copy of the License at
  8363. *
  8364. * http://www.apache.org/licenses/LICENSE-2.0
  8365. *
  8366. * Unless required by applicable law or agreed to in writing, software
  8367. * distributed under the License is distributed on an "AS IS" BASIS,
  8368. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8369. * See the License for the specific language governing permissions and
  8370. * limitations under the License.
  8371. */
  8372. var ErrorTypes = exports.ErrorTypes = {
  8373. NETWORK_ERROR: 'NetworkError',
  8374. MEDIA_ERROR: 'MediaError',
  8375. OTHER_ERROR: 'OtherError'
  8376. };
  8377. var ErrorDetails = exports.ErrorDetails = {
  8378. NETWORK_EXCEPTION: _loader.LoaderErrors.EXCEPTION,
  8379. NETWORK_STATUS_CODE_INVALID: _loader.LoaderErrors.HTTP_STATUS_CODE_INVALID,
  8380. NETWORK_TIMEOUT: _loader.LoaderErrors.CONNECTING_TIMEOUT,
  8381. NETWORK_UNRECOVERABLE_EARLY_EOF: _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF,
  8382. MEDIA_MSE_ERROR: 'MediaMSEError',
  8383. MEDIA_FORMAT_ERROR: _demuxErrors2.default.FORMAT_ERROR,
  8384. MEDIA_FORMAT_UNSUPPORTED: _demuxErrors2.default.FORMAT_UNSUPPORTED,
  8385. MEDIA_CODEC_UNSUPPORTED: _demuxErrors2.default.CODEC_UNSUPPORTED
  8386. };
  8387. },{"../demux/demux-errors.js":16,"../io/loader.js":24}],35:[function(_dereq_,module,exports){
  8388. 'use strict';
  8389. Object.defineProperty(exports, "__esModule", {
  8390. value: true
  8391. });
  8392. /*
  8393. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  8394. *
  8395. * @author zheng qian <xqq@xqq.im>
  8396. *
  8397. * Licensed under the Apache License, Version 2.0 (the "License");
  8398. * you may not use this file except in compliance with the License.
  8399. * You may obtain a copy of the License at
  8400. *
  8401. * http://www.apache.org/licenses/LICENSE-2.0
  8402. *
  8403. * Unless required by applicable law or agreed to in writing, software
  8404. * distributed under the License is distributed on an "AS IS" BASIS,
  8405. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8406. * See the License for the specific language governing permissions and
  8407. * limitations under the License.
  8408. */
  8409. var PlayerEvents = {
  8410. ERROR: 'error',
  8411. LOADING_COMPLETE: 'loading_complete',
  8412. RECOVERED_EARLY_EOF: 'recovered_early_eof',
  8413. MEDIA_INFO: 'media_info',
  8414. STATISTICS_INFO: 'statistics_info'
  8415. };
  8416. exports.default = PlayerEvents;
  8417. },{}],36:[function(_dereq_,module,exports){
  8418. 'use strict';
  8419. Object.defineProperty(exports, "__esModule", {
  8420. value: true
  8421. });
  8422. 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; }; }();
  8423. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8424. /*
  8425. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  8426. *
  8427. * This file is modified from dailymotion's hls.js library (hls.js/src/helper/aac.js)
  8428. * @author zheng qian <xqq@xqq.im>
  8429. *
  8430. * Licensed under the Apache License, Version 2.0 (the "License");
  8431. * you may not use this file except in compliance with the License.
  8432. * You may obtain a copy of the License at
  8433. *
  8434. * http://www.apache.org/licenses/LICENSE-2.0
  8435. *
  8436. * Unless required by applicable law or agreed to in writing, software
  8437. * distributed under the License is distributed on an "AS IS" BASIS,
  8438. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8439. * See the License for the specific language governing permissions and
  8440. * limitations under the License.
  8441. */
  8442. var AAC = function () {
  8443. function AAC() {
  8444. _classCallCheck(this, AAC);
  8445. }
  8446. _createClass(AAC, null, [{
  8447. key: 'getSilentFrame',
  8448. value: function getSilentFrame(codec, channelCount) {
  8449. if (codec === 'mp4a.40.2') {
  8450. // handle LC-AAC
  8451. if (channelCount === 1) {
  8452. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  8453. } else if (channelCount === 2) {
  8454. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  8455. } else if (channelCount === 3) {
  8456. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  8457. } else if (channelCount === 4) {
  8458. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  8459. } else if (channelCount === 5) {
  8460. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  8461. } else if (channelCount === 6) {
  8462. 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]);
  8463. }
  8464. } else {
  8465. // handle HE-AAC (mp4a.40.5 / mp4a.40.29)
  8466. if (channelCount === 1) {
  8467. // 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
  8468. 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]);
  8469. } else if (channelCount === 2) {
  8470. // 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
  8471. 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]);
  8472. } else if (channelCount === 3) {
  8473. // 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
  8474. 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]);
  8475. }
  8476. }
  8477. return null;
  8478. }
  8479. }]);
  8480. return AAC;
  8481. }();
  8482. exports.default = AAC;
  8483. },{}],37:[function(_dereq_,module,exports){
  8484. 'use strict';
  8485. Object.defineProperty(exports, "__esModule", {
  8486. value: true
  8487. });
  8488. 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; }; }();
  8489. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8490. /*
  8491. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  8492. *
  8493. * This file is derived from dailymotion's hls.js library (hls.js/src/remux/mp4-generator.js)
  8494. * @author zheng qian <xqq@xqq.im>
  8495. *
  8496. * Licensed under the Apache License, Version 2.0 (the "License");
  8497. * you may not use this file except in compliance with the License.
  8498. * You may obtain a copy of the License at
  8499. *
  8500. * http://www.apache.org/licenses/LICENSE-2.0
  8501. *
  8502. * Unless required by applicable law or agreed to in writing, software
  8503. * distributed under the License is distributed on an "AS IS" BASIS,
  8504. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8505. * See the License for the specific language governing permissions and
  8506. * limitations under the License.
  8507. */
  8508. // MP4 boxes generator for ISO BMFF (ISO Base Media File Format, defined in ISO/IEC 14496-12)
  8509. var MP4 = function () {
  8510. function MP4() {
  8511. _classCallCheck(this, MP4);
  8512. }
  8513. _createClass(MP4, null, [{
  8514. key: 'init',
  8515. value: function init() {
  8516. MP4.types = {
  8517. avc1: [], avcC: [], btrt: [], dinf: [],
  8518. dref: [], esds: [], ftyp: [], hdlr: [],
  8519. mdat: [], mdhd: [], mdia: [], mfhd: [],
  8520. minf: [], moof: [], moov: [], mp4a: [],
  8521. mvex: [], mvhd: [], sdtp: [], stbl: [],
  8522. stco: [], stsc: [], stsd: [], stsz: [],
  8523. stts: [], tfdt: [], tfhd: [], traf: [],
  8524. trak: [], trun: [], trex: [], tkhd: [],
  8525. vmhd: [], smhd: [], '.mp3': []
  8526. };
  8527. for (var name in MP4.types) {
  8528. if (MP4.types.hasOwnProperty(name)) {
  8529. MP4.types[name] = [name.charCodeAt(0), name.charCodeAt(1), name.charCodeAt(2), name.charCodeAt(3)];
  8530. }
  8531. }
  8532. var constants = MP4.constants = {};
  8533. constants.FTYP = new Uint8Array([0x69, 0x73, 0x6F, 0x6D, // major_brand: isom
  8534. 0x0, 0x0, 0x0, 0x1, // minor_version: 0x01
  8535. 0x69, 0x73, 0x6F, 0x6D, // isom
  8536. 0x61, 0x76, 0x63, 0x31 // avc1
  8537. ]);
  8538. constants.STSD_PREFIX = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8539. 0x00, 0x00, 0x00, 0x01 // entry_count
  8540. ]);
  8541. constants.STTS = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8542. 0x00, 0x00, 0x00, 0x00 // entry_count
  8543. ]);
  8544. constants.STSC = constants.STCO = constants.STTS;
  8545. constants.STSZ = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8546. 0x00, 0x00, 0x00, 0x00, // sample_size
  8547. 0x00, 0x00, 0x00, 0x00 // sample_count
  8548. ]);
  8549. constants.HDLR_VIDEO = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8550. 0x00, 0x00, 0x00, 0x00, // pre_defined
  8551. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  8552. 0x00, 0x00, 0x00, 0x00, // reserved: 3 * 4 bytes
  8553. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x69, 0x64, 0x65, 0x6F, 0x48, 0x61, 0x6E, 0x64, 0x6C, 0x65, 0x72, 0x00 // name: VideoHandler
  8554. ]);
  8555. constants.HDLR_AUDIO = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8556. 0x00, 0x00, 0x00, 0x00, // pre_defined
  8557. 0x73, 0x6F, 0x75, 0x6E, // handler_type: 'soun'
  8558. 0x00, 0x00, 0x00, 0x00, // reserved: 3 * 4 bytes
  8559. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x6F, 0x75, 0x6E, 0x64, 0x48, 0x61, 0x6E, 0x64, 0x6C, 0x65, 0x72, 0x00 // name: SoundHandler
  8560. ]);
  8561. constants.DREF = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8562. 0x00, 0x00, 0x00, 0x01, // entry_count
  8563. 0x00, 0x00, 0x00, 0x0C, // entry_size
  8564. 0x75, 0x72, 0x6C, 0x20, // type 'url '
  8565. 0x00, 0x00, 0x00, 0x01 // version(0) + flags
  8566. ]);
  8567. // Sound media header
  8568. constants.SMHD = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8569. 0x00, 0x00, 0x00, 0x00 // balance(2) + reserved(2)
  8570. ]);
  8571. // video media header
  8572. constants.VMHD = new Uint8Array([0x00, 0x00, 0x00, 0x01, // version(0) + flags
  8573. 0x00, 0x00, // graphicsmode: 2 bytes
  8574. 0x00, 0x00, 0x00, 0x00, // opcolor: 3 * 2 bytes
  8575. 0x00, 0x00]);
  8576. }
  8577. // Generate a box
  8578. }, {
  8579. key: 'box',
  8580. value: function box(type) {
  8581. var size = 8;
  8582. var result = null;
  8583. var datas = Array.prototype.slice.call(arguments, 1);
  8584. var arrayCount = datas.length;
  8585. for (var i = 0; i < arrayCount; i++) {
  8586. size += datas[i].byteLength;
  8587. }
  8588. result = new Uint8Array(size);
  8589. result[0] = size >>> 24 & 0xFF; // size
  8590. result[1] = size >>> 16 & 0xFF;
  8591. result[2] = size >>> 8 & 0xFF;
  8592. result[3] = size & 0xFF;
  8593. result.set(type, 4); // type
  8594. var offset = 8;
  8595. for (var _i = 0; _i < arrayCount; _i++) {
  8596. // data body
  8597. result.set(datas[_i], offset);
  8598. offset += datas[_i].byteLength;
  8599. }
  8600. return result;
  8601. }
  8602. // emit ftyp & moov
  8603. }, {
  8604. key: 'generateInitSegment',
  8605. value: function generateInitSegment(meta) {
  8606. var ftyp = MP4.box(MP4.types.ftyp, MP4.constants.FTYP);
  8607. var moov = MP4.moov(meta);
  8608. var result = new Uint8Array(ftyp.byteLength + moov.byteLength);
  8609. result.set(ftyp, 0);
  8610. result.set(moov, ftyp.byteLength);
  8611. return result;
  8612. }
  8613. // Movie metadata box
  8614. }, {
  8615. key: 'moov',
  8616. value: function moov(meta) {
  8617. var mvhd = MP4.mvhd(meta.timescale, meta.duration);
  8618. var trak = MP4.trak(meta);
  8619. var mvex = MP4.mvex(meta);
  8620. return MP4.box(MP4.types.moov, mvhd, trak, mvex);
  8621. }
  8622. // Movie header box
  8623. }, {
  8624. key: 'mvhd',
  8625. value: function mvhd(timescale, duration) {
  8626. return MP4.box(MP4.types.mvhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8627. 0x00, 0x00, 0x00, 0x00, // creation_time
  8628. 0x00, 0x00, 0x00, 0x00, // modification_time
  8629. timescale >>> 24 & 0xFF, // timescale: 4 bytes
  8630. timescale >>> 16 & 0xFF, timescale >>> 8 & 0xFF, timescale & 0xFF, duration >>> 24 & 0xFF, // duration: 4 bytes
  8631. duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x00, 0x01, 0x00, 0x00, // Preferred rate: 1.0
  8632. 0x01, 0x00, 0x00, 0x00, // PreferredVolume(1.0, 2bytes) + reserved(2bytes)
  8633. 0x00, 0x00, 0x00, 0x00, // reserved: 4 + 4 bytes
  8634. 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, // ----begin composition matrix----
  8635. 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----
  8636. 0x00, 0x00, 0x00, 0x00, // ----begin pre_defined 6 * 4 bytes----
  8637. 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----
  8638. 0xFF, 0xFF, 0xFF, 0xFF // next_track_ID
  8639. ]));
  8640. }
  8641. // Track box
  8642. }, {
  8643. key: 'trak',
  8644. value: function trak(meta) {
  8645. return MP4.box(MP4.types.trak, MP4.tkhd(meta), MP4.mdia(meta));
  8646. }
  8647. // Track header box
  8648. }, {
  8649. key: 'tkhd',
  8650. value: function tkhd(meta) {
  8651. var trackId = meta.id,
  8652. duration = meta.duration;
  8653. var width = meta.presentWidth,
  8654. height = meta.presentHeight;
  8655. return MP4.box(MP4.types.tkhd, new Uint8Array([0x00, 0x00, 0x00, 0x07, // version(0) + flags
  8656. 0x00, 0x00, 0x00, 0x00, // creation_time
  8657. 0x00, 0x00, 0x00, 0x00, // modification_time
  8658. trackId >>> 24 & 0xFF, // track_ID: 4 bytes
  8659. trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF, 0x00, 0x00, 0x00, 0x00, // reserved: 4 bytes
  8660. duration >>> 24 & 0xFF, // duration: 4 bytes
  8661. duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes
  8662. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // layer(2bytes) + alternate_group(2bytes)
  8663. 0x00, 0x00, 0x00, 0x00, // volume(2bytes) + reserved(2bytes)
  8664. 0x00, 0x01, 0x00, 0x00, // ----begin composition matrix----
  8665. 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----
  8666. width >>> 8 & 0xFF, // width and height
  8667. width & 0xFF, 0x00, 0x00, height >>> 8 & 0xFF, height & 0xFF, 0x00, 0x00]));
  8668. }
  8669. // Media Box
  8670. }, {
  8671. key: 'mdia',
  8672. value: function mdia(meta) {
  8673. return MP4.box(MP4.types.mdia, MP4.mdhd(meta), MP4.hdlr(meta), MP4.minf(meta));
  8674. }
  8675. // Media header box
  8676. }, {
  8677. key: 'mdhd',
  8678. value: function mdhd(meta) {
  8679. var timescale = meta.timescale;
  8680. var duration = meta.duration;
  8681. return MP4.box(MP4.types.mdhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8682. 0x00, 0x00, 0x00, 0x00, // creation_time
  8683. 0x00, 0x00, 0x00, 0x00, // modification_time
  8684. timescale >>> 24 & 0xFF, // timescale: 4 bytes
  8685. timescale >>> 16 & 0xFF, timescale >>> 8 & 0xFF, timescale & 0xFF, duration >>> 24 & 0xFF, // duration: 4 bytes
  8686. duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x55, 0xC4, // language: und (undetermined)
  8687. 0x00, 0x00 // pre_defined = 0
  8688. ]));
  8689. }
  8690. // Media handler reference box
  8691. }, {
  8692. key: 'hdlr',
  8693. value: function hdlr(meta) {
  8694. var data = null;
  8695. if (meta.type === 'audio') {
  8696. data = MP4.constants.HDLR_AUDIO;
  8697. } else {
  8698. data = MP4.constants.HDLR_VIDEO;
  8699. }
  8700. return MP4.box(MP4.types.hdlr, data);
  8701. }
  8702. // Media infomation box
  8703. }, {
  8704. key: 'minf',
  8705. value: function minf(meta) {
  8706. var xmhd = null;
  8707. if (meta.type === 'audio') {
  8708. xmhd = MP4.box(MP4.types.smhd, MP4.constants.SMHD);
  8709. } else {
  8710. xmhd = MP4.box(MP4.types.vmhd, MP4.constants.VMHD);
  8711. }
  8712. return MP4.box(MP4.types.minf, xmhd, MP4.dinf(), MP4.stbl(meta));
  8713. }
  8714. // Data infomation box
  8715. }, {
  8716. key: 'dinf',
  8717. value: function dinf() {
  8718. var result = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, MP4.constants.DREF));
  8719. return result;
  8720. }
  8721. // Sample table box
  8722. }, {
  8723. key: 'stbl',
  8724. value: function stbl(meta) {
  8725. var result = MP4.box(MP4.types.stbl, // type: stbl
  8726. MP4.stsd(meta), // Sample Description Table
  8727. MP4.box(MP4.types.stts, MP4.constants.STTS), // Time-To-Sample
  8728. MP4.box(MP4.types.stsc, MP4.constants.STSC), // Sample-To-Chunk
  8729. MP4.box(MP4.types.stsz, MP4.constants.STSZ), // Sample size
  8730. MP4.box(MP4.types.stco, MP4.constants.STCO // Chunk offset
  8731. ));
  8732. return result;
  8733. }
  8734. // Sample description box
  8735. }, {
  8736. key: 'stsd',
  8737. value: function stsd(meta) {
  8738. if (meta.type === 'audio') {
  8739. if (meta.codec === 'mp3') {
  8740. return MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.mp3(meta));
  8741. }
  8742. // else: aac -> mp4a
  8743. return MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.mp4a(meta));
  8744. } else {
  8745. return MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.avc1(meta));
  8746. }
  8747. }
  8748. }, {
  8749. key: 'mp3',
  8750. value: function mp3(meta) {
  8751. var channelCount = meta.channelCount;
  8752. var sampleRate = meta.audioSampleRate;
  8753. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // reserved(4)
  8754. 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2)
  8755. 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes
  8756. 0x00, 0x00, 0x00, 0x00, 0x00, channelCount, // channelCount(2)
  8757. 0x00, 0x10, // sampleSize(2)
  8758. 0x00, 0x00, 0x00, 0x00, // reserved(4)
  8759. sampleRate >>> 8 & 0xFF, // Audio sample rate
  8760. sampleRate & 0xFF, 0x00, 0x00]);
  8761. return MP4.box(MP4.types['.mp3'], data);
  8762. }
  8763. }, {
  8764. key: 'mp4a',
  8765. value: function mp4a(meta) {
  8766. var channelCount = meta.channelCount;
  8767. var sampleRate = meta.audioSampleRate;
  8768. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // reserved(4)
  8769. 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2)
  8770. 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes
  8771. 0x00, 0x00, 0x00, 0x00, 0x00, channelCount, // channelCount(2)
  8772. 0x00, 0x10, // sampleSize(2)
  8773. 0x00, 0x00, 0x00, 0x00, // reserved(4)
  8774. sampleRate >>> 8 & 0xFF, // Audio sample rate
  8775. sampleRate & 0xFF, 0x00, 0x00]);
  8776. return MP4.box(MP4.types.mp4a, data, MP4.esds(meta));
  8777. }
  8778. }, {
  8779. key: 'esds',
  8780. value: function esds(meta) {
  8781. var config = meta.config || [];
  8782. var configSize = config.length;
  8783. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version 0 + flags
  8784. 0x03, // descriptor_type
  8785. 0x17 + configSize, // length3
  8786. 0x00, 0x01, // es_id
  8787. 0x00, // stream_priority
  8788. 0x04, // descriptor_type
  8789. 0x0F + configSize, // length
  8790. 0x40, // codec: mpeg4_audio
  8791. 0x15, // stream_type: Audio
  8792. 0x00, 0x00, 0x00, // buffer_size
  8793. 0x00, 0x00, 0x00, 0x00, // maxBitrate
  8794. 0x00, 0x00, 0x00, 0x00, // avgBitrate
  8795. 0x05 // descriptor_type
  8796. ].concat([configSize]).concat(config).concat([0x06, 0x01, 0x02 // GASpecificConfig
  8797. ]));
  8798. return MP4.box(MP4.types.esds, data);
  8799. }
  8800. }, {
  8801. key: 'avc1',
  8802. value: function avc1(meta) {
  8803. var avcc = meta.avcc;
  8804. var width = meta.codecWidth,
  8805. height = meta.codecHeight;
  8806. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // reserved(4)
  8807. 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2)
  8808. 0x00, 0x00, 0x00, 0x00, // pre_defined(2) + reserved(2)
  8809. 0x00, 0x00, 0x00, 0x00, // pre_defined: 3 * 4 bytes
  8810. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, width >>> 8 & 0xFF, // width: 2 bytes
  8811. width & 0xFF, height >>> 8 & 0xFF, // height: 2 bytes
  8812. height & 0xFF, 0x00, 0x48, 0x00, 0x00, // horizresolution: 4 bytes
  8813. 0x00, 0x48, 0x00, 0x00, // vertresolution: 4 bytes
  8814. 0x00, 0x00, 0x00, 0x00, // reserved: 4 bytes
  8815. 0x00, 0x01, // frame_count
  8816. 0x0A, // strlen
  8817. 0x78, 0x71, 0x71, 0x2F, // compressorname: 32 bytes
  8818. 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
  8819. 0xFF, 0xFF // pre_defined = -1
  8820. ]);
  8821. return MP4.box(MP4.types.avc1, data, MP4.box(MP4.types.avcC, avcc));
  8822. }
  8823. // Movie Extends box
  8824. }, {
  8825. key: 'mvex',
  8826. value: function mvex(meta) {
  8827. return MP4.box(MP4.types.mvex, MP4.trex(meta));
  8828. }
  8829. // Track Extends box
  8830. }, {
  8831. key: 'trex',
  8832. value: function trex(meta) {
  8833. var trackId = meta.id;
  8834. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  8835. trackId >>> 24 & 0xFF, // track_ID
  8836. trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF, 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  8837. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  8838. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  8839. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  8840. ]);
  8841. return MP4.box(MP4.types.trex, data);
  8842. }
  8843. // Movie fragment box
  8844. }, {
  8845. key: 'moof',
  8846. value: function moof(track, baseMediaDecodeTime) {
  8847. return MP4.box(MP4.types.moof, MP4.mfhd(track.sequenceNumber), MP4.traf(track, baseMediaDecodeTime));
  8848. }
  8849. }, {
  8850. key: 'mfhd',
  8851. value: function mfhd(sequenceNumber) {
  8852. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, sequenceNumber >>> 24 & 0xFF, // sequence_number: int32
  8853. sequenceNumber >>> 16 & 0xFF, sequenceNumber >>> 8 & 0xFF, sequenceNumber & 0xFF]);
  8854. return MP4.box(MP4.types.mfhd, data);
  8855. }
  8856. // Track fragment box
  8857. }, {
  8858. key: 'traf',
  8859. value: function traf(track, baseMediaDecodeTime) {
  8860. var trackId = track.id;
  8861. // Track fragment header box
  8862. var tfhd = MP4.box(MP4.types.tfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) & flags
  8863. trackId >>> 24 & 0xFF, // track_ID
  8864. trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF]));
  8865. // Track Fragment Decode Time
  8866. var tfdt = MP4.box(MP4.types.tfdt, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) & flags
  8867. baseMediaDecodeTime >>> 24 & 0xFF, // baseMediaDecodeTime: int32
  8868. baseMediaDecodeTime >>> 16 & 0xFF, baseMediaDecodeTime >>> 8 & 0xFF, baseMediaDecodeTime & 0xFF]));
  8869. var sdtp = MP4.sdtp(track);
  8870. var trun = MP4.trun(track, sdtp.byteLength + 16 + 16 + 8 + 16 + 8 + 8);
  8871. return MP4.box(MP4.types.traf, tfhd, tfdt, trun, sdtp);
  8872. }
  8873. // Sample Dependency Type box
  8874. }, {
  8875. key: 'sdtp',
  8876. value: function sdtp(track) {
  8877. var samples = track.samples || [];
  8878. var sampleCount = samples.length;
  8879. var data = new Uint8Array(4 + sampleCount);
  8880. // 0~4 bytes: version(0) & flags
  8881. for (var i = 0; i < sampleCount; i++) {
  8882. var flags = samples[i].flags;
  8883. data[i + 4] = flags.isLeading << 6 | // is_leading: 2 (bit)
  8884. flags.dependsOn << 4 // sample_depends_on
  8885. | flags.isDependedOn << 2 // sample_is_depended_on
  8886. | flags.hasRedundancy; // sample_has_redundancy
  8887. }
  8888. return MP4.box(MP4.types.sdtp, data);
  8889. }
  8890. // Track fragment run box
  8891. }, {
  8892. key: 'trun',
  8893. value: function trun(track, offset) {
  8894. var samples = track.samples || [];
  8895. var sampleCount = samples.length;
  8896. var dataSize = 12 + 16 * sampleCount;
  8897. var data = new Uint8Array(dataSize);
  8898. offset += 8 + dataSize;
  8899. data.set([0x00, 0x00, 0x0F, 0x01, // version(0) & flags
  8900. sampleCount >>> 24 & 0xFF, // sample_count
  8901. sampleCount >>> 16 & 0xFF, sampleCount >>> 8 & 0xFF, sampleCount & 0xFF, offset >>> 24 & 0xFF, // data_offset
  8902. offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF], 0);
  8903. for (var i = 0; i < sampleCount; i++) {
  8904. var duration = samples[i].duration;
  8905. var size = samples[i].size;
  8906. var flags = samples[i].flags;
  8907. var cts = samples[i].cts;
  8908. data.set([duration >>> 24 & 0xFF, // sample_duration
  8909. duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, size >>> 24 & 0xFF, // sample_size
  8910. size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, flags.isLeading << 2 | flags.dependsOn, // sample_flags
  8911. flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.isNonSync, 0x00, 0x00, // sample_degradation_priority
  8912. cts >>> 24 & 0xFF, // sample_composition_time_offset
  8913. cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF], 12 + 16 * i);
  8914. }
  8915. return MP4.box(MP4.types.trun, data);
  8916. }
  8917. }, {
  8918. key: 'mdat',
  8919. value: function mdat(data) {
  8920. return MP4.box(MP4.types.mdat, data);
  8921. }
  8922. }]);
  8923. return MP4;
  8924. }();
  8925. MP4.init();
  8926. exports.default = MP4;
  8927. },{}],38:[function(_dereq_,module,exports){
  8928. 'use strict';
  8929. Object.defineProperty(exports, "__esModule", {
  8930. value: true
  8931. });
  8932. 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; }; }(); /*
  8933. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  8934. *
  8935. * @author zheng qian <xqq@xqq.im>
  8936. *
  8937. * Licensed under the Apache License, Version 2.0 (the "License");
  8938. * you may not use this file except in compliance with the License.
  8939. * You may obtain a copy of the License at
  8940. *
  8941. * http://www.apache.org/licenses/LICENSE-2.0
  8942. *
  8943. * Unless required by applicable law or agreed to in writing, software
  8944. * distributed under the License is distributed on an "AS IS" BASIS,
  8945. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8946. * See the License for the specific language governing permissions and
  8947. * limitations under the License.
  8948. */
  8949. var _logger = _dereq_('../utils/logger.js');
  8950. var _logger2 = _interopRequireDefault(_logger);
  8951. var _mp4Generator = _dereq_('./mp4-generator.js');
  8952. var _mp4Generator2 = _interopRequireDefault(_mp4Generator);
  8953. var _aacSilent = _dereq_('./aac-silent.js');
  8954. var _aacSilent2 = _interopRequireDefault(_aacSilent);
  8955. var _browser = _dereq_('../utils/browser.js');
  8956. var _browser2 = _interopRequireDefault(_browser);
  8957. var _mediaSegmentInfo = _dereq_('../core/media-segment-info.js');
  8958. var _exception = _dereq_('../utils/exception.js');
  8959. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8960. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8961. // Fragmented mp4 remuxer
  8962. var MP4Remuxer = function () {
  8963. function MP4Remuxer(config) {
  8964. _classCallCheck(this, MP4Remuxer);
  8965. this.TAG = 'MP4Remuxer';
  8966. this._config = config;
  8967. this._isLive = config.isLive === true ? true : false;
  8968. this._dtsBase = -1;
  8969. this._dtsBaseInited = false;
  8970. this._audioDtsBase = Infinity;
  8971. this._videoDtsBase = Infinity;
  8972. this._audioNextDts = undefined;
  8973. this._videoNextDts = undefined;
  8974. this._audioStashedLastSample = null;
  8975. this._videoStashedLastSample = null;
  8976. this._audioMeta = null;
  8977. this._videoMeta = null;
  8978. this._audioSegmentInfoList = new _mediaSegmentInfo.MediaSegmentInfoList('audio');
  8979. this._videoSegmentInfoList = new _mediaSegmentInfo.MediaSegmentInfoList('video');
  8980. this._onInitSegment = null;
  8981. this._onMediaSegment = null;
  8982. // Workaround for chrome < 50: Always force first sample as a Random Access Point in media segment
  8983. // see https://bugs.chromium.org/p/chromium/issues/detail?id=229412
  8984. this._forceFirstIDR = _browser2.default.chrome && (_browser2.default.version.major < 50 || _browser2.default.version.major === 50 && _browser2.default.version.build < 2661) ? true : false;
  8985. // Workaround for IE11/Edge: Fill silent aac frame after keyframe-seeking
  8986. // Make audio beginDts equals with video beginDts, in order to fix seek freeze
  8987. this._fillSilentAfterSeek = _browser2.default.msedge || _browser2.default.msie;
  8988. // While only FireFox supports 'audio/mp4, codecs="mp3"', use 'audio/mpeg' for chrome, safari, ...
  8989. this._mp3UseMpegAudio = !_browser2.default.firefox;
  8990. this._fillAudioTimestampGap = this._config.fixAudioTimestampGap;
  8991. }
  8992. _createClass(MP4Remuxer, [{
  8993. key: 'destroy',
  8994. value: function destroy() {
  8995. this._dtsBase = -1;
  8996. this._dtsBaseInited = false;
  8997. this._audioMeta = null;
  8998. this._videoMeta = null;
  8999. this._audioSegmentInfoList.clear();
  9000. this._audioSegmentInfoList = null;
  9001. this._videoSegmentInfoList.clear();
  9002. this._videoSegmentInfoList = null;
  9003. this._onInitSegment = null;
  9004. this._onMediaSegment = null;
  9005. }
  9006. }, {
  9007. key: 'bindDataSource',
  9008. value: function bindDataSource(producer) {
  9009. producer.onDataAvailable = this.remux.bind(this);
  9010. producer.onTrackMetadata = this._onTrackMetadataReceived.bind(this);
  9011. return this;
  9012. }
  9013. /* prototype: function onInitSegment(type: string, initSegment: ArrayBuffer): void
  9014. InitSegment: {
  9015. type: string,
  9016. data: ArrayBuffer,
  9017. codec: string,
  9018. container: string
  9019. }
  9020. */
  9021. }, {
  9022. key: 'insertDiscontinuity',
  9023. value: function insertDiscontinuity() {
  9024. this._audioNextDts = this._videoNextDts = undefined;
  9025. }
  9026. }, {
  9027. key: 'seek',
  9028. value: function seek(originalDts) {
  9029. this._audioStashedLastSample = null;
  9030. this._videoStashedLastSample = null;
  9031. this._videoSegmentInfoList.clear();
  9032. this._audioSegmentInfoList.clear();
  9033. }
  9034. }, {
  9035. key: 'remux',
  9036. value: function remux(audioTrack, videoTrack) {
  9037. if (!this._onMediaSegment) {
  9038. throw new _exception.IllegalStateException('MP4Remuxer: onMediaSegment callback must be specificed!');
  9039. }
  9040. if (!this._dtsBaseInited) {
  9041. this._calculateDtsBase(audioTrack, videoTrack);
  9042. }
  9043. this._remuxVideo(videoTrack);
  9044. this._remuxAudio(audioTrack);
  9045. }
  9046. }, {
  9047. key: '_onTrackMetadataReceived',
  9048. value: function _onTrackMetadataReceived(type, metadata) {
  9049. var metabox = null;
  9050. var container = 'mp4';
  9051. var codec = metadata.codec;
  9052. if (type === 'audio') {
  9053. this._audioMeta = metadata;
  9054. if (metadata.codec === 'mp3' && this._mp3UseMpegAudio) {
  9055. // 'audio/mpeg' for MP3 audio track
  9056. container = 'mpeg';
  9057. codec = '';
  9058. metabox = new Uint8Array();
  9059. } else {
  9060. // 'audio/mp4, codecs="codec"'
  9061. metabox = _mp4Generator2.default.generateInitSegment(metadata);
  9062. }
  9063. } else if (type === 'video') {
  9064. this._videoMeta = metadata;
  9065. metabox = _mp4Generator2.default.generateInitSegment(metadata);
  9066. } else {
  9067. return;
  9068. }
  9069. // dispatch metabox (Initialization Segment)
  9070. if (!this._onInitSegment) {
  9071. throw new _exception.IllegalStateException('MP4Remuxer: onInitSegment callback must be specified!');
  9072. }
  9073. this._onInitSegment(type, {
  9074. type: type,
  9075. data: metabox.buffer,
  9076. codec: codec,
  9077. container: type + '/' + container,
  9078. mediaDuration: metadata.duration // in timescale 1000 (milliseconds)
  9079. });
  9080. }
  9081. }, {
  9082. key: '_calculateDtsBase',
  9083. value: function _calculateDtsBase(audioTrack, videoTrack) {
  9084. if (this._dtsBaseInited) {
  9085. return;
  9086. }
  9087. if (audioTrack.samples && audioTrack.samples.length) {
  9088. this._audioDtsBase = audioTrack.samples[0].dts;
  9089. }
  9090. if (videoTrack.samples && videoTrack.samples.length) {
  9091. this._videoDtsBase = videoTrack.samples[0].dts;
  9092. }
  9093. this._dtsBase = Math.min(this._audioDtsBase, this._videoDtsBase);
  9094. this._dtsBaseInited = true;
  9095. }
  9096. }, {
  9097. key: 'flushStashedSamples',
  9098. value: function flushStashedSamples() {
  9099. var videoSample = this._videoStashedLastSample;
  9100. var audioSample = this._audioStashedLastSample;
  9101. var videoTrack = {
  9102. type: 'video',
  9103. id: 1,
  9104. sequenceNumber: 0,
  9105. samples: [],
  9106. length: 0
  9107. };
  9108. if (videoSample != null) {
  9109. videoTrack.samples.push(videoSample);
  9110. videoTrack.length = videoSample.length;
  9111. }
  9112. var audioTrack = {
  9113. type: 'audio',
  9114. id: 2,
  9115. sequenceNumber: 0,
  9116. samples: [],
  9117. length: 0
  9118. };
  9119. if (audioSample != null) {
  9120. audioTrack.samples.push(audioSample);
  9121. audioTrack.length = audioSample.length;
  9122. }
  9123. this._videoStashedLastSample = null;
  9124. this._audioStashedLastSample = null;
  9125. this._remuxVideo(videoTrack, true);
  9126. this._remuxAudio(audioTrack, true);
  9127. }
  9128. }, {
  9129. key: '_remuxAudio',
  9130. value: function _remuxAudio(audioTrack, force) {
  9131. if (this._audioMeta == null) {
  9132. return;
  9133. }
  9134. var track = audioTrack;
  9135. var samples = track.samples;
  9136. var dtsCorrection = undefined;
  9137. var firstDts = -1,
  9138. lastDts = -1,
  9139. lastPts = -1;
  9140. var refSampleDuration = this._audioMeta.refSampleDuration;
  9141. var mpegRawTrack = this._audioMeta.codec === 'mp3' && this._mp3UseMpegAudio;
  9142. var firstSegmentAfterSeek = this._dtsBaseInited && this._audioNextDts === undefined;
  9143. var insertPrefixSilentFrame = false;
  9144. if (!samples || samples.length === 0) {
  9145. return;
  9146. }
  9147. if (samples.length === 1 && !force) {
  9148. // If [sample count in current batch] === 1 && (force != true)
  9149. // Ignore and keep in demuxer's queue
  9150. return;
  9151. } // else if (force === true) do remux
  9152. var offset = 0;
  9153. var mdatbox = null;
  9154. var mdatBytes = 0;
  9155. // calculate initial mdat size
  9156. if (mpegRawTrack) {
  9157. // for raw mpeg buffer
  9158. offset = 0;
  9159. mdatBytes = track.length;
  9160. } else {
  9161. // for fmp4 mdat box
  9162. offset = 8; // size + type
  9163. mdatBytes = 8 + track.length;
  9164. }
  9165. var lastSample = null;
  9166. // Pop the lastSample and waiting for stash
  9167. if (samples.length > 1) {
  9168. lastSample = samples.pop();
  9169. mdatBytes -= lastSample.length;
  9170. }
  9171. // Insert [stashed lastSample in the previous batch] to the front
  9172. if (this._audioStashedLastSample != null) {
  9173. var sample = this._audioStashedLastSample;
  9174. this._audioStashedLastSample = null;
  9175. samples.unshift(sample);
  9176. mdatBytes += sample.length;
  9177. }
  9178. // Stash the lastSample of current batch, waiting for next batch
  9179. if (lastSample != null) {
  9180. this._audioStashedLastSample = lastSample;
  9181. }
  9182. var firstSampleOriginalDts = samples[0].dts - this._dtsBase;
  9183. // calculate dtsCorrection
  9184. if (this._audioNextDts) {
  9185. dtsCorrection = firstSampleOriginalDts - this._audioNextDts;
  9186. } else {
  9187. // this._audioNextDts == undefined
  9188. if (this._audioSegmentInfoList.isEmpty()) {
  9189. dtsCorrection = 0;
  9190. if (this._fillSilentAfterSeek && !this._videoSegmentInfoList.isEmpty()) {
  9191. if (this._audioMeta.originalCodec !== 'mp3') {
  9192. insertPrefixSilentFrame = true;
  9193. }
  9194. }
  9195. } else {
  9196. var _lastSample = this._audioSegmentInfoList.getLastSampleBefore(firstSampleOriginalDts);
  9197. if (_lastSample != null) {
  9198. var distance = firstSampleOriginalDts - (_lastSample.originalDts + _lastSample.duration);
  9199. if (distance <= 3) {
  9200. distance = 0;
  9201. }
  9202. var expectedDts = _lastSample.dts + _lastSample.duration + distance;
  9203. dtsCorrection = firstSampleOriginalDts - expectedDts;
  9204. } else {
  9205. // lastSample == null, cannot found
  9206. dtsCorrection = 0;
  9207. }
  9208. }
  9209. }
  9210. if (insertPrefixSilentFrame) {
  9211. // align audio segment beginDts to match with current video segment's beginDts
  9212. var firstSampleDts = firstSampleOriginalDts - dtsCorrection;
  9213. var videoSegment = this._videoSegmentInfoList.getLastSegmentBefore(firstSampleOriginalDts);
  9214. if (videoSegment != null && videoSegment.beginDts < firstSampleDts) {
  9215. var silentUnit = _aacSilent2.default.getSilentFrame(this._audioMeta.originalCodec, this._audioMeta.channelCount);
  9216. if (silentUnit) {
  9217. var dts = videoSegment.beginDts;
  9218. var silentFrameDuration = firstSampleDts - videoSegment.beginDts;
  9219. _logger2.default.v(this.TAG, 'InsertPrefixSilentAudio: dts: ' + dts + ', duration: ' + silentFrameDuration);
  9220. samples.unshift({ unit: silentUnit, dts: dts, pts: dts });
  9221. mdatBytes += silentUnit.byteLength;
  9222. } // silentUnit == null: Cannot generate, skip
  9223. } else {
  9224. insertPrefixSilentFrame = false;
  9225. }
  9226. }
  9227. var mp4Samples = [];
  9228. // Correct dts for each sample, and calculate sample duration. Then output to mp4Samples
  9229. for (var i = 0; i < samples.length; i++) {
  9230. var _sample = samples[i];
  9231. var unit = _sample.unit;
  9232. var originalDts = _sample.dts - this._dtsBase;
  9233. var _dts = originalDts - dtsCorrection;
  9234. if (firstDts === -1) {
  9235. firstDts = _dts;
  9236. }
  9237. var sampleDuration = 0;
  9238. if (i !== samples.length - 1) {
  9239. var nextDts = samples[i + 1].dts - this._dtsBase - dtsCorrection;
  9240. sampleDuration = nextDts - _dts;
  9241. } else {
  9242. // the last sample
  9243. if (lastSample != null) {
  9244. // use stashed sample's dts to calculate sample duration
  9245. var _nextDts = lastSample.dts - this._dtsBase - dtsCorrection;
  9246. sampleDuration = _nextDts - _dts;
  9247. } else if (mp4Samples.length >= 1) {
  9248. // use second last sample duration
  9249. sampleDuration = mp4Samples[mp4Samples.length - 1].duration;
  9250. } else {
  9251. // the only one sample, use reference sample duration
  9252. sampleDuration = Math.floor(refSampleDuration);
  9253. }
  9254. }
  9255. var needFillSilentFrames = false;
  9256. var silentFrames = null;
  9257. // Silent frame generation, if large timestamp gap detected && config.fixAudioTimestampGap
  9258. if (sampleDuration > refSampleDuration * 1.5 && this._audioMeta.codec !== 'mp3' && this._fillAudioTimestampGap && !_browser2.default.safari) {
  9259. // We need to insert silent frames to fill timestamp gap
  9260. needFillSilentFrames = true;
  9261. var delta = Math.abs(sampleDuration - refSampleDuration);
  9262. var frameCount = Math.ceil(delta / refSampleDuration);
  9263. var currentDts = _dts + refSampleDuration; // Notice: in float
  9264. _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'));
  9265. var _silentUnit = _aacSilent2.default.getSilentFrame(this._audioMeta.originalCodec, this._audioMeta.channelCount);
  9266. if (_silentUnit == null) {
  9267. _logger2.default.w(this.TAG, 'Unable to generate silent frame for ' + (this._audioMeta.originalCodec + ' with ' + this._audioMeta.channelCount + ' channels, repeat last frame'));
  9268. // Repeat last frame
  9269. _silentUnit = unit;
  9270. }
  9271. silentFrames = [];
  9272. for (var j = 0; j < frameCount; j++) {
  9273. var intDts = Math.round(currentDts); // round to integer
  9274. if (silentFrames.length > 0) {
  9275. // Set previous frame sample duration
  9276. var previousFrame = silentFrames[silentFrames.length - 1];
  9277. previousFrame.duration = intDts - previousFrame.dts;
  9278. }
  9279. var frame = {
  9280. dts: intDts,
  9281. pts: intDts,
  9282. cts: 0,
  9283. unit: _silentUnit,
  9284. size: _silentUnit.byteLength,
  9285. duration: 0, // wait for next sample
  9286. originalDts: originalDts,
  9287. flags: {
  9288. isLeading: 0,
  9289. dependsOn: 1,
  9290. isDependedOn: 0,
  9291. hasRedundancy: 0
  9292. }
  9293. };
  9294. silentFrames.push(frame);
  9295. mdatBytes += unit.byteLength;
  9296. currentDts += refSampleDuration;
  9297. }
  9298. // last frame: align end time to next frame dts
  9299. var lastFrame = silentFrames[silentFrames.length - 1];
  9300. lastFrame.duration = _dts + sampleDuration - lastFrame.dts;
  9301. // silentFrames.forEach((frame) => {
  9302. // Log.w(this.TAG, `SilentAudio: dts: ${frame.dts}, duration: ${frame.duration}`);
  9303. // });
  9304. // Set correct sample duration for current frame
  9305. sampleDuration = Math.round(refSampleDuration);
  9306. }
  9307. mp4Samples.push({
  9308. dts: _dts,
  9309. pts: _dts,
  9310. cts: 0,
  9311. unit: _sample.unit,
  9312. size: _sample.unit.byteLength,
  9313. duration: sampleDuration,
  9314. originalDts: originalDts,
  9315. flags: {
  9316. isLeading: 0,
  9317. dependsOn: 1,
  9318. isDependedOn: 0,
  9319. hasRedundancy: 0
  9320. }
  9321. });
  9322. if (needFillSilentFrames) {
  9323. // Silent frames should be inserted after wrong-duration frame
  9324. mp4Samples.push.apply(mp4Samples, silentFrames);
  9325. }
  9326. }
  9327. // allocate mdatbox
  9328. if (mpegRawTrack) {
  9329. // allocate for raw mpeg buffer
  9330. mdatbox = new Uint8Array(mdatBytes);
  9331. } else {
  9332. // allocate for fmp4 mdat box
  9333. mdatbox = new Uint8Array(mdatBytes);
  9334. // size field
  9335. mdatbox[0] = mdatBytes >>> 24 & 0xFF;
  9336. mdatbox[1] = mdatBytes >>> 16 & 0xFF;
  9337. mdatbox[2] = mdatBytes >>> 8 & 0xFF;
  9338. mdatbox[3] = mdatBytes & 0xFF;
  9339. // type field (fourCC)
  9340. mdatbox.set(_mp4Generator2.default.types.mdat, 4);
  9341. }
  9342. // Write samples into mdatbox
  9343. for (var _i = 0; _i < mp4Samples.length; _i++) {
  9344. var _unit = mp4Samples[_i].unit;
  9345. mdatbox.set(_unit, offset);
  9346. offset += _unit.byteLength;
  9347. }
  9348. var latest = mp4Samples[mp4Samples.length - 1];
  9349. lastDts = latest.dts + latest.duration;
  9350. this._audioNextDts = lastDts;
  9351. // fill media segment info & add to info list
  9352. var info = new _mediaSegmentInfo.MediaSegmentInfo();
  9353. info.beginDts = firstDts;
  9354. info.endDts = lastDts;
  9355. info.beginPts = firstDts;
  9356. info.endPts = lastDts;
  9357. info.originalBeginDts = mp4Samples[0].originalDts;
  9358. info.originalEndDts = latest.originalDts + latest.duration;
  9359. info.firstSample = new _mediaSegmentInfo.SampleInfo(mp4Samples[0].dts, mp4Samples[0].pts, mp4Samples[0].duration, mp4Samples[0].originalDts, false);
  9360. info.lastSample = new _mediaSegmentInfo.SampleInfo(latest.dts, latest.pts, latest.duration, latest.originalDts, false);
  9361. if (!this._isLive) {
  9362. this._audioSegmentInfoList.append(info);
  9363. }
  9364. track.samples = mp4Samples;
  9365. track.sequenceNumber++;
  9366. var moofbox = null;
  9367. if (mpegRawTrack) {
  9368. // Generate empty buffer, because useless for raw mpeg
  9369. moofbox = new Uint8Array();
  9370. } else {
  9371. // Generate moof for fmp4 segment
  9372. moofbox = _mp4Generator2.default.moof(track, firstDts);
  9373. }
  9374. track.samples = [];
  9375. track.length = 0;
  9376. var segment = {
  9377. type: 'audio',
  9378. data: this._mergeBoxes(moofbox, mdatbox).buffer,
  9379. sampleCount: mp4Samples.length,
  9380. info: info
  9381. };
  9382. if (mpegRawTrack && firstSegmentAfterSeek) {
  9383. // For MPEG audio stream in MSE, if seeking occurred, before appending new buffer
  9384. // We need explicitly set timestampOffset to the desired point in timeline for mpeg SourceBuffer.
  9385. segment.timestampOffset = firstDts;
  9386. }
  9387. this._onMediaSegment('audio', segment);
  9388. }
  9389. }, {
  9390. key: '_remuxVideo',
  9391. value: function _remuxVideo(videoTrack, force) {
  9392. if (this._videoMeta == null) {
  9393. return;
  9394. }
  9395. var track = videoTrack;
  9396. var samples = track.samples;
  9397. var dtsCorrection = undefined;
  9398. var firstDts = -1,
  9399. lastDts = -1;
  9400. var firstPts = -1,
  9401. lastPts = -1;
  9402. if (!samples || samples.length === 0) {
  9403. return;
  9404. }
  9405. if (samples.length === 1 && !force) {
  9406. // If [sample count in current batch] === 1 && (force != true)
  9407. // Ignore and keep in demuxer's queue
  9408. return;
  9409. } // else if (force === true) do remux
  9410. var offset = 8;
  9411. var mdatbox = null;
  9412. var mdatBytes = 8 + videoTrack.length;
  9413. var lastSample = null;
  9414. // Pop the lastSample and waiting for stash
  9415. if (samples.length > 1) {
  9416. lastSample = samples.pop();
  9417. mdatBytes -= lastSample.length;
  9418. }
  9419. // Insert [stashed lastSample in the previous batch] to the front
  9420. if (this._videoStashedLastSample != null) {
  9421. var sample = this._videoStashedLastSample;
  9422. this._videoStashedLastSample = null;
  9423. samples.unshift(sample);
  9424. mdatBytes += sample.length;
  9425. }
  9426. // Stash the lastSample of current batch, waiting for next batch
  9427. if (lastSample != null) {
  9428. this._videoStashedLastSample = lastSample;
  9429. }
  9430. var firstSampleOriginalDts = samples[0].dts - this._dtsBase;
  9431. // calculate dtsCorrection
  9432. if (this._videoNextDts) {
  9433. dtsCorrection = firstSampleOriginalDts - this._videoNextDts;
  9434. } else {
  9435. // this._videoNextDts == undefined
  9436. if (this._videoSegmentInfoList.isEmpty()) {
  9437. dtsCorrection = 0;
  9438. } else {
  9439. var _lastSample2 = this._videoSegmentInfoList.getLastSampleBefore(firstSampleOriginalDts);
  9440. if (_lastSample2 != null) {
  9441. var distance = firstSampleOriginalDts - (_lastSample2.originalDts + _lastSample2.duration);
  9442. if (distance <= 3) {
  9443. distance = 0;
  9444. }
  9445. var expectedDts = _lastSample2.dts + _lastSample2.duration + distance;
  9446. dtsCorrection = firstSampleOriginalDts - expectedDts;
  9447. } else {
  9448. // lastSample == null, cannot found
  9449. dtsCorrection = 0;
  9450. }
  9451. }
  9452. }
  9453. var info = new _mediaSegmentInfo.MediaSegmentInfo();
  9454. var mp4Samples = [];
  9455. // Correct dts for each sample, and calculate sample duration. Then output to mp4Samples
  9456. for (var i = 0; i < samples.length; i++) {
  9457. var _sample2 = samples[i];
  9458. var originalDts = _sample2.dts - this._dtsBase;
  9459. var isKeyframe = _sample2.isKeyframe;
  9460. var dts = originalDts - dtsCorrection;
  9461. var cts = _sample2.cts;
  9462. var pts = dts + cts;
  9463. if (firstDts === -1) {
  9464. firstDts = dts;
  9465. firstPts = pts;
  9466. }
  9467. var sampleDuration = 0;
  9468. if (i !== samples.length - 1) {
  9469. var nextDts = samples[i + 1].dts - this._dtsBase - dtsCorrection;
  9470. sampleDuration = nextDts - dts;
  9471. } else {
  9472. // the last sample
  9473. if (lastSample != null) {
  9474. // use stashed sample's dts to calculate sample duration
  9475. var _nextDts2 = lastSample.dts - this._dtsBase - dtsCorrection;
  9476. sampleDuration = _nextDts2 - dts;
  9477. } else if (mp4Samples.length >= 1) {
  9478. // use second last sample duration
  9479. sampleDuration = mp4Samples[mp4Samples.length - 1].duration;
  9480. } else {
  9481. // the only one sample, use reference sample duration
  9482. sampleDuration = Math.floor(this._videoMeta.refSampleDuration);
  9483. }
  9484. }
  9485. if (isKeyframe) {
  9486. var syncPoint = new _mediaSegmentInfo.SampleInfo(dts, pts, sampleDuration, _sample2.dts, true);
  9487. syncPoint.fileposition = _sample2.fileposition;
  9488. info.appendSyncPoint(syncPoint);
  9489. }
  9490. mp4Samples.push({
  9491. dts: dts,
  9492. pts: pts,
  9493. cts: cts,
  9494. units: _sample2.units,
  9495. size: _sample2.length,
  9496. isKeyframe: isKeyframe,
  9497. duration: sampleDuration,
  9498. originalDts: originalDts,
  9499. flags: {
  9500. isLeading: 0,
  9501. dependsOn: isKeyframe ? 2 : 1,
  9502. isDependedOn: isKeyframe ? 1 : 0,
  9503. hasRedundancy: 0,
  9504. isNonSync: isKeyframe ? 0 : 1
  9505. }
  9506. });
  9507. }
  9508. // allocate mdatbox
  9509. mdatbox = new Uint8Array(mdatBytes);
  9510. mdatbox[0] = mdatBytes >>> 24 & 0xFF;
  9511. mdatbox[1] = mdatBytes >>> 16 & 0xFF;
  9512. mdatbox[2] = mdatBytes >>> 8 & 0xFF;
  9513. mdatbox[3] = mdatBytes & 0xFF;
  9514. mdatbox.set(_mp4Generator2.default.types.mdat, 4);
  9515. // Write samples into mdatbox
  9516. for (var _i2 = 0; _i2 < mp4Samples.length; _i2++) {
  9517. var units = mp4Samples[_i2].units;
  9518. while (units.length) {
  9519. var unit = units.shift();
  9520. var data = unit.data;
  9521. mdatbox.set(data, offset);
  9522. offset += data.byteLength;
  9523. }
  9524. }
  9525. var latest = mp4Samples[mp4Samples.length - 1];
  9526. lastDts = latest.dts + latest.duration;
  9527. lastPts = latest.pts + latest.duration;
  9528. this._videoNextDts = lastDts;
  9529. // fill media segment info & add to info list
  9530. info.beginDts = firstDts;
  9531. info.endDts = lastDts;
  9532. info.beginPts = firstPts;
  9533. info.endPts = lastPts;
  9534. info.originalBeginDts = mp4Samples[0].originalDts;
  9535. info.originalEndDts = latest.originalDts + latest.duration;
  9536. info.firstSample = new _mediaSegmentInfo.SampleInfo(mp4Samples[0].dts, mp4Samples[0].pts, mp4Samples[0].duration, mp4Samples[0].originalDts, mp4Samples[0].isKeyframe);
  9537. info.lastSample = new _mediaSegmentInfo.SampleInfo(latest.dts, latest.pts, latest.duration, latest.originalDts, latest.isKeyframe);
  9538. if (!this._isLive) {
  9539. this._videoSegmentInfoList.append(info);
  9540. }
  9541. track.samples = mp4Samples;
  9542. track.sequenceNumber++;
  9543. // workaround for chrome < 50: force first sample as a random access point
  9544. // see https://bugs.chromium.org/p/chromium/issues/detail?id=229412
  9545. if (this._forceFirstIDR) {
  9546. var flags = mp4Samples[0].flags;
  9547. flags.dependsOn = 2;
  9548. flags.isNonSync = 0;
  9549. }
  9550. var moofbox = _mp4Generator2.default.moof(track, firstDts);
  9551. track.samples = [];
  9552. track.length = 0;
  9553. this._onMediaSegment('video', {
  9554. type: 'video',
  9555. data: this._mergeBoxes(moofbox, mdatbox).buffer,
  9556. sampleCount: mp4Samples.length,
  9557. info: info
  9558. });
  9559. }
  9560. }, {
  9561. key: '_mergeBoxes',
  9562. value: function _mergeBoxes(moof, mdat) {
  9563. var result = new Uint8Array(moof.byteLength + mdat.byteLength);
  9564. result.set(moof, 0);
  9565. result.set(mdat, moof.byteLength);
  9566. return result;
  9567. }
  9568. }, {
  9569. key: 'onInitSegment',
  9570. get: function get() {
  9571. return this._onInitSegment;
  9572. },
  9573. set: function set(callback) {
  9574. this._onInitSegment = callback;
  9575. }
  9576. /* prototype: function onMediaSegment(type: string, mediaSegment: MediaSegment): void
  9577. MediaSegment: {
  9578. type: string,
  9579. data: ArrayBuffer,
  9580. sampleCount: int32
  9581. info: MediaSegmentInfo
  9582. }
  9583. */
  9584. }, {
  9585. key: 'onMediaSegment',
  9586. get: function get() {
  9587. return this._onMediaSegment;
  9588. },
  9589. set: function set(callback) {
  9590. this._onMediaSegment = callback;
  9591. }
  9592. }]);
  9593. return MP4Remuxer;
  9594. }();
  9595. exports.default = MP4Remuxer;
  9596. },{"../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){
  9597. 'use strict';
  9598. Object.defineProperty(exports, "__esModule", {
  9599. value: true
  9600. });
  9601. /*
  9602. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  9603. *
  9604. * @author zheng qian <xqq@xqq.im>
  9605. *
  9606. * Licensed under the Apache License, Version 2.0 (the "License");
  9607. * you may not use this file except in compliance with the License.
  9608. * You may obtain a copy of the License at
  9609. *
  9610. * http://www.apache.org/licenses/LICENSE-2.0
  9611. *
  9612. * Unless required by applicable law or agreed to in writing, software
  9613. * distributed under the License is distributed on an "AS IS" BASIS,
  9614. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9615. * See the License for the specific language governing permissions and
  9616. * limitations under the License.
  9617. */
  9618. var Browser = {};
  9619. function detect() {
  9620. // modified from jquery-browser-plugin
  9621. var ua = self.navigator.userAgent.toLowerCase();
  9622. 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) || [];
  9623. 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) || [];
  9624. var matched = {
  9625. browser: match[5] || match[3] || match[1] || '',
  9626. version: match[2] || match[4] || '0',
  9627. majorVersion: match[4] || match[2] || '0',
  9628. platform: platform_match[0] || ''
  9629. };
  9630. var browser = {};
  9631. if (matched.browser) {
  9632. browser[matched.browser] = true;
  9633. var versionArray = matched.majorVersion.split('.');
  9634. browser.version = {
  9635. major: parseInt(matched.majorVersion, 10),
  9636. string: matched.version
  9637. };
  9638. if (versionArray.length > 1) {
  9639. browser.version.minor = parseInt(versionArray[1], 10);
  9640. }
  9641. if (versionArray.length > 2) {
  9642. browser.version.build = parseInt(versionArray[2], 10);
  9643. }
  9644. }
  9645. if (matched.platform) {
  9646. browser[matched.platform] = true;
  9647. }
  9648. if (browser.chrome || browser.opr || browser.safari) {
  9649. browser.webkit = true;
  9650. }
  9651. // MSIE. IE11 has 'rv' identifer
  9652. if (browser.rv || browser.iemobile) {
  9653. if (browser.rv) {
  9654. delete browser.rv;
  9655. }
  9656. var msie = 'msie';
  9657. matched.browser = msie;
  9658. browser[msie] = true;
  9659. }
  9660. // Microsoft Edge
  9661. if (browser.edge) {
  9662. delete browser.edge;
  9663. var msedge = 'msedge';
  9664. matched.browser = msedge;
  9665. browser[msedge] = true;
  9666. }
  9667. // Opera 15+
  9668. if (browser.opr) {
  9669. var opera = 'opera';
  9670. matched.browser = opera;
  9671. browser[opera] = true;
  9672. }
  9673. // Stock android browsers are marked as Safari
  9674. if (browser.safari && browser.android) {
  9675. var android = 'android';
  9676. matched.browser = android;
  9677. browser[android] = true;
  9678. }
  9679. browser.name = matched.browser;
  9680. browser.platform = matched.platform;
  9681. for (var key in Browser) {
  9682. if (Browser.hasOwnProperty(key)) {
  9683. delete Browser[key];
  9684. }
  9685. }
  9686. Object.assign(Browser, browser);
  9687. }
  9688. detect();
  9689. exports.default = Browser;
  9690. },{}],40:[function(_dereq_,module,exports){
  9691. 'use strict';
  9692. Object.defineProperty(exports, "__esModule", {
  9693. value: true
  9694. });
  9695. 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; }; }();
  9696. 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; }
  9697. 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; }
  9698. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9699. /*
  9700. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  9701. *
  9702. * @author zheng qian <xqq@xqq.im>
  9703. *
  9704. * Licensed under the Apache License, Version 2.0 (the "License");
  9705. * you may not use this file except in compliance with the License.
  9706. * You may obtain a copy of the License at
  9707. *
  9708. * http://www.apache.org/licenses/LICENSE-2.0
  9709. *
  9710. * Unless required by applicable law or agreed to in writing, software
  9711. * distributed under the License is distributed on an "AS IS" BASIS,
  9712. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9713. * See the License for the specific language governing permissions and
  9714. * limitations under the License.
  9715. */
  9716. var RuntimeException = exports.RuntimeException = function () {
  9717. function RuntimeException(message) {
  9718. _classCallCheck(this, RuntimeException);
  9719. this._message = message;
  9720. }
  9721. _createClass(RuntimeException, [{
  9722. key: 'toString',
  9723. value: function toString() {
  9724. return this.name + ': ' + this.message;
  9725. }
  9726. }, {
  9727. key: 'name',
  9728. get: function get() {
  9729. return 'RuntimeException';
  9730. }
  9731. }, {
  9732. key: 'message',
  9733. get: function get() {
  9734. return this._message;
  9735. }
  9736. }]);
  9737. return RuntimeException;
  9738. }();
  9739. var IllegalStateException = exports.IllegalStateException = function (_RuntimeException) {
  9740. _inherits(IllegalStateException, _RuntimeException);
  9741. function IllegalStateException(message) {
  9742. _classCallCheck(this, IllegalStateException);
  9743. return _possibleConstructorReturn(this, (IllegalStateException.__proto__ || Object.getPrototypeOf(IllegalStateException)).call(this, message));
  9744. }
  9745. _createClass(IllegalStateException, [{
  9746. key: 'name',
  9747. get: function get() {
  9748. return 'IllegalStateException';
  9749. }
  9750. }]);
  9751. return IllegalStateException;
  9752. }(RuntimeException);
  9753. var InvalidArgumentException = exports.InvalidArgumentException = function (_RuntimeException2) {
  9754. _inherits(InvalidArgumentException, _RuntimeException2);
  9755. function InvalidArgumentException(message) {
  9756. _classCallCheck(this, InvalidArgumentException);
  9757. return _possibleConstructorReturn(this, (InvalidArgumentException.__proto__ || Object.getPrototypeOf(InvalidArgumentException)).call(this, message));
  9758. }
  9759. _createClass(InvalidArgumentException, [{
  9760. key: 'name',
  9761. get: function get() {
  9762. return 'InvalidArgumentException';
  9763. }
  9764. }]);
  9765. return InvalidArgumentException;
  9766. }(RuntimeException);
  9767. var NotImplementedException = exports.NotImplementedException = function (_RuntimeException3) {
  9768. _inherits(NotImplementedException, _RuntimeException3);
  9769. function NotImplementedException(message) {
  9770. _classCallCheck(this, NotImplementedException);
  9771. return _possibleConstructorReturn(this, (NotImplementedException.__proto__ || Object.getPrototypeOf(NotImplementedException)).call(this, message));
  9772. }
  9773. _createClass(NotImplementedException, [{
  9774. key: 'name',
  9775. get: function get() {
  9776. return 'NotImplementedException';
  9777. }
  9778. }]);
  9779. return NotImplementedException;
  9780. }(RuntimeException);
  9781. },{}],41:[function(_dereq_,module,exports){
  9782. 'use strict';
  9783. Object.defineProperty(exports, "__esModule", {
  9784. value: true
  9785. });
  9786. 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; }; }(); /*
  9787. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  9788. *
  9789. * @author zheng qian <xqq@xqq.im>
  9790. *
  9791. * Licensed under the Apache License, Version 2.0 (the "License");
  9792. * you may not use this file except in compliance with the License.
  9793. * You may obtain a copy of the License at
  9794. *
  9795. * http://www.apache.org/licenses/LICENSE-2.0
  9796. *
  9797. * Unless required by applicable law or agreed to in writing, software
  9798. * distributed under the License is distributed on an "AS IS" BASIS,
  9799. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9800. * See the License for the specific language governing permissions and
  9801. * limitations under the License.
  9802. */
  9803. var _events = _dereq_('events');
  9804. var _events2 = _interopRequireDefault(_events);
  9805. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9806. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9807. var Log = function () {
  9808. function Log() {
  9809. _classCallCheck(this, Log);
  9810. }
  9811. _createClass(Log, null, [{
  9812. key: 'e',
  9813. value: function e(tag, msg) {
  9814. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  9815. var str = '[' + tag + '] > ' + msg;
  9816. if (Log.ENABLE_CALLBACK) {
  9817. Log.emitter.emit('log', 'error', str);
  9818. }
  9819. if (!Log.ENABLE_ERROR) {
  9820. return;
  9821. }
  9822. if (console.error) {
  9823. console.error(str);
  9824. } else if (console.warn) {
  9825. console.warn(str);
  9826. } else {
  9827. console.log(str);
  9828. }
  9829. }
  9830. }, {
  9831. key: 'i',
  9832. value: function i(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', 'info', str);
  9837. }
  9838. if (!Log.ENABLE_INFO) {
  9839. return;
  9840. }
  9841. if (console.info) {
  9842. console.info(str);
  9843. } else {
  9844. console.log(str);
  9845. }
  9846. }
  9847. }, {
  9848. key: 'w',
  9849. value: function w(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', 'warn', str);
  9854. }
  9855. if (!Log.ENABLE_WARN) {
  9856. return;
  9857. }
  9858. if (console.warn) {
  9859. console.warn(str);
  9860. } else {
  9861. console.log(str);
  9862. }
  9863. }
  9864. }, {
  9865. key: 'd',
  9866. value: function d(tag, msg) {
  9867. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  9868. var str = '[' + tag + '] > ' + msg;
  9869. if (Log.ENABLE_CALLBACK) {
  9870. Log.emitter.emit('log', 'debug', str);
  9871. }
  9872. if (!Log.ENABLE_DEBUG) {
  9873. return;
  9874. }
  9875. if (console.debug) {
  9876. console.debug(str);
  9877. } else {
  9878. console.log(str);
  9879. }
  9880. }
  9881. }, {
  9882. key: 'v',
  9883. value: function v(tag, msg) {
  9884. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  9885. var str = '[' + tag + '] > ' + msg;
  9886. if (Log.ENABLE_CALLBACK) {
  9887. Log.emitter.emit('log', 'verbose', str);
  9888. }
  9889. if (!Log.ENABLE_VERBOSE) {
  9890. return;
  9891. }
  9892. console.log(str);
  9893. }
  9894. }]);
  9895. return Log;
  9896. }();
  9897. Log.GLOBAL_TAG = 'flv.js';
  9898. Log.FORCE_GLOBAL_TAG = false;
  9899. Log.ENABLE_ERROR = true;
  9900. Log.ENABLE_INFO = true;
  9901. Log.ENABLE_WARN = true;
  9902. Log.ENABLE_DEBUG = true;
  9903. Log.ENABLE_VERBOSE = true;
  9904. Log.ENABLE_CALLBACK = false;
  9905. Log.emitter = new _events2.default();
  9906. exports.default = Log;
  9907. },{"events":2}],42:[function(_dereq_,module,exports){
  9908. 'use strict';
  9909. Object.defineProperty(exports, "__esModule", {
  9910. value: true
  9911. });
  9912. 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; }; }(); /*
  9913. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  9914. *
  9915. * @author zheng qian <xqq@xqq.im>
  9916. *
  9917. * Licensed under the Apache License, Version 2.0 (the "License");
  9918. * you may not use this file except in compliance with the License.
  9919. * You may obtain a copy of the License at
  9920. *
  9921. * http://www.apache.org/licenses/LICENSE-2.0
  9922. *
  9923. * Unless required by applicable law or agreed to in writing, software
  9924. * distributed under the License is distributed on an "AS IS" BASIS,
  9925. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9926. * See the License for the specific language governing permissions and
  9927. * limitations under the License.
  9928. */
  9929. var _events = _dereq_('events');
  9930. var _events2 = _interopRequireDefault(_events);
  9931. var _logger = _dereq_('./logger.js');
  9932. var _logger2 = _interopRequireDefault(_logger);
  9933. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9934. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9935. var LoggingControl = function () {
  9936. function LoggingControl() {
  9937. _classCallCheck(this, LoggingControl);
  9938. }
  9939. _createClass(LoggingControl, null, [{
  9940. key: 'getConfig',
  9941. value: function getConfig() {
  9942. return {
  9943. globalTag: _logger2.default.GLOBAL_TAG,
  9944. forceGlobalTag: _logger2.default.FORCE_GLOBAL_TAG,
  9945. enableVerbose: _logger2.default.ENABLE_VERBOSE,
  9946. enableDebug: _logger2.default.ENABLE_DEBUG,
  9947. enableInfo: _logger2.default.ENABLE_INFO,
  9948. enableWarn: _logger2.default.ENABLE_WARN,
  9949. enableError: _logger2.default.ENABLE_ERROR,
  9950. enableCallback: _logger2.default.ENABLE_CALLBACK
  9951. };
  9952. }
  9953. }, {
  9954. key: 'applyConfig',
  9955. value: function applyConfig(config) {
  9956. _logger2.default.GLOBAL_TAG = config.globalTag;
  9957. _logger2.default.FORCE_GLOBAL_TAG = config.forceGlobalTag;
  9958. _logger2.default.ENABLE_VERBOSE = config.enableVerbose;
  9959. _logger2.default.ENABLE_DEBUG = config.enableDebug;
  9960. _logger2.default.ENABLE_INFO = config.enableInfo;
  9961. _logger2.default.ENABLE_WARN = config.enableWarn;
  9962. _logger2.default.ENABLE_ERROR = config.enableError;
  9963. _logger2.default.ENABLE_CALLBACK = config.enableCallback;
  9964. }
  9965. }, {
  9966. key: '_notifyChange',
  9967. value: function _notifyChange() {
  9968. var emitter = LoggingControl.emitter;
  9969. if (emitter.listenerCount('change') > 0) {
  9970. var config = LoggingControl.getConfig();
  9971. emitter.emit('change', config);
  9972. }
  9973. }
  9974. }, {
  9975. key: 'registerListener',
  9976. value: function registerListener(listener) {
  9977. LoggingControl.emitter.addListener('change', listener);
  9978. }
  9979. }, {
  9980. key: 'removeListener',
  9981. value: function removeListener(listener) {
  9982. LoggingControl.emitter.removeListener('change', listener);
  9983. }
  9984. }, {
  9985. key: 'addLogListener',
  9986. value: function addLogListener(listener) {
  9987. _logger2.default.emitter.addListener('log', listener);
  9988. if (_logger2.default.emitter.listenerCount('log') > 0) {
  9989. _logger2.default.ENABLE_CALLBACK = true;
  9990. LoggingControl._notifyChange();
  9991. }
  9992. }
  9993. }, {
  9994. key: 'removeLogListener',
  9995. value: function removeLogListener(listener) {
  9996. _logger2.default.emitter.removeListener('log', listener);
  9997. if (_logger2.default.emitter.listenerCount('log') === 0) {
  9998. _logger2.default.ENABLE_CALLBACK = false;
  9999. LoggingControl._notifyChange();
  10000. }
  10001. }
  10002. }, {
  10003. key: 'forceGlobalTag',
  10004. get: function get() {
  10005. return _logger2.default.FORCE_GLOBAL_TAG;
  10006. },
  10007. set: function set(enable) {
  10008. _logger2.default.FORCE_GLOBAL_TAG = enable;
  10009. LoggingControl._notifyChange();
  10010. }
  10011. }, {
  10012. key: 'globalTag',
  10013. get: function get() {
  10014. return _logger2.default.GLOBAL_TAG;
  10015. },
  10016. set: function set(tag) {
  10017. _logger2.default.GLOBAL_TAG = tag;
  10018. LoggingControl._notifyChange();
  10019. }
  10020. }, {
  10021. key: 'enableAll',
  10022. get: function get() {
  10023. return _logger2.default.ENABLE_VERBOSE && _logger2.default.ENABLE_DEBUG && _logger2.default.ENABLE_INFO && _logger2.default.ENABLE_WARN && _logger2.default.ENABLE_ERROR;
  10024. },
  10025. set: function set(enable) {
  10026. _logger2.default.ENABLE_VERBOSE = enable;
  10027. _logger2.default.ENABLE_DEBUG = enable;
  10028. _logger2.default.ENABLE_INFO = enable;
  10029. _logger2.default.ENABLE_WARN = enable;
  10030. _logger2.default.ENABLE_ERROR = enable;
  10031. LoggingControl._notifyChange();
  10032. }
  10033. }, {
  10034. key: 'enableDebug',
  10035. get: function get() {
  10036. return _logger2.default.ENABLE_DEBUG;
  10037. },
  10038. set: function set(enable) {
  10039. _logger2.default.ENABLE_DEBUG = enable;
  10040. LoggingControl._notifyChange();
  10041. }
  10042. }, {
  10043. key: 'enableVerbose',
  10044. get: function get() {
  10045. return _logger2.default.ENABLE_VERBOSE;
  10046. },
  10047. set: function set(enable) {
  10048. _logger2.default.ENABLE_VERBOSE = enable;
  10049. LoggingControl._notifyChange();
  10050. }
  10051. }, {
  10052. key: 'enableInfo',
  10053. get: function get() {
  10054. return _logger2.default.ENABLE_INFO;
  10055. },
  10056. set: function set(enable) {
  10057. _logger2.default.ENABLE_INFO = enable;
  10058. LoggingControl._notifyChange();
  10059. }
  10060. }, {
  10061. key: 'enableWarn',
  10062. get: function get() {
  10063. return _logger2.default.ENABLE_WARN;
  10064. },
  10065. set: function set(enable) {
  10066. _logger2.default.ENABLE_WARN = enable;
  10067. LoggingControl._notifyChange();
  10068. }
  10069. }, {
  10070. key: 'enableError',
  10071. get: function get() {
  10072. return _logger2.default.ENABLE_ERROR;
  10073. },
  10074. set: function set(enable) {
  10075. _logger2.default.ENABLE_ERROR = enable;
  10076. LoggingControl._notifyChange();
  10077. }
  10078. }]);
  10079. return LoggingControl;
  10080. }();
  10081. LoggingControl.emitter = new _events2.default();
  10082. exports.default = LoggingControl;
  10083. },{"./logger.js":41,"events":2}],43:[function(_dereq_,module,exports){
  10084. 'use strict';
  10085. Object.defineProperty(exports, "__esModule", {
  10086. value: true
  10087. });
  10088. 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; }; }();
  10089. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10090. /*
  10091. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  10092. *
  10093. * @author zheng qian <xqq@xqq.im>
  10094. *
  10095. * Licensed under the Apache License, Version 2.0 (the "License");
  10096. * you may not use this file except in compliance with the License.
  10097. * You may obtain a copy of the License at
  10098. *
  10099. * http://www.apache.org/licenses/LICENSE-2.0
  10100. *
  10101. * Unless required by applicable law or agreed to in writing, software
  10102. * distributed under the License is distributed on an "AS IS" BASIS,
  10103. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10104. * See the License for the specific language governing permissions and
  10105. * limitations under the License.
  10106. */
  10107. var Polyfill = function () {
  10108. function Polyfill() {
  10109. _classCallCheck(this, Polyfill);
  10110. }
  10111. _createClass(Polyfill, null, [{
  10112. key: 'install',
  10113. value: function install() {
  10114. // ES6 Object.setPrototypeOf
  10115. Object.setPrototypeOf = Object.setPrototypeOf || function (obj, proto) {
  10116. obj.__proto__ = proto;
  10117. return obj;
  10118. };
  10119. // ES6 Object.assign
  10120. Object.assign = Object.assign || function (target) {
  10121. if (target === undefined || target === null) {
  10122. throw new TypeError('Cannot convert undefined or null to object');
  10123. }
  10124. var output = Object(target);
  10125. for (var i = 1; i < arguments.length; i++) {
  10126. var source = arguments[i];
  10127. if (source !== undefined && source !== null) {
  10128. for (var key in source) {
  10129. if (source.hasOwnProperty(key)) {
  10130. output[key] = source[key];
  10131. }
  10132. }
  10133. }
  10134. }
  10135. return output;
  10136. };
  10137. // ES6 Promise (missing support in IE11)
  10138. if (typeof self.Promise !== 'function') {
  10139. _dereq_('es6-promise').polyfill();
  10140. }
  10141. }
  10142. }]);
  10143. return Polyfill;
  10144. }();
  10145. Polyfill.install();
  10146. exports.default = Polyfill;
  10147. },{"es6-promise":1}],44:[function(_dereq_,module,exports){
  10148. 'use strict';
  10149. Object.defineProperty(exports, "__esModule", {
  10150. value: true
  10151. });
  10152. /*
  10153. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  10154. *
  10155. * This file is derived from C++ project libWinTF8 (https://github.com/m13253/libWinTF8)
  10156. * @author zheng qian <xqq@xqq.im>
  10157. *
  10158. * Licensed under the Apache License, Version 2.0 (the "License");
  10159. * you may not use this file except in compliance with the License.
  10160. * You may obtain a copy of the License at
  10161. *
  10162. * http://www.apache.org/licenses/LICENSE-2.0
  10163. *
  10164. * Unless required by applicable law or agreed to in writing, software
  10165. * distributed under the License is distributed on an "AS IS" BASIS,
  10166. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10167. * See the License for the specific language governing permissions and
  10168. * limitations under the License.
  10169. */
  10170. function checkContinuation(uint8array, start, checkLength) {
  10171. var array = uint8array;
  10172. if (start + checkLength < array.length) {
  10173. while (checkLength--) {
  10174. if ((array[++start] & 0xC0) !== 0x80) return false;
  10175. }
  10176. return true;
  10177. } else {
  10178. return false;
  10179. }
  10180. }
  10181. function decodeUTF8(uint8array) {
  10182. var out = [];
  10183. var input = uint8array;
  10184. var i = 0;
  10185. var length = uint8array.length;
  10186. while (i < length) {
  10187. if (input[i] < 0x80) {
  10188. out.push(String.fromCharCode(input[i]));
  10189. ++i;
  10190. continue;
  10191. } else if (input[i] < 0xC0) {
  10192. // fallthrough
  10193. } else if (input[i] < 0xE0) {
  10194. if (checkContinuation(input, i, 1)) {
  10195. var ucs4 = (input[i] & 0x1F) << 6 | input[i + 1] & 0x3F;
  10196. if (ucs4 >= 0x80) {
  10197. out.push(String.fromCharCode(ucs4 & 0xFFFF));
  10198. i += 2;
  10199. continue;
  10200. }
  10201. }
  10202. } else if (input[i] < 0xF0) {
  10203. if (checkContinuation(input, i, 2)) {
  10204. var _ucs = (input[i] & 0xF) << 12 | (input[i + 1] & 0x3F) << 6 | input[i + 2] & 0x3F;
  10205. if (_ucs >= 0x800 && (_ucs & 0xF800) !== 0xD800) {
  10206. out.push(String.fromCharCode(_ucs & 0xFFFF));
  10207. i += 3;
  10208. continue;
  10209. }
  10210. }
  10211. } else if (input[i] < 0xF8) {
  10212. if (checkContinuation(input, i, 3)) {
  10213. var _ucs2 = (input[i] & 0x7) << 18 | (input[i + 1] & 0x3F) << 12 | (input[i + 2] & 0x3F) << 6 | input[i + 3] & 0x3F;
  10214. if (_ucs2 > 0x10000 && _ucs2 < 0x110000) {
  10215. _ucs2 -= 0x10000;
  10216. out.push(String.fromCharCode(_ucs2 >>> 10 | 0xD800));
  10217. out.push(String.fromCharCode(_ucs2 & 0x3FF | 0xDC00));
  10218. i += 4;
  10219. continue;
  10220. }
  10221. }
  10222. }
  10223. out.push(String.fromCharCode(0xFFFD));
  10224. ++i;
  10225. }
  10226. return out.join('');
  10227. }
  10228. exports.default = decodeUTF8;
  10229. },{}]},{},[21])(21)
  10230. });
  10231. //# sourceMappingURL=flv.js.map