zx-player.common.js 1.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249
  1. module.exports =
  2. /******/ (function(modules) { // webpackBootstrap
  3. /******/ // The module cache
  4. /******/ var installedModules = {};
  5. /******/
  6. /******/ // The require function
  7. /******/ function __webpack_require__(moduleId) {
  8. /******/
  9. /******/ // Check if module is in cache
  10. /******/ if(installedModules[moduleId]) {
  11. /******/ return installedModules[moduleId].exports;
  12. /******/ }
  13. /******/ // Create a new module (and put it into the cache)
  14. /******/ var module = installedModules[moduleId] = {
  15. /******/ i: moduleId,
  16. /******/ l: false,
  17. /******/ exports: {}
  18. /******/ };
  19. /******/
  20. /******/ // Execute the module function
  21. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  22. /******/
  23. /******/ // Flag the module as loaded
  24. /******/ module.l = true;
  25. /******/
  26. /******/ // Return the exports of the module
  27. /******/ return module.exports;
  28. /******/ }
  29. /******/
  30. /******/
  31. /******/ // expose the modules object (__webpack_modules__)
  32. /******/ __webpack_require__.m = modules;
  33. /******/
  34. /******/ // expose the module cache
  35. /******/ __webpack_require__.c = installedModules;
  36. /******/
  37. /******/ // define getter function for harmony exports
  38. /******/ __webpack_require__.d = function(exports, name, getter) {
  39. /******/ if(!__webpack_require__.o(exports, name)) {
  40. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  41. /******/ }
  42. /******/ };
  43. /******/
  44. /******/ // define __esModule on exports
  45. /******/ __webpack_require__.r = function(exports) {
  46. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  47. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  48. /******/ }
  49. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  50. /******/ };
  51. /******/
  52. /******/ // create a fake namespace object
  53. /******/ // mode & 1: value is a module id, require it
  54. /******/ // mode & 2: merge all properties of value into the ns
  55. /******/ // mode & 4: return value when already ns object
  56. /******/ // mode & 8|1: behave like require
  57. /******/ __webpack_require__.t = function(value, mode) {
  58. /******/ if(mode & 1) value = __webpack_require__(value);
  59. /******/ if(mode & 8) return value;
  60. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  61. /******/ var ns = Object.create(null);
  62. /******/ __webpack_require__.r(ns);
  63. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  64. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  65. /******/ return ns;
  66. /******/ };
  67. /******/
  68. /******/ // getDefaultExport function for compatibility with non-harmony modules
  69. /******/ __webpack_require__.n = function(module) {
  70. /******/ var getter = module && module.__esModule ?
  71. /******/ function getDefault() { return module['default']; } :
  72. /******/ function getModuleExports() { return module; };
  73. /******/ __webpack_require__.d(getter, 'a', getter);
  74. /******/ return getter;
  75. /******/ };
  76. /******/
  77. /******/ // Object.prototype.hasOwnProperty.call
  78. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  79. /******/
  80. /******/ // __webpack_public_path__
  81. /******/ __webpack_require__.p = "";
  82. /******/
  83. /******/
  84. /******/ // Load entry module and return exports
  85. /******/ return __webpack_require__(__webpack_require__.s = "fae3");
  86. /******/ })
  87. /************************************************************************/
  88. /******/ ({
  89. /***/ "06cf":
  90. /***/ (function(module, exports, __webpack_require__) {
  91. var DESCRIPTORS = __webpack_require__("83ab");
  92. var propertyIsEnumerableModule = __webpack_require__("d1e7");
  93. var createPropertyDescriptor = __webpack_require__("5c6c");
  94. var toIndexedObject = __webpack_require__("fc6a");
  95. var toPrimitive = __webpack_require__("c04e");
  96. var has = __webpack_require__("5135");
  97. var IE8_DOM_DEFINE = __webpack_require__("0cfb");
  98. var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  99. // `Object.getOwnPropertyDescriptor` method
  100. // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
  101. exports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
  102. O = toIndexedObject(O);
  103. P = toPrimitive(P, true);
  104. if (IE8_DOM_DEFINE) try {
  105. return nativeGetOwnPropertyDescriptor(O, P);
  106. } catch (error) { /* empty */ }
  107. if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]);
  108. };
  109. /***/ }),
  110. /***/ "0cfb":
  111. /***/ (function(module, exports, __webpack_require__) {
  112. var DESCRIPTORS = __webpack_require__("83ab");
  113. var fails = __webpack_require__("d039");
  114. var createElement = __webpack_require__("cc12");
  115. // Thank's IE8 for his funny defineProperty
  116. module.exports = !DESCRIPTORS && !fails(function () {
  117. return Object.defineProperty(createElement('div'), 'a', {
  118. get: function () { return 7; }
  119. }).a != 7;
  120. });
  121. /***/ }),
  122. /***/ "1d80":
  123. /***/ (function(module, exports) {
  124. // `RequireObjectCoercible` abstract operation
  125. // https://tc39.github.io/ecma262/#sec-requireobjectcoercible
  126. module.exports = function (it) {
  127. if (it == undefined) throw TypeError("Can't call method on " + it);
  128. return it;
  129. };
  130. /***/ }),
  131. /***/ "23cb":
  132. /***/ (function(module, exports, __webpack_require__) {
  133. var toInteger = __webpack_require__("a691");
  134. var max = Math.max;
  135. var min = Math.min;
  136. // Helper for a popular repeating case of the spec:
  137. // Let integer be ? ToInteger(index).
  138. // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
  139. module.exports = function (index, length) {
  140. var integer = toInteger(index);
  141. return integer < 0 ? max(integer + length, 0) : min(integer, length);
  142. };
  143. /***/ }),
  144. /***/ "23e7":
  145. /***/ (function(module, exports, __webpack_require__) {
  146. var global = __webpack_require__("da84");
  147. var getOwnPropertyDescriptor = __webpack_require__("06cf").f;
  148. var createNonEnumerableProperty = __webpack_require__("9112");
  149. var redefine = __webpack_require__("6eeb");
  150. var setGlobal = __webpack_require__("ce4e");
  151. var copyConstructorProperties = __webpack_require__("e893");
  152. var isForced = __webpack_require__("94ca");
  153. /*
  154. options.target - name of the target object
  155. options.global - target is the global object
  156. options.stat - export as static methods of target
  157. options.proto - export as prototype methods of target
  158. options.real - real prototype method for the `pure` version
  159. options.forced - export even if the native feature is available
  160. options.bind - bind methods to the target, required for the `pure` version
  161. options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
  162. options.unsafe - use the simple assignment of property instead of delete + defineProperty
  163. options.sham - add a flag to not completely full polyfills
  164. options.enumerable - export as enumerable property
  165. options.noTargetGet - prevent calling a getter on target
  166. */
  167. module.exports = function (options, source) {
  168. var TARGET = options.target;
  169. var GLOBAL = options.global;
  170. var STATIC = options.stat;
  171. var FORCED, target, key, targetProperty, sourceProperty, descriptor;
  172. if (GLOBAL) {
  173. target = global;
  174. } else if (STATIC) {
  175. target = global[TARGET] || setGlobal(TARGET, {});
  176. } else {
  177. target = (global[TARGET] || {}).prototype;
  178. }
  179. if (target) for (key in source) {
  180. sourceProperty = source[key];
  181. if (options.noTargetGet) {
  182. descriptor = getOwnPropertyDescriptor(target, key);
  183. targetProperty = descriptor && descriptor.value;
  184. } else targetProperty = target[key];
  185. FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
  186. // contained in target
  187. if (!FORCED && targetProperty !== undefined) {
  188. if (typeof sourceProperty === typeof targetProperty) continue;
  189. copyConstructorProperties(sourceProperty, targetProperty);
  190. }
  191. // add a flag to not completely full polyfills
  192. if (options.sham || (targetProperty && targetProperty.sham)) {
  193. createNonEnumerableProperty(sourceProperty, 'sham', true);
  194. }
  195. // extend global
  196. redefine(target, key, sourceProperty, options);
  197. }
  198. };
  199. /***/ }),
  200. /***/ "241c":
  201. /***/ (function(module, exports, __webpack_require__) {
  202. var internalObjectKeys = __webpack_require__("ca84");
  203. var enumBugKeys = __webpack_require__("7839");
  204. var hiddenKeys = enumBugKeys.concat('length', 'prototype');
  205. // `Object.getOwnPropertyNames` method
  206. // https://tc39.github.io/ecma262/#sec-object.getownpropertynames
  207. exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
  208. return internalObjectKeys(O, hiddenKeys);
  209. };
  210. /***/ }),
  211. /***/ "428f":
  212. /***/ (function(module, exports, __webpack_require__) {
  213. var global = __webpack_require__("da84");
  214. module.exports = global;
  215. /***/ }),
  216. /***/ "44ad":
  217. /***/ (function(module, exports, __webpack_require__) {
  218. var fails = __webpack_require__("d039");
  219. var classof = __webpack_require__("c6b6");
  220. var split = ''.split;
  221. // fallback for non-array-like ES3 and non-enumerable old V8 strings
  222. module.exports = fails(function () {
  223. // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
  224. // eslint-disable-next-line no-prototype-builtins
  225. return !Object('z').propertyIsEnumerable(0);
  226. }) ? function (it) {
  227. return classof(it) == 'String' ? split.call(it, '') : Object(it);
  228. } : Object;
  229. /***/ }),
  230. /***/ "4d64":
  231. /***/ (function(module, exports, __webpack_require__) {
  232. var toIndexedObject = __webpack_require__("fc6a");
  233. var toLength = __webpack_require__("50c4");
  234. var toAbsoluteIndex = __webpack_require__("23cb");
  235. // `Array.prototype.{ indexOf, includes }` methods implementation
  236. var createMethod = function (IS_INCLUDES) {
  237. return function ($this, el, fromIndex) {
  238. var O = toIndexedObject($this);
  239. var length = toLength(O.length);
  240. var index = toAbsoluteIndex(fromIndex, length);
  241. var value;
  242. // Array#includes uses SameValueZero equality algorithm
  243. // eslint-disable-next-line no-self-compare
  244. if (IS_INCLUDES && el != el) while (length > index) {
  245. value = O[index++];
  246. // eslint-disable-next-line no-self-compare
  247. if (value != value) return true;
  248. // Array#indexOf ignores holes, Array#includes - not
  249. } else for (;length > index; index++) {
  250. if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
  251. } return !IS_INCLUDES && -1;
  252. };
  253. };
  254. module.exports = {
  255. // `Array.prototype.includes` method
  256. // https://tc39.github.io/ecma262/#sec-array.prototype.includes
  257. includes: createMethod(true),
  258. // `Array.prototype.indexOf` method
  259. // https://tc39.github.io/ecma262/#sec-array.prototype.indexof
  260. indexOf: createMethod(false)
  261. };
  262. /***/ }),
  263. /***/ "50c4":
  264. /***/ (function(module, exports, __webpack_require__) {
  265. var toInteger = __webpack_require__("a691");
  266. var min = Math.min;
  267. // `ToLength` abstract operation
  268. // https://tc39.github.io/ecma262/#sec-tolength
  269. module.exports = function (argument) {
  270. return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
  271. };
  272. /***/ }),
  273. /***/ "5135":
  274. /***/ (function(module, exports) {
  275. var hasOwnProperty = {}.hasOwnProperty;
  276. module.exports = function (it, key) {
  277. return hasOwnProperty.call(it, key);
  278. };
  279. /***/ }),
  280. /***/ "5392":
  281. /***/ (function(module, exports, __webpack_require__) {
  282. !function(e,t){ true?module.exports=t():undefined}(window,(function(){return function(e){var t={};function n(a){if(t[a])return t[a].exports;var r=t[a]={i:a,l:!1,exports:{}};return e[a].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=e,n.c=t,n.d=function(e,t,a){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:a})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(n.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(a,r,function(t){return e[t]}.bind(null,r));return a},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=6)}([function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}return function(t,n,a){return n&&e(t.prototype,n),a&&e(t,a),t}}(),r=function e(t,n,a){null===t&&(t=Function.prototype);var r=Object.getOwnPropertyDescriptor(t,n);if(void 0===r){var i=Object.getPrototypeOf(t);return null===i?void 0:e(i,n,a)}if("value"in r)return r.value;var o=r.get;return void 0!==o?o.call(a):void 0},i=g(n(8)),o=g(n(3)),l=g(n(28)),s=g(n(29)),u=g(n(4)),c=g(n(30)),p=n(35),d=g(n(36)),f=n(5);function g(e){return e&&e.__esModule?e:{default:e}}function y(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}var h=function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var n=y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));if(n.config=o.default.deepCopy({width:600,height:337.5,ignores:[],whitelist:[],lang:(document.documentElement.getAttribute("lang")||navigator.language||"zh-cn").toLocaleLowerCase(),inactive:3e3,volume:.6,controls:!0,controlsList:["nodownload"]},e),n.version=f.version,n.userTimer=null,n.waitTimer=null,n.database=new l.default,n.history=[],n.isProgressMoving=!1,n.root=o.default.findDom(document,"#"+n.config.id),n.controls=o.default.createDom("xg-controls","",{unselectable:"on",onselectstart:"return false"},"xgplayer-controls"),n.config.isShowControl&&(n.controls.style.display="none"),!n.root){var a=n.config.el;if(!a||1!==a.nodeType)return n.emit("error",new u.default({type:"use",errd:{line:45,handle:"Constructor",msg:"container id can't be empty"},vid:n.config.vid})),console.error("container id can't be empty"),!1,y(n,!1);n.root=a}if(o.default.addClass(n.root,"xgplayer xgplayer-"+s.default.device+" xgplayer-nostart "+(n.config.controls?"":"no-controls")),n.root.appendChild(n.controls),n.config.fluid?(n.root.style["max-width"]="100%",n.root.style.width="100%",n.root.style.height="0",n.root.style["padding-top"]=100*n.config.height/n.config.width+"%",n.video.style.position="absolute",n.video.style.top="0",n.video.style.left="0"):(n.config.width&&("number"!=typeof n.config.width?n.root.style.width=n.config.width:n.root.style.width=n.config.width+"px"),n.config.height&&("number"!=typeof n.config.height?n.root.style.height=n.config.height:n.root.style.height=n.config.height+"px")),n.config.execBeforePluginsCall&&n.config.execBeforePluginsCall.forEach((function(e){e.call(n,n)})),n.config.controlStyle&&"String"===o.default.typeOf(n.config.controlStyle)){var r=n;fetch(r.config.controlStyle,{method:"GET",headers:{Accept:"application/json"}}).then((function(e){e.ok&&e.json().then((function(e){for(var t in e)e.hasOwnProperty(t)&&(r.config[t]=e[t]);r.pluginsCall()}))})).catch((function(e){console.log("Fetch错误:"+e)}))}else n.pluginsCall();n.ev.forEach((function(e){var t=Object.keys(e)[0],a=n[e[t]];a&&n.on(t,a)})),["focus","blur"].forEach((function(e){n.on(e,n["on"+e.charAt(0).toUpperCase()+e.slice(1)])}));var i=n;return n.mousemoveFunc=function(){i.emit("focus"),i.config.closeFocusVideoFocus||i.video.focus()},n.root.addEventListener("mousemove",n.mousemoveFunc),n.playFunc=function(){i.emit("focus"),i.config.closePlayVideoFocus||i.video.focus()},i.once("play",n.playFunc),n.getVideoSize=function(){if(this.video.videoWidth&&this.video.videoHeight){var e=i.root.getBoundingClientRect();"auto"===i.config.fitVideoSize?e.width/e.height>this.video.videoWidth/this.video.videoHeight?i.root.style.height=this.video.videoHeight/this.video.videoWidth*e.width+"px":i.root.style.width=this.video.videoWidth/this.video.videoHeight*e.height+"px":"fixWidth"===i.config.fitVideoSize?i.root.style.height=this.video.videoHeight/this.video.videoWidth*e.width+"px":"fixHeight"===i.config.fitVideoSize&&(i.root.style.width=this.video.videoWidth/this.video.videoHeight*e.height+"px")}},i.once("loadeddata",n.getVideoSize),setTimeout((function(){n.emit("ready"),n.isReady=!0}),0),n.config.keyShortcut&&"on"!==n.config.keyShortcut||["video","controls"].forEach((function(e){i[e].addEventListener("keydown",(function(e){i.onKeydown(e,i)}))})),n.config.videoInit&&o.default.hasClass(n.root,"xgplayer-nostart")&&n.start(),i.config.rotate&&(i.on("requestFullscreen",n.updateRotateDeg),i.on("exitFullscreen",n.updateRotateDeg)),i.once("destroy",(function e(){i.root.removeEventListener("mousemove",i.mousemoveFunc),i.off("destroy",e)})),n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),a(t,[{key:"start",value:function(){var e=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.config.url,a=this.root,r=this;n&&""!==n||this.emit("urlNull"),this.logParams.playSrc=n,this.canPlayFunc=function(){r.off("canplay",r.canPlayFunc);var e=r.video.play();void 0!==e&&e&&e.then((function(){r.emit("autoplay started")})).catch((function(){r.emit("autoplay was prevented"),t.util.addClass(r.root,"xgplayer-is-autoplay")}))},"String"===o.default.typeOf(n)?n.indexOf("blob:")>-1&&n===this.video.src||(this.video.src=n):n.forEach((function(t){e.video.appendChild(o.default.createDom("source","",{src:""+t.src,type:""+(t.type||"")}))})),this.logParams.pt=(new Date).getTime(),this.logParams.vt=this.logParams.pt,this.loadeddataFunc=function(){r.logParams.vt=(new Date).getTime(),r.logParams.pt>r.logParams.vt&&(r.logParams.pt=r.logParams.vt),r.logParams.vd=r.video.duration},this.once("loadeddata",this.loadeddataFunc),this.config.autoplay&&(s.default.os.isPhone?this.canPlayFunc():this.on("canplay",this.canPlayFunc)),this.config.disableStartLoad||this.video.load(),a.insertBefore(this.video,a.firstChild),setTimeout((function(){e.emit("complete"),e.danmu&&"function"==typeof e.danmu.resize&&e.danmu.resize()}),1)}},{key:"reload",value:function(){this.video.load(),this.reloadFunc=function(){var e=this.play();void 0!==e&&e&&e.catch((function(e){}))},this.once("loadeddata",this.reloadFunc)}},{key:"destroy",value:function(){var e=this,n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],a=this;for(var i in clearInterval(this.bulletResizeTimer),this._interval)clearInterval(this._interval[i]),this._interval[i]=null;function o(){if(this.emit("destroy"),this.video.removeAttribute("src"),this.video.load(),n){this.root.innerHTML="";var e=this.root.className.split(" ");e.length>0?this.root.className=e.filter((function(e){return e.indexOf("xgplayer")<0})).join(" "):this.root.className=""}for(var t in this)delete this[t];this.off("pause",o)}this.checkTimer&&clearInterval(this.checkTimer),this.waitTimer&&clearTimeout(this.waitTimer),this.ev.forEach((function(t){var n=Object.keys(t)[0],a=e[t[n]];a&&e.off(n,a)})),this.loadeddataFunc&&this.off("loadeddata",this.loadeddataFunc),this.reloadFunc&&this.off("loadeddata",this.reloadFunc),this.replayFunc&&this.off("play",this.replayFunc),this.playFunc&&this.off("play",this.playFunc),this.getVideoSize&&this.off("loadeddata",this.getVideoSize),["focus","blur"].forEach((function(t){e.off(t,e["on"+t.charAt(0).toUpperCase()+t.slice(1)])})),this.config.keyShortcut&&"on"!==this.config.keyShortcut||["video","controls"].forEach((function(t){e[t]&&e[t].removeEventListener("keydown",(function(e){a.onKeydown(e,a)}))})),this.paused?o.call(this):(this.pause(),this.once("pause",o)),r(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"destroy",this).call(this)}},{key:"replay",value:function(){var e=this,t=this._replay;if(o.default.removeClass(this.root,"xgplayer-ended"),this.logParams={bc:0,bu_acu_t:0,played:[],pt:(new Date).getTime(),vt:(new Date).getTime(),vd:0},this.logParams.pt=(new Date).getTime(),this.logParams.vt=this.logParams.pt,this.replayFunc=function(){e.logParams.vt=(new Date).getTime(),e.logParams.pt>e.logParams.vt&&(e.logParams.pt=e.logParams.vt),e.logParams.vd=e.video.duration},this.once("play",this.replayFunc),this.logParams.playSrc=this.video.currentSrc,t&&t instanceof Function)t();else{this.currentTime=0;var n=this.play();void 0!==n&&n&&n.catch((function(e){}))}}},{key:"getFullscreen",value:function(e){e.requestFullscreen?e.requestFullscreen():e.mozRequestFullScreen?e.mozRequestFullScreen():e.webkitRequestFullscreen?e.webkitRequestFullscreen(window.Element.ALLOW_KEYBOARD_INPUT):this.video.webkitSupportsFullscreen?this.video.webkitEnterFullscreen():e.msRequestFullscreen?e.msRequestFullscreen():o.default.addClass(e,"xgplayer-is-cssfullscreen")}},{key:"exitFullscreen",value:function(e){document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen?document.webkitExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.msExitFullscreen&&document.msExitFullscreen(),o.default.removeClass(e,"xgplayer-is-cssfullscreen")}},{key:"getCssFullscreen",value:function(){this.config.fluid&&(this.root.style["padding-top"]=""),o.default.addClass(this.root,"xgplayer-is-cssfullscreen"),this.emit("requestCssFullscreen")}},{key:"exitCssFullscreen",value:function(){this.config.fluid&&(this.root.style.width="100%",this.root.style.height="0",this.root.style["padding-top"]=100*this.config.height/this.config.width+"%"),o.default.removeClass(this.root,"xgplayer-is-cssfullscreen"),this.emit("exitCssFullscreen")}},{key:"getRotateFullscreen",value:function(){document.documentElement.style.width="100%",document.documentElement.style.height="100%",this.root&&!t.util.hasClass(this.root,"xgplayer-rotate-fullscreen")&&t.util.addClass(this.root,"xgplayer-rotate-fullscreen"),this.emit("getRotateFullscreen")}},{key:"exitRotateFullscreen",value:function(){document.documentElement.style.width="unset",document.documentElement.style.height="unset",this.root&&t.util.hasClass(this.root,"xgplayer-rotate-fullscreen")&&t.util.removeClass(this.root,"xgplayer-rotate-fullscreen"),this.emit("exitRotateFullscreen")}},{key:"download",value:function(){var e=(0,p.getAbsoluteURL)(this.config.url);(0,d.default)(e)}},{key:"pluginsCall",value:function(){var e=this,n=this;if(t.plugins){var a=this.config.ignores;Object.keys(t.plugins).forEach((function(r){var i=t.plugins[r];a.some((function(e){return r===e||r==="s_"+e}))||(["pc","tablet","mobile"].some((function(e){return e===r}))?r===s.default.device&&setTimeout((function(){i.call(n,n)}),0):i.call(e,e))}))}}},{key:"getPIP",value:function(){var e=o.default.createDom("xg-pip-lay","<div></div>",{},"xgplayer-pip-lay");this.root.appendChild(e);var t=o.default.createDom("xg-pip-drag",'<div class="drag-handle"><span>'+this.lang.PIP_DRAG+"</span></div>",{tabindex:9},"xgplayer-pip-drag");this.root.appendChild(t);new c.default(".xgplayer",{handle:".drag-handle"});o.default.addClass(this.root,"xgplayer-pip-active"),this.root.style.right=0,this.root.style.bottom="200px",this.root.style.top="",this.root.style.left="",this.root.style.width="320px",this.root.style.height="180px",this.config.pipConfig&&(void 0!==this.config.pipConfig.top&&(this.root.style.top=this.config.pipConfig.top+"px",this.root.style.bottom=""),void 0!==this.config.pipConfig.bottom&&(this.root.style.bottom=this.config.pipConfig.bottom+"px"),void 0!==this.config.pipConfig.left&&(this.root.style.left=this.config.pipConfig.left+"px",this.root.style.right=""),void 0!==this.config.pipConfig.right&&(this.root.style.right=this.config.pipConfig.right+"px"),void 0!==this.config.pipConfig.width&&(this.root.style.width=this.config.pipConfig.width+"px"),void 0!==this.config.pipConfig.height&&(this.root.style.height=this.config.pipConfig.height+"px")),this.config.fluid&&(this.root.style["padding-top"]="");var n=this;["click","touchend"].forEach((function(t){e.addEventListener(t,(function(e){e.preventDefault(),e.stopPropagation(),n.exitPIP()}))}))}},{key:"exitPIP",value:function(){o.default.removeClass(this.root,"xgplayer-pip-active"),this.root.style.right="",this.root.style.bottom="",this.root.style.top="",this.root.style.left="",this.config.fluid?(this.root.style.width="100%",this.root.style.height="0",this.root.style["padding-top"]=100*this.config.height/this.config.width+"%"):(this.config.width&&("number"!=typeof this.config.width?this.root.style.width=this.config.width:this.root.style.width=this.config.width+"px"),this.config.height&&("number"!=typeof this.config.height?this.root.style.height=this.config.height:this.root.style.height=this.config.height+"px"));var e=o.default.findDom(this.root,".xgplayer-pip-lay");e&&e.parentNode&&e.parentNode.removeChild(e);var t=o.default.findDom(this.root,".xgplayer-pip-drag");t&&t.parentNode&&t.parentNode.removeChild(t)}},{key:"updateRotateDeg",value:function(){this.rotateDeg||(this.rotateDeg=0);var e=this.root.offsetWidth,t=this.root.offsetHeight,n=this.video.videoWidth,a=this.video.videoHeight;!this.config.rotate.innerRotate&&this.config.rotate.controlsFix&&(this.root.style.width=t+"px",this.root.style.height=e+"px");var r=void 0;if(.25===this.rotateDeg||.75===this.rotateDeg){if(this.config.rotate.innerRotate)if(n/a>t/e){r=t/(a/n>t/e?t*n/a:e)}else{r=e/(a/n>t/e?t:e*a/n)}else r=e>=t?e/t:t/e;r=Number(r.toFixed(5))}else r=1;this.config.rotate.innerRotate||this.config.rotate.controlsFix?(this.video.style.transformOrigin="center center",this.video.style.transform="rotate("+this.rotateDeg+"turn) scale("+r+")",this.video.style.webKitTransform="rotate("+this.rotateDeg+"turn) scale("+r+")"):(this.root.style.transformOrigin="center center",this.root.style.transform="rotate("+this.rotateDeg+"turn) scale(1)",this.root.style.webKitTransform="rotate("+this.rotateDeg+"turn) scale(1)")}},{key:"rotate",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=this;n.rotateDeg||(n.rotateDeg=0);var a=e?1:-1;n.rotateDeg=(n.rotateDeg+1+.25*a*t)%1,this.updateRotateDeg(),n.emit("rotate",360*n.rotateDeg)}},{key:"onFocus",value:function(){var e=this;o.default.removeClass(this.root,"xgplayer-inactive"),e.userTimer&&clearTimeout(e.userTimer),e.userTimer=setTimeout((function(){e.emit("blur")}),e.config.inactive)}},{key:"onBlur",value:function(){!this.config.enablePausedInactive&&this.paused||this.ended||this.config.closeInactive||o.default.addClass(this.root,"xgplayer-inactive")}},{key:"onPlay",value:function(){o.default.addClass(this.root,"xgplayer-isloading"),o.default.addClass(this.root,"xgplayer-playing"),o.default.removeClass(this.root,"xgplayer-pause")}},{key:"onPause",value:function(){o.default.addClass(this.root,"xgplayer-pause"),this.userTimer&&clearTimeout(this.userTimer),this.emit("focus")}},{key:"onEnded",value:function(){o.default.addClass(this.root,"xgplayer-ended"),o.default.removeClass(this.root,"xgplayer-playing")}},{key:"onSeeking",value:function(){this.isSeeking=!0,this.onWaiting()}},{key:"onTimeupdate",value:function(){this.waitTimer&&clearTimeout(this.waitTimer),o.default.removeClass(this.root,"xgplayer-isloading")}},{key:"onSeeked",value:function(){this.isSeeking=!1,this.waitTimer&&clearTimeout(this.waitTimer),o.default.removeClass(this.root,"xgplayer-isloading")}},{key:"onWaiting",value:function(){var e=this;e.waitTimer&&clearTimeout(e.waitTimer),e.checkTimer&&(clearInterval(e.checkTimer),e.checkTimer=null);var t=e.currentTime;e.waitTimer=setTimeout((function(){o.default.addClass(e.root,"xgplayer-isloading"),e.checkTimer=setInterval((function(){e.currentTime!==t&&(o.default.removeClass(this.root,"xgplayer-isloading"),clearInterval(e.checkTimer),e.checkTimer=null)}),1e3)}),500)}},{key:"onPlaying",value:function(){this.paused||(this.isSeeking=!1,this.waitTimer&&clearTimeout(this.waitTimer),o.default.removeClass(this.root,"xgplayer-isloading xgplayer-nostart xgplayer-pause xgplayer-ended xgplayer-is-error xgplayer-replay"),o.default.addClass(this.root,"xgplayer-playing"))}},{key:"onKeydown",value:function(e,t){var n=e||window.event;if(!n||37!==n.keyCode&&38!==n.keyCode&&39!==n.keyCode&&40!==n.keyCode&&32!==n.keyCode||t.emit("focus"),!n||40!==n.keyCode&&38!==n.keyCode){if(n&&39===n.keyCode)t.currentTime+10<=t.duration?t.currentTime+=10:t.currentTime=t.duration-1;else if(n&&37===n.keyCode)t.currentTime-10>=0?t.currentTime-=10:t.currentTime=0;else if(n&&32===n.keyCode)if(t.paused){var a=t.play();void 0!==a&&a&&a.catch((function(e){}))}else t.pause()}else{if(t.controls){var r=t.controls.querySelector(".xgplayer-slider");r&&(o.default.hasClass(r,"xgplayer-none")&&o.default.removeClass(r,"xgplayer-none"),t.sliderTimer&&clearTimeout(t.sliderTimer),t.sliderTimer=setTimeout((function(){o.default.addClass(r,"xgplayer-none")}),t.config.inactive))}n&&40===n.keyCode?t.volume-.1>=0?t.volume=Number((t.volume-.1).toFixed(1)):t.volume=0:n&&38===n.keyCode&&(t.volume+.1<=1?t.volume=Number((t.volume+.1).toFixed(1)):t.volume=1)}}},{key:"cumulateTime",get:function(){if(this.logParams&&this.logParams.played instanceof Array){var e=o.default.computeWatchDur(this.logParams.played)||0;return Number(e.toFixed(3))}return 0}}],[{key:"install",value:function(e,n){t.plugins||(t.plugins={}),t.plugins[e]||(t.plugins[e]=n)}},{key:"use",value:function(e,n){t.plugins||(t.plugins={}),t.plugins[e]=n}}]),t}(i.default);h.util=o.default,h.sniffer=s.default,h.Errors=u.default,t.default=h,e.exports=t.default},function(e,t,n){"use strict";var a=n(21)();e.exports=function(e){return e!==a&&null!==e}},function(e,t,n){"use strict";e.exports=function(e){return null!=e}},function(module,exports,__webpack_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var util={createDom:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"div",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",r=document.createElement(e);return r.className=a,r.innerHTML=t,Object.keys(n).forEach((function(t){var a=t,i=n[t];"video"===e||"audio"===e?i&&r.setAttribute(a,i):r.setAttribute(a,i)})),r},hasClass:function(e,t){return!!e&&(e.classList?Array.prototype.some.call(e.classList,(function(e){return e===t})):!!e.className.match(new RegExp("(\\s|^)"+t+"(\\s|$)")))},addClass:function(e,t){e&&(e.classList?t.replace(/(^\s+|\s+$)/g,"").split(/\s+/g).forEach((function(t){t&&e.classList.add(t)})):util.hasClass(e,t)||(e.className+=" "+t))},removeClass:function(e,t){e&&(e.classList?t.split(/\s+/g).forEach((function(t){e.classList.remove(t)})):util.hasClass(e,t)&&t.split(/\s+/g).forEach((function(t){var n=new RegExp("(\\s|^)"+t+"(\\s|$)");e.className=e.className.replace(n," ")})))},toggleClass:function(e,t){e&&t.split(/\s+/g).forEach((function(t){util.hasClass(e,t)?util.removeClass(e,t):util.addClass(e,t)}))},findDom:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document,t=arguments[1],n=void 0;try{n=e.querySelector(t)}catch(a){0===t.indexOf("#")&&(n=e.getElementById(t.slice(1)))}return n},padStart:function(e,t,n){for(var a=String(n),r=t>>0,i=Math.ceil(r/a.length),o=[],l=String(e);i--;)o.push(a);return o.join("").substring(0,r-l.length)+l},format:function(e){if(window.isNaN(e))return"";var t=util.padStart(Math.floor(e/3600),2,0),n=util.padStart(Math.floor((e-3600*t)/60),2,0),a=util.padStart(Math.floor(e-3600*t-60*n),2,0);return("00"===t?[n,a]:[t,n,a]).join(":")},event:function(e){if(e.touches){var t=e.touches[0]||e.changedTouches[0];e.clientX=t.clientX||0,e.clientY=t.clientY||0,e.offsetX=t.pageX-t.target.offsetLeft,e.offsetY=t.pageY-t.target.offsetTop}e._target=e.target||e.srcElement},typeOf:function(e){return Object.prototype.toString.call(e).match(/([^\s.*]+)(?=]$)/g)[0]},deepCopy:function(e,t){if("Object"===util.typeOf(t)&&"Object"===util.typeOf(e))return Object.keys(t).forEach((function(n){"Object"!==util.typeOf(t[n])||t[n]instanceof Node?"Array"===util.typeOf(t[n])?e[n]="Array"===util.typeOf(e[n])?e[n].concat(t[n]):t[n]:e[n]=t[n]:e[n]?util.deepCopy(e[n],t[n]):e[n]=t[n]})),e},getBgImage:function(e){var t=(e.currentStyle||window.getComputedStyle(e,null)).backgroundImage;if(!t||"none"===t)return"";var n=document.createElement("a");return n.href=t.replace(/url\("|"\)/g,""),n.href},copyDom:function(e){if(e&&1===e.nodeType){var t=document.createElement(e.tagName);return Array.prototype.forEach.call(e.attributes,(function(e){t.setAttribute(e.name,e.value)})),e.innerHTML&&(t.innerHTML=e.innerHTML),t}return""},setInterval:function(e,t,n,a){e._interval[t]||(e._interval[t]=setInterval(n.bind(e),a))},clearInterval:function(e,t){clearInterval(e._interval[t]),e._interval[t]=null},createImgBtn:function(e,t,n,a){var r=util.createDom("xg-"+e,"",{},"xgplayer-"+e+"-img");if(r.style.backgroundImage='url("'+t+'")',n&&a){var i=void 0,o=void 0,l=void 0;["px","rem","em","pt","dp","vw","vh","vm","%"].every((function(e){return!(n.indexOf(e)>-1&&a.indexOf(e)>-1)||(i=Number(n.slice(0,n.indexOf(e)).trim()),o=Number(a.slice(0,a.indexOf(e)).trim()),l=e,!1)})),r.style.width=""+i+l,r.style.height=""+o+l,r.style.backgroundSize=""+i+l+" "+o+l,r.style.margin="start"===e?"-"+o/2+l+" auto auto -"+i/2+l:"auto 5px auto 5px"}return r},Hex2RGBA:function(hex,alpha){var rgb=[];if(/^\#[0-9A-F]{3}$/i.test(hex)){var sixHex="#";hex.replace(/[0-9A-F]/gi,(function(e){sixHex+=e+e})),hex=sixHex}return/^#[0-9A-F]{6}$/i.test(hex)?(hex.replace(/[0-9A-F]{2}/gi,(function(kw){rgb.push(eval("0x"+kw))})),"rgba("+rgb.join(",")+", "+alpha+")"):"rgba(255, 255, 255, 0.1)"},isWeiXin:function(){return window.navigator.userAgent.toLowerCase().indexOf("micromessenger")>-1},isUc:function(){return window.navigator.userAgent.toLowerCase().indexOf("ucbrowser")>-1},computeWatchDur:function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=[],n=0;n<e.length;n++)if(!(!e[n].end||e[n].begin<0||e[n].end<0||e[n].end<e[n].begin))if(t.length<1)t.push({begin:e[n].begin,end:e[n].end});else for(var a=0;a<t.length;a++){var r=e[n].begin,i=e[n].end;if(i<t[a].begin){t.splice(a,0,{begin:r,end:i});break}if(!(r>t[a].end)){var o=t[a].begin,l=t[a].end;t[a].begin=Math.min(r,o),t[a].end=Math.max(i,l);break}if(a>t.length-2){t.push({begin:r,end:i});break}}for(var s=0,u=0;u<t.length;u++)s+=t[u].end-t[u].begin;return s},downloadFile:function(e){var t=this;return new Promise((function(n,a){var r=new XMLHttpRequest;r.open("get",e),r.responseType="arraybuffer",r.onload=function(){var a=void 0,i=r.response;try{a=new Blob([i],{type:"application/x-mpegURL"})}catch(e){window.BlobBuilder=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder,(a=new BlobBuilder).append(i),a=a.getBlob()}var o=URL.createObjectURL(a);t.cacheBuffer[e]={blobUrl:o,blob:a},t.options.backupUrls&&t.options.backupUrls.length&&!t.backup_download_success&&t.options.backupUrls.every((function(e){return t.cacheBuffer[e]&&!isPromise(t.cacheBuffer[e])}))&&(t.emit("backup_download_success"),t.backup_download_success=!0),n({blobUrl:o,blob:a})},r.onerror=function(a){delete t.cacheBuffer[e],n(e)},r.onprogress=function(n){-1==t.cacheBuffer[e]&&r&&(r.abort(),delete t.cacheBuffer[e])},r.send()}))}};exports.default=util,module.exports=exports.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=n(5);function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var i={network:{code:1,msg:"视频下载错误",remark:"只要视频下载错误就使用此类型,无论是video本身的超时还是xhr的分段请求超时或者资源不存在"},mse:{code:2,msg:"流追加错误",remark:"追加流的时候如果类型不对、无法被正确解码则会触发此类错误"},parse:{code:3,msg:"解析错误",remark:"mp4、hls、flv我们都是使用js进行格式解析,如果解析失败则会触发此类错误"},format:{code:4,msg:"格式错误",remark:"如果浏览器不支持的格式导致播放错误"},decoder:{code:5,msg:"解码错误",remark:"浏览器解码异常会抛出此类型错误"},runtime:{code:6,msg:"语法错误",remark:"播放器语法错误"},timeout:{code:7,msg:"播放超时",remark:"播放过程中无法正常请求下一个分段导致播放中断"},other:{code:8,msg:"其他错误",remark:"不可知的错误或被忽略的错误类型"}};t.default=function e(t,n,o,l,s,u,c,p){var d=arguments.length>8&&void 0!==arguments[8]?arguments[8]:{line:"",handle:"",msg:"",version:""},f=arguments[9],g=arguments[10];r(this,e);var y={};if(arguments.length>1)y.playerVersion=a.version,y.errorType=t,y.domain=document.domain,y.duration=o,y.currentTime=n,y.networkState=l,y.readyState=s,y.currentSrc=c,y.src=u,y.ended=p,y.errd=d,y.ex=(i[t]||{}).msg,y.errorCode=f,y.mediaError=g;else{var h=arguments[0];Object.keys(h).map((function(e){y[e]=h[e]})),y.ex=(h.type&&i[h.type]||{}).msg}return y},e.exports=t.default},function(e){e.exports=JSON.parse('{"version":"2.10.2"}')},function(e,t,n){e.exports=n(7)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=E(n(0)),r=E(n(37)),i=E(n(38)),o=E(n(39)),l=E(n(40)),s=E(n(41)),u=E(n(42)),c=E(n(43)),p=E(n(44)),d=E(n(45)),f=E(n(46)),g=E(n(47)),y=E(n(48)),h=E(n(49)),x=E(n(50)),m=E(n(51)),v=E(n(52)),b=E(n(53)),k=E(n(54)),w=E(n(55)),_=E(n(56));E(n(57));function E(e){return e&&e.__esModule?e:{default:e}}var C={};function T(e,t,n){var a=e;t.map((function(e,r){a[e]=r==t.length-1?n:a[e]||{},a=a[e]}))}T(C,["controls","cssFullscreen"],_.default),T(C,["controls","danmu"],w.default),T(C,["controls","definition"],k.default),T(C,["controls","download"],b.default),T(C,["controls","errorRetry"],v.default),T(C,["controls","fullscreen"],m.default),T(C,["controls","i18n"],x.default),T(C,["controls","localPreview"],h.default),T(C,["controls","memoryPlay"],y.default),T(C,["controls","mobile"],g.default),T(C,["controls","pc"],f.default),T(C,["controls","pip"],d.default),T(C,["controls","play"],p.default),T(C,["controls","playNext"],c.default),T(C,["controls","reload"],u.default),T(C,["controls","replay"],s.default),T(C,["controls","rotate"],l.default),T(C,["controls","screenShot"],o.default),T(C,["controls","start"],i.default),T(C,["controls","volume"],r.default),t.default=a.default,e.exports=t.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}return function(t,n,a){return n&&e(t.prototype,n),a&&e(t,a),t}}(),r=l(n(9)),i=l(n(3)),o=l(n(4));function l(e){return e&&e.__esModule?e:{default:e}}var s=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.logParams={bc:0,bu_acu_t:0,played:[]},this._hasStart=!1,this.videoConfig={controls:!!t.isShowControl,autoplay:t.autoplay,playsinline:t.playsinline,"webkit-playsinline":t.playsinline,"x5-playsinline":t.playsinline,"x5-video-player-type":t["x5-video-player-type"]||t.x5VideoPlayerType,"x5-video-player-fullscreen":t["x5-video-player-fullscreen"]||t.x5VideoPlayerFullscreen,"x5-video-orientation":t["x5-video-orientation"]||t.x5VideoOrientation,airplay:t.airplay,"webkit-airplay":t.airplay,tabindex:2,mediaType:t.mediaType||"video"},t.muted&&(this.videoConfig.muted="muted"),t.loop&&(this.videoConfig.loop="loop");var n="";if(this.textTrackShowDefault=!0,t.textTrack&&Array.isArray(t.textTrack)&&(t.textTrack.length>0&&!t.textTrack.some((function(e){return e.default}))&&(t.textTrack[0].default=!0,this.textTrackShowDefault=!1),t.textTrack.some((function(e){if(e.src&&e.label&&e.default)return n+='<track src="'+e.src+'" ',e.kind&&(n+='kind="'+e.kind+'" '),n+='label="'+e.label+'" ',e.srclang&&(n+='srclang="'+e.srclang+'" '),n+=(e.default?"default":"")+">",!0})),this.videoConfig.crossorigin="anonymous"),t.textTrackStyle){var a=document.createElement("style");this.textTrackStyle=a,document.head.appendChild(a);var o="";for(var l in t.textTrackStyle)o+=l+": "+t.textTrackStyle[l]+";";var s=t.id?"#"+t.id:t.el.id?"#"+t.el.id:"."+t.el.className;a.sheet.insertRule?a.sheet.insertRule(s+" video::cue { "+o+" }",0):a.sheet.addRule&&a.sheet.addRule(s+" video::cue",o)}(this.video=i.default.createDom(this.videoConfig.mediaType,n,this.videoConfig,""),!this.textTrackShowDefault&&n)&&(this.video.getElementsByTagName("Track")[0].track.mode="hidden");t.autoplay&&(this.video.autoplay=!0,t.autoplayMuted&&(this.video.muted=!0)),this.ev=["play","playing","pause","ended","error","seeking","seeked","timeupdate","waiting","canplay","canplaythrough","durationchange","volumechange","loadeddata","loadstart"].map((function(e){return t={},n=e,a="on"+e.charAt(0).toUpperCase()+e.slice(1),n in t?Object.defineProperty(t,n,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[n]=a,t;var t,n,a})),(0,r.default)(this),this._interval={};var u="0,0",c=this;this.ev.forEach((function(e){c.evItem=Object.keys(e)[0];var t=Object.keys(e)[0];c.video.addEventListener(Object.keys(e)[0],(function(){c&&c.logParams&&("play"===t?c.hasStart=!0:"canplay"===t?i.default.removeClass(c.root,"xgplayer-is-enter"):"waiting"===t?(c.logParams.bc++,c.inWaitingStart=(new Date).getTime()):"playing"===t?(i.default.removeClass(c.root,"xgplayer-is-enter"),c.inWaitingStart&&(c.logParams.bu_acu_t+=(new Date).getTime()-c.inWaitingStart,c.inWaitingStart=void 0)):"loadeddata"===t?c.logParams.played.push({begin:0,end:-1}):"seeking"===t?c.logParams.played.push({begin:c.video.currentTime,end:-1}):c&&c.logParams&&c.logParams.played&&"timeupdate"===t&&(c.logParams.played.length<1&&c.logParams.played.push({begin:c.video.currentTime,end:-1}),c.logParams.played[c.logParams.played.length-1].end=c.video.currentTime),"error"===t?c._onError(t):c.emit(t,c),c.hasOwnProperty("_interval")&&(["ended","error","timeupdate"].indexOf(t)<0?(clearInterval(c._interval.bufferedChange),i.default.setInterval(c,"bufferedChange",(function(){if(c.video&&c.video.buffered){for(var e=[],t=0,n=c.video.buffered.length;t<n;t++)e.push([c.video.buffered.start(t),c.video.buffered.end(t)]);e.toString()!==u&&(u=e.toString(),c.emit("bufferedChange",e))}}),200)):"timeupdate"!==t&&i.default.clearInterval(c,"bufferedChange")))}),!1)}))}return a(e,[{key:"_onError",value:function(e){this.video&&this.video.error&&this.emit(e,new o.default("other",this.currentTime,this.duration,this.networkState,this.readyState,this.currentSrc,this.src,this.ended,{line:162,msg:this.error,handle:"Constructor"},this.video.error.code,this.video.error))}},{key:"destroy",value:function(){this.textTrackStyle&&this.textTrackStyle.parentNode.removeChild(this.textTrackStyle)}},{key:"play",value:function(){return this.video.play()}},{key:"pause",value:function(){this.video.pause()}},{key:"canPlayType",value:function(e){return this.video.canPlayType(e)}},{key:"getBufferedRange",value:function(){var e=[0,0],t=this.video,n=t.buffered,a=t.currentTime;if(n)for(var r=0,i=n.length;r<i&&(e[0]=n.start(r),e[1]=n.end(r),!(e[0]<=a&&a<=e[1]));r++);return e[0]-a<=0&&a-e[1]<=0?e:[0,0]}},{key:"hasStart",get:function(){return this._hasStart},set:function(e){"boolean"!=typeof e||!0!==e||this._hasStart||(this._hasStart=!0,this.emit("hasstart"))}},{key:"autoplay",set:function(e){this.video.autoplay=e},get:function(){return this.video.autoplay}},{key:"buffered",get:function(){return this.video.buffered}},{key:"crossOrigin",get:function(){return this.video.crossOrigin},set:function(e){this.video.crossOrigin=e}},{key:"currentSrc",get:function(){return this.video.currentSrc},set:function(e){this.video.currentSrc=e}},{key:"currentTime",get:function(){return this.video.currentTime},set:function(e){var t=this;("function"!=typeof isFinite||isFinite(e))&&(i.default.hasClass(this.root,"xgplayer-ended")?(this.once("playing",(function(){t.video.currentTime=e})),this.replay()):this.video.currentTime=e,this.emit("currentTimeChange"))}},{key:"defaultMuted",get:function(){return this.video.defaultMuted},set:function(e){this.video.defaultMuted=e}},{key:"duration",get:function(){return this.video.duration}},{key:"ended",get:function(){return this.video.ended}},{key:"error",get:function(){var e=this.video.error;if(!e)return null;var t=[{en:"MEDIA_ERR_ABORTED",cn:"取回过程被用户中止"},{en:"MEDIA_ERR_NETWORK",cn:"当下载时发生错误"},{en:"MEDIA_ERR_DECODE",cn:"当解码时发生错误"},{en:"MEDIA_ERR_SRC_NOT_SUPPORTED",cn:"不支持音频/视频"}];return this.lang?this.lang[t[e.code-1].en]:t[e.code-1].en}},{key:"loop",get:function(){return this.video.loop},set:function(e){this.video.loop=e}},{key:"muted",get:function(){return this.video.muted},set:function(e){this.video.muted=e}},{key:"networkState",get:function(){var e=[{en:"NETWORK_EMPTY",cn:"音频/视频尚未初始化"},{en:"NETWORK_IDLE",cn:"音频/视频是活动的且已选取资源,但并未使用网络"},{en:"NETWORK_LOADING",cn:"浏览器正在下载数据"},{en:"NETWORK_NO_SOURCE",cn:"未找到音频/视频来源"}];return this.lang?this.lang[e[this.video.networkState].en]:e[this.video.networkState].en}},{key:"paused",get:function(){return this.video.paused}},{key:"playbackRate",get:function(){return this.video.playbackRate},set:function(e){this.video.playbackRate=e}},{key:"played",get:function(){return this.video.played}},{key:"preload",get:function(){return this.video.preload},set:function(e){this.video.preload=e}},{key:"readyState",get:function(){var e=[{en:"HAVE_NOTHING",cn:"没有关于音频/视频是否就绪的信息"},{en:"HAVE_METADATA",cn:"关于音频/视频就绪的元数据"},{en:"HAVE_CURRENT_DATA",cn:"关于当前播放位置的数据是可用的,但没有足够的数据来播放下一帧/毫秒"},{en:"HAVE_FUTURE_DATA",cn:"当前及至少下一帧的数据是可用的"},{en:"HAVE_ENOUGH_DATA",cn:"可用数据足以开始播放"}];return this.lang?this.lang[e[this.video.readyState].en]:e[this.video.readyState]}},{key:"seekable",get:function(){return this.video.seekable}},{key:"seeking",get:function(){return this.video.seeking}},{key:"src",get:function(){return this.video.src},set:function(e){var t=this;i.default.hasClass(this.root,"xgplayer-ended")||this.emit("urlchange",JSON.parse(JSON.stringify(t.logParams))),this.logParams={bc:0,bu_acu_t:0,played:[],pt:(new Date).getTime(),vt:(new Date).getTime(),vd:0},this.video.pause(),this.video.src=e,this.emit("srcChange"),this.logParams.playSrc=e,this.logParams.pt=(new Date).getTime(),this.logParams.vt=this.logParams.pt,this.once("loadeddata",(function e(){t.logParams.vt=(new Date).getTime(),t.logParams.pt>t.logParams.vt&&(t.logParams.pt=t.logParams.vt),t.logParams.vd=t.video.duration,t.off("loadeddata",e)}))}},{key:"poster",set:function(e){var t=i.default.findDom(this.root,".xgplayer-poster");t&&(t.style.backgroundImage="url("+e+")")}},{key:"volume",get:function(){return this.video.volume},set:function(e){this.video.volume=e}},{key:"fullscreen",get:function(){return i.default.hasClass(this.root,"xgplayer-is-fullscreen")||i.default.hasClass(this.root,"xgplayer-fullscreen-active")}},{key:"bullet",get:function(){return!!i.default.findDom(this.root,"xg-danmu")&&i.default.hasClass(i.default.findDom(this.root,"xg-danmu"),"xgplayer-has-danmu")}},{key:"textTrack",get:function(){return i.default.hasClass(this.root,"xgplayer-is-textTrack")}},{key:"pip",get:function(){return i.default.hasClass(this.root,"xgplayer-pip-active")}}]),e}();t.default=s,e.exports=t.default},function(e,t,n){"use strict";var a,r,i,o,l,s,u,c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},p=n(10),d=n(27),f=Function.prototype.apply,g=Function.prototype.call,y=Object.create,h=Object.defineProperty,x=Object.defineProperties,m=Object.prototype.hasOwnProperty,v={configurable:!0,enumerable:!1,writable:!0};r=function(e,t){var n,r;return d(t),r=this,a.call(this,e,n=function(){i.call(r,e,n),f.call(t,this,arguments)}),n.__eeOnceListener__=t,this},l={on:a=function(e,t){var n;return d(t),m.call(this,"__ee__")?n=this.__ee__:(n=v.value=y(null),h(this,"__ee__",v),v.value=null),n[e]?"object"===c(n[e])?n[e].push(t):n[e]=[n[e],t]:n[e]=t,this},once:r,off:i=function(e,t){var n,a,r,i;if(d(t),!m.call(this,"__ee__"))return this;if(!(n=this.__ee__)[e])return this;if("object"===(void 0===(a=n[e])?"undefined":c(a)))for(i=0;r=a[i];++i)r!==t&&r.__eeOnceListener__!==t||(2===a.length?n[e]=a[i?0:1]:a.splice(i,1));else a!==t&&a.__eeOnceListener__!==t||delete n[e];return this},emit:o=function(e){var t,n,a,r,i;if(m.call(this,"__ee__")&&(r=this.__ee__[e]))if("object"===(void 0===r?"undefined":c(r))){for(n=arguments.length,i=new Array(n-1),t=1;t<n;++t)i[t-1]=arguments[t];for(r=r.slice(),t=0;a=r[t];++t)f.call(a,this,i)}else switch(arguments.length){case 1:g.call(r,this);break;case 2:g.call(r,this,arguments[1]);break;case 3:g.call(r,this,arguments[1],arguments[2]);break;default:for(n=arguments.length,i=new Array(n-1),t=1;t<n;++t)i[t-1]=arguments[t];f.call(r,this,i)}}},s={on:p(a),once:p(r),off:p(i),emit:p(o)},u=x({},s),e.exports=t=function(e){return null==e?y(u):x(Object(e),s)},t.methods=l},function(e,t,n){"use strict";var a=n(2),r=n(11),i=n(15),o=n(23),l=n(24);(e.exports=function(e,t){var n,r,s,u,c;return arguments.length<2||"string"!=typeof e?(u=t,t=e,e=null):u=arguments[2],a(e)?(n=l.call(e,"c"),r=l.call(e,"e"),s=l.call(e,"w")):(n=s=!0,r=!1),c={value:t,configurable:n,enumerable:r,writable:s},u?i(o(u),c):c}).gs=function(e,t,n){var s,u,c,p;return"string"!=typeof e?(c=n,n=t,t=e,e=null):c=arguments[3],a(t)?r(t)?a(n)?r(n)||(c=n,n=void 0):n=void 0:(c=t,t=n=void 0):t=void 0,a(e)?(s=l.call(e,"c"),u=l.call(e,"e")):(s=!0,u=!1),p={get:t,set:n,configurable:s,enumerable:u},c?i(o(c),p):p}},function(e,t,n){"use strict";var a=n(12),r=/^\s*class[\s{/}]/,i=Function.prototype.toString;e.exports=function(e){return!!a(e)&&!r.test(i.call(e))}},function(e,t,n){"use strict";var a=n(13);e.exports=function(e){if("function"!=typeof e)return!1;if(!hasOwnProperty.call(e,"length"))return!1;try{if("number"!=typeof e.length)return!1;if("function"!=typeof e.call)return!1;if("function"!=typeof e.apply)return!1}catch(e){return!1}return!a(e)}},function(e,t,n){"use strict";var a=n(14);e.exports=function(e){if(!a(e))return!1;try{return!!e.constructor&&e.constructor.prototype===e}catch(e){return!1}}},function(e,t,n){"use strict";var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r=n(2),i={object:!0,function:!0,undefined:!0};e.exports=function(e){return!!r(e)&&hasOwnProperty.call(i,void 0===e?"undefined":a(e))}},function(e,t,n){"use strict";e.exports=n(16)()?Object.assign:n(17)},function(e,t,n){"use strict";e.exports=function(){var e,t=Object.assign;return"function"==typeof t&&(t(e={foo:"raz"},{bar:"dwa"},{trzy:"trzy"}),e.foo+e.bar+e.trzy==="razdwatrzy")}},function(e,t,n){"use strict";var a=n(18),r=n(22),i=Math.max;e.exports=function(e,t){var n,o,l,s=i(arguments.length,2);for(e=Object(r(e)),l=function(a){try{e[a]=t[a]}catch(e){n||(n=e)}},o=1;o<s;++o)a(t=arguments[o]).forEach(l);if(void 0!==n)throw n;return e}},function(e,t,n){"use strict";e.exports=n(19)()?Object.keys:n(20)},function(e,t,n){"use strict";e.exports=function(){try{return Object.keys("primitive"),!0}catch(e){return!1}}},function(e,t,n){"use strict";var a=n(1),r=Object.keys;e.exports=function(e){return r(a(e)?Object(e):e)}},function(e,t,n){"use strict";e.exports=function(){}},function(e,t,n){"use strict";var a=n(1);e.exports=function(e){if(!a(e))throw new TypeError("Cannot use null or undefined");return e}},function(e,t,n){"use strict";var a=n(1),r=Array.prototype.forEach,i=Object.create,o=function(e,t){var n;for(n in e)t[n]=e[n]};e.exports=function(e){var t=i(null);return r.call(arguments,(function(e){a(e)&&o(Object(e),t)})),t}},function(e,t,n){"use strict";e.exports=n(25)()?String.prototype.contains:n(26)},function(e,t,n){"use strict";var a="razdwatrzy";e.exports=function(){return"function"==typeof a.contains&&(!0===a.contains("dwa")&&!1===a.contains("foo"))}},function(e,t,n){"use strict";var a=String.prototype.indexOf;e.exports=function(e){return a.call(this,e,arguments[1])>-1}},function(e,t,n){"use strict";e.exports=function(e){if("function"!=typeof e)throw new TypeError(e+" is not a function");return e}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}return function(t,n,a){return n&&e(t.prototype,n),a&&e(t,a),t}}();function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var i=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{name:"xgplayer",version:1,db:null,ojstore:{name:"xg-m4a",keypath:"vid"}};r(this,e),this.indexedDB=window.indexedDB||window.webkitindexedDB,this.IDBKeyRange=window.IDBKeyRange||window.webkitIDBKeyRange,this.myDB=t}return a(e,[{key:"openDB",value:function(e){var t=this,n=this,a=this.myDB.version||1,r=n.indexedDB.open(n.myDB.name,a);r.onerror=function(e){},r.onsuccess=function(a){t.myDB.db=a.target.result,e.call(n)},r.onupgradeneeded=function(e){var t=e.target.result;e.target.transaction;t.objectStoreNames.contains(n.myDB.ojstore.name)||t.createObjectStore(n.myDB.ojstore.name,{keyPath:n.myDB.ojstore.keypath})}}},{key:"deletedb",value:function(){this.indexedDB.deleteDatabase(this.myDB.name)}},{key:"closeDB",value:function(){this.myDB.db.close()}},{key:"addData",value:function(e,t){for(var n=this.myDB.db.transaction(e,"readwrite").objectStore(e),a=void 0,r=0;r<t.length;r++)(a=n.add(t[r])).onerror=function(){},a.onsuccess=function(){}}},{key:"putData",value:function(e,t){for(var n=this.myDB.db.transaction(e,"readwrite").objectStore(e),a=void 0,r=0;r<t.length;r++)(a=n.put(t[r])).onerror=function(){},a.onsuccess=function(){}}},{key:"getDataByKey",value:function(e,t,n){var a=this,r=this.myDB.db.transaction(e,"readwrite").objectStore(e).get(t);r.onerror=function(){n.call(a,null)},r.onsuccess=function(e){var t=e.target.result;n.call(a,t)}}},{key:"deleteData",value:function(e,t){this.myDB.db.transaction(e,"readwrite").objectStore(e).delete(t)}},{key:"clearData",value:function(e){this.myDB.db.transaction(e,"readwrite").objectStore(e).clear()}}]),e}();t.default=i,e.exports=t.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a={get device(){return a.os.isPc?"pc":"mobile"},get browser(){var e=navigator.userAgent.toLowerCase(),t={ie:/rv:([\d.]+)\) like gecko/,firfox:/firefox\/([\d.]+)/,chrome:/chrome\/([\d.]+)/,opera:/opera.([\d.]+)/,safari:/version\/([\d.]+).*safari/};return[].concat(Object.keys(t).filter((function(n){return t[n].test(e)})))[0]},get os(){var e=navigator.userAgent,t=/(?:Windows Phone)/.test(e),n=/(?:SymbianOS)/.test(e)||t,a=/(?:Android)/.test(e),r=/(?:Firefox)/.test(e),i=/(?:iPad|PlayBook)/.test(e)||a&&!/(?:Mobile)/.test(e)||r&&/(?:Tablet)/.test(e),o=/(?:iPhone)/.test(e)&&!i;return{isTablet:i,isPhone:o,isAndroid:a,isPc:!(o||a||n||i),isSymbian:n,isWindowsPhone:t,isFireFox:r}}};t.default=a,e.exports=t.default},function(e,t,n){"use strict";var a,r;"function"==typeof Symbol&&Symbol.iterator;
  283. /*!
  284. * Draggabilly v2.3.0
  285. * Make that shiz draggable
  286. * https://draggabilly.desandro.com
  287. * MIT license
  288. */
  289. !function(i,o){a=[n(31),n(32)],void 0===(r=function(e,t){return function(e,t,n){function a(e,t){for(var n in t)e[n]=t[n];return e}var r=e.jQuery;function i(e,t){this.element="string"==typeof e?document.querySelector(e):e,r&&(this.$element=r(this.element)),this.options=a({},this.constructor.defaults),this.option(t),this._create()}var o=i.prototype=Object.create(n.prototype);i.defaults={},o.option=function(e){a(this.options,e)};var l={relative:!0,absolute:!0,fixed:!0};function s(e,t,n){return n=n||"round",t?Math[n](e/t)*t:e}o._create=function(){this.position={},this._getPosition(),this.startPoint={x:0,y:0},this.dragPoint={x:0,y:0},this.startPosition=a({},this.position);var e=getComputedStyle(this.element);l[e.position]||(this.element.style.position="relative"),this.on("pointerMove",this.onPointerMove),this.on("pointerUp",this.onPointerUp),this.enable(),this.setHandles()},o.setHandles=function(){this.handles=this.options.handle?this.element.querySelectorAll(this.options.handle):[this.element],this.bindHandles()},o.dispatchEvent=function(e,t,n){var a=[t].concat(n);this.emitEvent(e,a),this.dispatchJQueryEvent(e,t,n)},o.dispatchJQueryEvent=function(t,n,a){var r=e.jQuery;if(r&&this.$element){var i=r.Event(n);i.type=t,this.$element.trigger(i,a)}},o._getPosition=function(){var e=getComputedStyle(this.element),t=this._getPositionCoord(e.left,"width"),n=this._getPositionCoord(e.top,"height");this.position.x=isNaN(t)?0:t,this.position.y=isNaN(n)?0:n,this._addTransformPosition(e)},o._getPositionCoord=function(e,n){if(-1!=e.indexOf("%")){var a=t(this.element.parentNode);return a?parseFloat(e)/100*a[n]:0}return parseInt(e,10)},o._addTransformPosition=function(e){var t=e.transform;if(0===t.indexOf("matrix")){var n=t.split(","),a=0===t.indexOf("matrix3d")?12:4,r=parseInt(n[a],10),i=parseInt(n[a+1],10);this.position.x+=r,this.position.y+=i}},o.onPointerDown=function(e,t){this.element.classList.add("is-pointer-down"),this.dispatchJQueryEvent("pointerDown",e,[t])},o.pointerDown=function(e,t){this.okayPointerDown(e)&&this.isEnabled?(this.pointerDownPointer={pageX:t.pageX,pageY:t.pageY},e.preventDefault(),this.pointerDownBlur(),this._bindPostStartEvents(e),this.element.classList.add("is-pointer-down"),this.dispatchEvent("pointerDown",e,[t])):this._pointerReset()},o.dragStart=function(e,t){this.isEnabled&&(this._getPosition(),this.measureContainment(),this.startPosition.x=this.position.x,this.startPosition.y=this.position.y,this.setLeftTop(),this.dragPoint.x=0,this.dragPoint.y=0,this.element.classList.add("is-dragging"),this.dispatchEvent("dragStart",e,[t]),this.animate())},o.measureContainment=function(){var e=this.getContainer();if(e){var n=t(this.element),a=t(e),r=this.element.getBoundingClientRect(),i=e.getBoundingClientRect(),o=a.borderLeftWidth+a.borderRightWidth,l=a.borderTopWidth+a.borderBottomWidth,s=this.relativeStartPosition={x:r.left-(i.left+a.borderLeftWidth),y:r.top-(i.top+a.borderTopWidth)};this.containSize={width:a.width-o-s.x-n.width,height:a.height-l-s.y-n.height}}},o.getContainer=function(){var e=this.options.containment;if(e)return e instanceof HTMLElement?e:"string"==typeof e?document.querySelector(e):this.element.parentNode},o.onPointerMove=function(e,t,n){this.dispatchJQueryEvent("pointerMove",e,[t,n])},o.dragMove=function(e,t,n){if(this.isEnabled){var a=n.x,r=n.y,i=this.options.grid,o=i&&i[0],l=i&&i[1];a=s(a,o),r=s(r,l),a=this.containDrag("x",a,o),r=this.containDrag("y",r,l),a="y"==this.options.axis?0:a,r="x"==this.options.axis?0:r,this.position.x=this.startPosition.x+a,this.position.y=this.startPosition.y+r,this.dragPoint.x=a,this.dragPoint.y=r,this.dispatchEvent("dragMove",e,[t,n])}},o.containDrag=function(e,t,n){if(!this.options.containment)return t;var a="x"==e?"width":"height",r=s(-this.relativeStartPosition[e],n,"ceil"),i=this.containSize[a];return i=s(i,n,"floor"),Math.max(r,Math.min(i,t))},o.onPointerUp=function(e,t){this.element.classList.remove("is-pointer-down"),this.dispatchJQueryEvent("pointerUp",e,[t])},o.dragEnd=function(e,t){this.isEnabled&&(this.element.style.transform="",this.setLeftTop(),this.element.classList.remove("is-dragging"),this.dispatchEvent("dragEnd",e,[t]))},o.animate=function(){if(this.isDragging){this.positionDrag();var e=this;requestAnimationFrame((function(){e.animate()}))}},o.setLeftTop=function(){this.element.style.left=this.position.x+"px",this.element.style.top=this.position.y+"px"},o.positionDrag=function(){this.element.style.transform="translate3d( "+this.dragPoint.x+"px, "+this.dragPoint.y+"px, 0)"},o.staticClick=function(e,t){this.dispatchEvent("staticClick",e,[t])},o.setPosition=function(e,t){this.position.x=e,this.position.y=t,this.setLeftTop()},o.enable=function(){this.isEnabled=!0},o.disable=function(){this.isEnabled=!1,this.isDragging&&this.dragEnd()},o.destroy=function(){this.disable(),this.element.style.transform="",this.element.style.left="",this.element.style.top="",this.element.style.position="",this.unbindHandles(),this.$element&&this.$element.removeData("draggabilly")},o._init=function(){},r&&r.bridget&&r.bridget("draggabilly",i);return i}(i,e,t)}.apply(t,a))||(e.exports=r)}(window)},function(e,t,n){"use strict";var a,r,i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};window,void 0===(r="function"==typeof(a=function(){function e(e){var t=parseFloat(e);return-1==e.indexOf("%")&&!isNaN(t)&&t}var t="undefined"==typeof console?function(){}:function(e){console.error(e)},n=["paddingLeft","paddingRight","paddingTop","paddingBottom","marginLeft","marginRight","marginTop","marginBottom","borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"],a=n.length;function r(e){var n=getComputedStyle(e);return n||t("Style returned "+n+". Are you running this code in a hidden iframe on Firefox? See https://bit.ly/getsizebug1"),n}var o,l=!1;function s(t){if(function(){if(!l){l=!0;var t=document.createElement("div");t.style.width="200px",t.style.padding="1px 2px 3px 4px",t.style.borderStyle="solid",t.style.borderWidth="1px 2px 3px 4px",t.style.boxSizing="border-box";var n=document.body||document.documentElement;n.appendChild(t);var a=r(t);o=200==Math.round(e(a.width)),s.isBoxSizeOuter=o,n.removeChild(t)}}(),"string"==typeof t&&(t=document.querySelector(t)),t&&"object"==(void 0===t?"undefined":i(t))&&t.nodeType){var u=r(t);if("none"==u.display)return function(){for(var e={width:0,height:0,innerWidth:0,innerHeight:0,outerWidth:0,outerHeight:0},t=0;t<a;t++)e[n[t]]=0;return e}();var c={};c.width=t.offsetWidth,c.height=t.offsetHeight;for(var p=c.isBorderBox="border-box"==u.boxSizing,d=0;d<a;d++){var f=n[d],g=u[f],y=parseFloat(g);c[f]=isNaN(y)?0:y}var h=c.paddingLeft+c.paddingRight,x=c.paddingTop+c.paddingBottom,m=c.marginLeft+c.marginRight,v=c.marginTop+c.marginBottom,b=c.borderLeftWidth+c.borderRightWidth,k=c.borderTopWidth+c.borderBottomWidth,w=p&&o,_=e(u.width);!1!==_&&(c.width=_+(w?0:h+b));var E=e(u.height);return!1!==E&&(c.height=E+(w?0:x+k)),c.innerWidth=c.width-(h+b),c.innerHeight=c.height-(x+k),c.outerWidth=c.width+m,c.outerHeight=c.height+v,c}}return s})?a.call(t,n,t,e):a)||(e.exports=r)},function(e,t,n){"use strict";var a,r;"function"==typeof Symbol&&Symbol.iterator;
  290. /*!
  291. * Unidragger v2.3.1
  292. * Draggable base class
  293. * MIT license
  294. */
  295. !function(i,o){a=[n(33)],void 0===(r=function(e){return function(e,t){function n(){}var a=n.prototype=Object.create(t.prototype);a.bindHandles=function(){this._bindHandles(!0)},a.unbindHandles=function(){this._bindHandles(!1)},a._bindHandles=function(t){for(var n=(t=void 0===t||t)?"addEventListener":"removeEventListener",a=t?this._touchActionValue:"",r=0;r<this.handles.length;r++){var i=this.handles[r];this._bindStartEvent(i,t),i[n]("click",this),e.PointerEvent&&(i.style.touchAction=a)}},a._touchActionValue="none",a.pointerDown=function(e,t){this.okayPointerDown(e)&&(this.pointerDownPointer={pageX:t.pageX,pageY:t.pageY},e.preventDefault(),this.pointerDownBlur(),this._bindPostStartEvents(e),this.emitEvent("pointerDown",[e,t]))};var r={TEXTAREA:!0,INPUT:!0,SELECT:!0,OPTION:!0},i={radio:!0,checkbox:!0,button:!0,submit:!0,image:!0,file:!0};return a.okayPointerDown=function(e){var t=r[e.target.nodeName],n=i[e.target.type],a=!t||n;return a||this._pointerReset(),a},a.pointerDownBlur=function(){var e=document.activeElement;e&&e.blur&&e!=document.body&&e.blur()},a.pointerMove=function(e,t){var n=this._dragPointerMove(e,t);this.emitEvent("pointerMove",[e,t,n]),this._dragMove(e,t,n)},a._dragPointerMove=function(e,t){var n={x:t.pageX-this.pointerDownPointer.pageX,y:t.pageY-this.pointerDownPointer.pageY};return!this.isDragging&&this.hasDragStarted(n)&&this._dragStart(e,t),n},a.hasDragStarted=function(e){return Math.abs(e.x)>3||Math.abs(e.y)>3},a.pointerUp=function(e,t){this.emitEvent("pointerUp",[e,t]),this._dragPointerUp(e,t)},a._dragPointerUp=function(e,t){this.isDragging?this._dragEnd(e,t):this._staticClick(e,t)},a._dragStart=function(e,t){this.isDragging=!0,this.isPreventingClicks=!0,this.dragStart(e,t)},a.dragStart=function(e,t){this.emitEvent("dragStart",[e,t])},a._dragMove=function(e,t,n){this.isDragging&&this.dragMove(e,t,n)},a.dragMove=function(e,t,n){e.preventDefault(),this.emitEvent("dragMove",[e,t,n])},a._dragEnd=function(e,t){this.isDragging=!1,setTimeout(function(){delete this.isPreventingClicks}.bind(this)),this.dragEnd(e,t)},a.dragEnd=function(e,t){this.emitEvent("dragEnd",[e,t])},a.onclick=function(e){this.isPreventingClicks&&e.preventDefault()},a._staticClick=function(e,t){this.isIgnoringMouseUp&&"mouseup"==e.type||(this.staticClick(e,t),"mouseup"!=e.type&&(this.isIgnoringMouseUp=!0,setTimeout(function(){delete this.isIgnoringMouseUp}.bind(this),400)))},a.staticClick=function(e,t){this.emitEvent("staticClick",[e,t])},n.getPointerPoint=t.getPointerPoint,n}(i,e)}.apply(t,a))||(e.exports=r)}(window)},function(e,t,n){"use strict";var a,r;"function"==typeof Symbol&&Symbol.iterator;
  296. /*!
  297. * Unipointer v2.3.0
  298. * base class for doing one thing with pointer event
  299. * MIT license
  300. */
  301. !function(i,o){a=[n(34)],void 0===(r=function(e){return function(e,t){function n(){}var a=n.prototype=Object.create(t.prototype);a.bindStartEvent=function(e){this._bindStartEvent(e,!0)},a.unbindStartEvent=function(e){this._bindStartEvent(e,!1)},a._bindStartEvent=function(t,n){var a=(n=void 0===n||n)?"addEventListener":"removeEventListener",r="mousedown";e.PointerEvent?r="pointerdown":"ontouchstart"in e&&(r="touchstart"),t[a](r,this)},a.handleEvent=function(e){var t="on"+e.type;this[t]&&this[t](e)},a.getTouch=function(e){for(var t=0;t<e.length;t++){var n=e[t];if(n.identifier==this.pointerIdentifier)return n}},a.onmousedown=function(e){var t=e.button;t&&0!==t&&1!==t||this._pointerDown(e,e)},a.ontouchstart=function(e){this._pointerDown(e,e.changedTouches[0])},a.onpointerdown=function(e){this._pointerDown(e,e)},a._pointerDown=function(e,t){e.button||this.isPointerDown||(this.isPointerDown=!0,this.pointerIdentifier=void 0!==t.pointerId?t.pointerId:t.identifier,this.pointerDown(e,t))},a.pointerDown=function(e,t){this._bindPostStartEvents(e),this.emitEvent("pointerDown",[e,t])};var r={mousedown:["mousemove","mouseup"],touchstart:["touchmove","touchend","touchcancel"],pointerdown:["pointermove","pointerup","pointercancel"]};return a._bindPostStartEvents=function(t){if(t){var n=r[t.type];n.forEach((function(t){e.addEventListener(t,this)}),this),this._boundPointerEvents=n}},a._unbindPostStartEvents=function(){this._boundPointerEvents&&(this._boundPointerEvents.forEach((function(t){e.removeEventListener(t,this)}),this),delete this._boundPointerEvents)},a.onmousemove=function(e){this._pointerMove(e,e)},a.onpointermove=function(e){e.pointerId==this.pointerIdentifier&&this._pointerMove(e,e)},a.ontouchmove=function(e){var t=this.getTouch(e.changedTouches);t&&this._pointerMove(e,t)},a._pointerMove=function(e,t){this.pointerMove(e,t)},a.pointerMove=function(e,t){this.emitEvent("pointerMove",[e,t])},a.onmouseup=function(e){this._pointerUp(e,e)},a.onpointerup=function(e){e.pointerId==this.pointerIdentifier&&this._pointerUp(e,e)},a.ontouchend=function(e){var t=this.getTouch(e.changedTouches);t&&this._pointerUp(e,t)},a._pointerUp=function(e,t){this._pointerDone(),this.pointerUp(e,t)},a.pointerUp=function(e,t){this.emitEvent("pointerUp",[e,t])},a._pointerDone=function(){this._pointerReset(),this._unbindPostStartEvents(),this.pointerDone()},a._pointerReset=function(){this.isPointerDown=!1,delete this.pointerIdentifier},a.pointerDone=function(){},a.onpointercancel=function(e){e.pointerId==this.pointerIdentifier&&this._pointerCancel(e,e)},a.ontouchcancel=function(e){var t=this.getTouch(e.changedTouches);t&&this._pointerCancel(e,t)},a._pointerCancel=function(e,t){this._pointerDone(),this.pointerCancel(e,t)},a.pointerCancel=function(e,t){this.emitEvent("pointerCancel",[e,t])},n.getPointerPoint=function(e){return{x:e.pageX,y:e.pageY}},n}(i,e)}.apply(t,a))||(e.exports=r)}(window)},function(e,t,n){"use strict";var a,r;"function"==typeof Symbol&&Symbol.iterator;"undefined"!=typeof window&&window,void 0===(r="function"==typeof(a=function(){function e(){}var t=e.prototype;return t.on=function(e,t){if(e&&t){var n=this._events=this._events||{},a=n[e]=n[e]||[];return-1==a.indexOf(t)&&a.push(t),this}},t.once=function(e,t){if(e&&t){this.on(e,t);var n=this._onceEvents=this._onceEvents||{};return(n[e]=n[e]||{})[t]=!0,this}},t.off=function(e,t){var n=this._events&&this._events[e];if(n&&n.length){var a=n.indexOf(t);return-1!=a&&n.splice(a,1),this}},t.emitEvent=function(e,t){var n=this._events&&this._events[e];if(n&&n.length){n=n.slice(0),t=t||[];for(var a=this._onceEvents&&this._onceEvents[e],r=0;r<n.length;r++){var i=n[r];a&&a[i]&&(this.off(e,i),delete a[i]),i.apply(this,t)}return this}},t.allOff=function(){delete this._events,delete this._onceEvents},e})?a.call(t,n,t,e):a)||(e.exports=r)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.getAbsoluteURL=function(e){if(!e.match(/^https?:\/\//)){var t=document.createElement("div");t.innerHTML='<a href="'+e+'">x</a>',e=t.firstChild.href}return e}},function(e,t,n){"use strict";var a,r,i;"function"==typeof Symbol&&Symbol.iterator;r=[],void 0===(i="function"==typeof(a=function(){return function e(t,n,a){var r,i,o=window,l="application/octet-stream",s=a||l,u=t,c=!n&&!a&&u,p=document.createElement("a"),d=function(e){return String(e)},f=o.Blob||o.MozBlob||o.WebKitBlob||d,g=n||"download";if(f=f.call?f.bind(o):Blob,"true"===String(this)&&(s=(u=[u,s])[0],u=u[1]),c&&c.length<2048&&(g=c.split("/").pop().split("?")[0],p.href=c,-1!==p.href.indexOf(c))){var y=new XMLHttpRequest;return y.open("GET",c,!0),y.responseType="blob",y.onload=function(t){e(t.target.response,g,l)},setTimeout((function(){y.send()}),0),y}if(/^data:([\w+-]+\/[\w+.-]+)?[,;]/.test(u)){if(!(u.length>2096103.424&&f!==d))return navigator.msSaveBlob?navigator.msSaveBlob(v(u),g):b(u);s=(u=v(u)).type||l}else if(/([\x80-\xff])/.test(u)){for(var h=0,x=new Uint8Array(u.length),m=x.length;h<m;++h)x[h]=u.charCodeAt(h);u=new f([x],{type:s})}function v(e){for(var t=e.split(/[:;,]/),n=t[1],a=("base64"==t[2]?atob:decodeURIComponent)(t.pop()),r=a.length,i=0,o=new Uint8Array(r);i<r;++i)o[i]=a.charCodeAt(i);return new f([o],{type:n})}function b(e,t){if("download"in p)return p.href=e,p.setAttribute("download",g),p.className="download-js-link",p.innerHTML="downloading...",p.style.display="none",document.body.appendChild(p),setTimeout((function(){p.click(),document.body.removeChild(p),!0===t&&setTimeout((function(){o.URL.revokeObjectURL(p.href)}),250)}),66),!0;if(/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent))return/^data:/.test(e)&&(e="data:"+e.replace(/^data:([\w\/\-\+]+)/,l)),window.open(e)||confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")&&(location.href=e),!0;var n=document.createElement("iframe");document.body.appendChild(n),!t&&/^data:/.test(e)&&(e="data:"+e.replace(/^data:([\w\/\-\+]+)/,l)),n.src=e,setTimeout((function(){document.body.removeChild(n)}),333)}if(r=u instanceof f?u:new f([u],{type:s}),navigator.msSaveBlob)return navigator.msSaveBlob(r,g);if(o.URL)b(o.URL.createObjectURL(r),!0);else{if("string"==typeof r||r.constructor===d)try{return b("data:"+s+";base64,"+o.btoa(r))}catch(e){return b("data:"+s+","+encodeURIComponent(r))}(i=new FileReader).onload=function(e){b(this.result)},i.readAsDataURL(r)}return!0}})?a.apply(t,r):a)||(e.exports=i)},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("volume",(function(){var e=this,t=e.root,n=i.default.util,a=void 0,r=void 0,o=void 0,l=void 0;function s(){e.controls&&(e.volume=e.config.volume,(a=e.controls.querySelector(".xgplayer-volume"))&&(r=a.querySelector(".xgplayer-slider"),o=a.querySelector(".xgplayer-bar"),l=a.querySelector(".xgplayer-drag"),"mobile"===i.default.sniffer.device&&g()))}function u(t){e.video.muted=!1,r.focus(),n.event(t);var a=o.getBoundingClientRect(),i=(t.clientX,t.clientY),s=l.getBoundingClientRect().height,u=!1,c=function(t){t.preventDefault(),t.stopPropagation(),n.event(t),u=!0;var r=s-t.clientY+i,o=r/a.height;l.style.height=r+"px",e.volume=Math.max(Math.min(o,1),0)},p=function t(i){if(i.preventDefault(),i.stopPropagation(),n.event(i),window.removeEventListener("mousemove",c),window.removeEventListener("touchmove",c),window.removeEventListener("mouseup",t),window.removeEventListener("touchend",t),!u){var o=a.height-(i.clientY-a.top),s=o/a.height;l.style.height=o+"px",s<=0&&(e.volume>0?l.volume=e.video.volume:s=l.volume),e.volume=Math.max(Math.min(s,1),0)}r.volume=e.volume,u=!1};return window.addEventListener("mousemove",c),window.addEventListener("touchmove",c),window.addEventListener("mouseup",p),window.addEventListener("touchend",p),!1}function c(){"mobile"===i.default.sniffer.device?e.video.muted?(e.video.muted=!1,e.emit("unmute"),e.volume=1):(e.video.muted=!0,e.emit("mute"),e.volume=0):(e.video.muted=!1,e.volume<.1?(r.volume<.1?e.volume=.6:e.volume=r.volume,e.emit("unmute")):(e.volume=0,e.emit("mute")))}function p(){n.addClass(t,"xgplayer-volume-active"),a&&a.focus()}function d(){n.removeClass(t,"xgplayer-volume-active")}e.once("canplay",s),e.on("volumeBarClick",u),e.on("volumeIconClick",c),e.on("volumeIconEnter",p),e.on("volumeIconLeave",d);var f=null;function g(){f&&clearTimeout(f),f=setTimeout((function(){if("mobile"===i.default.sniffer.device)n.removeClass(t,"xgplayer-volume-muted"),n.removeClass(t,"xgplayer-volume-large"),e.video.muted||e.video.defaultMuted?(e.video.muted||(e.video.muted=!0),e.video.defaultMuted=!1,n.addClass(t,"xgplayer-volume-muted")):n.addClass(t,"xgplayer-volume-large");else{if(n.removeClass(t,"xgplayer-volume-muted"),n.removeClass(t,"xgplayer-volume-small"),n.removeClass(t,"xgplayer-volume-large"),0===e.volume?n.addClass(t,"xgplayer-volume-muted"):e.volume<.5?n.addClass(t,"xgplayer-volume-small"):n.addClass(t,"xgplayer-volume-large"),!o)return;var a=o.getBoundingClientRect().height||76;l.style.height=e.volume*a+"px"}}),50)}e.on("volumechange",g),e.once("destroy",(function t(){e.off("canplay",s),e.off("volumeBarClick",u),e.off("volumeIconClick",c),e.off("volumeIconEnter",p),e.off("volumeIconLeave",d),e.off("volumechange",g),e.off("destroy",t),f&&(clearTimeout(f),f=null)}))}))},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("start",(function(){var e=this,t=e.root,n=i.default.util;function a(){if(n.hasClass(t,"xgplayer-nostart")){n.removeClass(t,"xgplayer-nostart"),n.addClass(t,"xgplayer-is-enter"),t.querySelector("video")||e.start();var a=e.play();void 0!==a&&a&&a.catch((function(e){}))}else e.paused&&(n.removeClass(t,"xgplayer-nostart xgplayer-isloading"),setTimeout((function(){var t=e.play();void 0!==t&&t&&t.catch((function(e){}))}),10))}e.on("startBtnClick",a),e.once("destroy",(function t(){e.off("startBtnClick",a),e.off("destroy",t)}))}))},function(e,t,n){"use strict";var a,r=n(0);((a=r)&&a.__esModule?a:{default:a}).default.install("screenShot",(function(){var e=this,t=(e.root,e.config.screenShot);if(t){var n=.92;(t.quality||0===t.quality)&&(n=t.quality);var a=void 0===t.type?"image/png":t.type,r=void 0===t.format?".png":t.format,i=document.createElement("canvas"),o=i.getContext("2d"),l=new Image;i.width=this.config.width||600,i.height=this.config.height||337.5;var s=function(e,t){var n=document.createElement("a");n.href=e,n.download=t;var a=document.createEvent("MouseEvents");a.initMouseEvent("click",!0,!1,window,0,0,0,0,0,!1,!1,!1,!1,0,null),n.dispatchEvent(a)};e.on("screenShotBtnClick",u),e.once("destroy",(function t(){e.off("screenShotBtnClick",u),e.off("destroy",t)}))}function u(){var t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];i.width=e.video.videoWidth||600,i.height=e.video.videoHeight||337.5,l.onload=function(){o.drawImage(e.video,0,0,i.width,i.height),l.setAttribute("crossOrigin","anonymous"),l.src=i.toDataURL(a,n).replace(a,"image/octet-stream");var u=l.src.replace(/^data:image\/[^;]+/,"data:application/octet-stream");e.emit("screenShot",u),t&&s(u,"截图"+r)}()}}))},function(e,t,n){"use strict";var a,r=n(0);((a=r)&&a.__esModule?a:{default:a}).default.install("rotate",(function(){var e=this,t=e.config.rotate;function n(){e.rotate(t.clockwise,t.innerRotate)}t&&(e.on("rotateBtnClick",n),e.once("destroy",(function t(){e.off("rotateBtnClick",n),e.off("destroy",t)})))}))},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("replay",(function(){var e=this,t=i.default.util,n=e.root;function a(){t.removeClass(n,"replay"),e.replay()}e.on("replayBtnClick",a),e.on("ended",(function(){e.config.loop||t.addClass(n,"replay")})),e.once("destroy",(function t(){e.off("replayBtnClick",a),e.off("destroy",t)}))}))},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("reload",(function(){var e=this;function t(){i.default.util.removeClass(e.root,"xgplayer-is-error"),e.src=e.config.url}e.config.reload&&(e.on("reloadBtnClick",t),e.once("destroy",(function n(){e.off("reloadBtnClick",t),e.off("destroy",n)})))}))},function(e,t,n){"use strict";var a,r=n(0);((a=r)&&a.__esModule?a:{default:a}).default.install("playNext",(function(){var e=this,t=e.config.playNext;function n(){e.currentVideoIndex+1<t.urlList.length&&(e.currentVideoIndex++,e.video.autoplay=!0,e.src=t.urlList[e.currentVideoIndex],e.emit("playerNext",e.currentVideoIndex+1),e.currentVideoIndex+1===t.urlList.length&&e.emit("urlListEnd"))}e.currentVideoIndex=-1,e.on("playNextBtnClick",n),e.once("destroy",(function t(){e.off("playNextBtnClick",n),e.off("destroy",t)}))}))},function(e,t,n){"use strict";var a,r=n(0);((a=r)&&a.__esModule?a:{default:a}).default.install("play",(function(){var e=this;function t(){if(e.config.allowPlayAfterEnded||!e.ended)if(e.paused){var t=e.play();void 0!==t&&t&&t.catch((function(e){}))}else e.pause()}e.on("playBtnClick",t),e.once("destroy",(function n(){e.off("playBtnClick",t),e.off("destroy",n)}))}))},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("pip",(function(){var e=this,t=i.default.util,n=e.root;function a(){t.hasClass(n,"xgplayer-pip-active")?e.exitPIP():e.getPIP()}e.on("pipBtnClick",a),e.once("destroy",(function t(){e.off("pipBtnClick",a),e.off("destroy",t)}))}))},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("pc",(function(){var e=this,t=i.default.util,n=e.controls,a=e.root,r=0,o=void 0;function l(){clearTimeout(e.leavePlayerTimer),e.emit("focus",e)}function s(){e.config.closePlayerBlur||(e.leavePlayerTimer=setTimeout((function(){e.emit("blur",e)}),e.config.leavePlayerTime||0))}function u(t){e.config.autoplay&&e.start()}e.onElementClick=function(e,n){e.preventDefault(),this.config.closeVideoStopPropagation||e.stopPropagation();var a=this;a.config.closeVideoClick||(r++,o&&clearTimeout(o),1===r?o=setTimeout((function(){if(t.hasClass(a.root,"xgplayer-nostart"))return!1;if(!a.ended)if(a.paused){var e=a.play();void 0!==e&&e&&e.catch((function(e){}))}else a.pause();r=0}),200):r=0)},e.video.addEventListener("click",(function(t){e.onElementClick(t,e.video)}),!1),e.onElementDblclick=function(e,t){e.preventDefault(),e.stopPropagation();if(!this.config.closeVideoDblclick){var a=n.querySelector(".xgplayer-fullscreen");if(a){var r=void 0;document.createEvent?(r=document.createEvent("Event")).initEvent("click",!0,!0):r=new Event("click"),a.dispatchEvent(r)}}},e.video.addEventListener("dblclick",(function(t){e.onElementDblclick(t,e.video)}),!1),a.addEventListener("mouseenter",l),a.addEventListener("mouseleave",s),n.addEventListener("mouseenter",(function(t){e.userTimer&&clearTimeout(e.userTimer)}),!1),n.addEventListener("mouseleave",(function(t){e.config.closeControlsBlur||e.emit("focus",e)}),!1),e.once("ready",u),e.once("destroy",(function t(){a.removeEventListener("mouseenter",l),a.removeEventListener("mouseleave",s),e.off("ready",u),e.off("destroy",t)}))}))},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("mobile",(function(){var e=this,t=i.default.util,n=(e.controls,e.root);function a(t){e.video.addEventListener("touchend",(function(t){e.onElementTouchend(t,e.video)})),e.video.addEventListener("touchstart",(function(){e.isTouchMove=!1})),e.video.addEventListener("touchmove",(function(){e.isTouchMove=!0})),e.config.autoplay&&e.start()}e.onElementTouchend=function(e,a){e.preventDefault(),e.stopPropagation();if(t.hasClass(n,"xgplayer-inactive")?this.emit("focus"):this.emit("blur"),!this.config.closeVideoTouch&&!this.isTouchMove){if(t.hasClass(this.root,"xgplayer-nostart"))return!1;if(!this.ended)if(this.paused){var r=this.play();void 0!==r&&r&&r.catch((function(e){}))}else this.pause()}},e.once("ready",a),e.once("destroy",(function t(){e.off("ready",a),e.off("destroy",t)}))}))},function(e,t,n){"use strict";var a,r=n(0);((a=r)&&a.__esModule?a:{default:a}).default.install("memoryPlay",(function(){var e=this;e.on("memoryPlayStart",(function(t){e.currentTime=t}))}))},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("localPreview",(function(){var e=this,t=e.root;function n(n){e.uploadFile=n.files[0];var a=URL.createObjectURL(e.uploadFile);if(i.default.util.hasClass(t,"xgplayer-nostart"))e.config.url=a,e.start();else{e.src=a;var r=e.play();void 0!==r&&r&&r.catch((function(e){}))}}e.on("upload",n),e.once("destroy",(function t(){e.off("upload",n),e.off("destroy",t)}))}))},function(e,t,n){"use strict";var a,r=n(0);((a=r)&&a.__esModule?a:{default:a}).default.install("i18n",(function(){var e=this,t={},n=e.constructor.util;t.en={HAVE_NOTHING:"There is no information on whether audio/video is ready",HAVE_METADATA:"Audio/video metadata is ready ",HAVE_CURRENT_DATA:"Data about the current play location is available, but there is not enough data to play the next frame/millisecond",HAVE_FUTURE_DATA:"Current and at least one frame of data is available",HAVE_ENOUGH_DATA:"The available data is sufficient to start playing",NETWORK_EMPTY:"Audio/video has not been initialized",NETWORK_IDLE:"Audio/video is active and has been selected for resources, but no network is used",NETWORK_LOADING:"The browser is downloading the data",NETWORK_NO_SOURCE:"No audio/video source was found",MEDIA_ERR_ABORTED:"The fetch process is aborted by the user",MEDIA_ERR_NETWORK:"An error occurred while downloading",MEDIA_ERR_DECODE:"An error occurred while decoding",MEDIA_ERR_SRC_NOT_SUPPORTED:"Audio/video is not supported",REPLAY:"Replay",ERROR:"Network is offline",PLAY_TIPS:"Play",PAUSE_TIPS:"Pause",PLAYNEXT_TIPS:"Play next",DOWNLOAD_TIPS:"Download",ROTATE_TIPS:"Rotate",RELOAD_TIPS:"Reload",FULLSCREEN_TIPS:"Fullscreen",EXITFULLSCREEN_TIPS:"Exit fullscreen",CSSFULLSCREEN_TIPS:"Cssfullscreen",EXITCSSFULLSCREEN_TIPS:"Exit cssfullscreen",TEXTTRACK:"Caption",PIP:"Pip",SCREENSHOT:"Screenshot",LIVE:"LIVE",OFF:"Off",PIP_DRAG:"Click and hold to drag"},t["zh-cn"]={HAVE_NOTHING:"没有关于音频/视频是否就绪的信息",HAVE_METADATA:"音频/视频的元数据已就绪",HAVE_CURRENT_DATA:"关于当前播放位置的数据是可用的,但没有足够的数据来播放下一帧/毫秒",HAVE_FUTURE_DATA:"当前及至少下一帧的数据是可用的",HAVE_ENOUGH_DATA:"可用数据足以开始播放",NETWORK_EMPTY:"音频/视频尚未初始化",NETWORK_IDLE:"音频/视频是活动的且已选取资源,但并未使用网络",NETWORK_LOADING:"浏览器正在下载数据",NETWORK_NO_SOURCE:"未找到音频/视频来源",MEDIA_ERR_ABORTED:"取回过程被用户中止",MEDIA_ERR_NETWORK:"当下载时发生错误",MEDIA_ERR_DECODE:"当解码时发生错误",MEDIA_ERR_SRC_NOT_SUPPORTED:"不支持的音频/视频格式",REPLAY:"重播",ERROR:"网络连接似乎出现了问题",PLAY_TIPS:"播放",PAUSE_TIPS:"暂停",PLAYNEXT_TIPS:"下一集",DOWNLOAD_TIPS:"下载",ROTATE_TIPS:"旋转",RELOAD_TIPS:"重新载入",FULLSCREEN_TIPS:"进入全屏",EXITFULLSCREEN_TIPS:"退出全屏",CSSFULLSCREEN_TIPS:"进入样式全屏",EXITCSSFULLSCREEN_TIPS:"退出样式全屏",TEXTTRACK:"字幕",PIP:"画中画",SCREENSHOT:"截图",LIVE:"正在直播",OFF:"关闭",PIP_DRAG:"点击按住可拖动视频"},t["zh-hk"]={HAVE_NOTHING:"沒有關於音頻/視頻是否就緒的信息",HAVE_METADATA:"音頻/視頻的元數據已就緒",HAVE_CURRENT_DATA:"關於當前播放位置的數據是可用的,但沒有足夠的數據來播放下壹幀/毫秒",HAVE_FUTURE_DATA:"當前及至少下壹幀的數據是可用的",HAVE_ENOUGH_DATA:"可用數據足以開始播放",NETWORK_EMPTY:"音頻/視頻尚未初始化",NETWORK_IDLE:"音頻/視頻是活動的且已選取資源,但並未使用網絡",NETWORK_LOADING:"瀏覽器正在下載數據",NETWORK_NO_SOURCE:"未找到音頻/視頻來源",MEDIA_ERR_ABORTED:"取回過程被用戶中止",MEDIA_ERR_NETWORK:"當下載時發生錯誤",MEDIA_ERR_DECODE:"當解碼時發生錯誤",MEDIA_ERR_SRC_NOT_SUPPORTED:"不支持的音頻/視頻格式",REPLAY:"重播",ERROR:"網絡連接似乎出現了問題",PLAY_TIPS:"播放",PAUSE_TIPS:"暫停",PLAYNEXT_TIPS:"下壹集",DOWNLOAD_TIPS:"下載",ROTATE_TIPS:"旋轉",RELOAD_TIPS:"重新載入",FULLSCREEN_TIPS:"進入全屏",EXITFULLSCREEN_TIPS:"退出全屏",CSSFULLSCREEN_TIPS:"進入樣式全屏",EXITCSSFULLSCREEN_TIPS:"退出樣式全屏",TEXTTRACK:"字幕",PIP:"畫中畫",SCREENSHOT:"截圖",LIVE:"正在直播",OFF:"關閉",PIP_DRAG:"點擊按住可拖動視頻"},t.jp={HAVE_NOTHING:"オーディオ/ビデオが準備できているか情報がありません",HAVE_METADATA:"オーディオ/ビデオのメタデータは準備できています",HAVE_CURRENT_DATA:"現在の再生位置に関するデータは利用可能ですが、次のフレーム/ミリ秒を再生するのに十分なデータがありません",HAVE_FUTURE_DATA:"現在、少なくとも次のフレームのデータが利用可能です",HAVE_ENOUGH_DATA:"利用可能なデータは再生を開始するのに十分です",NETWORK_EMPTY:"オーディオ/ビデオが初期化されていません",NETWORK_IDLE:"オーディオ/ビデオはアクティブでリソースが選択されていますが、ネットワークが使用されていません",NETWORK_LOADING:"ブラウザーはデータをダウンロードしています",NETWORK_NO_SOURCE:"オーディオ/ビデオ のソースが見つかりません",MEDIA_ERR_ABORTED:"ユーザーによってフェッチプロセスが中止されました",MEDIA_ERR_NETWORK:"ダウンロード中にエラーが発生しました",MEDIA_ERR_DECODE:"デコード中にエラーが発生しました",MEDIA_ERR_SRC_NOT_SUPPORTED:"オーディオ/ビデオ の形式がサポートされていません",REPLAY:"リプレイ",ERROR:"ネットワークの接続に問題が発生しました",PLAY_TIPS:"プレイ",PAUSE_TIPS:"一時停止",PLAYNEXT_TIPS:"次をプレイ",DOWNLOAD_TIPS:"ダウンロード",ROTATE_TIPS:"回転",RELOAD_TIPS:"再読み込み",FULLSCREEN_TIPS:"フルスクリーン",EXITFULLSCREEN_TIPS:"フルスクリーンを終了",CSSFULLSCREEN_TIPS:"シアターモード",EXITCSSFULLSCREEN_TIPS:"シアターモードを終了",TEXTTRACK:"字幕",PIP:"ミニプレーヤー",SCREENSHOT:"スクリーンショット",LIVE:"生放送",OFF:"オフ",PIP_DRAG:"ボタンを押して働画をドラッグする"},Object.defineProperty(e,"lang",{get:function(){return e.config&&t[e.config.lang]||t.en},set:function(e){"Object"===n.typeOf(e)&&Object.keys(e).forEach((function(n){t[n]=e[n]}))}})}))},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("fullscreen",(function(){var e=this,t=e.root,n=i.default.util;function a(){e.config.rotateFullscreen?n.hasClass(t,"xgplayer-rotate-fullscreen")?e.exitRotateFullscreen():e.getRotateFullscreen():n.hasClass(t,"xgplayer-is-fullscreen")?e.exitFullscreen(t):e.getFullscreen(t)}function r(){var a=document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement;a&&a===t?(n.addClass(t,"xgplayer-is-fullscreen"),e.emit("requestFullscreen")):n.hasClass(t,"xgplayer-is-fullscreen")&&(n.removeClass(t,"xgplayer-is-fullscreen"),e.emit("exitFullscreen")),e.danmu&&"function"==typeof e.danmu.resize&&e.danmu.resize()}e.on("fullscreenBtnClick",a),["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"].forEach((function(e){document.addEventListener(e,r)})),e.once("destroy",(function t(){e.off("fullscreenBtnClick",a),["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"].forEach((function(e){document.removeEventListener(e,r)})),e.off("destroy",t)}))}))},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};var o={maxCount:3,backupUrl:"",isFetch:!0,fetchTimeout:100};i.default.install("errorretry",(function(){var e=this,t=this;if(t.config.errorConfig&&!(t.src.indexOf("blob:")>-1)){var n={},a=t.config.errorConfig;for(var r in o)void 0===a[r]?n[r]=o[r]:n[r]=a[r];t.retryData={count:0,errfTimer:null,isFetchReturn:!1,currentTime:0};var l=t._onError;t._onError=function(a){var r=e.retryData.count;if(r>n.maxCount)n.isFetch?function(e,t,n){var a=function(t,n){e.retryData.isFetchReturn||(e.retryData.isFetchReturn=!0,t(n))};return new Promise((function(r,i){try{var o=new window.XMLHttpRequest;o.open("get",t),o.onload=function(){a(r,{status:o.status,statusText:o.statusText,xhr:o})},o.onerror=function(){a(r,{status:o.status,statusText:o.statusText||"The network environment is disconnected or the address is invalid",xhr:o})},o.onabort=function(){},e.retryData.errfTimer=window.setTimeout((function(){var t=e.retryData.errfTimer;window.clearTimeout(t),e.retryData.errfTimer=null,a(r,{status:-1,statusText:"request timeout"})}),n),o.send()}catch(t){e.retryData.isFetchReturn=!0,a(r,{status:-2,statusText:"request error"})}}))}(e,e.currentSrc,n.fetchTimeout).then((function(t){e.emit("error",new i.default.Errors({type:"network",currentTime:e.currentTime,duration:e.duration||0,networkState:e.networkState,readyState:e.readyState,currentSrc:e.currentSrc,src:e.src,ended:e.ended,httpCode:t.status,httpMsg:t.statusText,errd:{line:101,msg:e.error,handle:"plugin errorRetry"},errorCode:e.video&&e.video.error.code,mediaError:e.video&&e.video.error})),l.call(e,t)})):l.call(e,a);else{0===r&&(e.retryData.currentTime=e.currentTime,e.once("canplay",s.bind(e)));var o="";o=n.count<2?n.backupUrl?n.backupUrl:t.currentSrc:n.backupUrl&&r>1?n.backupUrl:t.currentSrc,e.retryData.count++,e.src=o}}}function s(){this.currentTime=this.retryData.currentTime,this.play(),this.retryData.retryCode=0,this.retryData.isFetchReturn=!1,this.retryData.currentTime=0}}))},function(e,t,n){"use strict";var a,r=n(0);((a=r)&&a.__esModule?a:{default:a}).default.install("download",(function(){var e=this;function t(){e.download()}e.on("downloadBtnClick",t),e.once("destroy",(function n(){e.off("downloadBtnClick",t),e.off("destroy",n)}))}))},function(e,t,n){"use strict";var a,r=n(0);((a=r)&&a.__esModule?a:{default:a}).default.install("definition",(function(){var e=this;e.root;e.once("destroy",(function t(){e.off("destroy",t)}))}))},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("danmu",(function(){var e=this,t=(e.root,i.default.util);e.on("initDefaultDanmu",(function(n){var a=e.root.querySelector("xg-danmu");if(t.addClass(a,"xgplayer-has-danmu"),!e.config.danmu.closeDefaultBtn){var r=function(){n.start()},i=function(){t.hasClass(e.danmuBtn,"danmu-switch-active")&&n.pause()},o=function(){t.hasClass(e.danmuBtn,"danmu-switch-active")&&n.play()},l=function(){t.hasClass(e.danmuBtn,"danmu-switch-active")&&(n.stop(),n.start())};e.danmuBtn=t.copyDom(n.bulletBtn.createSwitch(!0)),e.controls.appendChild(e.danmuBtn),["click","touchend"].forEach((function(i){e.danmuBtn.addEventListener(i,(function(i){i.preventDefault(),i.stopPropagation(),t.toggleClass(e.danmuBtn,"danmu-switch-active"),t.hasClass(e.danmuBtn,"danmu-switch-active")?(e.emit("danmuBtnOn"),t.addClass(a,"xgplayer-has-danmu"),e.once("timeupdate",r)):(e.emit("danmuBtnOff"),t.removeClass(a,"xgplayer-has-danmu"),n.stop())}))})),e.onElementClick&&a.addEventListener("click",(function(t){e.onElementClick(t,a)}),!1),e.onElementDblclick&&a.addEventListener("dblclick",(function(t){e.onElementDblclick(t,a)}),!1),e.on("pause",i),e.on("play",o),e.on("seeked",l),e.once("destroy",(function t(){e.off("timeupdate",r),e.off("pause",i),e.off("play",o),e.off("seeked",l),e.off("destroy",t)}))}}))}))},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("cssFullscreen",(function(){var e=this,t=e.root,n=i.default.util;function a(){n.hasClass(t,"xgplayer-is-cssfullscreen")?e.exitCssFullscreen():e.getCssFullscreen()}e.on("cssFullscreenBtnClick",a),e.on("exitFullscreen",(function(){n.removeClass(t,"xgplayer-is-cssfullscreen")})),e.once("destroy",(function t(){e.off("cssFullscreenBtnClick",a),e.off("destroy",t)}))}))},function(e,t,n){"use strict";n(58),n(63),n(64),n(67),n(70),n(71),n(72),n(75),n(78),n(82),n(83),n(85),n(86),n(87),n(89),n(90),n(91),n(93),n(97),n(98),n(100),n(102),n(104),n(105),n(106),n(107)},function(e,t,n){var a=n(59);"string"==typeof a&&(a=[[e.i,a,""]]);var r={hmr:!0,transform:void 0,insertInto:void 0};n(61)(a,r);a.locals&&(e.exports=a.locals)},function(e,t,n){(e.exports=n(60)(!1)).push([e.i,'.xgplayer-skin-default{background:#000;width:100%;height:100%;position:relative;-webkit-user-select:none;-moz-user-select:none;user-select:none;-ms-user-select:none}.xgplayer-skin-default *{margin:0;padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline}.xgplayer-skin-default.xgplayer-rotate-fullscreen{position:absolute;top:0;left:100%;bottom:0;right:0;height:100vw!important;width:100vh!important;-webkit-transform-origin:top left;-ms-transform-origin:top left;transform-origin:top left;-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.xgplayer-skin-default.xgplayer-is-fullscreen{width:100%!important;height:100%!important;padding-top:0!important;z-index:9999}.xgplayer-skin-default.xgplayer-is-fullscreen.xgplayer-inactive{cursor:none}.xgplayer-skin-default video{width:100%;height:100%;outline:none}.xgplayer-skin-default .xgplayer-none{display:none}@-webkit-keyframes loadingRotate{0%{-webkit-transform:rotate(0);transform:rotate(0)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes loadingRotate{0%{-webkit-transform:rotate(0);transform:rotate(0)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@-webkit-keyframes loadingDashOffset{0%{stroke-dashoffset:236}to{stroke-dashoffset:0}}@keyframes loadingDashOffset{0%{stroke-dashoffset:236}to{stroke-dashoffset:0}}.xgplayer-skin-default .xgplayer-play,.xgplayer-skin-default .xgplayer-play-img{width:40px;position:relative;-webkit-order:0;-moz-box-ordinal-group:1;order:0;display:block;cursor:pointer;margin-left:3px}.xgplayer-skin-default .xgplayer-play-img .xgplayer-icon,.xgplayer-skin-default .xgplayer-play .xgplayer-icon{margin-top:3px;width:32px}.xgplayer-skin-default .xgplayer-play-img .xgplayer-icon div,.xgplayer-skin-default .xgplayer-play .xgplayer-icon div{position:absolute}.xgplayer-skin-default .xgplayer-play-img .xgplayer-icon .xgplayer-icon-play,.xgplayer-skin-default .xgplayer-play .xgplayer-icon .xgplayer-icon-play{display:block}.xgplayer-skin-default .xgplayer-play-img .xgplayer-icon .xgplayer-icon-pause,.xgplayer-skin-default .xgplayer-play .xgplayer-icon .xgplayer-icon-pause{display:none}.xgplayer-skin-default .xgplayer-play-img .xgplayer-tips .xgplayer-tip-play,.xgplayer-skin-default .xgplayer-play .xgplayer-tips .xgplayer-tip-play{display:block}.xgplayer-skin-default .xgplayer-play-img .xgplayer-tips .xgplayer-tip-pause,.xgplayer-skin-default .xgplayer-play .xgplayer-tips .xgplayer-tip-pause{display:none}.xgplayer-skin-default .xgplayer-play-img:hover,.xgplayer-skin-default .xgplayer-play:hover{opacity:.85}.xgplayer-skin-default .xgplayer-play-img:hover .xgplayer-tips,.xgplayer-skin-default .xgplayer-play:hover .xgplayer-tips{display:block}.xgplayer-skin-default.xgplayer-playing .xgplayer-play-img .xgplayer-icon .xgplayer-icon-play,.xgplayer-skin-default.xgplayer-playing .xgplayer-play .xgplayer-icon .xgplayer-icon-play{display:none}.xgplayer-skin-default.xgplayer-playing .xgplayer-play-img .xgplayer-icon .xgplayer-icon-pause,.xgplayer-skin-default.xgplayer-playing .xgplayer-play .xgplayer-icon .xgplayer-icon-pause{display:block}.xgplayer-skin-default.xgplayer-playing .xgplayer-play-img .xgplayer-tips .xgplayer-tip-play,.xgplayer-skin-default.xgplayer-playing .xgplayer-play .xgplayer-tips .xgplayer-tip-play{display:none}.xgplayer-skin-default.xgplayer-pause .xgplayer-play-img .xgplayer-icon .xgplayer-icon-play,.xgplayer-skin-default.xgplayer-pause .xgplayer-play .xgplayer-icon .xgplayer-icon-play,.xgplayer-skin-default.xgplayer-playing .xgplayer-play-img .xgplayer-tips .xgplayer-tip-pause,.xgplayer-skin-default.xgplayer-playing .xgplayer-play .xgplayer-tips .xgplayer-tip-pause{display:block}.xgplayer-skin-default.xgplayer-pause .xgplayer-play-img .xgplayer-icon .xgplayer-icon-pause,.xgplayer-skin-default.xgplayer-pause .xgplayer-play .xgplayer-icon .xgplayer-icon-pause{display:none}.xgplayer-skin-default.xgplayer-pause .xgplayer-play-img .xgplayer-tips .xgplayer-tip-play,.xgplayer-skin-default.xgplayer-pause .xgplayer-play .xgplayer-tips .xgplayer-tip-play{display:block}.xgplayer-skin-default.xgplayer-pause .xgplayer-play-img .xgplayer-tips .xgplayer-tip-pause,.xgplayer-skin-default.xgplayer-pause .xgplayer-play .xgplayer-tips .xgplayer-tip-pause{display:none}.xgplayer-skin-default .xgplayer-start{border-radius:50%;display:inline-block;width:70px;height:70px;background:rgba(0,0,0,.38);overflow:hidden;text-align:center;line-height:70px;vertical-align:middle;position:absolute;left:50%;top:50%;z-index:115;margin:-35px auto auto -35px;cursor:pointer}.xgplayer-skin-default .xgplayer-start div{position:absolute}.xgplayer-skin-default .xgplayer-start div svg{fill:hsla(0,0%,100%,.7)}.xgplayer-skin-default .xgplayer-start .xgplayer-icon-play{display:block}.xgplayer-skin-default .xgplayer-start .xgplayer-icon-pause{display:none}.xgplayer-skin-default .xgplayer-start:hover{opacity:.85}.xgplayer-skin-default.xgplayer-playing .xgplayer-start,.xgplayer-skin-default.xgplayer-playing .xgplayer-start .xgplayer-icon-play{display:none}.xgplayer-skin-default.xgplayer-playing .xgplayer-start .xgplayer-icon-pause{display:block}.xgplayer-skin-default.xgplayer-pause .xgplayer-start{display:inline-block}.xgplayer-skin-default.xgplayer-pause .xgplayer-start .xgplayer-icon-play{display:block}.xgplayer-skin-default.replay .xgplayer-start,.xgplayer-skin-default.xgplayer-pause .xgplayer-start .xgplayer-icon-pause{display:none}.xgplayer-skin-default.replay .xgplayer-start .xgplayer-icon-play{display:block}.xgplayer-skin-default.replay .xgplayer-start .xgplayer-icon-pause{display:none}.xgplayer-skin-default .xgplayer-enter{display:none;position:absolute;left:0;top:0;width:100%;height:100%;background:#000;z-index:120}.xgplayer-skin-default .xgplayer-enter .xgplayer-enter-spinner{display:block;position:absolute;left:50%;top:50%;height:100px;width:100px;position:relative;-webkit-transform:translate(-50%,-50%);-ms-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}.xgplayer-skin-default .xgplayer-enter .xgplayer-enter-spinner div{width:12%;height:26%;background-color:hsla(0,0%,100%,.7);position:absolute;left:44%;top:37%;opacity:0;border-radius:30px;-webkit-animation:fade 1s linear infinite;animation:fade 1s linear infinite}.xgplayer-skin-default .xgplayer-enter .xgplayer-enter-spinner div.xgplayer-enter-bar1{-webkit-transform:rotate(0deg) translateY(-142%);-ms-transform:rotate(0deg) translateY(-142%);transform:rotate(0deg) translateY(-142%);-webkit-animation-delay:0s;animation-delay:0s}.xgplayer-skin-default .xgplayer-enter .xgplayer-enter-spinner div.xgplayer-enter-bar2{-webkit-transform:rotate(30deg) translateY(-142%);-ms-transform:rotate(30deg) translateY(-142%);transform:rotate(30deg) translateY(-142%);-webkit-animation-delay:-.9163s;animation-delay:-.9163s}.xgplayer-skin-default .xgplayer-enter .xgplayer-enter-spinner div.xgplayer-enter-bar3{-webkit-transform:rotate(60deg) translateY(-142%);-ms-transform:rotate(60deg) translateY(-142%);transform:rotate(60deg) translateY(-142%);-webkit-animation-delay:-.833s;animation-delay:-.833s}.xgplayer-skin-default .xgplayer-enter .xgplayer-enter-spinner div.xgplayer-enter-bar4{-webkit-transform:rotate(90deg) translateY(-142%);-ms-transform:rotate(90deg) translateY(-142%);transform:rotate(90deg) translateY(-142%);-webkit-animation-delay:-.7497s;animation-delay:-.7497s}.xgplayer-skin-default .xgplayer-enter .xgplayer-enter-spinner div.xgplayer-enter-bar5{-webkit-transform:rotate(120deg) translateY(-142%);-ms-transform:rotate(120deg) translateY(-142%);transform:rotate(120deg) translateY(-142%);-webkit-animation-delay:-.6664s;animation-delay:-.6664s}.xgplayer-skin-default .xgplayer-enter .xgplayer-enter-spinner div.xgplayer-enter-bar6{-webkit-transform:rotate(150deg) translateY(-142%);-ms-transform:rotate(150deg) translateY(-142%);transform:rotate(150deg) translateY(-142%);-webkit-animation-delay:-.5831s;animation-delay:-.5831s}.xgplayer-skin-default .xgplayer-enter .xgplayer-enter-spinner div.xgplayer-enter-bar7{-webkit-transform:rotate(180deg) translateY(-142%);-ms-transform:rotate(180deg) translateY(-142%);transform:rotate(180deg) translateY(-142%);-webkit-animation-delay:-.4998s;animation-delay:-.4998s}.xgplayer-skin-default .xgplayer-enter .xgplayer-enter-spinner div.xgplayer-enter-bar8{-webkit-transform:rotate(210deg) translateY(-142%);-ms-transform:rotate(210deg) translateY(-142%);transform:rotate(210deg) translateY(-142%);-webkit-animation-delay:-.4165s;animation-delay:-.4165s}.xgplayer-skin-default .xgplayer-enter .xgplayer-enter-spinner div.xgplayer-enter-bar9{-webkit-transform:rotate(240deg) translateY(-142%);-ms-transform:rotate(240deg) translateY(-142%);transform:rotate(240deg) translateY(-142%);-webkit-animation-delay:-.3332s;animation-delay:-.3332s}.xgplayer-skin-default .xgplayer-enter .xgplayer-enter-spinner div.xgplayer-enter-bar10{-webkit-transform:rotate(270deg) translateY(-142%);-ms-transform:rotate(270deg) translateY(-142%);transform:rotate(270deg) translateY(-142%);-webkit-animation-delay:-.2499s;animation-delay:-.2499s}.xgplayer-skin-default .xgplayer-enter .xgplayer-enter-spinner div.xgplayer-enter-bar11{-webkit-transform:rotate(300deg) translateY(-142%);-ms-transform:rotate(300deg) translateY(-142%);transform:rotate(300deg) translateY(-142%);-webkit-animation-delay:-.1666s;animation-delay:-.1666s}.xgplayer-skin-default .xgplayer-enter .xgplayer-enter-spinner div.xgplayer-enter-bar12{-webkit-transform:rotate(330deg) translateY(-142%);-ms-transform:rotate(330deg) translateY(-142%);transform:rotate(330deg) translateY(-142%);-webkit-animation-delay:-.0833s;animation-delay:-.0833s}@-webkit-keyframes fade{0%{opacity:1}to{opacity:.25}}@keyframes fade{0%{opacity:1}to{opacity:.25}}.xgplayer-skin-default.xgplayer-is-enter .xgplayer-enter{display:block}.xgplayer-skin-default .xgplayer-poster{display:none;position:absolute;left:0;top:0;width:100%;height:100%;z-index:100;background-size:cover;background-position:50%}.xgplayer-skin-default.xgplayer-nostart .xgplayer-poster{display:block}.xgplayer-skin-default .xgplayer-placeholder{-webkit-flex:1;-moz-box-flex:1;flex:1;-webkit-order:3;-moz-box-ordinal-group:4;order:3;display:block}.xgplayer-skin-default .xgplayer-fullscreen,.xgplayer-skin-default .xgplayer-fullscreen-img{position:relative;-webkit-order:13;-moz-box-ordinal-group:14;order:13;display:block;cursor:pointer;margin-left:5px;margin-right:3px}.xgplayer-skin-default .xgplayer-fullscreen-img .xgplayer-icon,.xgplayer-skin-default .xgplayer-fullscreen .xgplayer-icon{margin-top:3px}.xgplayer-skin-default .xgplayer-fullscreen-img .xgplayer-icon div,.xgplayer-skin-default .xgplayer-fullscreen .xgplayer-icon div{position:absolute}.xgplayer-skin-default .xgplayer-fullscreen-img .xgplayer-icon .xgplayer-icon-requestfull,.xgplayer-skin-default .xgplayer-fullscreen .xgplayer-icon .xgplayer-icon-requestfull{display:block}.xgplayer-skin-default .xgplayer-fullscreen-img .xgplayer-icon .xgplayer-icon-exitfull,.xgplayer-skin-default .xgplayer-fullscreen .xgplayer-icon .xgplayer-icon-exitfull{display:none}.xgplayer-skin-default .xgplayer-fullscreen-img .xgplayer-tips,.xgplayer-skin-default .xgplayer-fullscreen .xgplayer-tips{position:absolute;right:0;left:auto}.xgplayer-skin-default .xgplayer-fullscreen-img .xgplayer-tips .xgplayer-tip-requestfull,.xgplayer-skin-default .xgplayer-fullscreen .xgplayer-tips .xgplayer-tip-requestfull{display:block}.xgplayer-skin-default .xgplayer-fullscreen-img .xgplayer-tips .xgplayer-tip-exitfull,.xgplayer-skin-default .xgplayer-fullscreen .xgplayer-tips .xgplayer-tip-exitfull{display:none}.xgplayer-skin-default .xgplayer-fullscreen-img:hover,.xgplayer-skin-default .xgplayer-fullscreen:hover{opacity:.85}.xgplayer-skin-default .xgplayer-fullscreen-img:hover .xgplayer-tips,.xgplayer-skin-default .xgplayer-fullscreen:hover .xgplayer-tips{display:block}.xgplayer-skin-default.xgplayer-is-fullscreen .xgplayer-fullscreen-img .xgplayer-icon .xgplayer-icon-requestfull,.xgplayer-skin-default.xgplayer-is-fullscreen .xgplayer-fullscreen .xgplayer-icon .xgplayer-icon-requestfull,.xgplayer-skin-default.xgplayer-rotate-fullscreen .xgplayer-fullscreen-img .xgplayer-icon .xgplayer-icon-requestfull,.xgplayer-skin-default.xgplayer-rotate-fullscreen .xgplayer-fullscreen .xgplayer-icon .xgplayer-icon-requestfull{display:none}.xgplayer-skin-default.xgplayer-is-fullscreen .xgplayer-fullscreen-img .xgplayer-icon .xgplayer-icon-exitfull,.xgplayer-skin-default.xgplayer-is-fullscreen .xgplayer-fullscreen .xgplayer-icon .xgplayer-icon-exitfull,.xgplayer-skin-default.xgplayer-rotate-fullscreen .xgplayer-fullscreen-img .xgplayer-icon .xgplayer-icon-exitfull,.xgplayer-skin-default.xgplayer-rotate-fullscreen .xgplayer-fullscreen .xgplayer-icon .xgplayer-icon-exitfull{display:block}.xgplayer-skin-default.xgplayer-is-fullscreen .xgplayer-fullscreen-img .xgplayer-tips .xgplayer-tip-requestfull,.xgplayer-skin-default.xgplayer-is-fullscreen .xgplayer-fullscreen .xgplayer-tips .xgplayer-tip-requestfull,.xgplayer-skin-default.xgplayer-rotate-fullscreen .xgplayer-fullscreen-img .xgplayer-tips .xgplayer-tip-requestfull,.xgplayer-skin-default.xgplayer-rotate-fullscreen .xgplayer-fullscreen .xgplayer-tips .xgplayer-tip-requestfull{display:none}.xgplayer-skin-default.xgplayer-is-fullscreen .xgplayer-fullscreen-img .xgplayer-tips .xgplayer-tip-exitfull,.xgplayer-skin-default.xgplayer-is-fullscreen .xgplayer-fullscreen .xgplayer-tips .xgplayer-tip-exitfull,.xgplayer-skin-default.xgplayer-rotate-fullscreen .xgplayer-fullscreen-img .xgplayer-tips .xgplayer-tip-exitfull,.xgplayer-skin-default.xgplayer-rotate-fullscreen .xgplayer-fullscreen .xgplayer-tips .xgplayer-tip-exitfull{display:block}.xgplayer-skin-default .xgplayer-cssfullscreen,.xgplayer-skin-default .xgplayer-cssfullscreen-img{position:relative;-webkit-order:12;-moz-box-ordinal-group:13;order:12;display:block;cursor:pointer}.xgplayer-skin-default .xgplayer-cssfullscreen-img .xgplayer-icon,.xgplayer-skin-default .xgplayer-cssfullscreen .xgplayer-icon{width:32px;margin-top:5px}.xgplayer-skin-default .xgplayer-cssfullscreen-img .xgplayer-icon div,.xgplayer-skin-default .xgplayer-cssfullscreen .xgplayer-icon div{position:absolute}.xgplayer-skin-default .xgplayer-cssfullscreen-img .xgplayer-icon .xgplayer-icon-requestfull,.xgplayer-skin-default .xgplayer-cssfullscreen .xgplayer-icon .xgplayer-icon-requestfull{display:block}.xgplayer-skin-default .xgplayer-cssfullscreen-img .xgplayer-icon .xgplayer-icon-exitfull,.xgplayer-skin-default .xgplayer-cssfullscreen .xgplayer-icon .xgplayer-icon-exitfull{display:none}.xgplayer-skin-default .xgplayer-cssfullscreen-img .xgplayer-tips,.xgplayer-skin-default .xgplayer-cssfullscreen .xgplayer-tips{margin-left:-40px}.xgplayer-skin-default .xgplayer-cssfullscreen-img .xgplayer-tips .xgplayer-tip-requestfull,.xgplayer-skin-default .xgplayer-cssfullscreen .xgplayer-tips .xgplayer-tip-requestfull{display:block}.xgplayer-skin-default .xgplayer-cssfullscreen-img .xgplayer-tips .xgplayer-tip-exitfull,.xgplayer-skin-default .xgplayer-cssfullscreen .xgplayer-tips .xgplayer-tip-exitfull{display:none}.xgplayer-skin-default .xgplayer-cssfullscreen-img:hover,.xgplayer-skin-default .xgplayer-cssfullscreen:hover{opacity:.85}.xgplayer-skin-default .xgplayer-cssfullscreen-img:hover .xgplayer-tips,.xgplayer-skin-default .xgplayer-cssfullscreen:hover .xgplayer-tips{display:block}.xgplayer-skin-default.xgplayer-is-cssfullscreen .xgplayer-cssfullscreen-img .xgplayer-icon .xgplayer-icon-requestfull,.xgplayer-skin-default.xgplayer-is-cssfullscreen .xgplayer-cssfullscreen .xgplayer-icon .xgplayer-icon-requestfull{display:none}.xgplayer-skin-default.xgplayer-is-cssfullscreen .xgplayer-cssfullscreen-img .xgplayer-icon .xgplayer-icon-exitfull,.xgplayer-skin-default.xgplayer-is-cssfullscreen .xgplayer-cssfullscreen .xgplayer-icon .xgplayer-icon-exitfull{display:block}.xgplayer-skin-default.xgplayer-is-cssfullscreen .xgplayer-cssfullscreen-img .xgplayer-tips,.xgplayer-skin-default.xgplayer-is-cssfullscreen .xgplayer-cssfullscreen .xgplayer-tips{margin-left:-47px}.xgplayer-skin-default.xgplayer-is-cssfullscreen .xgplayer-cssfullscreen-img .xgplayer-tips .xgplayer-tip-requestfull,.xgplayer-skin-default.xgplayer-is-cssfullscreen .xgplayer-cssfullscreen .xgplayer-tips .xgplayer-tip-requestfull{display:none}.xgplayer-skin-default.xgplayer-is-cssfullscreen .xgplayer-cssfullscreen-img .xgplayer-tips .xgplayer-tip-exitfull,.xgplayer-skin-default.xgplayer-is-cssfullscreen .xgplayer-cssfullscreen .xgplayer-tips .xgplayer-tip-exitfull{display:block}.xgplayer-skin-default.xgplayer-is-fullscreen .xgplayer-cssfullscreen,.xgplayer-skin-default.xgplayer-is-fullscreen .xgplayer-cssfullscreen-img{display:none}.xgplayer-skin-default.xgplayer-is-cssfullscreen{position:fixed!important;left:0!important;top:0!important;width:100%!important;height:100%!important;z-index:99999!important}.lang-is-en .xgplayer-cssfullscreen-img .xgplayer-tips,.lang-is-en .xgplayer-cssfullscreen .xgplayer-tips,.lang-is-en.xgplayer-is-cssfullscreen .xgplayer-cssfullscreen-img .xgplayer-tips,.lang-is-en.xgplayer-is-cssfullscreen .xgplayer-cssfullscreen .xgplayer-tips{margin-left:-46px}.lang-is-jp .xgplayer-cssfullscreen-img .xgplayer-tips,.lang-is-jp .xgplayer-cssfullscreen .xgplayer-tips{margin-left:-120px}.lang-is-jp.xgplayer-is-cssfullscreen .xgplayer-cssfullscreen-img .xgplayer-tips,.lang-is-jp.xgplayer-is-cssfullscreen .xgplayer-cssfullscreen .xgplayer-tips{margin-left:-60px}.xgplayer-skin-default .xgplayer-volume{outline:none;-webkit-order:4;-moz-box-ordinal-group:5;order:4;width:40px;height:40px;display:block;position:relative;z-index:18}.xgplayer-skin-default .xgplayer-volume .xgplayer-icon{margin-top:8px;cursor:pointer;position:absolute;bottom:-9px}.xgplayer-skin-default .xgplayer-volume .xgplayer-icon div{position:absolute}.xgplayer-skin-default .xgplayer-volume .xgplayer-icon .xgplayer-icon-large{display:block}.xgplayer-skin-default .xgplayer-volume .xgplayer-icon .xgplayer-icon-muted,.xgplayer-skin-default .xgplayer-volume .xgplayer-icon .xgplayer-icon-small{display:none}.xgplayer-skin-default .xgplayer-slider{display:none;position:absolute;width:28px;height:92px;background:rgba(0,0,0,.54);border-radius:1px;bottom:42px;outline:none}.xgplayer-skin-default .xgplayer-slider:after{content:" ";display:block;height:15px;width:28px;position:absolute;bottom:-15px;left:0;z-index:20}.xgplayer-skin-default .xgplayer-bar,.xgplayer-skin-default .xgplayer-drag{display:block;position:absolute;bottom:6px;left:12px;background:hsla(0,0%,100%,.3);border-radius:100px;width:4px;height:76px;outline:none;cursor:pointer}.xgplayer-skin-default .xgplayer-drag{bottom:0;left:0;background:#fa1f41;max-height:76px}.xgplayer-skin-default .xgplayer-drag:after{content:" ";display:inline-block;width:8px;height:8px;background:#fff;box-shadow:0 0 5px 0 rgba(0,0,0,.26);position:absolute;border-radius:50%;left:-2px;top:-6px}.xgplayer-skin-default.xgplayer-volume-active .xgplayer-slider,.xgplayer-skin-default.xgplayer-volume-large .xgplayer-volume .xgplayer-icon .xgplayer-icon-large{display:block}.xgplayer-skin-default.xgplayer-volume-large .xgplayer-volume .xgplayer-icon .xgplayer-icon-muted,.xgplayer-skin-default.xgplayer-volume-large .xgplayer-volume .xgplayer-icon .xgplayer-icon-small,.xgplayer-skin-default.xgplayer-volume-small .xgplayer-volume .xgplayer-icon .xgplayer-icon-large{display:none}.xgplayer-skin-default.xgplayer-volume-small .xgplayer-volume .xgplayer-icon .xgplayer-icon-small{display:block}.xgplayer-skin-default.xgplayer-volume-muted .xgplayer-volume .xgplayer-icon .xgplayer-icon-large,.xgplayer-skin-default.xgplayer-volume-muted .xgplayer-volume .xgplayer-icon .xgplayer-icon-small,.xgplayer-skin-default.xgplayer-volume-small .xgplayer-volume .xgplayer-icon .xgplayer-icon-muted{display:none}.xgplayer-skin-default.xgplayer-volume-muted .xgplayer-volume .xgplayer-icon .xgplayer-icon-muted{display:block}.xgplayer-skin-default.xgplayer-mobile .xgplayer-volume .xgplayer-slider{display:none}.xgplayer-skin-default .xgplayer-definition{-webkit-order:5;-moz-box-ordinal-group:6;order:5;width:60px;height:42px;z-index:18;position:relative;outline:none;display:none;cursor:default;margin-left:10px;margin-top:-7px}.xgplayer-skin-default .xgplayer-definition ul{display:none;list-style:none;width:78px;background:rgba(0,0,0,.54);border-radius:1px;position:absolute;bottom:42px;left:0;text-align:center;white-space:nowrap;margin-left:-10px;z-index:26;cursor:pointer}.xgplayer-skin-default .xgplayer-definition ul li{opacity:.7;font-family:PingFangSC-Regular;font-size:11px;color:hsla(0,0%,100%,.8);padding:6px 13px}.xgplayer-skin-default .xgplayer-definition ul li.selected,.xgplayer-skin-default .xgplayer-definition ul li:hover{color:#fff;opacity:1}.xgplayer-skin-default .xgplayer-definition .name{text-align:center;font-family:PingFangSC-Regular;font-size:13px;cursor:pointer;color:hsla(0,0%,100%,.8);position:absolute;bottom:5px;width:60px;height:20px;line-height:20px;background:rgba(0,0,0,.38);border-radius:10px;display:inline-block;vertical-align:middle}.xgplayer-skin-default.xgplayer-definition-active .xgplayer-definition ul,.xgplayer-skin-default.xgplayer-is-definition .xgplayer-definition{display:block}.xgplayer-skin-default .xgplayer-time{-webkit-order:2;-moz-box-ordinal-group:3;order:2;font-family:ArialMT;font-size:13px;color:#fff;line-height:40px;height:40px;text-align:center;display:inline-block;margin:auto 8px}.xgplayer-skin-default .xgplayer-time span{color:hsla(0,0%,100%,.5)}.xgplayer-skin-default .xgplayer-time .xgplayer-time-current{color:#fff}.xgplayer-skin-default .xgplayer-time .xgplayer-time-current:after{content:"/";display:inline-block;padding:0 3px}.xgplayer-skin-default .xgplayer-controls{display:-webkit-flex;display:-moz-box;display:flex;position:absolute;bottom:0;left:0;right:0;height:40px;background-image:linear-gradient(180deg,transparent,rgba(0,0,0,.37),rgba(0,0,0,.75),rgba(0,0,0,.75));z-index:10}.xgplayer-skin-default.no-controls .xgplayer-controls,.xgplayer-skin-default.xgplayer-inactive .xgplayer-controls,.xgplayer-skin-default.xgplayer-is-live .xgplayer-controls .xgplayer-progress,.xgplayer-skin-default.xgplayer-is-live .xgplayer-controls .xgplayer-time,.xgplayer-skin-default.xgplayer-nostart .xgplayer-controls{display:none}.xgplayer-skin-default.xgplayer-is-live .xgplayer-controls .xgplayer-live{display:block}.xgplayer-skin-default .xgplayer-live{display:block;font-size:12px;color:#fff;line-height:40px;-webkit-order:1;-moz-box-ordinal-group:2;order:1}.xgplayer-skin-default .xgplayer-loading{display:none;width:100px;height:100px;overflow:hidden;-webkit-transform:scale(.7);-ms-transform:scale(.7);transform:scale(.7);position:absolute;left:50%;top:50%;margin:-50px auto auto -50px}.xgplayer-skin-default .xgplayer-loading svg{border-radius:50%;-webkit-transform-origin:center;-ms-transform-origin:center;transform-origin:center;-webkit-animation:loadingRotate 1s linear infinite;animation:loadingRotate 1s linear infinite}.xgplayer-skin-default .xgplayer-loading svg path{stroke:#ddd;stroke-dasharray:236;-webkit-animation:loadingDashOffset 2s linear infinite;animation:loadingDashOffset 2s linear infinite;animation-direction:alternate-reverse;fill:none;stroke-width:12px}.xgplayer-skin-default.xgplayer-nostart .xgplayer-loading{display:none}.xgplayer-skin-default.xgplayer-pause .xgplayer-loading{display:none!important}.xgplayer-skin-default.xgplayer-isloading .xgplayer-loading{display:block}.xgplayer-skin-default .xgplayer-progress{display:block;position:absolute;height:20px;line-height:20px;left:12px;right:12px;outline:none;top:-15px;z-index:35}.xgplayer-skin-default .xgplayer-progress-outer{background:hsla(0,0%,100%,.3);display:block;height:3px;line-height:3px;margin-top:8.5px;width:100%;position:relative;cursor:pointer}.xgplayer-skin-default .xgplayer-progress-cache,.xgplayer-skin-default .xgplayer-progress-played{display:block;height:100%;line-height:1;position:absolute;left:0;top:0}.xgplayer-skin-default .xgplayer-progress-cache{width:0;background:hsla(0,0%,100%,.5)}.xgplayer-skin-default .xgplayer-progress-played{display:block;width:0;background-image:linear-gradient(-90deg,#fa1f41,#e31106);border-radius:0 1.5px 1.5px 0}.xgplayer-skin-default .xgplayer-progress-btn{display:none;position:absolute;left:0;top:-5px;width:13px;height:13px;border-radius:30px;background:#fff;box-shadow:0 0 2px 0 rgba(0,0,0,.26);left:100%;-webkit-transform:translate(-50%);-ms-transform:translate(-50%);transform:translate(-50%)}.xgplayer-skin-default .xgplayer-progress-point{position:absolute}.xgplayer-skin-default .xgplayer-progress-point.xgplayer-tips{margin-left:0;top:-25px;display:none;z-index:100}.xgplayer-skin-default .xgplayer-progress-dot{display:inline-block;position:absolute;height:3px;width:5px;top:0;background:#fff;border-radius:6px;z-index:16}.xgplayer-skin-default .xgplayer-progress-dot .xgplayer-progress-tip{position:absolute;left:0;top:-40px;height:auto;line-height:30px;width:auto;-webkit-transform:scale(.8);-ms-transform:scale(.8);transform:scale(.8);background:rgba(0,0,0,.3);border-radius:6px;border:1px solid rgba(0,0,0,.8);cursor:default;white-space:nowrap;display:none}.xgplayer-skin-default .xgplayer-progress-dot-show .xgplayer-progress-tip{display:block}.xgplayer-skin-default .xgplayer-progress-thumbnail{position:absolute;-moz-box-sizing:border-box;box-sizing:border-box}.xgplayer-skin-default .xgplayer-progress-thumbnail.xgplayer-tips{margin-left:0;display:none;z-index:99}.xgplayer-skin-default .xgplayer-progress:focus .xgplayer-progress-outer,.xgplayer-skin-default .xgplayer-progress:hover .xgplayer-progress-outer{height:6px;margin-top:7px}.xgplayer-skin-default .xgplayer-progress:focus .xgplayer-progress-dot,.xgplayer-skin-default .xgplayer-progress:hover .xgplayer-progress-dot{height:6px}.xgplayer-skin-default .xgplayer-progress:focus .xgplayer-progress-btn,.xgplayer-skin-default .xgplayer-progress:hover .xgplayer-progress-btn{display:block;top:-3px}.xgplayer-skin-default.xgplayer-definition-active .xgplayer-progress,.xgplayer-skin-default.xgplayer-playbackrate-active .xgplayer-progress,.xgplayer-skin-default.xgplayer-texttrack-active .xgplayer-progress,.xgplayer-skin-default.xgplayer-volume-active .xgplayer-progress{z-index:15}.xgplayer-skin-default.xgplayer-mobile .xgplayer-progress-btn{display:block!important}.xgplayer-skin-default.xgplayer-mobile .xgplayer-progress:focus .xgplayer-progress-outer,.xgplayer-skin-default.xgplayer-mobile .xgplayer-progress:hover .xgplayer-progress-outer{height:3px!important;margin-top:8.5px!important}.xgplayer-skin-default.xgplayer-mobile .xgplayer-progress:focus .xgplayer-progress-btn,.xgplayer-skin-default.xgplayer-mobile .xgplayer-progress:hover .xgplayer-progress-btn{display:block!important;top:-5px!important}.xgplayer-skin-default .xgplayer-replay{position:absolute;left:0;top:0;width:100%;height:100%;z-index:105;display:none;-webkit-justify-content:center;-moz-box-pack:center;justify-content:center;-webkit-align-items:center;-moz-box-align:center;align-items:center;background:rgba(0,0,0,.54);-webkit-flex-direction:column;-moz-box-orient:vertical;-moz-box-direction:normal;flex-direction:column}.xgplayer-skin-default .xgplayer-replay svg{background:rgba(0,0,0,.58);border-radius:100%;cursor:pointer}.xgplayer-skin-default .xgplayer-replay svg path{-webkit-transform:translate(20px,21px);-ms-transform:translate(20px,21px);transform:translate(20px,21px);fill:#ddd}.xgplayer-skin-default .xgplayer-replay svg:hover{background:rgba(0,0,0,.38)}.xgplayer-skin-default .xgplayer-replay svg:hover path{fill:#fff}.xgplayer-skin-default .xgplayer-replay .xgplayer-replay-txt{display:inline-block;font-family:PingFangSC-Regular;font-size:14px;color:#fff;line-height:34px}.xgplayer-skin-default.xgplayer.xgplayer-ended .xgplayer-controls{display:none}.xgplayer-skin-default.xgplayer.xgplayer-ended .xgplayer-replay{display:-webkit-flex;display:-moz-box;display:flex}.xgplayer-skin-default .xgplayer-playbackrate{-webkit-order:8;-moz-box-ordinal-group:9;order:8;width:60px;height:20px;z-index:18;position:relative;display:inline-block;cursor:default}.xgplayer-skin-default .xgplayer-playbackrate ul{display:none;list-style:none;width:78px;background:rgba(0,0,0,.54);border-radius:1px;position:absolute;bottom:20px;left:50%;-webkit-transform:translateX(-50%);-ms-transform:translateX(-50%);transform:translateX(-50%);text-align:left;white-space:nowrap;z-index:26;cursor:pointer}.xgplayer-skin-default .xgplayer-playbackrate ul li{opacity:.7;font-family:PingFangSC-Regular;font-size:11px;color:hsla(0,0%,100%,.8);position:relative;padding:4px 0;text-align:center}.xgplayer-skin-default .xgplayer-playbackrate ul li.selected,.xgplayer-skin-default .xgplayer-playbackrate ul li:hover{color:#fff;opacity:1}.xgplayer-skin-default .xgplayer-playbackrate ul li:first-child{position:relative;margin-top:12px}.xgplayer-skin-default .xgplayer-playbackrate ul li:last-child{position:relative;margin-bottom:12px}.xgplayer-skin-default .xgplayer-playbackrate .name{height:20px;position:relative;top:11px;text-align:center;background:rgba(0,0,0,.38);color:hsla(0,0%,100%,.8);border-radius:10px;line-height:20px}.xgplayer-skin-default .xgplayer-playbackrate span{position:relative;top:19px;font-weight:700;text-shadow:0 0 4px rgba(0,0,0,.6)}.xgplayer-skin-default .xgplayer-playbackrate:hover{opacity:1}.xgplayer-skin-default.xgplayer-playbackrate-active .xgplayer-playbackrate ul{display:block}.xgplayer-skin-default .xgplayer-download{position:relative;-webkit-order:9;-moz-box-ordinal-group:10;order:9;display:block;cursor:pointer}.xgplayer-skin-default .xgplayer-download .xgplayer-icon{margin-top:3px}.xgplayer-skin-default .xgplayer-download .xgplayer-icon div{position:absolute}.xgplayer-skin-default .xgplayer-download .xgplayer-icon svg{position:relative;top:5px;left:5px}.xgplayer-skin-default .xgplayer-download .xgplayer-tips{margin-left:-20px}.xgplayer-skin-default .xgplayer-download .xgplayer-tips .xgplayer-tip-download{display:block}.xgplayer-skin-default .xgplayer-download:hover{opacity:.85}.xgplayer-skin-default .xgplayer-download:hover .xgplayer-tips{display:block}.lang-is-en .xgplayer-download .xgplayer-tips{margin-left:-32px}.lang-is-jp .xgplayer-download .xgplayer-tips{margin-left:-40px}.xgplayer-skin-default .danmu-switch{-webkit-order:6;-moz-box-ordinal-group:7;order:6;z-index:26}.xgplayer-skin-default .xgplayer-danmu{display:none;position:absolute;top:0;left:0;right:0;height:100%;overflow:hidden;z-index:9;outline:none}.xgplayer-skin-default .xgplayer-danmu>*{position:absolute;white-space:nowrap;z-index:9}.xgplayer-skin-default .xgplayer-danmu.xgplayer-has-danmu{display:block}.xgplayer-skin-default .xgplayer-panel{outline:none;-webkit-order:7;-moz-box-ordinal-group:8;order:7;width:40px;height:40px;display:inline-block;position:relative;font-family:PingFangSC-Regular;font-size:13px;color:hsla(0,0%,100%,.8);z-index:36}.xgplayer-skin-default .xgplayer-panel .xgplayer-panel-icon{cursor:pointer;position:absolute;margin-left:5px;top:10px}.xgplayer-skin-default .xgplayer-panel-active{display:block!important;bottom:30px}.xgplayer-skin-default .xgplayer-panel-slider{z-index:36;display:none;position:absolute;width:230px;height:230px;background:rgba(0,0,0,.54);border-radius:1px;padding:10px 20px;outline:none;left:-115px;bottom:40px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-hidemode{padding-bottom:10px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-hidemode-radio li{display:inline;list-style:none;cursor:pointer}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-hidemode ul{display:-webkit-flex;display:-moz-box;display:flex;-webkit-justify-content:space-around;justify-content:space-around}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-hidemode li{margin:0 12px;font-size:11px;color:#aaa}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-hidemode-font{margin-bottom:10px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-transparency{display:block;margin-top:10px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-transparency .xgplayer-transparency-line{-webkit-appearance:none;-moz-appearance:none;appearance:none;cursor:pointer;outline:none;width:150px;height:4px;background:#aaa;border-radius:4px;border-style:none;margin-left:10px;margin-top:-2px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-transparency .xgplayer-transparency-line::-moz-focus-outer{border:0!important}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-transparency .xgplayer-transparency-color::-webkit-slider-runnable-track{outline:none;width:150px;height:4px;border-radius:4px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-transparency .xgplayer-transparency-color::-moz-range-track{outline:none;background-color:#aaa;border-color:transparent;cursor:pointer;width:150px;height:4px;border-radius:4px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-transparency .xgplayer-transparency-color::-ms-track{outline:none;background-color:#aaa;color:transparent;border-color:transparent;width:150px;height:4px;border-radius:4px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-transparency .xgplayer-transparency-bar::-webkit-slider-thumb{outline:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:6px solid #f85959;height:6px;width:6px;margin-top:-4px;border-radius:6px;cursor:pointer}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-transparency .xgplayer-transparency-bar::-moz-range-thumb{outline:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:6px solid #f85959;height:0;width:0;border-radius:6px;cursor:pointer}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-transparency .xgplayer-transparency-bar::-ms-thumb{outline:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:6px solid #f85959;height:6px;width:6px;border-radius:6px;cursor:pointer}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-transparency .xgplayer-transparency-bar::-moz-range-progress{outline:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;height:4px;border-radius:4px;background:linear-gradient(90deg,#f85959,#f85959 100%,#aaa)}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea{display:block;margin-top:8px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea-name{display:inline-block;position:relative;top:-10px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea-control{display:inline-block}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea-control-up{width:150px;margin-left:10px;display:-moz-box;display:-webkit-flex;display:flex;-webkit-justify-content:space-between;-moz-box-pack:justify;justify-content:space-between;color:#aaa}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea-control-down{position:relative;top:-10px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea-control-down-dots{display:-webkit-flex;display:-moz-box;display:flex;width:150px;margin-left:10px;-webkit-justify-content:space-between;-moz-box-pack:justify;justify-content:space-between}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea-threequarters,.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea-twoquarters{margin-left:-6px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea-full{margin-right:3px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea .xgplayer-showarea-line{-webkit-appearance:none;-moz-appearance:none;appearance:none;cursor:pointer;outline:none;width:150px;height:4px;background:#aaa;border-radius:4px;border-style:none;margin-left:10px;margin-top:-2px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea .xgplayer-showarea-line::-moz-focus-outer{border:0!important}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea .xgplayer-showarea-color::-webkit-slider-runnable-track{outline:none;width:150px;height:4px;border-radius:4px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea .xgplayer-showarea-color::-moz-range-track{outline:none;background-color:#aaa;border-color:transparent;cursor:pointer;width:150px;height:4px;border-radius:4px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea .xgplayer-showarea-color::-ms-track{outline:none;background-color:#aaa;color:transparent;border-color:transparent;width:150px;height:4px;border-radius:4px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea .xgplayer-showarea-bar::-webkit-slider-thumb{outline:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:6px solid #f85959;height:6px;width:6px;margin-top:-4px;border-radius:6px;cursor:pointer}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea .xgplayer-showarea-bar::-moz-range-thumb{outline:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:6px solid #f85959;height:0;width:0;border-radius:6px;cursor:pointer}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea .xgplayer-showarea-bar::-ms-thumb{outline:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:6px solid #f85959;height:6px;width:6px;border-radius:6px;cursor:pointer}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea .xgplayer-showarea-full-dot,.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea .xgplayer-showarea-onequarters-dot,.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea .xgplayer-showarea-threequarters-dot,.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea .xgplayer-showarea-twoquarters-dot,.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-showarea .xgplayer-showarea-zero-dot{width:3px;height:3px;border:3px solid #aaa;border-radius:50%;background-color:#aaa;position:relative;top:16px;z-index:-1}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmuspeed{display:block}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmuspeed-name{display:inline-block;position:relative;top:-10px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmuspeed-control{display:inline-block}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmuspeed-control-up{width:150px;margin-left:10px;display:-moz-box;display:-webkit-flex;display:flex;-webkit-justify-content:space-between;-moz-box-pack:justify;justify-content:space-between;color:#aaa}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmuspeed-control-down{position:relative;top:-10px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmuspeed-control-down-dots{display:-webkit-flex;display:-moz-box;display:flex;width:150px;margin-left:10px;-webkit-justify-content:space-between;-moz-box-pack:justify;justify-content:space-between}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmuspeed .xgplayer-danmuspeed-line{-webkit-appearance:none;-moz-appearance:none;appearance:none;cursor:pointer;outline:none;width:150px;height:4px;background:#aaa;border-radius:4px;border-style:none;margin-left:10px;margin-top:-2px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmuspeed .xgplayer-danmuspeed-line::-moz-focus-outer{border:0!important}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmuspeed .xgplayer-danmuspeed-color::-webkit-slider-runnable-track{outline:none;width:150px;height:4px;border-radius:4px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmuspeed .xgplayer-danmuspeed-color::-moz-range-track{outline:none;background-color:#aaa;border-color:transparent;cursor:pointer;width:150px;height:4px;border-radius:4px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmuspeed .xgplayer-danmuspeed-color::-ms-track{outline:none;background-color:#aaa;color:transparent;border-color:transparent;width:150px;height:4px;border-radius:4px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmuspeed .xgplayer-danmuspeed-bar::-webkit-slider-thumb{outline:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:6px solid #f85959;height:6px;width:6px;margin-top:-4px;border-radius:6px;cursor:pointer}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmuspeed .xgplayer-danmuspeed-bar::-moz-range-thumb{outline:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:6px solid #f85959;height:0;width:0;border-radius:6px;cursor:pointer}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmuspeed .xgplayer-danmuspeed-bar::-ms-thumb{outline:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:6px solid #f85959;height:6px;width:6px;border-radius:6px;cursor:pointer}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmuspeed .xgplayer-danmuspeed-large-dot,.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmuspeed .xgplayer-danmuspeed-middle-dot,.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmuspeed .xgplayer-danmuspeed-small-dot{width:3px;height:3px;border:3px solid #aaa;border-radius:50%;background-color:#aaa;position:relative;top:16px;z-index:-1}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmufont{display:block}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmufont-name{display:inline-block;position:relative;top:-10px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmufont-control{display:inline-block}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmufont-control-up{width:150px;margin-left:10px;display:-moz-box;display:-webkit-flex;display:flex;-webkit-justify-content:space-between;-moz-box-pack:justify;justify-content:space-between;color:#aaa}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmufont-control-down{position:relative;top:-10px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmufont-control-down-dots{display:-webkit-flex;display:-moz-box;display:flex;width:150px;margin-left:10px;-webkit-justify-content:space-between;-moz-box-pack:justify;justify-content:space-between}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmufont .xgplayer-danmufont-line{-webkit-appearance:none;-moz-appearance:none;appearance:none;cursor:pointer;outline:none;width:150px;height:4px;background:#aaa;border-radius:4px;border-style:none;margin-left:10px;margin-top:-2px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmufont .xgplayer-danmufont-line::-moz-focus-outer{border:0!important}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmufont .xgplayer-danmufont-color::-webkit-slider-runnable-track{outline:none;width:150px;height:4px;border-radius:4px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmufont .xgplayer-danmufont-color::-moz-range-track{outline:none;background-color:#aaa;border-color:transparent;cursor:pointer;width:150px;height:4px;border-radius:4px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmufont .xgplayer-danmufont-color::-ms-track{outline:none;background-color:#aaa;color:transparent;border-color:transparent;width:150px;height:4px;border-radius:4px}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmufont .xgplayer-danmufont-bar::-webkit-slider-thumb{outline:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:6px solid #f85959;height:6px;width:6px;margin-top:-4px;border-radius:6px;cursor:pointer}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmufont .xgplayer-danmufont-bar::-moz-range-thumb{outline:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:6px solid #f85959;height:0;width:0;border-radius:6px;cursor:pointer}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmufont .xgplayer-danmufont-bar::-ms-thumb{outline:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:6px solid #f85959;height:6px;width:6px;border-radius:6px;cursor:pointer}.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmufont .xgplayer-danmufont-large-dot,.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmufont .xgplayer-danmufont-middle-dot,.xgplayer-skin-default .xgplayer-panel-slider .xgplayer-danmufont .xgplayer-danmufont-small-dot{width:3px;height:3px;border:3px solid #aaa;border-radius:50%;background-color:#aaa;position:relative;top:16px;z-index:-1}.xgplayer-skin-default .xgplayer-playnext{position:relative;-webkit-order:1;-moz-box-ordinal-group:2;order:1;display:block;cursor:pointer;top:-2px}.xgplayer-skin-default .xgplayer-playnext .xgplayer-icon div{position:absolute}.xgplayer-skin-default .xgplayer-playnext .xgplayer-tips .xgplayer-tip-playnext{display:block}.xgplayer-skin-default .xgplayer-playnext:hover{opacity:.85}.xgplayer-skin-default .xgplayer-playnext:hover .xgplayer-tips{display:block}.lang-is-en .xgplayer-playnext .xgplayer-tips{margin-left:-25px}.lang-is-jp .xgplayer-playnext .xgplayer-tips{margin-left:-38px}.xgplayer-skin-default.xgplayer-playnext-inactive .xgplayer-playnext{display:none}.xgplayer-skin-default .xgplayer-pip{-webkit-order:9;-moz-box-ordinal-group:10;order:9;position:relative;outline:none;display:block;cursor:pointer;height:20px;top:8px}.xgplayer-skin-default .xgplayer-pip .name{text-align:center;font-family:PingFangSC-Regular;font-size:13px;line-height:20px;height:20px;color:hsla(0,0%,100%,.8)}.xgplayer-skin-default .xgplayer-pip .name span{width:60px;height:20px;line-height:20px;background:rgba(0,0,0,.38);border-radius:10px;display:inline-block;vertical-align:middle}.xgplayer-skin-default .xgplayer-pip-lay{position:absolute;top:26px;left:0;width:100%;height:100%;z-index:130;cursor:pointer;background-color:transparent;display:none}.xgplayer-skin-default .xgplayer-pip-lay div{width:100%;height:100%}.xgplayer-skin-default .xgplayer-pip-drag{cursor:move;position:absolute;top:0;left:0;width:100%;height:26px;line-height:26px;background-image:linear-gradient(rgba(0,0,0,.3),transparent);z-index:130;display:none}.xgplayer-skin-default.xgplayer-pip-active{position:fixed;right:0;bottom:200px;width:320px!important;height:180px!important;z-index:110!important}.xgplayer-skin-default.xgplayer-pip-active .xgplayer-controls,.xgplayer-skin-default.xgplayer-pip-active .xgplayer-danmu{display:none}.xgplayer-skin-default.xgplayer-pip-active .xgplayer-pip-lay{display:block}.xgplayer-skin-default.xgplayer-pip-active .xgplayer-pip-drag{display:-webkit-flex;display:-moz-box;display:flex}.xgplayer-skin-default.xgplayer-inactive .xgplayer-pip-drag{display:none}.lang-is-jp .xgplayer-pip .name span{width:70px;height:20px}.xgplayer-skin-default .xgplayer-rotate{position:relative;-webkit-order:10;-moz-box-ordinal-group:11;order:10;display:block;cursor:pointer}.xgplayer-skin-default .xgplayer-rotate .xgplayer-icon{margin-top:7px;width:26px}.xgplayer-skin-default .xgplayer-rotate .xgplayer-icon div{position:absolute}.xgplayer-skin-default .xgplayer-rotate .xgplayer-tips{margin-left:-22px}.xgplayer-skin-default .xgplayer-rotate .xgplayer-tips .xgplayer-tip-rotate{display:block}.xgplayer-skin-default .xgplayer-rotate:hover{opacity:.85}.xgplayer-skin-default .xgplayer-rotate:hover .xgplayer-tips{display:block}.lang-is-en .xgplayer-rotate .xgplayer-tips{margin-left:-26px}.lang-is-jp .xgplayer-rotate .xgplayer-tips{margin-left:-38px}.xgplayer-skin-default .xgplayer-reload{position:relative;-webkit-order:1;-moz-box-ordinal-group:2;order:1;display:block;width:40px;height:40px;cursor:pointer}.xgplayer-skin-default .xgplayer-reload .xgplayer-icon{margin-top:7px;width:26px}.xgplayer-skin-default .xgplayer-reload .xgplayer-icon div{position:absolute}.xgplayer-skin-default .xgplayer-reload .xgplayer-tips{margin-left:-22px}.xgplayer-skin-default .xgplayer-reload .xgplayer-tips .xgplayer-tip-reload{display:block}.xgplayer-skin-default .xgplayer-reload:hover{opacity:.85}.xgplayer-skin-default .xgplayer-reload:hover .xgplayer-tips{display:block}.lang-is-en .xgplayer-reload .xgplayer-tips{margin-left:-26px}.lang-is-jp .xgplayer-reload .xgplayer-tips{margin-left:-38px}.xgplayer-skin-default .xgplayer-screenshot{-webkit-order:11;-moz-box-ordinal-group:12;order:11;position:relative;outline:none;display:block;cursor:pointer;height:20px;top:8px}.xgplayer-skin-default .xgplayer-screenshot .name{text-align:center;font-family:PingFangSC-Regular;font-size:13px;line-height:20px;height:20px;color:hsla(0,0%,100%,.8)}.xgplayer-skin-default .xgplayer-screenshot .name span{width:60px;height:20px;line-height:20px;background:rgba(0,0,0,.38);border-radius:10px;display:inline-block;vertical-align:middle}.lang-is-en .xgplayer-screenshot .name span,.lang-is-jp .xgplayer-screenshot .name span{width:75px;height:20px}.xgplayer-skin-default .xgplayer-texttrack{-webkit-order:7;-moz-box-ordinal-group:8;order:7;width:60px;height:150px;z-index:18;position:relative;outline:none;display:none;cursor:default;margin-top:-119px}.xgplayer-skin-default .xgplayer-texttrack ul{display:none;list-style:none;min-width:78px;background:rgba(0,0,0,.54);border-radius:1px;position:absolute;bottom:30px;text-align:center;white-space:nowrap;left:50%;-webkit-transform:translateX(-50%);-ms-transform:translateX(-50%);transform:translateX(-50%);width:-webkit-fit-content;width:-moz-fit-content;width:fit-content;z-index:26;cursor:pointer}.xgplayer-skin-default .xgplayer-texttrack ul li{opacity:.7;font-family:PingFangSC-Regular;font-size:11px;color:hsla(0,0%,100%,.8);width:-webkit-fit-content;width:-moz-fit-content;width:fit-content;margin:auto;padding:6px 13px}.xgplayer-skin-default .xgplayer-texttrack ul li.selected,.xgplayer-skin-default .xgplayer-texttrack ul li:hover{color:#fff;opacity:1}.xgplayer-skin-default .xgplayer-texttrack .name{text-align:center;font-family:PingFangSC-Regular;font-size:13px;cursor:pointer;color:hsla(0,0%,100%,.8);position:absolute;bottom:0;width:60px;height:20px;line-height:20px;background:rgba(0,0,0,.38);border-radius:10px;display:inline-block;vertical-align:middle}.xgplayer-skin-default.xgplayer-is-texttrack .xgplayer-texttrack,.xgplayer-skin-default.xgplayer-texttrack-active .xgplayer-texttrack ul{display:block}.xgplayer-skin-default .xgplayer-icon{display:block;width:40px;height:40px;overflow:hidden;fill:#fff}.xgplayer-skin-default .xgplayer-icon svg{position:absolute}.xgplayer-skin-default .xgplayer-tips{background:rgba(0,0,0,.54);border-radius:1px;display:none;position:absolute;font-family:PingFangSC-Regular;font-size:11px;color:#fff;padding:2px 4px;text-align:center;top:-30px;left:50%;margin-left:-16px;width:auto;white-space:nowrap}.xgplayer-skin-default.xgplayer-mobile .xgplayer-tips{display:none!important}.xgplayer-skin-default .xgplayer-error{background:#000;display:none;position:absolute;left:0;top:0;width:100%;height:100%;z-index:125;font-family:PingFangSC-Regular;font-size:14px;color:#fff;text-align:center;line-height:100%;-webkit-justify-content:center;-moz-box-pack:center;justify-content:center;-webkit-align-items:center;-moz-box-align:center;align-items:center}.xgplayer-skin-default .xgplayer-error .xgplayer-error-refresh{color:#fa1f41;padding:0 3px;cursor:pointer}.xgplayer-skin-default .xgplayer-error .xgplayer-error-text{line-height:18px;margin:auto 6px}.xgplayer-skin-default.xgplayer-is-error .xgplayer-error{display:-webkit-flex;display:-moz-box;display:flex}.xgplayer-skin-default .xgplayer-memoryplay-spot{position:absolute;height:32px;left:10px;bottom:46px;background:rgba(0,0,0,.5);border-radius:32px;line-height:32px;color:#ddd;z-index:15;padding:0 32px 0 16px}.xgplayer-skin-default .xgplayer-memoryplay-spot .xgplayer-lasttime{color:red;font-weight:700}.xgplayer-skin-default .xgplayer-memoryplay-spot .btn-close{position:absolute;width:16px;height:16px;right:10px;top:2px;cursor:pointer;color:#fff;font-size:16px}',""])},function(e,t,n){"use strict";e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var n=function(e,t){var n=e[1]||"",a=e[3];if(!a)return n;if(t&&"function"==typeof btoa){var r=(o=a,"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(o))))+" */"),i=a.sources.map((function(e){return"/*# sourceURL="+a.sourceRoot+e+" */"}));return[n].concat(i).concat([r]).join("\n")}var o;return[n].join("\n")}(t,e);return t[2]?"@media "+t[2]+"{"+n+"}":n})).join("")},t.i=function(e,n){"string"==typeof e&&(e=[[null,e,""]]);for(var a={},r=0;r<this.length;r++){var i=this[r][0];"number"==typeof i&&(a[i]=!0)}for(r=0;r<e.length;r++){var o=e[r];"number"==typeof o[0]&&a[o[0]]||(n&&!o[2]?o[2]=n:n&&(o[2]="("+o[2]+") and ("+n+")"),t.push(o))}},t}},function(e,t,n){var a,r,i={},o=(a=function(){return window&&document&&document.all&&!window.atob},function(){return void 0===r&&(r=a.apply(this,arguments)),r}),l=function(e){return document.querySelector(e)},s=function(e){var t={};return function(e){if("function"==typeof e)return e();if(void 0===t[e]){var n=l.call(this,e);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(e){n=null}t[e]=n}return t[e]}}(),u=null,c=0,p=[],d=n(62);function f(e,t){for(var n=0;n<e.length;n++){var a=e[n],r=i[a.id];if(r){r.refs++;for(var o=0;o<r.parts.length;o++)r.parts[o](a.parts[o]);for(;o<a.parts.length;o++)r.parts.push(v(a.parts[o],t))}else{var l=[];for(o=0;o<a.parts.length;o++)l.push(v(a.parts[o],t));i[a.id]={id:a.id,refs:1,parts:l}}}}function g(e,t){for(var n=[],a={},r=0;r<e.length;r++){var i=e[r],o=t.base?i[0]+t.base:i[0],l={css:i[1],media:i[2],sourceMap:i[3]};a[o]?a[o].parts.push(l):n.push(a[o]={id:o,parts:[l]})}return n}function y(e,t){var n=s(e.insertInto);if(!n)throw new Error("Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid.");var a=p[p.length-1];if("top"===e.insertAt)a?a.nextSibling?n.insertBefore(t,a.nextSibling):n.appendChild(t):n.insertBefore(t,n.firstChild),p.push(t);else if("bottom"===e.insertAt)n.appendChild(t);else{if("object"!=typeof e.insertAt||!e.insertAt.before)throw new Error("[Style Loader]\n\n Invalid value for parameter 'insertAt' ('options.insertAt') found.\n Must be 'top', 'bottom', or Object.\n (https://github.com/webpack-contrib/style-loader#insertat)\n");var r=s(e.insertInto+" "+e.insertAt.before);n.insertBefore(t,r)}}function h(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e);var t=p.indexOf(e);t>=0&&p.splice(t,1)}function x(e){var t=document.createElement("style");return e.attrs.type="text/css",m(t,e.attrs),y(e,t),t}function m(e,t){Object.keys(t).forEach((function(n){e.setAttribute(n,t[n])}))}function v(e,t){var n,a,r,i;if(t.transform&&e.css){if(!(i=t.transform(e.css)))return function(){};e.css=i}if(t.singleton){var o=c++;n=u||(u=x(t)),a=w.bind(null,n,o,!1),r=w.bind(null,n,o,!0)}else e.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(n=function(e){var t=document.createElement("link");return e.attrs.type="text/css",e.attrs.rel="stylesheet",m(t,e.attrs),y(e,t),t}(t),a=E.bind(null,n,t),r=function(){h(n),n.href&&URL.revokeObjectURL(n.href)}):(n=x(t),a=_.bind(null,n),r=function(){h(n)});return a(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;a(e=t)}else r()}}e.exports=function(e,t){if("undefined"!=typeof DEBUG&&DEBUG&&"object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");(t=t||{}).attrs="object"==typeof t.attrs?t.attrs:{},t.singleton||"boolean"==typeof t.singleton||(t.singleton=o()),t.insertInto||(t.insertInto="head"),t.insertAt||(t.insertAt="bottom");var n=g(e,t);return f(n,t),function(e){for(var a=[],r=0;r<n.length;r++){var o=n[r];(l=i[o.id]).refs--,a.push(l)}e&&f(g(e,t),t);for(r=0;r<a.length;r++){var l;if(0===(l=a[r]).refs){for(var s=0;s<l.parts.length;s++)l.parts[s]();delete i[l.id]}}}};var b,k=(b=[],function(e,t){return b[e]=t,b.filter(Boolean).join("\n")});function w(e,t,n,a){var r=n?"":a.css;if(e.styleSheet)e.styleSheet.cssText=k(t,r);else{var i=document.createTextNode(r),o=e.childNodes;o[t]&&e.removeChild(o[t]),o.length?e.insertBefore(i,o[t]):e.appendChild(i)}}function _(e,t){var n=t.css,a=t.media;if(a&&e.setAttribute("media",a),e.styleSheet)e.styleSheet.cssText=n;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(n))}}function E(e,t,n){var a=n.css,r=n.sourceMap,i=void 0===t.convertToAbsoluteUrls&&r;(t.convertToAbsoluteUrls||i)&&(a=d(a)),r&&(a+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(r))))+" */");var o=new Blob([a],{type:"text/css"}),l=e.href;e.href=URL.createObjectURL(o),l&&URL.revokeObjectURL(l)}},function(e,t,n){"use strict";e.exports=function(e){var t="undefined"!=typeof window&&window.location;if(!t)throw new Error("fixUrls requires window.location");if(!e||"string"!=typeof e)return e;var n=t.protocol+"//"+t.host,a=n+t.pathname.replace(/\/[^\/]*$/,"/");return e.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi,(function(e,t){var r,i=t.trim().replace(/^"(.*)"$/,(function(e,t){return t})).replace(/^'(.*)'$/,(function(e,t){return t}));return/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/|\s*$)/i.test(i)?e:(r=0===i.indexOf("//")?i:0===i.indexOf("/")?n+i:a+i.replace(/^\.\//,""),"url("+JSON.stringify(r)+")")}))}},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("s_enter",(function(){for(var e=this.root,t=i.default.util,n="",a=1;a<=12;a++)n+='<div class="xgplayer-enter-bar'+a+'"></div>';var r=t.createDom("xg-enter",'<div class="xgplayer-enter-spinner">\n '+n+"\n </div>",{},"xgplayer-enter");e.appendChild(r)}))},function(e,t,n){"use strict";var a=o(n(0)),r=o(n(65)),i=o(n(66));function o(e){return e&&e.__esModule?e:{default:e}}a.default.install("s_play",(function(){var e=this,t=a.default.util,n=e.config.playBtn?e.config.playBtn:{},o=void 0;o="img"===n.type?t.createImgBtn("play",n.url.play,n.width,n.height):t.createDom("xg-play",'<xg-icon class="xgplayer-icon">\n <div class="xgplayer-icon-play">'+r.default+'</div>\n <div class="xgplayer-icon-pause">'+i.default+"</div>\n </xg-icon>",{},"xgplayer-play");var l={};l.play=e.lang.PLAY_TIPS,l.pause=e.lang.PAUSE_TIPS;var s=t.createDom("xg-tips",'<span class="xgplayer-tip-play">'+l.play+'</span>\n <span class="xgplayer-tip-pause">'+l.pause+"</span>",{},"xgplayer-tips");o.appendChild(s),e.once("ready",(function(){e.controls.appendChild(o)})),["click","touchend"].forEach((function(t){o.addEventListener(t,(function(t){t.preventDefault(),t.stopPropagation(),e.emit("playBtnClick")}))}))}))},function(e,t,n){"use strict";n.r(t),t.default='<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40">\n <path transform="translate(2,2) scale(0.0320625 0.0320625)" d="M576,363L810,512L576,661zM342,214L576,363L576,661L342,810z"></path>\n</svg>\n'},function(e,t,n){"use strict";n.r(t),t.default='<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40">\n <path transform="translate(2,2) scale(0.0320625 0.0320625)" d="M598,214h170v596h-170v-596zM256 810v-596h170v596h-170z"></path>\n</svg>\n'},function(e,t,n){"use strict";var a=o(n(0)),r=o(n(68)),i=o(n(69));function o(e){return e&&e.__esModule?e:{default:e}}a.default.install("s_start",(function(){var e=this,t=e.root,n=a.default.util,o=n.createDom("xg-start",'<div class="xgplayer-icon-play">'+r.default+'</div>\n <div class="xgplayer-icon-pause">'+i.default+"</div>",{},"xgplayer-start");function l(e){n.addClass(e.root,"xgplayer-skin-default"),e.config&&(e.config.autoplay&&!n.isWeiXin()&&!n.isUc()&&n.addClass(e.root,"xgplayer-is-enter"),e.config.lang&&"en"===e.config.lang?n.addClass(e.root,"lang-is-en"):"jp"===e.config.lang&&n.addClass(e.root,"lang-is-jp"),e.config.enableContextmenu||e.video.addEventListener("contextmenu",(function(e){e.preventDefault(),e.stopPropagation()})))}e.isReady?(t.appendChild(o),l(e)):e.once("ready",(function(){t.appendChild(o),l(e)})),e.once("autoplay was prevented",(function(){n.removeClass(e.root,"xgplayer-is-enter"),n.addClass(e.root,"xgplayer-nostart")})),e.once("canplay",(function(){n.removeClass(e.root,"xgplayer-is-enter")})),o.onclick=function(t){t.preventDefault(),t.stopPropagation(),e.emit("startBtnClick")}}))},function(e,t,n){"use strict";n.r(t),t.default='<svg xmlns="http://www.w3.org/2000/svg" width="70" height="70" viewBox="0 0 70 70">\n <path transform="translate(15,15) scale(0.04,0.04)" d="M576,363L810,512L576,661zM342,214L576,363L576,661L342,810z"></path>\n</svg>\n'},function(e,t,n){"use strict";n.r(t),t.default='<svg xmlns="http://www.w3.org/2000/svg" width="70" height="70" viewBox="0 0 70 70">\n <path transform="translate(15,15) scale(0.04 0.04)" d="M598,214h170v596h-170v-596zM256 810v-596h170v596h-170z"></path>\n</svg>\n'},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("s_poster",(function(){var e=this.root,t=i.default.util;if(this.config.poster){var n=t.createDom("xg-poster","",{},"xgplayer-poster");n.style.backgroundImage="url("+this.config.poster+")",e.appendChild(n)}}))},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("s_flex",(function(){this.root;var e=i.default.util.createDom("xg-placeholder","",{},"xgplayer-placeholder");this.controls.appendChild(e)}))},function(e,t,n){"use strict";var a=o(n(0)),r=o(n(73)),i=o(n(74));function o(e){return e&&e.__esModule?e:{default:e}}a.default.install("s_fullscreen",(function(){var e=this,t=a.default.util,n=e.config.fullscreenBtn?e.config.fullscreenBtn:{},o=void 0;o="img"===n.type?t.createImgBtn("fullscreen",n.url.request,n.width,n.height):t.createDom("xg-fullscreen",'<xg-icon class="xgplayer-icon">\n <div class="xgplayer-icon-requestfull">'+r.default+'</div>\n <div class="xgplayer-icon-exitfull">'+i.default+"</div>\n </xg-icon>",{},"xgplayer-fullscreen");var l={};l.requestfull=e.lang.FULLSCREEN_TIPS,l.exitfull=e.lang.EXITFULLSCREEN_TIPS;var s=t.createDom("xg-tips",'<span class="xgplayer-tip-requestfull">'+l.requestfull+'</span>\n <span class="xgplayer-tip-exitfull">'+l.exitfull+"</span>",{},"xgplayer-tips");o.appendChild(s),e.once("ready",(function(){e.controls.appendChild(o)})),["click","touchend"].forEach((function(t){o.addEventListener(t,(function(t){t.preventDefault(),t.stopPropagation(),e.emit("fullscreenBtnClick")}))}))}))},function(e,t,n){"use strict";n.r(t),t.default='<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40">\n <path transform="scale(0.0320625 0.0320625)" d="M598 214h212v212h-84v-128h-128v-84zM726 726v-128h84v212h-212v-84h128zM214 426v-212h212v84h-128v128h-84zM298 598v128h128v84h-212v-212h84z"></path>\n</svg>\n'},function(e,t,n){"use strict";n.r(t),t.default='<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40">\n <path transform="scale(0.0320625 0.0320625)" d="M682 342h128v84h-212v-212h84v128zM598 810v-212h212v84h-128v128h-84zM342 342v-128h84v212h-212v-84h128zM214 682v-84h212v212h-84v-128h-128z"></path>\n</svg>\n'},function(e,t,n){"use strict";var a=o(n(0)),r=o(n(76)),i=o(n(77));function o(e){return e&&e.__esModule?e:{default:e}}a.default.install("s_cssFullscreen",(function(){var e=this,t=a.default.util;if(e.config.cssFullscreen){var n=t.createDom("xg-cssfullscreen",'<xg-icon class="xgplayer-icon">\n <div class="xgplayer-icon-requestfull">'+r.default+'</div>\n <div class="xgplayer-icon-exitfull">'+i.default+"</div>\n </xg-icon>",{},"xgplayer-cssfullscreen"),o={};o.requestfull=e.lang.CSSFULLSCREEN_TIPS,o.exitfull=e.lang.EXITCSSFULLSCREEN_TIPS;var l=t.createDom("xg-tips",'<span class="xgplayer-tip-requestfull">'+o.requestfull+'</span>\n <span class="xgplayer-tip-exitfull">'+o.exitfull+"</span>",{},"xgplayer-tips");n.appendChild(l),e.once("ready",(function(){e.controls.appendChild(n)})),["click","touchend"].forEach((function(t){n.addEventListener(t,(function(t){t.preventDefault(),t.stopPropagation(),e.emit("cssFullscreenBtnClick")}))}))}}))},function(e,t,n){"use strict";n.r(t),t.default='<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40">\n <path transform="scale(0.028 0.028)" d="M843.617212 67.898413 175.411567 67.898413c-61.502749 0-111.367437 49.856501-111.367437 111.367437l0 668.205645c0 61.510936 49.864688 111.367437 111.367437 111.367437L843.617212 958.838931c61.510936 0 111.367437-49.856501 111.367437-111.367437L954.984648 179.26585C954.984648 117.754914 905.12917 67.898413 843.617212 67.898413zM398.146441 736.104057c15.380292 0 27.842115 12.461823 27.842115 27.842115 0 15.379269-12.461823 27.841092-27.842115 27.841092L259.725858 791.787264c-7.785314 0-14.781658-3.217275-19.838837-8.365528-5.383614-4.577249-8.791224-11.228739-8.791224-19.475564L231.095797 624.736621c0-15.371082 12.471033-27.842115 27.842115-27.842115 15.380292 0 27.842115 12.471033 27.842115 27.842115l-0.61603 71.426773 133.036969-133.037992 39.378869 39.378869L324.962651 736.113267 398.146441 736.104057zM419.199942 463.611943 286.162974 330.565764l0.61603 71.435982c0 15.380292-12.461823 27.842115-27.842115 27.842115-15.371082 0-27.842115-12.461823-27.842115-27.842115L231.094774 262.791172c0-8.256034 3.40761-14.908548 8.791224-19.476587 5.057179-5.148253 12.053524-8.374738 19.838837-8.374738l138.420583 0.00921c15.380292 0 27.842115 12.461823 27.842115 27.842115s-12.461823 27.842115-27.842115 27.842115l-73.175603-0.00921 133.607974 133.607974L419.199942 463.611943zM787.932981 763.946172c0 8.247848-3.40761 14.899338-8.791224 19.475564-5.057179 5.148253-12.053524 8.365528-19.839861 8.365528L620.881314 791.787264c-15.379269 0-27.841092-12.461823-27.841092-27.841092 0-15.380292 12.461823-27.842115 27.841092-27.842115l73.185836 0.00921L560.449967 602.50427l39.378869-39.378869L732.875015 696.163393l-0.62524-71.426773c0-15.371082 12.462846-27.842115 27.842115-27.842115 15.380292 0 27.842115 12.471033 27.842115 27.842115L787.934005 763.946172zM787.932981 402.000724c0 15.380292-12.461823 27.842115-27.842115 27.842115-15.379269 0-27.842115-12.461823-27.842115-27.842115l0.62524-71.435982L599.828836 463.611943l-39.378869-39.378869 133.617184-133.607974-73.185836 0.00921c-15.379269 0-27.841092-12.461823-27.841092-27.842115s12.461823-27.842115 27.841092-27.842115l138.421606-0.00921c7.785314 0 14.781658 3.226484 19.839861 8.374738 5.383614 4.568039 8.791224 11.219529 8.791224 19.476587L787.934005 402.000724z"></path>\n</svg>\n'},function(e,t,n){"use strict";n.r(t),t.default='<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40">\n <path transform="scale(0.028 0.028)" d="M834.56 81.92H189.44c-59.392 0-107.52 48.128-107.52 107.52v645.12c0 59.392 48.128 107.52 107.52 107.52h645.12c59.392 0 107.52-48.128 107.52-107.52V189.44c0-59.392-48.128-107.52-107.52-107.52zM458.24 727.04c0 14.848-12.288 26.624-26.624 26.624S404.48 741.888 404.48 727.04v-69.632L289.28 773.12c-10.752 10.24-27.648 10.24-37.888 0-10.24-10.752-10.24-27.648 0-37.888L366.592 619.52H296.96c-14.848 0-26.624-12.288-26.624-26.624s12.288-26.624 26.624-26.624h134.144c14.848 0 26.624 12.288 26.624 26.624V727.04z m0-295.936c0 14.848-12.288 26.624-26.624 26.624H296.96c-14.848 0-26.624-12.288-26.624-26.624S282.112 404.48 296.96 404.48h69.632L251.392 289.28c-10.24-10.752-10.24-27.648 0-37.888 5.12-5.12 12.288-7.68 18.944-7.68 6.656 0 13.824 2.56 18.944 7.68L404.48 366.592V296.96c0-14.848 12.288-26.624 26.624-26.624s26.624 12.288 26.624 26.624v134.144zM773.12 773.12c-10.752 10.24-27.648 10.24-37.888 0L619.52 657.408V727.04c0 14.848-12.288 26.624-26.624 26.624s-26.624-11.776-26.624-26.624v-134.144c0-14.848 12.288-26.624 26.624-26.624H727.04c14.848 0 26.624 12.288 26.624 26.624s-12.288 26.624-26.624 26.624h-69.632l115.2 115.2c10.752 10.752 10.752 27.648 0.512 38.4z m0-483.84L657.408 404.48H727.04c14.848 0 26.624 12.288 26.624 26.624 0 14.848-12.288 26.624-26.624 26.624h-134.144c-14.848 0-26.624-12.288-26.624-26.624V296.96c0-14.848 12.288-26.624 26.624-26.624s26.624 12.288 26.624 26.624v69.632L734.72 250.88c5.12-5.12 12.288-7.68 18.944-7.68s13.824 2.56 18.944 7.68c10.752 10.752 10.752 27.648 0.512 38.4z"></path>\n</svg>\n'},function(e,t,n){"use strict";var a=l(n(0)),r=l(n(79)),i=l(n(80)),o=l(n(81));function l(e){return e&&e.__esModule?e:{default:e}}a.default.install("s_volume",(function(){var e=this,t=a.default.util.createDom("xg-volume",'<xg-icon class="xgplayer-icon">\n <div class="xgplayer-icon-large">'+o.default+'</div>\n <div class="xgplayer-icon-small">'+i.default+'</div>\n <div class="xgplayer-icon-muted">'+r.default+'</div>\n </xg-icon>\n <xg-slider class="xgplayer-slider" tabindex="2">\n <xg-bar class="xgplayer-bar">\n <xg-drag class="xgplayer-drag"></xg-drag>\n </xg-bar>\n </xg-slider>',{},"xgplayer-volume");e.once("ready",(function(){e.controls.appendChild(t)}));var n=t.querySelector(".xgplayer-slider"),l=t.querySelector(".xgplayer-bar"),s=t.querySelector(".xgplayer-drag"),u=t.querySelector(".xgplayer-icon");s.style.height=100*e.config.volume+"%",n.volume=e.config.volume,l.addEventListener("mousedown",(function(t){t.preventDefault(),t.stopPropagation(),e.emit("volumeBarClick",t)})),["click","touchend"].forEach((function(t){u.addEventListener(t,(function(t){t.preventDefault(),t.stopPropagation(),e.emit("volumeIconClick")}))})),u.addEventListener("mouseenter",(function(t){t.preventDefault(),t.stopPropagation(),e.emit("volumeIconEnter")})),["blur","mouseleave"].forEach((function(n){t.addEventListener(n,(function(t){t.preventDefault(),t.stopPropagation(),e.emit("volumeIconLeave")}))}))}))},function(e,t,n){"use strict";n.r(t),t.default='<svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 28 28">\n <path transform="scale(0.0220625 0.0220625)" d="M358.4 358.4h-204.8v307.2h204.8l256 256v-819.2l-256 256z"></path>\n <path transform="scale(0.0220625 0.0220625)" d="M920.4 439.808l-108.544-109.056-72.704 72.704 109.568 108.544-109.056 108.544 72.704 72.704 108.032-109.568 108.544 109.056 72.704-72.704-109.568-108.032 109.056-108.544-72.704-72.704-108.032 109.568z"></path>\n</svg>\n'},function(e,t,n){"use strict";n.r(t),t.default='<svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 28 28">\n <path transform="scale(0.0220625 0.0220625)" d="M358.4 358.4h-204.8v307.2h204.8l256 256v-819.2l-256 256z"></path>\n <path transform="scale(0.0220625 0.0220625)" d="M795.648 693.248l-72.704-72.704c27.756-27.789 44.921-66.162 44.921-108.544s-17.165-80.755-44.922-108.546l0.002 0.002 72.704-72.704c46.713 46.235 75.639 110.363 75.639 181.248s-28.926 135.013-75.617 181.227l-0.021 0.021zM795.648 693.248l-72.704-72.704c27.756-27.789 44.921-66.162 44.921-108.544s-17.165-80.755-44.922-108.546l0.002 0.002 72.704-72.704c46.713 46.235 75.639 110.363 75.639 181.248s-28.926 135.013-75.617 181.227l-0.021 0.021z"></path>\n</svg>\n'},function(e,t,n){"use strict";n.r(t),t.default='<svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 28 28">\n <path transform="scale(0.0220625 0.0220625)" d="M358.4 358.4h-204.8v307.2h204.8l256 256v-819.2l-256 256z"></path>\n <path transform="scale(0.0220625 0.0220625)" d="M940.632 837.632l-72.192-72.192c65.114-64.745 105.412-154.386 105.412-253.44s-40.299-188.695-105.396-253.424l-0.016-0.016 72.192-72.192c83.639 83.197 135.401 198.37 135.401 325.632s-51.762 242.434-135.381 325.612l-0.020 0.020zM795.648 693.248l-72.704-72.704c27.756-27.789 44.921-66.162 44.921-108.544s-17.165-80.755-44.922-108.546l0.002 0.002 72.704-72.704c46.713 46.235 75.639 110.363 75.639 181.248s-28.926 135.013-75.617 181.227l-0.021 0.021z"></path>\n</svg>\n'},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("s_definition",(function(){var e=this,t=e.root,n=i.default.util,a=i.default.sniffer,r=void 0,o=n.createDom("xg-definition","",{tabindex:3},"xgplayer-definition");function l(){var a=e.definitionList,r=["<ul>"],i=e.config.url,l=document.createElement("a");e.switchURL?["mp4","hls","__flv__","dash"].every((function(t){return!e[t]||(e[t].url&&(l.href=e[t].url),"__flv__"===t&&(e[t]._options?l.href=e[t]._options.url:l.href=e[t]._mediaDataSource.url),i=l.href,!1)})):i=e.currentSrc||e.src,e.hls&&(l.href=e.hls.url,i=l.href),a.forEach((function(t){l.href=t.url,e.dash?r.push("<li url='"+t.url+"' cname='"+t.name+"' class='"+(t.selected?"selected":"")+"'>"+t.name+"</li>"):r.push("<li url='"+t.url+"' cname='"+t.name+"' class='"+(l.href===i?"selected":"")+"'>"+t.name+"</li>")}));var s=a.filter((function(t){return l.href=t.url,e.dash?!0===t.selected:l.href===i}));r.push("</ul><p class='name'>"+(s[0]||{name:""}).name+"</p>");var u=t.querySelector(".xgplayer-definition");if(u){u.innerHTML=r.join("");var c=u.querySelector(".name");e.config.definitionActive&&"hover"!==e.config.definitionActive||c.addEventListener("mouseenter",(function(t){t.preventDefault(),t.stopPropagation(),n.addClass(e.root,"xgplayer-definition-active"),u.focus()}))}else{o.innerHTML=r.join("");var p=o.querySelector(".name");e.config.definitionActive&&"hover"!==e.config.definitionActive||p.addEventListener("mouseenter",(function(t){t.preventDefault(),t.stopPropagation(),n.addClass(e.root,"xgplayer-definition-active"),o.focus()})),e.controls.appendChild(o)}}function s(a){e.definitionList=a,a&&a instanceof Array&&a.length>1&&(n.addClass(t,"xgplayer-is-definition"),e.on("canplay",l))}function u(){if(e.currentTime=e.curTime,!r){var t=e.play();void 0!==t&&t&&t.catch((function(e){}))}}function c(){n.removeClass(t,"xgplayer-definition-active")}"mobile"===a.device&&(e.config.definitionActive="click"),e.on("resourceReady",s),["touchend","click"].forEach((function(t){o.addEventListener(t,(function(t){t.preventDefault(),t.stopPropagation();var i=e.definitionList,l=t.target||t.srcElement,s=document.createElement("a");if(l&&"li"===l.tagName.toLocaleLowerCase()){e.emit("beforeDefinitionChange",s.href);var c,p=void 0;if(Array.prototype.forEach.call(l.parentNode.childNodes,(function(e){n.hasClass(e,"selected")&&(p=e.getAttribute("cname"),n.removeClass(e,"selected"))})),e.dash&&i.forEach((function(e){e.selected=!1,e.name===l.innerHTML&&(e.selected=!0)})),n.addClass(l,"selected"),c=l.getAttribute("cname"),l.parentNode.nextSibling.innerHTML=""+l.getAttribute("cname"),s.href=l.getAttribute("url"),e.switchURL){var d=document.createElement("a");["mp4","hls","__flv__","dash"].every((function(t){return!e[t]||(e[t].url&&(d.href=e[t].url),"__flv__"===t&&(e[t]._options?d.href=e[t]._options.url:d.href=e[t]._mediaDataSource.url),!1)})),d.href===s.href||e.ended||e.switchURL(s.href)}else{if(e.hls){document.createElement("a");e.hls.url}s.href!==e.currentSrc&&(e.curTime=e.currentTime,r=e.paused,e.ended||(e.src=s.href,e.once("canplay",u)))}e.emit("definitionChange",{from:p,to:c}),"mobile"===a.device&&n.removeClass(e.root,"xgplayer-definition-active")}else"click"!==e.config.definitionActive||!l||"p"!==l.tagName.toLocaleLowerCase()&&"em"!==l.tagName.toLocaleLowerCase()||("mobile"===a.device?n.toggleClass(e.root,"xgplayer-definition-active"):n.addClass(e.root,"xgplayer-definition-active"),o.focus());e.emit("focus")}),!1)})),o.addEventListener("mouseleave",(function(e){e.preventDefault(),e.stopPropagation(),n.removeClass(t,"xgplayer-definition-active")})),e.on("blur",c),e.once("destroy",(function t(){e.off("resourceReady",s),e.off("canplay",l),e.off("canplay",u),e.off("blur",c),e.off("destroy",t)}))}))},function(e,t,n){"use strict";var a=i(n(0)),r=i(n(84));function i(e){return e&&e.__esModule?e:{default:e}}a.default.install("s_loading",(function(){var e=this.root,t=a.default.util.createDom("xg-loading",""+r.default,{},"xgplayer-loading");this.once("ready",(function(){e.appendChild(t)}))}))},function(e,t,n){"use strict";n.r(t),t.default='<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewbox="0 0 100 100">\n <path d="M100,50A50,50,0,1,1,50,0"></path>\n</svg>\n'},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};var o=function(e){return i.default.util.hasClass(e.root,"xgplayer-rotate-fullscreen")};i.default.install("s_progress",(function(){var e=this,t=i.default.util,n=t.createDom("xg-progress",'<xg-outer class="xgplayer-progress-outer">\n <xg-cache class="xgplayer-progress-cache"></xg-cache>\n <xg-played class="xgplayer-progress-played">\n <xg-progress-btn class="xgplayer-progress-btn"></xg-progress-btn>\n <xg-point class="xgplayer-progress-point xgplayer-tips"></xg-point>\n <xg-thumbnail class="xgplayer-progress-thumbnail xgplayer-tips"></xg-thumbnail>\n </xg-played>\n </xg-outer>',{tabindex:1},"xgplayer-progress"),a=void 0;e.controls.appendChild(n);var r=n.querySelector(".xgplayer-progress-played"),l=(n.querySelector(".xgplayer-progress-btn"),n.querySelector(".xgplayer-progress-outer")),s=n.querySelector(".xgplayer-progress-cache"),u=n.querySelector(".xgplayer-progress-point"),c=n.querySelector(".xgplayer-progress-thumbnail");function p(a,r){a.addEventListener("mouseenter",(function(e){r&&(t.addClass(a,"xgplayer-progress-dot-show"),t.addClass(n,"xgplayer-progress-dot-active"))})),a.addEventListener("mouseleave",(function(e){r&&(t.removeClass(a,"xgplayer-progress-dot-show"),t.removeClass(n,"xgplayer-progress-dot-active"))})),a.addEventListener("touchend",(function(i){i.stopPropagation(),r&&(t.hasClass(a,"xgplayer-progress-dot-show")||Object.keys(e.dotArr).forEach((function(n){e.dotArr[n]&&t.removeClass(e.dotArr[n],"xgplayer-progress-dot-show")})),t.toggleClass(a,"xgplayer-progress-dot-show"),t.toggleClass(n,"xgplayer-progress-dot-active"))}))}function d(){e.config.progressDot&&"Array"===t.typeOf(e.config.progressDot)&&e.config.progressDot.forEach((function(n){if(n.time>=0&&n.time<=e.duration){var a=t.createDom("xg-progress-dot",n.text?'<span class="xgplayer-progress-tip">'+n.text+"</span>":"",{},"xgplayer-progress-dot");a.style.left=n.time/e.duration*100+"%",n.duration>=0&&(a.style.width=Math.min(n.duration,e.duration-n.time)/e.duration*100+"%"),l.appendChild(a),e.dotArr[n.time]=a,p(a,n.text)}}))}e.dotArr={},e.once("canplay",d),e.addProgressDot=function(n,a,r){if(!e.dotArr[n]&&n>=0&&n<=e.duration){var i=t.createDom("xg-progress-dot","",{},"xgplayer-progress-dot");i.style.left=n/e.duration*100+"%",r>=0&&(i.style.width=Math.min(r,e.duration-n)/e.duration*100+"%"),l.appendChild(i),e.dotArr[n]=i,p(i,a)}},e.removeProgressDot=function(t){if(t>=0&&t<=e.duration&&e.dotArr[t]){var n=e.dotArr[t];n.parentNode.removeChild(n),n=null,e.dotArr[t]=null}},e.removeAllProgressDot=function(){Object.keys(e.dotArr).forEach((function(t){if(e.dotArr[t]){var n=e.dotArr[t];n.parentNode.removeChild(n),n=null,e.dotArr[t]=null}}))};var f=0,g=0,y=0,h=0,x=0,m=0,v=[];e.config.thumbnail&&(f=e.config.thumbnail.pic_num,g=e.config.thumbnail.width,y=e.config.thumbnail.height,h=e.config.thumbnail.col,x=e.config.thumbnail.row,v=e.config.thumbnail.urls,c.style.width=g+"px",c.style.height=y+"px"),"function"==typeof e.config.disableSwipeHandler&&"function"==typeof e.config.enableSwipeHandler&&(e.root.addEventListener("touchmove",(function(t){t.preventDefault(),e.disableSwipe||(e.disableSwipe=!0,e.config.disableSwipeHandler.call(e))})),e.root.addEventListener("touchstart",(function(t){e.disableSwipe=!0,e.config.disableSwipeHandler.call(e)})),e.root.addEventListener("touchend",(function(t){e.disableSwipe=!1,e.config.enableSwipeHandler.call(e)}))),["touchstart","mousedown"].forEach((function(i){n.addEventListener(i,(function(i){if(!e.config.disableProgress){if(i.stopPropagation(),t.event(i),i._target===u||!e.config.allowSeekAfterEnded&&e.ended)return!0;n.focus();var l=r.getBoundingClientRect().left,s=o(e);s?(l=r.getBoundingClientRect().top,a=n.getBoundingClientRect().height):(a=n.getBoundingClientRect().width,l=r.getBoundingClientRect().left);var c=function(n){n.stopPropagation(),t.event(n),e.isProgressMoving=!0;var i=(s?n.clientY:n.clientX)-l;i>a&&(i=a);var o=i/a*e.duration;if(r.style.width=100*i/a+"%","video"!==e.videoConfig.mediaType||e.dash||e.config.closeMoveSeek){var u=t.findDom(e.controls,".xgplayer-time");u&&(u.innerHTML='<span class="xgplayer-time-current">'+t.format(o||0)+"</span><span>"+t.format(e.duration)+"</span>")}else e.currentTime=Number(o).toFixed(1);e.emit("focus")},p=function i(o){if(o.stopPropagation(),t.event(o),window.removeEventListener("mousemove",c),window.removeEventListener("touchmove",c,{passive:!1}),window.removeEventListener("mouseup",i),window.removeEventListener("touchend",i),n.blur(),!e.isProgressMoving||"audio"===e.videoConfig.mediaType||e.dash||e.config.closeMoveSeek){var u=(s?o.clientY:o.clientX)-l;u>a&&(u=a);var p=u/a*e.duration;r.style.width=100*u/a+"%",e.currentTime=Number(p).toFixed(1)}e.emit("focus"),e.isProgressMoving=!1};return window.addEventListener("mousemove",c),window.addEventListener("touchmove",c,{passive:!1}),window.addEventListener("mouseup",p),window.addEventListener("touchend",p),!0}}))})),n.addEventListener("mouseenter",(function(a){if(!e.config.allowSeekAfterEnded&&e.ended)return!0;var r=o(e),i=r?n.getBoundingClientRect().top:n.getBoundingClientRect().left,l=r?n.getBoundingClientRect().height:n.getBoundingClientRect().width,s=function(a){var o=((r?a.clientY:a.clientX)-i)/l*e.duration;o=o<0?0:o,u.textContent=t.format(o);var s=u.getBoundingClientRect().width;if(e.config.thumbnail){m=e.duration/f;var p=Math.floor(o/m);c.style.backgroundImage="url("+v[Math.ceil((p+1)/(h*x))-1]+")";var d=p+1-h*x*(Math.ceil((p+1)/(h*x))-1),b=Math.ceil(d/x)-1,k=d-b*x-1;c.style["background-position"]="-"+k*g+"px -"+b*y+"px";var w=(r?a.clientY:a.clientX)-i-g/2;w=(w=w>0?w:0)<l-g?w:l-g,c.style.left=w+"px",c.style.top=-10-y+"px",c.style.display="block",u.style.left=w+g/2-s/2+"px"}else{var _=a.clientX-i-s/2;_=(_=_>0?_:0)>l-s?l-s:_,u.style.left=_+"px"}t.hasClass(n,"xgplayer-progress-dot-active")?u.style.display="none":u.style.display="block"},p=function(e){s(e)};n.addEventListener("mousemove",p,!1),n.addEventListener("mouseleave",(function e(t){n.removeEventListener("mousemove",p,!1),n.removeEventListener("mouseleave",e,!1),s(t),u.style.display="none",c.style.display="none"}),!1),s(a)}),!1);var b=function(){if(!a&&n&&(a=n.getBoundingClientRect().width),"audio"!==e.videoConfig.mediaType||!e.isProgressMoving||!e.dash){var t=e.currentTime/e.duration,i=Number(r.style.width.replace("%","")||"0")/Number(n.style.width||"100");Math.abs(t-i)<=1&&(r.style.width=100*e.currentTime/e.duration+"%")}};e.on("timeupdate",b);var k=function(){r.style.width=100*e.currentTime/e.duration+"%"};e.on("currentTimeChange",k);var w=function(){r.style.width="0%"};e.on("srcChange",w);var _=function(){var t=e.buffered;if(t&&t.length>0){for(var n=t.end(t.length-1),a=0,r=t.length;a<r;a++)if(e.currentTime>=t.start(a)&&e.currentTime<=t.end(a)){n=t.end(a);for(var i=a+1;i<t.length;i++)if(t.start(i)-t.end(i-1)>=2){n=t.end(i-1);break}break}s.style.width=n/e.duration*100+"%"}},E=["bufferedChange","cacheupdate","ended","timeupdate"];E.forEach((function(t){e.on(t,_)})),e.once("destroy",(function t(){e.removeAllProgressDot(),e.off("canplay",d),e.off("timeupdate",b),e.off("currentTimeChange",k),e.off("srcChange",w),E.forEach((function(t){e.off(t,_)})),e.off("destroy",t)}))}))},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("s_time",(function(){var e=this,t=(e.root,i.default.util),n=t.createDom("xg-time",'<span class="xgplayer-time-current">'+(e.currentTime||t.format(0))+"</span>\n <span>"+(e.duration||t.format(0))+"</span>",{},"xgplayer-time");e.once("ready",(function(){e.controls.appendChild(n)}));var a=function(){"audio"===e.videoConfig.mediaType&&e.isProgressMoving&&e.dash||(n.innerHTML='<span class="xgplayer-time-current">'+t.format(e.currentTime||0)+"</span><span>"+t.format(e.duration)+"</span>")};e.on("durationchange",a),e.on("timeupdate",a),e.once("destroy",(function t(){e.off("durationchange",a),e.off("timeupdate",a),e.off("destroy",t)}))}))},function(e,t,n){"use strict";var a=i(n(0)),r=i(n(88));function i(e){return e&&e.__esModule?e:{default:e}}a.default.install("s_replay",(function(){var e=this,t=a.default.util,n=e.root,i=e.lang.REPLAY,o=t.createDom("xg-replay",r.default+'\n <xg-replay-txt class="xgplayer-replay-txt">'+i+"</xg-replay-txt>\n ",{},"xgplayer-replay");function l(){var e=o.querySelector("path");if(e){var t=window.getComputedStyle(e).getPropertyValue("transform");if("string"==typeof t&&t.indexOf("none")>-1)return;e.setAttribute("transform",t)}}e.once("ready",(function(){n.appendChild(o)})),e.on("ended",l);var s=o.querySelector("svg");["click","touchend"].forEach((function(t){s.addEventListener(t,(function(t){t.preventDefault(),t.stopPropagation(),e.emit("replayBtnClick")}))})),e.once("destroy",(function t(){e.off("ended",l),e.off("destroy",t)}))}))},function(e,t,n){"use strict";n.r(t),t.default='<svg class="xgplayer-replay-svg" xmlns="http://www.w3.org/2000/svg" width="78" height="78" viewbox="0 0 78 78">\n <path d="M8.22708362,13.8757234 L11.2677371,12.6472196 C11.7798067,12.4403301 12.3626381,12.6877273 12.5695276,13.1997969 L12.9441342,14.1269807 C13.1510237,14.6390502 12.9036264,15.2218816 12.3915569,15.4287712 L6.8284538,17.6764107 L5.90126995,18.0510173 C5.38920044,18.2579068 4.80636901,18.0105096 4.5994795,17.49844 L1.97723335,11.0081531 C1.77034384,10.4960836 2.0177411,9.91325213 2.52981061,9.70636262 L3.45699446,9.33175602 C3.96906396,9.12486652 4.5518954,9.37226378 4.75878491,9.88433329 L5.67885163,12.1615783 C7.99551726,6.6766934 13.3983951,3 19.5,3 C27.7842712,3 34.5,9.71572875 34.5,18 C34.5,26.2842712 27.7842712,33 19.5,33 C15.4573596,33 11.6658607,31.3912946 8.87004692,28.5831991 C8.28554571,27.9961303 8.28762719,27.0463851 8.87469603,26.4618839 C9.46176488,25.8773827 10.4115101,25.8794641 10.9960113,26.466533 C13.2344327,28.7147875 16.263503,30 19.5,30 C26.127417,30 31.5,24.627417 31.5,18 C31.5,11.372583 26.127417,6 19.5,6 C14.4183772,6 9.94214483,9.18783811 8.22708362,13.8757234 Z"></path>\n</svg>\n'},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("s_playbackRate",(function(){var e=this,t=i.default.sniffer,n=i.default.util;if(!e.config.playbackRate)return!1;e.config.playbackRate.sort((function(e,t){return t-e}));var a=n.createDom("xg-playbackrate"," ",{},"xgplayer-playbackrate");"mobile"===t.device&&(e.config.playbackRateActive="click");var r=[];e.config.playbackRate.forEach((function(e){r.push({name:""+e,rate:e+"x",selected:!1})}));var o=1,l=["<ul>"];r.forEach((function(t){e.config.defaultPlaybackRate&&e.config.defaultPlaybackRate.toString()===t.name?(t.selected=!0,o=e.config.defaultPlaybackRate,e.once("playing",(function(){e.video.playbackRate=e.config.defaultPlaybackRate}))):"1.0"!==t.name&&"1"!==t.name||e.config.defaultPlaybackRate&&1!==e.config.defaultPlaybackRate||(t.selected=!0),l.push("<li cname='"+t.name+"' class='"+(t.selected?"selected":"")+"'>"+t.rate+"</li>")})),l.push("</ul><p class='name'>"+o+"x</p>");var s=e.root.querySelector(".xgplayer-playbackrate");if(s){s.innerHTML=l.join("");var u=s.querySelector(".name");e.config.playbackRateActive&&"hover"!==e.config.playbackRateActive||u.addEventListener("mouseenter",(function(t){t.preventDefault(),t.stopPropagation(),n.addClass(e.root,"xgplayer-playbackrate-active"),s.focus()}))}else{a.innerHTML=l.join("");var c=a.querySelector(".name");e.config.playbackRateActive&&"hover"!==e.config.playbackRateActive||c.addEventListener("mouseenter",(function(t){t.preventDefault(),t.stopPropagation(),n.addClass(e.root,"xgplayer-playbackrate-active"),a.focus()})),e.once("ready",(function(){e.controls.appendChild(a)}))}["touchend","click"].forEach((function(i){a.addEventListener(i,(function(i){i.stopPropagation(),i.preventDefault();var l=i.target;if(l&&"li"===l.tagName.toLocaleLowerCase()){var s,u=void 0;r.forEach((function(t){t.selected=!1,l.textContent.replace(/\s+/g,"")===t.rate&&(Array.prototype.forEach.call(l.parentNode.childNodes,(function(e){n.hasClass(e,"selected")&&(u=Number(e.getAttribute("cname")),n.removeClass(e,"selected"))})),t.selected=!0,e.video.playbackRate=1*t.name,o=1*t.name)})),n.addClass(l,"selected"),s=Number(l.getAttribute("cname")),l.parentNode.nextSibling.innerHTML=l.getAttribute("cname")+"x",e.emit("playbackrateChange",{from:u,to:s}),"mobile"===t.device&&n.removeClass(e.root,"xgplayer-playbackrate-active")}else"click"!==e.config.playbackRateActive||!l||"p"!==l.tagName.toLocaleLowerCase()&&"span"!==l.tagName.toLocaleLowerCase()||("mobile"===t.device?n.toggleClass(e.root,"xgplayer-playbackrate-active"):n.addClass(e.root,"xgplayer-playbackrate-active"),a.focus());e.emit("focus")}),!1)})),a.addEventListener("mouseleave",(function(t){t.preventDefault(),t.stopPropagation(),n.removeClass(e.root,"xgplayer-playbackrate-active")})),e.on("blur",(function(){n.removeClass(e.root,"xgplayer-playbackrate-active")})),e.on("play",(function(){e.video.playbackRate.toFixed(1)!==o.toFixed(1)&&(e.video.playbackRate=o)}))}))},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("s_localPreview",(function(){var e=this,t=(e.root,i.default.util);if(e.config.preview&&e.config.preview.uploadEl){var n=t.createDom("xg-preview",'<input type="file">',{},"xgplayer-preview"),a=n.querySelector("input");e.config.preview.uploadEl.appendChild(n),a.onchange=function(){e.emit("upload",a)}}}))},function(e,t,n){"use strict";var a=i(n(0)),r=i(n(92));function i(e){return e&&e.__esModule?e:{default:e}}a.default.install("s_download",(function(){var e=this,t=a.default.util;if(e.config.download){var n=t.createDom("xg-download",'<xg-icon class="xgplayer-icon">'+r.default+"</xg-icon>",{},"xgplayer-download"),i=e.lang.DOWNLOAD_TIPS,o=t.createDom("xg-tips",'<span class="xgplayer-tip-download">'+i+"</span>",{},"xgplayer-tips");n.appendChild(o),e.once("ready",(function(){e.controls.appendChild(n)})),["click","touchend"].forEach((function(t){n.addEventListener(t,(function(t){t.preventDefault(),t.stopPropagation(),e.emit("downloadBtnClick")}))}))}}))},function(e,t,n){"use strict";n.r(t),t.default='<svg xmlns="http://www.w3.org/2000/svg" width="24px" height="24px" viewBox="0 0 24 24">\n <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\n <g transform="translate(-488.000000, -340.000000)" fill="#FFFFFF">\n <g id="Group-2">\n <g id="volme_big-copy" transform="translate(488.000000, 340.000000)">\n <rect id="Rectangle-18" x="11" y="4" width="2" height="12" rx="1"></rect>\n <rect id="Rectangle-2" x="3" y="18" width="18" height="2" rx="1"></rect>\n <rect id="Rectangle-2" transform="translate(4.000000, 17.500000) rotate(90.000000) translate(-4.000000, -17.500000) " x="1.5" y="16.5" width="5" height="2" rx="1"></rect><rect id="Rectangle-2-Copy-3" transform="translate(20.000000, 17.500000) rotate(90.000000) translate(-20.000000, -17.500000) " x="17.5" y="16.5" width="5" height="2" rx="1"></rect>\n <path d="M9.48791171,8.26502656 L9.48791171,14.2650266 C9.48791171,14.8173113 9.04019646,15.2650266 8.48791171,15.2650266 C7.93562696,15.2650266 7.48791171,14.8173113 7.48791171,14.2650266 L7.48791171,7.26502656 C7.48791171,6.71274181 7.93562696,6.26502656 8.48791171,6.26502656 L15.4879117,6.26502656 C16.0401965,6.26502656 16.4879117,6.71274181 16.4879117,7.26502656 C16.4879117,7.81731131 16.0401965,8.26502656 15.4879117,8.26502656 L9.48791171,8.26502656 Z" id="Combined-Shape" transform="translate(11.987912, 10.765027) scale(1, -1) rotate(45.000000) translate(-11.987912, -10.765027) "></path>\n </g>\n </g>\n </g>\n </g>\n</svg>\n'},function(e,t,n){"use strict";var a=o(n(0)),r=o(n(94)),i=o(n(96));function o(e){return e&&e.__esModule?e:{default:e}}a.default.install("s_danmu",(function(){var e=this,t=e.root,n=a.default.util;if(e.config.danmu){var o=n.createDom("xg-danmu","",{},"xgplayer-danmu");e.once("ready",(function(){t.appendChild(o)}));var l=n.deepCopy({container:o,player:e.video,comments:[],area:{start:0,end:1}},e.config.danmu),s=void 0;e.config.danmu.panel&&(s=a.default.util.createDom("xg-panel",'<xg-panel-icon class="xgplayer-panel-icon">\n '+i.default+'\n </xg-panel-icon>\n <xg-panel-slider class="xgplayer-panel-slider">\n <xg-hidemode class="xgplayer-hidemode">\n <p class="xgplayer-hidemode-font">屏蔽类型</p>\n <ul class="xgplayer-hidemode-radio">\n <li class="xgplayer-hidemode-scroll" id="false">滚动</li><li class="xgplayer-hidemode-top" id="false">顶部</li><li class="xgplayer-hidemode-bottom" id="false">底部</li><li class="xgplayer-hidemode-color" id="false">色彩</li>\n </ul>\n </xg-hidemode>\n <xg-transparency class="xgplayer-transparency">\n <span>不透明度</span>\n <input class="xgplayer-transparency-line xgplayer-transparency-color xgplayer-transparency-bar xgplayer-transparency-gradient" type="range" min="0" max="100" step="0.1" value="50"></input>\n </xg-transparency>\n <xg-showarea class="xgplayer-showarea">\n <div class="xgplayer-showarea-name">显示区域</div>\n <div class="xgplayer-showarea-control">\n <div class="xgplayer-showarea-control-up">\n <span class="xgplayer-showarea-control-up-item xgplayer-showarea-onequarters">1/4</span>\n <span class="xgplayer-showarea-control-up-item xgplayer-showarea-twoquarters selected-color">1/2</span>\n <span class="xgplayer-showarea-control-up-item xgplayer-showarea-threequarters">3/4</span>\n <span class="xgplayer-showarea-control-up-item xgplayer-showarea-full">1</span>\n </div>\n <div class="xgplayer-showarea-control-down">\n <div class="xgplayer-showarea-control-down-dots">\n <span class="xgplayer-showarea-onequarters-dot"></span>\n <span class="xgplayer-showarea-twoquarters-dot"></span>\n <span class="xgplayer-showarea-threequarters-dot"></span>\n <span class="xgplayer-showarea-full-dot"></span>\n </div>\n <input class="xgplayer-showarea-line xgplayer-showarea-color xgplayer-showarea-bar xgplayer-gradient" type="range" min="1" max="4" step="1" value="1">\n </div>\n </div>\n </xg-showarea>\n <xg-danmuspeed class="xgplayer-danmuspeed">\n <div class="xgplayer-danmuspeed-name">弹幕速度</div>\n <div class="xgplayer-danmuspeed-control">\n <div class="xgplayer-danmuspeed-control-up">\n <span class="xgplayer-danmuspeed-control-up-item xgplayer-danmuspeed-small">慢</span>\n <span class="xgplayer-danmuspeed-control-up-item xgplayer-danmuspeed-middle selected-color">中</span>\n <span class="xgplayer-danmuspeed-control-up-item xgplayer-danmuspeed-large">快</span>\n </div>\n <div class="xgplayer-danmuspeed-control-down">\n <div class="xgplayer-danmuspeed-control-down-dots">\n <span class="xgplayer-danmuspeed-small-dot"></span>\n <span class="xgplayer-danmuspeed-middle-dot"></span>\n <span class="xgplayer-danmuspeed-large-dot"></span>\n </div>\n <input class="xgplayer-danmuspeed-line xgplayer-danmuspeed-color xgplayer-danmuspeed-bar xgplayer-gradient" type="range" min="50" max="150" step="50" value="100">\n </div>\n </div>\n </xg-danmuspeed>\n <xg-danmufont class="xgplayer-danmufont">\n <div class="xgplayer-danmufont-name">字体大小</div>\n <div class="xgplayer-danmufont-control">\n <div class="xgplayer-danmufont-control-up">\n <span class="xgplayer-danmufont-control-up-item xgplayer-danmufont-small">小</span>\n <span class="xgplayer-danmufont-control-up-item xgplayer-danmufont-middle">中</span>\n <span class="xgplayer-danmufont-control-up-item xgplayer-danmufont-large selected-color">大</span>\n </div>\n <div class="xgplayer-danmufont-control-down">\n <div class="xgplayer-danmufont-control-down-dots">\n <span class="xgplayer-danmufont-small-dot"></span>\n <span class="xgplayer-danmufont-middle-dot"></span>\n <span class="xgplayer-danmufont-large-dot"></span>\n </div>\n <input class="xgplayer-danmufont-line xgplayer-danmufont-color xgplayer-danmufont-bar xgplayer-gradient" type="range" min="20" max="30" step="5" value="25">\n </div>\n </div>\n </xg-danmufont>\n </xg-panel-slider>',{tabindex:7},"xgplayer-panel"),e.once("ready",(function(){e.controls.appendChild(s)}))),e.once("complete",(function(){var t=new r.default(l);if(e.emit("initDefaultDanmu",t),e.danmu=t,e.config.danmu.panel){var n=s.querySelector(".xgplayer-panel-slider"),i=void 0;["mouseenter","touchend","click"].forEach((function(e){s.addEventListener(e,(function(e){e.preventDefault(),e.stopPropagation(),a.default.util.addClass(n,"xgplayer-panel-active"),s.focus(),i=!0}))})),s.addEventListener("mouseleave",(function(e){e.preventDefault(),e.stopPropagation(),a.default.util.removeClass(n,"xgplayer-panel-active"),i=!1})),n.addEventListener("mouseleave",(function(e){e.preventDefault(),e.stopPropagation(),!1===i&&a.default.util.removeClass(n,"xgplayer-panel-active")}));var o=e.config.danmu,u={scroll:s.querySelector(".xgplayer-hidemode-scroll"),top:s.querySelector(".xgplayer-hidemode-top"),bottom:s.querySelector(".xgplayer-hidemode-bottom"),color:s.querySelector(".xgplayer-hidemode-color")},c=function(t){var n=t;["touchend","click"].forEach((function(t){u[n].addEventListener(t,(function(t){"true"!==u[n].getAttribute("id")?(u[n].style.color="#f85959",u[n].setAttribute("id","true"),e.danmu.hide(n)):(u[n].style.color="#aaa",u[n].setAttribute("id","false"),e.danmu.show(n))}))}))};for(var p in u)c(p);var d=s.querySelector(".xgplayer-transparency-line"),f=s.querySelector(".xgplayer-transparency-gradient"),g=50;if(f.style.background="linear-gradient(to right, #f85959 0%, #f85959 "+g+"%, #aaa "+g+"%, #aaa)",d.addEventListener("input",(function(e){e.preventDefault(),e.stopPropagation(),g=e.target.value,f.style.background="linear-gradient(to right, #f85959 0%, #f85959 "+g+"%, #aaa "+g+"%, #aaa)",o.comments.forEach((function(e){e.style.opacity=g/100}))})),s.querySelector(".xgplayer-showarea-line").addEventListener("input",(function(t){t.preventDefault(),t.stopPropagation();var n=t.target.value;e.danmu.config.area.end=n/100,e.config.danmu.area.end=n/100,e.danmu.bulletBtn.main.channel.resize()})),s.querySelector(".xgplayer-danmuspeed-line").addEventListener("input",(function(e){e.preventDefault(),e.stopPropagation();var t=e.target.value;o.comments.forEach((function(e){e.duration=100*(200-t)}))})),s.querySelector(".xgplayer-danmufont-line").addEventListener("input",(function(e){e.preventDefault(),e.stopPropagation();var t=e.target.value;o.comments.forEach((function(e){e.style.fontSize=t+"px"}))})),navigator.userAgent.indexOf("Firefox")>-1)for(var y=0;y<n.querySelectorAll("input").length;y++)n.querySelectorAll("input")[y].style.marginTop="10px"}}))}}))},function(e,t,n){"use strict";(function(e){var n,a,r,i,o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};window,i=function(){return function(e){var t={};function n(a){if(t[a])return t[a].exports;var r=t[a]={i:a,l:!1,exports:{}};return e[a].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=e,n.c=t,n.d=function(e,t,a){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:a})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==(void 0===e?"undefined":o(e))&&e&&e.__esModule)return e;var a=Object.create(null);if(n.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(a,r,function(t){return e[t]}.bind(null,r));return a},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=4)}([function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var a,r=function(){function e(e,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}return function(t,n,a){return n&&e(t.prototype,n),a&&e(t,a),t}}(),i=(a=n(26))&&a.__esModule?a:{default:a},o=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return r(e,[{key:"setLogger",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.logger=new i.default(e+".js")}}]),e}();t.default=o,e.exports=t.default},function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var a={createDom:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"div",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",r=document.createElement(e);return r.className=a,r.innerHTML=t,Object.keys(n).forEach((function(t){var a=t,i=n[t];"video"===e||"audio"===e?i&&r.setAttribute(a,i):r.setAttribute(a,i)})),r},hasClass:function(e,t){return e.classList?Array.prototype.some.call(e.classList,(function(e){return e===t})):!!e.className.match(new RegExp("(\\s|^)"+t+"(\\s|$)"))},addClass:function(e,t){e.classList?t.replace(/(^\s+|\s+$)/g,"").split(/\s+/g).forEach((function(t){t&&e.classList.add(t)})):a.hasClass(e,t)||(e.className+=" "+t)},removeClass:function(e,t){e.classList?t.split(/\s+/g).forEach((function(t){e.classList.remove(t)})):a.hasClass(e,t)&&t.split(/\s+/g).forEach((function(t){var n=new RegExp("(\\s|^)"+t+"(\\s|$)");e.className=e.className.replace(n," ")}))},toggleClass:function(e,t){t.split(/\s+/g).forEach((function(t){a.hasClass(e,t)?a.removeClass(e,t):a.addClass(e,t)}))},findDom:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document,t=arguments[1],n=void 0;try{n=e.querySelector(t)}catch(a){t.startsWith("#")&&(n=e.getElementById(t.slice(1)))}return n},deepCopy:function(e,t){if("Object"===a.typeOf(t)&&"Object"===a.typeOf(e))return Object.keys(t).forEach((function(n){"Object"!==a.typeOf(t[n])||t[n]instanceof Node?"Array"===a.typeOf(t[n])?e[n]="Array"===a.typeOf(e[n])?e[n].concat(t[n]):t[n]:e[n]=t[n]:e[n]?a.deepCopy(e[n],t[n]):e[n]=t[n]})),e},typeOf:function(e){return Object.prototype.toString.call(e).match(/([^\s.*]+)(?=]$)/g)[0]},copyDom:function(e){if(e&&1===e.nodeType){var t=document.createElement(e.tagName);return Array.prototype.forEach.call(e.attributes,(function(e){t.setAttribute(e.name,e.value)})),e.innerHTML&&(t.innerHTML=e.innerHTML),t}return""},formatTime:function(e){var t=Math.floor(e);return 1e3*t+(e-t)},offInDestroy:function(e,t,n,a){e.once(a,(function r(){e.off(t,n),e.off(a,r)}))},on:function(e,t,n,r){r?(e.on(t,n),a.offInDestroy(e,t,n,r)):e.on(t,(function a(r){n(r),e.off(t,a)}))}};t.default=a,e.exports=t.default},function(e,t,n){var a=n(19)();e.exports=function(e){return e!==a&&null!==e}},function(e,t,n){e.exports=function(e){return null!=e}},function(e,t,n){e.exports=n(5)},function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var a,r=(a=n(6))&&a.__esModule?a:{default:a};n(33),t.default=r.default,e.exports=t.default},function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}return function(t,n,a){return n&&e(t.prototype,n),a&&e(t,a),t}}(),r=p(n(7)),i=p(n(0)),l=p(n(27)),s=p(n(31)),u=p(n(1)),c=n(32);function p(e){return e&&e.__esModule?e:{default:e}}function d(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=(void 0===t?"undefined":o(t))&&"function"!=typeof t?e:t}var f=function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var n=d(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));n.setLogger("danmu"),n.logger.info("danmu.js version: "+c.version);var a=n;if(a.config=u.default.deepCopy({overlap:!1,area:{start:0,end:1},live:!1,comments:[],direction:"r2l"},e),a.hideArr=[],a.domObj=new s.default,(0,r.default)(a),a.config.comments.forEach((function(e){e.duration=e.duration?e.duration:5e3,e.mode||(e.mode="scroll")})),!a.config.container||1!==a.config.container.nodeType)return a.emit("error","container id can't be empty"),d(n,!1);if(a.container=a.config.container,a.config.containerStyle){var i=a.config.containerStyle;Object.keys(i).forEach((function(e){a.container.style[e]=i[e]}))}return a.live=a.config.live,a.player=a.config.player,a.direction=a.config.direction,u.default.addClass(a.container,"danmu"),a.bulletBtn=new l.default(a),a.emit("ready"),n.logger.info("ready"),n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":o(t)));e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),a(t,[{key:"start",value:function(){this.logger.info("start"),this.bulletBtn.main.start()}},{key:"pause",value:function(){this.logger.info("pause"),this.bulletBtn.main.pause()}},{key:"play",value:function(){this.logger.info("play"),this.bulletBtn.main.play()}},{key:"stop",value:function(){this.logger.info("stop"),this.bulletBtn.main.stop()}},{key:"destroy",value:function(){for(var e in this.logger.info("destroy"),this.stop(),this.bulletBtn.destroy(),this.domObj.destroy(),this)delete this[e];this.emit("destroy")}},{key:"sendComment",value:function(e){this.logger.info("sendComment: "+(e.txt||"[DOM Element]")),e.duration||(e.duration=15e3),e&&e.id&&e.duration&&(e.el||e.txt)&&(e.duration=e.duration?e.duration:5e3,e.style&&(this.opacity&&this.opacity!==e.style.opacity&&(e.style.opacity=this.opacity),this.fontSize&&this.fontSize!==e.style.fontSize&&(e.style.fontSize=this.fontSize),this.like&&(e.like=e.like?e.like:this.like)),e.prior||e.realTime?(this.bulletBtn.main.data.unshift(e),e.realTime&&(this.bulletBtn.main.readData(),this.bulletBtn.main.dataHandle())):this.bulletBtn.main.data.push(e))}},{key:"setCommentID",value:function(e,t){var n=this;this.logger.info("setCommentID: oldID "+e+" newID "+t);var a=this.container.getBoundingClientRect();e&&t&&(this.bulletBtn.main.data.some((function(n){return n.id===e&&(n.id=t,!0)})),this.bulletBtn.main.queue.some((function(r){return r.id===e&&(r.id=t,r.pauseMove(a),"paused"!==n.bulletBtn.main.status&&r.startMove(a),!0)})))}},{key:"setCommentDuration",value:function(e,t){var n=this;this.logger.info("setCommentDuration: id "+e+" duration "+t);var a=this.container.getBoundingClientRect();e&&t&&(t=t||5e3,this.bulletBtn.main.data.some((function(n){return n.id===e&&(n.duration=t,!0)})),this.bulletBtn.main.queue.some((function(r){return r.id===e&&(r.duration=t,r.pauseMove(a),"paused"!==n.bulletBtn.main.status&&r.startMove(a),!0)})))}},{key:"setCommentLike",value:function(e,t){this.logger.info("setCommentLike: id "+e+" like "+t);var n=this.container.getBoundingClientRect();this.like=t,e&&t&&(this.bulletBtn.main.data.some((function(n){return n.id===e&&(n.like=t,!0)})),this.bulletBtn.main.queue.some((function(a){return a.id===e&&(a.pauseMove(n),a.setLikeDom(t.el,t.style),"paused"!==a.danmu.bulletBtn.main.status&&a.startMove(n),!0)})))}},{key:"restartComment",value:function(e){this.logger.info("restartComment: id "+e),this.mouseControl=!1;var t=this.container.getBoundingClientRect();e&&this.bulletBtn.main.queue.some((function(n){return n.id===e&&("paused"!==n.danmu.bulletBtn.main.status?n.startMove(t,!0):n.status="paused",!0)}))}},{key:"freezeComment",value:function(e){this.logger.info("freezeComment: id "+e),this.mouseControl=!0;var t=this.container.getBoundingClientRect();e&&this.bulletBtn.main.queue.some((function(n){return n.id===e&&(n.status="forcedPause",n.pauseMove(t),n.el&&n.el.style&&(n.el.style.zIndex=10),!0)}))}},{key:"removeComment",value:function(e){this.logger.info("removeComment: id "+e),e&&(this.bulletBtn.main.queue.some((function(t){return t.id===e&&(t.remove(),!0)})),this.bulletBtn.main.data=this.bulletBtn.main.data.filter((function(t){return t.id!==e})))}},{key:"setAllDuration",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"scroll",t=arguments[1],n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];this.logger.info("setAllDuration: mode "+e+" duration "+t+" force "+n);var a=this.container.getBoundingClientRect();t&&(t=t||5e3,n&&(this.bulletBtn.main.forceDuration=t),this.bulletBtn.main.data.forEach((function(n){e===n.mode&&(n.duration=t)})),this.bulletBtn.main.queue.forEach((function(n){e===n.mode&&(n.duration=t,n.pauseMove(a),"paused"!==n.danmu.bulletBtn.main.status&&n.startMove(a))})))}},{key:"setOpacity",value:function(e){this.logger.info("setOpacity: opacity "+e),this.container.style.opacity=e}},{key:"setFontSize",value:function(e,t){var n=this;this.logger.info("setFontSize: size "+e+" channelSize "+t),this.fontSize=e+"px",e&&(this.bulletBtn.main.data.forEach((function(e){e.style&&(e.style.fontSize=n.fontSize)})),this.bulletBtn.main.queue.forEach((function(e){e.options.style||(e.options.style={}),e.options.style.fontSize=n.fontSize,e.setFontSize(n.fontSize),t&&(e.top=e.channel_id[0]*t,e.topInit())}))),t&&(this.config.channelSize=t,this.bulletBtn.main.channel.resize(!0))}},{key:"setArea",value:function(e){this.logger.info("setArea: area "+e),this.config.area=e,this.bulletBtn.main.channel.resize(!0)}},{key:"hide",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"scroll";this.logger.info("hide: mode "+e),this.hideArr.indexOf(e)<0&&this.hideArr.push(e);var t=this.bulletBtn.main.queue.filter((function(t){return e===t.mode||"color"===e&&t.color}));t.forEach((function(e){return e.remove()}))}},{key:"show",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"scroll";this.logger.info("show: mode "+e);var t=this.hideArr.indexOf(e);t>-1&&this.hideArr.splice(t,1)}},{key:"setDirection",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"r2l";this.logger.info("setDirection: direction "+e),this.emit("changeDirection",e)}},{key:"resize",value:function(){this.logger.info("resize"),this.emit("channel_resize")}}]),t}(i.default);t.default=f,e.exports=t.default},function(e,t,n){var a,r,i,l,s,u,c,p=n(8),d=n(25),f=Function.prototype.apply,g=Function.prototype.call,y=Object.create,h=Object.defineProperty,x=Object.defineProperties,m=Object.prototype.hasOwnProperty,v={configurable:!0,enumerable:!1,writable:!0};r=function(e,t){var n,r;return d(t),r=this,a.call(this,e,n=function(){i.call(r,e,n),f.call(t,this,arguments)}),n.__eeOnceListener__=t,this},s={on:a=function(e,t){var n;return d(t),m.call(this,"__ee__")?n=this.__ee__:(n=v.value=y(null),h(this,"__ee__",v),v.value=null),n[e]?"object"==o(n[e])?n[e].push(t):n[e]=[n[e],t]:n[e]=t,this},once:r,off:i=function(e,t){var n,a,r,i;if(d(t),!m.call(this,"__ee__"))return this;if(!(n=this.__ee__)[e])return this;if("object"==o(a=n[e]))for(i=0;r=a[i];++i)r!==t&&r.__eeOnceListener__!==t||(2===a.length?n[e]=a[i?0:1]:a.splice(i,1));else a!==t&&a.__eeOnceListener__!==t||delete n[e];return this},emit:l=function(e){var t,n,a,r,i;if(m.call(this,"__ee__")&&(r=this.__ee__[e]))if("object"==(void 0===r?"undefined":o(r))){for(n=arguments.length,i=new Array(n-1),t=1;t<n;++t)i[t-1]=arguments[t];for(r=r.slice(),t=0;a=r[t];++t)f.call(a,this,i)}else switch(arguments.length){case 1:g.call(r,this);break;case 2:g.call(r,this,arguments[1]);break;case 3:g.call(r,this,arguments[1],arguments[2]);break;default:for(n=arguments.length,i=new Array(n-1),t=1;t<n;++t)i[t-1]=arguments[t];f.call(r,this,i)}}},u={on:p(a),once:p(r),off:p(i),emit:p(l)},c=x({},u),e.exports=t=function(e){return null==e?y(c):x(Object(e),u)},t.methods=s},function(e,t,n){var a=n(3),r=n(9),i=n(13),o=n(21),l=n(22);(e.exports=function(e,t){var n,r,s,u,c;return arguments.length<2||"string"!=typeof e?(u=t,t=e,e=null):u=arguments[2],a(e)?(n=l.call(e,"c"),r=l.call(e,"e"),s=l.call(e,"w")):(n=s=!0,r=!1),c={value:t,configurable:n,enumerable:r,writable:s},u?i(o(u),c):c}).gs=function(e,t,n){var s,u,c,p;return"string"!=typeof e?(c=n,n=t,t=e,e=null):c=arguments[3],a(t)?r(t)?a(n)?r(n)||(c=n,n=void 0):n=void 0:(c=t,t=n=void 0):t=void 0,a(e)?(s=l.call(e,"c"),u=l.call(e,"e")):(s=!0,u=!1),p={get:t,set:n,configurable:s,enumerable:u},c?i(o(c),p):p}},function(e,t,n){var a=n(10),r=/^\s*class[\s{/}]/,i=Function.prototype.toString;e.exports=function(e){return!!a(e)&&!r.test(i.call(e))}},function(e,t,n){var a=n(11);e.exports=function(e){if("function"!=typeof e)return!1;if(!hasOwnProperty.call(e,"length"))return!1;try{if("number"!=typeof e.length)return!1;if("function"!=typeof e.call)return!1;if("function"!=typeof e.apply)return!1}catch(e){return!1}return!a(e)}},function(e,t,n){var a=n(12);e.exports=function(e){if(!a(e))return!1;try{return!!e.constructor&&e.constructor.prototype===e}catch(e){return!1}}},function(e,t,n){var a=n(3),r={object:!0,function:!0,undefined:!0};e.exports=function(e){return!!a(e)&&hasOwnProperty.call(r,void 0===e?"undefined":o(e))}},function(e,t,n){e.exports=n(14)()?Object.assign:n(15)},function(e,t,n){e.exports=function(){var e,t=Object.assign;return"function"==typeof t&&(t(e={foo:"raz"},{bar:"dwa"},{trzy:"trzy"}),e.foo+e.bar+e.trzy==="razdwatrzy")}},function(e,t,n){var a=n(16),r=n(20),i=Math.max;e.exports=function(e,t){var n,o,l,s=i(arguments.length,2);for(e=Object(r(e)),l=function(a){try{e[a]=t[a]}catch(e){n||(n=e)}},o=1;o<s;++o)a(t=arguments[o]).forEach(l);if(void 0!==n)throw n;return e}},function(e,t,n){e.exports=n(17)()?Object.keys:n(18)},function(e,t,n){e.exports=function(){try{return Object.keys("primitive"),!0}catch(e){return!1}}},function(e,t,n){var a=n(2),r=Object.keys;e.exports=function(e){return r(a(e)?Object(e):e)}},function(e,t,n){e.exports=function(){}},function(e,t,n){var a=n(2);e.exports=function(e){if(!a(e))throw new TypeError("Cannot use null or undefined");return e}},function(e,t,n){var a=n(2),r=Array.prototype.forEach,i=Object.create,o=function(e,t){var n;for(n in e)t[n]=e[n]};e.exports=function(e){var t=i(null);return r.call(arguments,(function(e){a(e)&&o(Object(e),t)})),t}},function(e,t,n){e.exports=n(23)()?String.prototype.contains:n(24)},function(e,t,n){var a="razdwatrzy";e.exports=function(){return"function"==typeof a.contains&&!0===a.contains("dwa")&&!1===a.contains("foo")}},function(e,t,n){var a=String.prototype.indexOf;e.exports=function(e){return a.call(this,e,arguments[1])>-1}},function(e,t,n){e.exports=function(e){if("function"!=typeof e)throw new TypeError(e+" is not a function");return e}},function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}return function(t,n,a){return n&&e(t.prototype,n),a&&e(t,a),t}}(),r=window.location.href.indexOf("danmu-debug")>-1,i=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.constructorName=t||""}return a(e,[{key:"info",value:function(e){for(var t,n=arguments.length,a=Array(n>1?n-1:0),i=1;i<n;i++)a[i-1]=arguments[i];r&&(t=console).log.apply(t,["[Danmu Log]["+this.constructorName+"]",e].concat(a))}}]),e}();t.default=i,e.exports=t.default},function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}return function(t,n,a){return n&&e(t.prototype,n),a&&e(t,a),t}}(),r=s(n(0)),i=s(n(1)),l=s(n(28));function s(e){return e&&e.__esModule?e:{default:e}}var u=function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var n=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=(void 0===t?"undefined":o(t))&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return n.setLogger("control"),n.danmu=e,n.main=new l.default(e),e.config.defaultOff||n.main.start(),n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":o(t)));e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),a(t,[{key:"createSwitch",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this.logger.info("createSwitch"),this.switchBtn=i.default.createDom("dk-switch",'<span class="txt">弹</span>',{},"danmu-switch "+(e?"danmu-switch-active":"")),this.switchBtn}},{key:"destroy",value:function(){for(var e in this.logger.info("destroy"),this.main.destroy(),this)delete this[e]}}]),t}(r.default);t.default=u,e.exports=t.default},function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}return function(t,n,a){return n&&e(t.prototype,n),a&&e(t,a),t}}(),r=u(n(0)),i=u(n(29)),l=u(n(30)),s=u(n(1));function u(e){return e&&e.__esModule?e:{default:e}}var c=function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var n=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=(void 0===t?"undefined":o(t))&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));n.setLogger("main"),n.danmu=e,n.container=e.container,n.channel=new i.default(e),n.data=[].concat(e.config.comments),n.playedData=[],n.queue=[],n.timer=null,n.retryTimer=null,n.retryStatus="normal",n.interval=e.config.interval||2e3,n.status="idle",s.default.on(e,"bullet_remove",n.updateQueue.bind(n),"destroy");var a=n;return s.default.on(n.danmu,"changeDirection",(function(e){a.danmu.direction=e}),"destroy"),n.nums=0,n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":o(t)));e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),a(t,[{key:"destroy",value:function(){for(var e in this.logger.info("destroy"),clearTimeout(this.dataHandleTimer),this.channel.destroy(),this.data=[],this)delete this[e]}},{key:"updateQueue",value:function(e){this.logger.info("updateQueue");var t=this;t.queue.some((function(n,a){return n.id===e.bullet.id&&(t.queue.splice(a,1),!0)}))}},{key:"init",value:function(e,t){t.logger.info("init"),t||(t=this),t.retryStatus="normal",t.data.sort((function(e,t){return e.start-t.start})),t.retryTimer||function e(){"closed"===t.status&&"stop"===t.retryStatus||("playing"===t.status&&(t.readData(),t.dataHandle()),"stop"===t.retryStatus&&"paused"!==this.status||(t.dataHandleTimer=setTimeout((function(){e()}),t.interval-1e3)))}()}},{key:"start",value:function(){this.logger.info("start"),this.status="playing",this.queue=[],this.container.innerHTML="",this.channel.resetWithCb(this.init,this)}},{key:"stop",value:function(){this.logger.info("stop"),this.status="closed",this.retryTimer=null,this.retryStatus="stop",this.channel.reset(),this.queue=[],this.container.innerHTML=""}},{key:"play",value:function(){var e=this;this.logger.info("play"),this.status="playing";var t=this.channel.channels,n=this.danmu.container.getBoundingClientRect();t&&t.length>0&&["scroll","top","bottom"].forEach((function(a){e.queue.forEach((function(e){e.startMove(n),e.resized=!0}));for(var r=0;r<t.length;r++)t[r].queue[a].forEach((function(e){e.resized=!1}))}))}},{key:"pause",value:function(){this.logger.info("pause"),this.status="paused";var e=this.channel.channels,t=this.danmu.container.getBoundingClientRect();e&&e.length>0&&this.queue.forEach((function(e){e.pauseMove(t)}))}},{key:"dataHandle",value:function(){var e=this;"paused"!==this.status&&"closed"!==this.status&&e.queue.length&&e.queue.forEach((function(t){"waiting"===t.status&&t.startMove(e.channel.containerPos)}))}},{key:"readData",value:function(){var e=this,t=this.danmu,n=0;t.player&&t.player.currentTime&&(n=s.default.formatTime(t.player.currentTime));var a=void 0,r=e.interval,i=e.channel,o=void 0;t.player?(o=e.data.filter((function(t){return!t.start&&e.danmu.hideArr.indexOf(t.mode)<0&&(!t.color||e.danmu.hideArr.indexOf("color")<0)&&(t.start=n),e.danmu.hideArr.indexOf(t.mode)<0&&(!t.color||e.danmu.hideArr.indexOf("color")<0)&&t.start-r<=n&&n<=t.start+r})),t.live&&(e.data=e.data.filter((function(e){return e.start||(e.start=n),e.start>n-3*r})))):0===(o=e.data.splice(0,1)).length&&(o=e.playedData.splice(0,1)),o.length>0&&o.forEach((function(n){e.forceDuration&&e.forceDuration!=n.duration&&(n.duration=e.forceDuration),a=new l.default(t,n),n.hasAttached||(a.attach(),n.hasAttached=!0,i.addBullet(a).result?(e.queue.push(a),e.nums++,a.topInit()):(a.detach(),n.hasAttached=!1,n.noDiscard&&(n.prior?e.data.unshift(n):e.data.push(n))))}))}}]),t}(r.default);t.default=c,e.exports=t.default},function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}return function(t,n,a){return n&&e(t.prototype,n),a&&e(t,a),t}}(),r=l(n(0)),i=l(n(1));function l(e){return e&&e.__esModule?e:{default:e}}var s=function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var n=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=(void 0===t?"undefined":o(t))&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));n.setLogger("channel"),n.danmu=e,n.reset();var a=n;return i.default.on(n.danmu,"bullet_remove",(function(e){a.removeBullet(e.bullet)}),"destroy"),n.direction=e.direction,i.default.on(n.danmu,"changeDirection",(function(e){a.direction=e}),"destroy"),n.containerPos=n.danmu.container.getBoundingClientRect(),n.containerWidth=n.containerPos.width,n.containerHeight=n.containerPos.height,n.containerLeft=n.containerPos.left,n.containerRight=n.containerPos.right,i.default.on(n.danmu,"channel_resize",(function(){a.containerPos=a.danmu.container.getBoundingClientRect(),a.resizing||(a.containerWidth=a.containerPos.width,a.containerHeight=a.containerPos.height,a.containerLeft=a.containerPos.left,a.containerRight=a.containerPos.right,a.resize(!0))}),"destroy"),n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":o(t)));e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),a(t,[{key:"destroy",value:function(){for(var e in this.logger.info("destroy"),clearTimeout(this.resizeTimer),clearTimeout(this.resetTimer),this.channels=[],this)delete this[e]}},{key:"resize",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.logger.info("resize");var t=this.danmu.container,n=this;n.resizing||(n.resizing=!0,this.resizeTimer=setTimeout((function(){n.danmu.bulletBtn.main.status,n.danmu.bulletBtn.main.data&&n.danmu.bulletBtn.main.data.forEach((function(e){e.bookChannelId&&(delete e.bookChannelId,n.logger.info("resize导致"+e.id+"号优先弹幕预定取消"))})),n.logger.info("resize导致所有轨道恢复正常使用");var a=t.getBoundingClientRect();n.width=a.width,n.height=a.height,n.danmu.config.area&&n.danmu.config.area.start>=0&&n.danmu.config.area.end>=n.danmu.config.area.start&&("b2t"===n.direction?n.width=n.width*(n.danmu.config.area.end-n.danmu.config.area.start):n.height=n.height*(n.danmu.config.area.end-n.danmu.config.area.start)),n.container=t;var r,i=n.danmu.config.channelSize||(/mobile/gi.test(navigator.userAgent)?10:12);r="b2t"===n.direction?Math.floor(n.width/i):Math.floor(n.height/i);for(var o=[],l=0;l<r;l++)o[l]={id:l,queue:{scroll:[],top:[],bottom:[]},operating:{scroll:!1,top:!1,bottom:!1},bookId:{}};if(n.channels&&n.channels.length<=o.length){for(var s=function(t){o[t]={id:t,queue:{scroll:[],top:[],bottom:[]},operating:{scroll:!1,top:!1,bottom:!1},bookId:{}},["scroll","top"].forEach((function(a){n.channels[t].queue[a].forEach((function(r){r.el&&(o[t].queue[a].push(r),r.resized||(r.pauseMove(n.containerPos,e),"paused"!==r.danmu.bulletBtn.main.status&&r.startMove(n.containerPos),r.resized=!0))}))})),n.channels[t].queue.bottom.forEach((function(a){if(a.el){if(o[t+o.length-n.channels.length].queue.bottom.push(a),a.channel_id[0]+a.channel_id[1]-1===t){var r=[].concat(a.channel_id);a.channel_id=[r[0]-n.channels.length+o.length,r[1]],a.top=a.channel_id[0]*i,n.danmu.config.area&&n.danmu.config.area.start&&(a.top+=n.containerHeight*n.danmu.config.area.start),a.topInit()}a.resized||(a.pauseMove(n.containerPos,e),"paused"!==a.danmu.bulletBtn.main.status&&a.startMove(n.containerPos),a.resized=!0)}}))},u=0;u<n.channels.length;u++)s(u);for(var c=function(e){["scroll","top","bottom"].forEach((function(t){o[e].queue[t].forEach((function(e){e.resized=!1}))}))},p=0;p<o.length;p++)c(p);n.channels=o,"b2t"===n.direction?n.channelWidth=i:n.channelHeight=i}else if(n.channels&&n.channels.length>o.length){for(var d=function(t){o[t]={id:t,queue:{scroll:[],top:[],bottom:[]},operating:{scroll:!1,top:!1,bottom:!1},bookId:{}},["scroll","top","bottom"].forEach((function(a){if("top"===a&&t>Math.floor(o.length/2));else if("bottom"===a&&t<=Math.floor(o.length/2));else{var r="bottom"===a?t-o.length+n.channels.length:t;n.channels[r].queue[a].forEach((function(l,s){if(l.el){if(o[t].queue[a].push(l),"bottom"===a&&l.channel_id[0]+l.channel_id[1]-1===r){var u=[].concat(l.channel_id);l.channel_id=[u[0]-n.channels.length+o.length,u[1]],l.top=l.channel_id[0]*i,n.danmu.config.area&&n.danmu.config.area.start&&(l.top+=n.containerHeight*n.danmu.config.area.start),l.topInit()}l.pauseMove(n.containerPos,e),"paused"!==l.danmu.bulletBtn.main.status&&l.startMove(n.containerPos),l.resized||(l.resized=!0)}n.channels[r].queue[a].splice(s,1)}))}}))},f=0;f<o.length;f++)d(f);for(var g=function(e){["scroll","top","bottom"].forEach((function(t){o[e].queue[t].forEach((function(e){e.resized=!1}))}))},y=0;y<o.length;y++)g(y);n.channels=o,"b2t"===n.direction?n.channelWidth=i:n.channelHeight=i}n.resizing=!1}),10))}},{key:"addBullet",value:function(e){var t=this,n=this.danmu,a=this.channels,r=void 0,i=void 0,o=void 0;if("b2t"===t.direction?(i=this.channelWidth,o=Math.ceil(e.width/i)):(r=this.channelHeight,o=Math.ceil(e.height/r)),o>a.length)return{result:!1,message:"exceed channels.length, occupy="+o+",channelsSize="+a.length};for(var l=!0,s=void 0,u=-1,c=0,p=a.length;c<p;c++)if(a[c].queue[e.mode].some((function(t){return t.id===e.id})))return{result:!1,message:"exsited, channelOrder="+c+",danmu_id="+e.id};if("scroll"===e.mode)for(var d=0,f=a.length-o;d<=f;d++){l=!0;for(var g=d;g<d+o;g++){if((s=a[g]).operating.scroll){l=!1;break}if((s.bookId.scroll||e.prior)&&s.bookId.scroll!==e.id){l=!1;break}s.operating.scroll=!0;var y=s.queue.scroll[0];if(y){var h=y.el.getBoundingClientRect();if("b2t"===t.direction){if(h.bottom>t.containerPos.bottom){l=!1,s.operating.scroll=!1;break}}else if(h.right>t.containerPos.right){l=!1,s.operating.scroll=!1;break}var x,m=void 0,v=void 0,b=void 0,k=void 0;if("b2t"===t.direction?(v=(h.top-t.containerPos.top+h.height)/(m=(t.containerPos.height+h.height)/y.duration),b=t.containerPos.height,k=(t.containerPos.height+e.height)/e.duration):(v=(h.left-t.containerPos.left+h.width)/(m=(t.containerPos.width+h.width)/y.duration),b=t.containerPos.width,k=(t.containerPos.width+e.width)/e.duration),x=b/k,n.config.bOffset||(n.config.bOffset=0),m<k&&v+n.config.bOffset>x){l=!1,s.operating.scroll=!1;break}}s.operating.scroll=!1}if(l){u=d;break}}else if("top"===e.mode)for(var w=0,_=a.length-o;w<=_;w++){l=!0;for(var E=w;E<w+o;E++){if(E>Math.floor(a.length/2)){l=!1;break}if((s=a[E]).operating[e.mode]){l=!1;break}if((s.bookId[e.mode]||e.prior)&&s.bookId[e.mode]!==e.id){l=!1;break}if(s.operating[e.mode]=!0,s.queue[e.mode].length>0){l=!1,s.operating[e.mode]=!1;break}s.operating[e.mode]=!1}if(l){u=w;break}}else if("bottom"===e.mode)for(var C=a.length-o;C>=0;C--){l=!0;for(var T=C;T<C+o;T++){if(T<=Math.floor(a.length/2)){l=!1;break}if((s=a[T]).operating[e.mode]){l=!1;break}if((s.bookId[e.mode]||e.prior)&&s.bookId[e.mode]!==e.id){l=!1;break}if(s.operating[e.mode]=!0,s.queue[e.mode].length>0){l=!1,s.operating[e.mode]=!1;break}s.operating[e.mode]=!1}if(l){u=C;break}}if(-1!==u){for(var S=u,P=u+o;S<P;S++)(s=a[S]).operating[e.mode]=!0,s.queue[e.mode].unshift(e),e.prior&&(delete s.bookId[e.mode],t.logger.info(S+"号轨道恢复正常使用")),s.operating[e.mode]=!1;return e.prior&&(t.logger.info(e.id+"号优先弹幕运行完毕"),delete e.bookChannelId,n.player&&n.bulletBtn.main.data.some((function(t){return t.id===e.id&&(delete t.bookChannelId,!0)}))),e.channel_id=[u,o],"b2t"===t.direction?(e.top=u*i,t.danmu.config.area&&t.danmu.config.area.start&&(e.top+=t.containerWidth*t.danmu.config.area.start)):(e.top=u*r,t.danmu.config.area&&t.danmu.config.area.start&&(e.top+=t.containerHeight*t.danmu.config.area.start)),{result:e,message:"success"}}if(e.options.realTime){var L=0,D=null;if(t.danmu.bulletBtn.main.queue.forEach((function(e,n){e.el&&e.el.getBoundingClientRect().right>t.containerPos.right&&e.start>=L&&(L=e.start,D=e)})),D){e.channel_id=D.channel_id;for(var O=D.channel_id[0],R=D.channel_id[0]+D.channel_id[1];O<R;O++)(s=a[O]).operating[e.mode]=!0,s.queue[e.mode].unshift(e),e.prior&&delete s.bookId[e.mode],s.operating[e.mode]=!1;return e.top=D.top,t.danmu.config.area&&t.danmu.config.area.start&&(e.top+=t.containerHeight*t.danmu.config.area.start),{result:e,message:"success"}}}if(e.prior)if(e.bookChannelId)n.player&&n.bulletBtn.main.data.some((function(n){return n.id===e.id&&(t.logger.info(e.id+"号优先弹幕将于2秒后再次请求注册"),n.start+=2e3,!0)}));else{u=-1;for(var M=0,A=a.length-o;M<=A;M++){l=!0;for(var z=M;z<M+o;z++)if(a[z].bookId[e.mode]){l=!1;break}if(l){u=M;break}}if(-1!==u){for(var B=u;B<u+o;B++)a[B].bookId[e.mode]=e.id,t.logger.info(B+"号轨道被"+e.id+"号优先弹幕预定");n.player&&n.bulletBtn.main.data.some((function(n){return n.id===e.id&&(t.logger.info(e.id+"号优先弹幕将于2秒后再次请求注册"),n.start+=2e3,n.bookChannelId=[u,o],t.logger.info(e.id+"号优先弹幕预定了"+u+"~"+(u+o-1)+"号轨道"),!0)}))}}return{result:!1,message:"no surplus will right"}}},{key:"removeBullet",value:function(e){this.logger.info("removeBullet "+(e.options.txt||"[DOM Element]"));for(var t=this.channels,n=e.channel_id,a=void 0,r=n[0],i=n[0]+n[1];r<i;r++)if(a=t[r]){a.operating[e.mode]=!0;var o=-1;a.queue[e.mode].some((function(t,n){return t.id===e.id&&(o=n,!0)})),o>-1&&a.queue[e.mode].splice(o,1),a.operating[e.mode]=!1}e.options.loop&&this.danmu.bulletBtn.main.playedData.push(e.options)}},{key:"resetArea",value:function(){this.logger.info("resetArea");var e=this.danmu.container,t=this,n=e.getBoundingClientRect();t.width=n.width,t.height=n.height,t.danmu.config.area&&t.danmu.config.area.start>=0&&t.danmu.config.area.end>=t.danmu.config.area.start&&("b2t"===t.direction?t.width=t.width*(t.danmu.config.area.end-t.danmu.config.area.start):t.height=t.height*(t.danmu.config.area.end-t.danmu.config.area.start)),t.container=e;var a,r=t.danmu.config.channelSize||(/mobile/gi.test(navigator.userAgent)?10:12);a="b2t"===t.direction?Math.floor(t.width/r):Math.floor(t.height/r);for(var i=[],o=0;o<a;o++)i[o]={id:o,queue:{scroll:[],top:[],bottom:[]},operating:{scroll:!1,top:!1,bottom:!1},bookId:{}};if(t.channels&&t.channels.length<=i.length){for(var l=function(e){i[e]={id:e,queue:{scroll:[],top:[],bottom:[]},operating:{scroll:!1,top:!1,bottom:!1},bookId:{}},["scroll","top"].forEach((function(n){t.channels[e].queue[n].forEach((function(a){a.el&&(i[e].queue[n].push(a),a.resized||(a.pauseMove(t.containerPos,!1),a.startMove(t.containerPos),a.resized=!0))}))})),t.channels[e].queue.bottom.forEach((function(n){if(n.el){if(i[e+i.length-t.channels.length].queue.bottom.push(n),n.channel_id[0]+n.channel_id[1]-1===e){var a=[].concat(n.channel_id);n.channel_id=[a[0]-t.channels.length+i.length,a[1]],n.top=n.channel_id[0]*r,t.danmu.config.area&&t.danmu.config.area.start&&(n.top+=t.containerHeight*t.danmu.config.area.start),n.topInit()}n.resized||(n.pauseMove(t.containerPos,!1),n.startMove(t.containerPos),n.resized=!0)}}))},s=0;s<t.channels.length;s++)l(s);for(var u=function(e){["scroll","top","bottom"].forEach((function(t){i[e].queue[t].forEach((function(e){e.resized=!1}))}))},c=0;c<i.length;c++)u(c);t.channels=i,"b2t"===t.direction?t.channelWidth=r:t.channelHeight=r}else if(t.channels&&t.channels.length>i.length){for(var p=function(e){i[e]={id:e,queue:{scroll:[],top:[],bottom:[]},operating:{scroll:!1,top:!1,bottom:!1},bookId:{}},["scroll","top","bottom"].forEach((function(n){if("top"===n&&e>Math.floor(i.length/2));else if("bottom"===n&&e<=Math.floor(i.length/2));else{var a="bottom"===n?e-i.length+t.channels.length:e;t.channels[a].queue[n].forEach((function(o,l){if(o.el){if(i[e].queue[n].push(o),"bottom"===n&&o.channel_id[0]+o.channel_id[1]-1===a){var s=[].concat(o.channel_id);o.channel_id=[s[0]-t.channels.length+i.length,s[1]],o.top=o.channel_id[0]*r,t.danmu.config.area&&t.danmu.config.area.start&&(o.top+=t.containerHeight*t.danmu.config.area.start),o.topInit()}o.resized||(o.pauseMove(t.containerPos,!1),o.startMove(t.containerPos),o.resized=!0)}t.channels[a].queue[n].splice(l,1)}))}}))},d=0;d<i.length;d++)p(d);for(var f=function(e){["scroll","top","bottom"].forEach((function(t){i[e].queue[t].forEach((function(e){e.resized=!1}))}))},g=0;g<i.length;g++)f(g);t.channels=i,"b2t"===t.direction?t.channelWidth=r:t.channelHeight=r}}},{key:"reset",value:function(){this.logger.info("reset");var e=this.danmu.container,t=this;t.danmu.bulletBtn&&t.danmu.bulletBtn.main&&t.danmu.bulletBtn.main.queue.forEach((function(e){e.pauseMove(t.containerPos),e.remove()})),t.channels&&t.channels.length>0&&["scroll","top","bottom"].forEach((function(e){for(var n=0;n<t.channels.length;n++)t.channels[n].queue[e].forEach((function(e){e.pauseMove(t.containerPos),e.remove()}))})),this.resetTimer=setTimeout((function(){var n=e.getBoundingClientRect();t.width=n.width,t.height=n.height,t.danmu.config.area&&t.danmu.config.area.start>=0&&t.danmu.config.area.end>=t.danmu.config.area.start&&("b2t"===t.direction?t.width=t.width*(t.danmu.config.area.end-t.danmu.config.area.start):t.height=t.height*(t.danmu.config.area.end-t.danmu.config.area.start)),t.container=e;var a,r=t.danmu.config.channelSize||(/mobile/gi.test(navigator.userAgent)?10:12);a="b2t"===t.direction?Math.floor(t.width/r):Math.floor(t.height/r);for(var i=[],o=0;o<a;o++)i[o]={id:o,queue:{scroll:[],top:[],bottom:[]},operating:{scroll:!1,top:!1,bottom:!1},bookId:{}};t.channels=i,"b2t"===t.direction?t.channelWidth=r:t.channelHeight=r}),200)}},{key:"resetWithCb",value:function(e,t){this.logger.info("resetWithCb");var n=this.danmu.container,a=this;a.channels&&a.channels.length>0&&["scroll","top","bottom"].forEach((function(e){for(var t=0;t<a.channels.length;t++)a.channels[t].queue[e].forEach((function(e){e.pauseMove(a.containerPos),e.remove()}))}));var r=n.getBoundingClientRect();a.width=r.width,a.height=r.height,a.danmu.config.area&&a.danmu.config.area.start>=0&&a.danmu.config.area.end>=a.danmu.config.area.start&&("b2t"===a.direction?a.width=a.width*(a.danmu.config.area.end-a.danmu.config.area.start):a.height=a.height*(a.danmu.config.area.end-a.danmu.config.area.start)),a.container=n;var i,o=a.danmu.config.channelSize||(/mobile/gi.test(navigator.userAgent)?10:12);i="b2t"===a.direction?Math.floor(a.width/o):Math.floor(a.height/o);for(var l=[],s=0;s<i;s++)l[s]={id:s,queue:{scroll:[],top:[],bottom:[]},operating:{scroll:!1,top:!1,bottom:!1},bookId:{}};a.channels=l,a.channelHeight=o,e&&e(!0,t)}}]),t}(r.default);t.default=s,e.exports=t.default},function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}return function(t,n,a){return n&&e(t.prototype,n),a&&e(t,a),t}}(),r=l(n(0)),i=l(n(1));function l(e){return e&&e.__esModule?e:{default:e}}var s=function(e){function t(e,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var a=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=(void 0===t?"undefined":o(t))&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));a.setLogger("bullet"),a.danmu=e,a.options=n,a.duration=n.duration,a.moveV=n.moveV,a.id=n.id,a.container=e.container,a.start=n.start,a.prior=n.prior,a.color=n.color,a.bookChannelId=n.bookChannelId,a.direction=e.direction;var r=a;a.onChangeDirection=function(e){r.direction=e},a.danmu.on("changeDirection",a.onChangeDirection);var l=void 0;if(a.domObj=e.domObj,n.el&&1===n.el.nodeType)(l=a.domObj.use()).appendChild(i.default.copyDom(n.el));else if((l=a.domObj.use()).textContent=n.txt,n.style){var s=n.style;Object.keys(s).forEach((function(e){l.style[e]=s[e]}))}"top"===n.mode||"bottom"===n.mode?a.mode=n.mode:a.mode="scroll",a.el=l,n.like&&n.like.el&&a.setLikeDom(n.like.el,n.like.style),a.status="waiting";var u=a.container.getBoundingClientRect(),c=Math.floor(Math.random()*(u.width/10>100?200:u.width/10));return n.realTime&&(c=0),a.el.style.left=u.width+c+"px",a.containerPos=u,a}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":o(t)));e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),a(t,[{key:"attach",value:function(){if(this.container.appendChild(this.el),this.elPos=this.el.getBoundingClientRect(),"b2t"===this.direction?(this.width=this.elPos.height,this.height=this.elPos.width):(this.width=this.elPos.width,this.height=this.elPos.height),this.moveV){var e=this.containerPos;this.duration=(e.width+this.width)/this.moveV*1e3}this.danmu.config.mouseControl&&this.el.addEventListener("mouseover",this.mouseoverFun.bind(this))}},{key:"mouseoverFun",value:function(e){this.danmu.mouseControl&&this.danmu.config.mouseControlPause||"waiting"===this.status||"end"===this.status||this.danmu.emit("bullet_hover",{bullet:this,event:e})}},{key:"detach",value:function(){this.container&&this.el&&this.domObj.unuse(this.el),this.danmu.off("changeDirection",this.onChangeDirection)}},{key:"topInit",value:function(){if(this.logger.info("topInit #"+(this.options.txt||"[DOM Element]")+"#"),"b2t"===this.direction){var e=this.containerPos;this.el.style.transformOrigin="left top",this.el.style.transform="translateX(-"+this.top+"px) translateY("+e.height+"px) translateZ(0px) rotate(90deg)",this.el.style.transition="transform 0s linear 0s"}else this.el.style.top=this.top+"px"}},{key:"pauseMove",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.logger.info("pauseMove #"+(this.options.txt||"[DOM Element]")+"#");var n=this;if("paused"!==this.status&&("forcedPause"!==n.status&&(this.status="paused"),clearTimeout(n.removeTimer),this.el))if(this.el.style.willChange="auto","scroll"===this.mode){if(t){var a=((new Date).getTime()-n.moveTime)/1e3,r=a*this.moveV,i=0;i=n.moveMoreS-r>=0?"b2t"===this.direction?(n.moveMoreS-r)/n.moveContainerHeight*e.height:(n.moveMoreS-r)/n.moveContainerWidth*e.width:n.moveMoreS-r,"b2t"===this.direction?this.el.style.transform="translateX(-"+this.top+"px) translateY("+i+"px) translateZ(0px) rotate(90deg)":this.el.style.left=i+"px"}else"b2t"===this.direction?this.el.style.transform="translateX(-"+this.top+"px) translateY("+(this.el.getBoundingClientRect().top-e.top)+"px) translateZ(0px) rotate(90deg)":this.el.style.left=this.el.getBoundingClientRect().left-e.left+"px";"b2t"===this.direction||(this.el.style.transform="translateX(0px) translateY(0px) translateZ(0px)"),this.el.style.transition="transform 0s linear 0s"}else this.pastDuration&&this.startTime?this.pastDuration=this.pastDuration+(new Date).getTime()-this.startTime:this.pastDuration=1}},{key:"startMove",value:function(e,t){this.logger.info("startMove #"+(this.options.txt||"[DOM Element]")+"#");var n=this;if(n.hasMove||(n.danmu.emit("bullet_start",n),n.hasMove=!0),("forcedPause"!==n.status||t)&&this.el&&"start"!==this.status)if(this.status="start",this.el.style.willChange="transform","scroll"===this.mode)if("b2t"===this.direction){this.moveV=(e.height+this.height)/this.duration*1e3;var a=(n.el.getBoundingClientRect().bottom-e.top)/this.moveV;this.el.style.transition="transform "+a+"s linear 0s",this.startMoveTimer=setTimeout((function(){n.el&&(n.el.style.transform="translateX(-"+n.top+"px) translateY(-"+n.height+"px) translateZ(0px) rotate(90deg)",n.moveTime=(new Date).getTime(),n.moveMoreS=n.el.getBoundingClientRect().top-e.top,n.moveContainerHeight=e.height,n.removeTimer=setTimeout(o,1e3*a))}),20)}else{this.moveV=(e.width+this.width)/this.duration*1e3;var r=(n.el.getBoundingClientRect().right-e.left)/this.moveV;this.el.style.transition="transform "+r+"s linear 0s",this.startMoveTimer=setTimeout((function(){n.el&&(n.el.style.transform="translateX(-"+(n.el.getBoundingClientRect().right-e.left)+"px) translateY(0px) translateZ(0px)",n.moveTime=(new Date).getTime(),n.moveMoreS=n.el.getBoundingClientRect().left-e.left,n.moveContainerWidth=e.width,n.removeTimer=setTimeout(o,1e3*r))}),20)}else{this.el.style.left="50%",this.el.style.margin="0 0 0 -"+this.width/2+"px",this.pastDuration||(this.pastDuration=1);var i=this.duration>=this.pastDuration?this.duration-this.pastDuration:0;this.removeTimer=setTimeout(o,i),this.startTime=(new Date).getTime()}function o(){if(n.el)if("scroll"===n.mode){var e=n.containerPos,t=n.el.getBoundingClientRect();"b2t"===n.direction?t&&t.bottom<=e.top+100?(n.status="end",n.remove()):(n.pauseMove(e),"paused"!==n.danmu.bulletBtn.main.status&&n.startMove(e)):t&&t.right<=e.left+100?(n.status="end",n.remove()):(n.pauseMove(e),"paused"!==n.danmu.bulletBtn.main.status&&n.startMove(e))}else n.status="end",n.remove()}}},{key:"remove",value:function(){this.logger.info("remove #"+(this.options.txt||"[DOM Element]")+"#"),this.removeTimer&&clearTimeout(this.removeTimer),this.startMoveTimer&&clearTimeout(this.startMoveTimer),this.el&&this.el.parentNode&&(this.el.style.willChange="auto",this.danmu.off("changeDirection",this.onChangeDirection),this.domObj.unuse(this.el),this.el.parentNode.removeChild(this.el),this.el=null,this.danmu.emit("bullet_remove",{bullet:this}))}},{key:"setFontSize",value:function(e){this.el&&(this.el.style.fontSize=e)}},{key:"setLikeDom",value:function(e,t){if(e&&(Object.keys(t).forEach((function(n){e.style[n]=t[n]})),e.className="danmu-like",this.el)){var n=this.el.querySelector(".danmu-like");n&&this.el.removeChild(n),this.el.innerHTML=""+this.el.innerHTML+e.outerHTML}return e}}]),t}(r.default);t.default=s,e.exports=t.default},function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}return function(t,n,a){return n&&e(t.prototype,n),a&&e(t,a),t}}(),r=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),t={initDOM:function(){return document.createElement("div")},initSize:10},this.init(t)}return a(e,[{key:"init",value:function(e){this.idleList=[],this.usingList=[],this._id=0,this.options=e,this._expand(e.initSize)}},{key:"use",value:function(){this.idleList.length||this._expand(1);var e=this.idleList.shift();return this.usingList.push(e),e}},{key:"unuse",value:function(e){var t=this.usingList.indexOf(e);t<0||(this.usingList.splice(t,1),e.innerHTML="",e.textcontent="",e.style="",this.idleList.push(e))}},{key:"_expand",value:function(e){for(var t=0;t<e;t++)this.idleList.push(this.options.initDOM(this._id++))}},{key:"destroy",value:function(){for(var e=0;e<this.idleList.length;e++)this.idleList[e].innerHTML="",this.idleList[e].textcontent="",this.idleList[e].style="";for(var t=0;t<this.usingList.length;t++)this.usingList[t].innerHTML="",this.usingList[t].textcontent="",this.usingList[t].style="";for(var n in this)delete this[n]}}]),e}();t.default=r,e.exports=t.default},function(e){e.exports=JSON.parse('{"version":"0.2.23"}')},function(e,t,n){var a=n(34);"string"==typeof a&&(a=[[e.i,a,""]]),n(36)(a,{hmr:!0,transform:void 0,insertInto:void 0}),a.locals&&(e.exports=a.locals)},function(e,t,n){(e.exports=n(35)(!1)).push([e.i,".danmu{overflow:hidden;-webkit-user-select:none;-moz-user-select:none;user-select:none;-ms-user-select:none}.danmu>*{position:absolute;white-space:nowrap}.danmu-switch{width:32px;height:20px;border-radius:100px;background-color:#ccc;-webkit-box-sizing:border-box;box-sizing:border-box;outline:none;cursor:pointer;position:relative;text-align:center;margin:10px auto}.danmu-switch.danmu-switch-active{padding-left:12px;background-color:#f85959}.danmu-switch span.txt{width:20px;height:20px;line-height:20px;text-align:center;display:block;border-radius:100px;background-color:#ffffff;-webkit-box-shadow:-2px 0 0 0 rgba(0, 0, 0, .04);box-shadow:-2px 0 0 0 rgba(0, 0, 0, .04);font-family:PingFangSC;font-size:10px;font-weight:500;color:#f44336}\n",""])},function(e,t){e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var n=function(e,t){var n,a=e[1]||"",r=e[3];if(!r)return a;if(t&&"function"==typeof btoa){var i=(n=r,"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(n))))+" */"),o=r.sources.map((function(e){return"/*# sourceURL="+r.sourceRoot+e+" */"}));return[a].concat(o).concat([i]).join("\n")}return[a].join("\n")}(t,e);return t[2]?"@media "+t[2]+"{"+n+"}":n})).join("")},t.i=function(e,n){"string"==typeof e&&(e=[[null,e,""]]);for(var a={},r=0;r<this.length;r++){var i=this[r][0];"number"==typeof i&&(a[i]=!0)}for(r=0;r<e.length;r++){var o=e[r];"number"==typeof o[0]&&a[o[0]]||(n&&!o[2]?o[2]=n:n&&(o[2]="("+o[2]+") and ("+n+")"),t.push(o))}},t}},function(e,t,n){var a,r,i={},l=(a=function(){return window&&document&&document.all&&!window.atob},function(){return void 0===r&&(r=a.apply(this,arguments)),r}),s=function(e){return document.querySelector(e)},u=function(e){var t={};return function(e){if("function"==typeof e)return e();if(void 0===t[e]){var n=s.call(this,e);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(e){n=null}t[e]=n}return t[e]}}(),c=null,p=0,d=[],f=n(37);function g(e,t){for(var n=0;n<e.length;n++){var a=e[n],r=i[a.id];if(r){r.refs++;for(var o=0;o<r.parts.length;o++)r.parts[o](a.parts[o]);for(;o<a.parts.length;o++)r.parts.push(b(a.parts[o],t))}else{var l=[];for(o=0;o<a.parts.length;o++)l.push(b(a.parts[o],t));i[a.id]={id:a.id,refs:1,parts:l}}}}function y(e,t){for(var n=[],a={},r=0;r<e.length;r++){var i=e[r],o=t.base?i[0]+t.base:i[0],l={css:i[1],media:i[2],sourceMap:i[3]};a[o]?a[o].parts.push(l):n.push(a[o]={id:o,parts:[l]})}return n}function h(e,t){var n=u(e.insertInto);if(!n)throw new Error("Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid.");var a=d[d.length-1];if("top"===e.insertAt)a?a.nextSibling?n.insertBefore(t,a.nextSibling):n.appendChild(t):n.insertBefore(t,n.firstChild),d.push(t);else if("bottom"===e.insertAt)n.appendChild(t);else{if("object"!=o(e.insertAt)||!e.insertAt.before)throw new Error("[Style Loader]\n\n Invalid value for parameter 'insertAt' ('options.insertAt') found.\n Must be 'top', 'bottom', or Object.\n (https://github.com/webpack-contrib/style-loader#insertat)\n");var r=u(e.insertInto+" "+e.insertAt.before);n.insertBefore(t,r)}}function x(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e);var t=d.indexOf(e);t>=0&&d.splice(t,1)}function m(e){var t=document.createElement("style");return void 0===e.attrs.type&&(e.attrs.type="text/css"),v(t,e.attrs),h(e,t),t}function v(e,t){Object.keys(t).forEach((function(n){e.setAttribute(n,t[n])}))}function b(e,t){var n,a,r,i;if(t.transform&&e.css){if(!(i=t.transform(e.css)))return function(){};e.css=i}if(t.singleton){var o=p++;n=c||(c=m(t)),a=_.bind(null,n,o,!1),r=_.bind(null,n,o,!0)}else e.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(n=function(e){var t=document.createElement("link");return void 0===e.attrs.type&&(e.attrs.type="text/css"),e.attrs.rel="stylesheet",v(t,e.attrs),h(e,t),t}(t),a=C.bind(null,n,t),r=function(){x(n),n.href&&URL.revokeObjectURL(n.href)}):(n=m(t),a=E.bind(null,n),r=function(){x(n)});return a(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;a(e=t)}else r()}}e.exports=function(e,t){if("undefined"!=typeof DEBUG&&DEBUG&&"object"!=("undefined"==typeof document?"undefined":o(document)))throw new Error("The style-loader cannot be used in a non-browser environment");(t=t||{}).attrs="object"==o(t.attrs)?t.attrs:{},t.singleton||"boolean"==typeof t.singleton||(t.singleton=l()),t.insertInto||(t.insertInto="head"),t.insertAt||(t.insertAt="bottom");var n=y(e,t);return g(n,t),function(e){for(var a=[],r=0;r<n.length;r++){var o=n[r];(l=i[o.id]).refs--,a.push(l)}for(e&&g(y(e,t),t),r=0;r<a.length;r++){var l;if(0===(l=a[r]).refs){for(var s=0;s<l.parts.length;s++)l.parts[s]();delete i[l.id]}}}};var k,w=(k=[],function(e,t){return k[e]=t,k.filter(Boolean).join("\n")});function _(e,t,n,a){var r=n?"":a.css;if(e.styleSheet)e.styleSheet.cssText=w(t,r);else{var i=document.createTextNode(r),o=e.childNodes;o[t]&&e.removeChild(o[t]),o.length?e.insertBefore(i,o[t]):e.appendChild(i)}}function E(e,t){var n=t.css,a=t.media;if(a&&e.setAttribute("media",a),e.styleSheet)e.styleSheet.cssText=n;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(n))}}function C(e,t,n){var a=n.css,r=n.sourceMap,i=void 0===t.convertToAbsoluteUrls&&r;(t.convertToAbsoluteUrls||i)&&(a=f(a)),r&&(a+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(r))))+" */");var o=new Blob([a],{type:"text/css"}),l=e.href;e.href=URL.createObjectURL(o),l&&URL.revokeObjectURL(l)}},function(e,t){e.exports=function(e){var t="undefined"!=typeof window&&window.location;if(!t)throw new Error("fixUrls requires window.location");if(!e||"string"!=typeof e)return e;var n=t.protocol+"//"+t.host,a=n+t.pathname.replace(/\/[^\/]*$/,"/");return e.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi,(function(e,t){var r,i=t.trim().replace(/^"(.*)"$/,(function(e,t){return t})).replace(/^'(.*)'$/,(function(e,t){return t}));return/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/|\s*$)/i.test(i)?e:(r=0===i.indexOf("//")?i:0===i.indexOf("/")?n+i:a+i.replace(/^\.\//,""),"url("+JSON.stringify(r)+")")}))}}])},"object"==o(t)&&"object"==o(e)?e.exports=i():(a=[],void 0===(r="function"==typeof(n=i)?n.apply(t,a):n)||(e.exports=r))}).call(this,n(95)(e))},function(e,t,n){"use strict";e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){"use strict";n.r(t),t.default='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" width="40" height="40">\n <path fill="#f85959" transform="scale(0.8 0.8)" d="M36.5,18.73a1.19,1.19,0,0,0,1-1.14V16.33a1.2,1.2,0,0,0-1-1.13l-.61-.08a1.75,1.75,0,0,1-1.3-.86l-.21-.36-.2-.36A1.72,1.72,0,0,1,34,12l.23-.58a1.18,1.18,0,0,0-.5-1.42l-1.1-.62a1.18,1.18,0,0,0-1.47.3l-.39.51a1.82,1.82,0,0,1-1.41.72c-.44,0-1.88-.27-2.22-.7l-.39-.49a1.18,1.18,0,0,0-1.48-.28l-1.09.64a1.19,1.19,0,0,0-.47,1.43l.25.59a1.87,1.87,0,0,1-.08,1.58c-.26.37-1.17,1.5-1.71,1.58l-.63.09a1.19,1.19,0,0,0-1,1.14l0,1.27a1.17,1.17,0,0,0,1,1.12l.61.08a1.74,1.74,0,0,1,1.3.87l.21.36.2.35A1.69,1.69,0,0,1,24,22.08l-.23.59a1.19,1.19,0,0,0,.5,1.42l1.1.62a1.19,1.19,0,0,0,1.48-.31l.38-.5a1.83,1.83,0,0,1,1.41-.72c.44,0,1.88.25,2.22.69l.39.49a1.18,1.18,0,0,0,1.48.28L33.86,24a1.19,1.19,0,0,0,.47-1.43L34.09,22a1.84,1.84,0,0,1,.07-1.58c.26-.37,1.17-1.5,1.72-1.58ZM31,18.94a2.76,2.76,0,0,1-4.65-1.2A2.71,2.71,0,0,1,27,15.13a2.76,2.76,0,0,1,4.64,1.2A2.7,2.7,0,0,1,31,18.94Z"/>\n <path fill="#f85959" transform="scale(0.8 0.8)" d="M32,0H3.59A3.59,3.59,0,0,0,0,3.59v17A3.59,3.59,0,0,0,3.59,24.2H19.72a12.59,12.59,0,0,1-.81-1.2A11.73,11.73,0,0,1,35.54,7.28V3.59A3.59,3.59,0,0,0,32,0ZM13,14.18H4.29a1.52,1.52,0,0,1,0-3H13a1.52,1.52,0,0,1,0,3ZM16.45,8H4.29a1.51,1.51,0,0,1,0-3H16.45a1.51,1.51,0,1,1,0,3Z"/>\n</svg>\n'},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("s_pip",(function(){var e=this,t=i.default.util;if(e.config.pip){var n=e.lang.PIP,a=t.createDom("xg-pip",'<p class="name"><span>'+n+"</span></p>",{tabindex:9},"xgplayer-pip");e.once("ready",(function(){e.controls.appendChild(a)})),["click","touchend"].forEach((function(t){a.addEventListener(t,(function(t){t.preventDefault(),t.stopPropagation(),e.emit("pipBtnClick")}))}))}}))},function(e,t,n){"use strict";var a=i(n(0)),r=i(n(99));function i(e){return e&&e.__esModule?e:{default:e}}a.default.install("s_playNext",(function(){var e=this,t=a.default.util,n=e.config.playNext;if(n&&n.urlList){var i=t.createDom("xg-playnext",'<xg-icon class="xgplayer-icon">'+r.default+"</xg-icon>",{},"xgplayer-playnext"),o=e.lang.PLAYNEXT_TIPS,l=t.createDom("xg-tips",'<span class="xgplayer-tip-playnext">'+o+"</span>",{},"xgplayer-tips");i.appendChild(l),e.once("ready",(function(){e.controls.appendChild(i)})),["click","touchend"].forEach((function(t){i.addEventListener(t,(function(t){t.preventDefault(),t.stopPropagation(),a.default.util.addClass(e.root,"xgplayer-is-enter"),e.emit("playNextBtnClick")}))}));var s=function(){a.default.util.addClass(e.root,"xgplayer-playnext-inactive")};e.on("urlListEnd",s),e.once("destroy",(function t(){e.off("urlListEnd",s),e.off("destroy",t)}))}}))},function(e,t,n){"use strict";n.r(t),t.default='<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40">\n <path transform="scale(0.038 0.028)" d="M800 380v768h-128v-352l-320 320v-704l320 320v-352z"></path>\n</svg>\n'},function(e,t,n){"use strict";var a=i(n(0)),r=i(n(101));function i(e){return e&&e.__esModule?e:{default:e}}a.default.install("s_rotate",(function(){var e=this,t=a.default.util;if(e.config.rotate){var n=t.createDom("xg-rotate",'<xg-icon class="xgplayer-icon">'+r.default+"</xg-icon>",{},"xgplayer-rotate"),i=e.lang.ROTATE_TIPS,o=t.createDom("xg-tips",'<span class="xgplayer-tip-rotate">'+i+"</span>",{},"xgplayer-tips");n.appendChild(o),e.once("ready",(function(){e.controls.appendChild(n)})),["click","touchend"].forEach((function(t){n.addEventListener(t,(function(t){t.preventDefault(),t.stopPropagation(),e.emit("rotateBtnClick")}))}))}}))},function(e,t,n){"use strict";n.r(t),t.default='<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 40 40" fill="none">\n <g clip-path="url(#clip0)">\n <path transform="scale(1.5 1.5)" d="M11.6665 9.16663H4.1665C2.78579 9.16663 1.6665 10.2859 1.6665 11.6666V15.8333C1.6665 17.214 2.78579 18.3333 4.1665 18.3333H11.6665C13.0472 18.3333 14.1665 17.214 14.1665 15.8333V11.6666C14.1665 10.2859 13.0472 9.16663 11.6665 9.16663Z" fill="white"/>\n <path transform="scale(1.5 1.5)" fill-rule="evenodd" clip-rule="evenodd" d="M3.88148 4.06298C3.75371 4.21005 3.67667 4.40231 3.67749 4.61242C3.67847 4.87253 3.79852 5.10435 3.98581 5.25646L6.99111 8.05895C7.32771 8.37283 7.85502 8.35443 8.16891 8.01782C8.48279 7.68122 8.46437 7.15391 8.12778 6.84003L6.62061 5.43457L9.8198 5.4224C9.82848 5.42239 9.8372 5.42221 9.84591 5.4219C10.9714 5.38233 12.0885 5.6285 13.0931 6.13744C14.0976 6.64635 14.957 7.40148 15.5908 8.33234C16.2246 9.2632 16.6122 10.3394 16.7177 11.4606C16.823 12.5819 16.6427 13.7115 16.1934 14.7442C16.0098 15.1661 16.203 15.6571 16.6251 15.8408C17.0471 16.0243 17.5381 15.8311 17.7216 15.4091C18.2833 14.1183 18.5087 12.7063 18.3771 11.3047C18.2453 9.90318 17.7607 8.55792 16.9684 7.39433C16.1761 6.23073 15.1021 5.28683 13.8463 4.65065C12.5946 4.01651 11.203 3.70872 9.80072 3.75583L6.43415 3.76862L7.96326 2.12885C8.27715 1.79225 8.25872 1.26494 7.92213 0.951061C7.58553 0.63718 7.05822 0.655585 6.74433 0.99219L3.90268 4.0395C3.89545 4.04724 3.88841 4.05509 3.88154 4.06303L3.88148 4.06298Z" fill="white"/>\n </g>\n <defs>\n <clipPath id="clip0">\n <rect width="40" height="40" fill="white"/>\n </clipPath>\n </defs>\n</svg>\n'},function(e,t,n){"use strict";var a=i(n(0)),r=i(n(103));function i(e){return e&&e.__esModule?e:{default:e}}a.default.install("s_reload",(function(){var e=this,t=a.default.util;if(e.config.reload){var n=t.createDom("xg-reload",'<xg-icon class="xgplayer-icon">'+r.default+"</xg-icon>",{},"xgplayer-reload"),i=e.lang.RELOAD_TIPS,o=t.createDom("xg-tips",'<span class="xgplayer-tip-reload">'+i+"</span>",{},"xgplayer-tips");n.appendChild(o),e.once("ready",(function(){e.controls.appendChild(n)})),["click","touchend"].forEach((function(t){n.addEventListener(t,(function(t){t.preventDefault(),t.stopPropagation(),e.emit("reloadBtnClick")}))}))}}))},function(e,t,n){"use strict";n.r(t),t.default='<svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 28 28">\n <path fill="#FFF" fill-opacity="1" fill-rule="nonzero" d="M18.17 19.988a7.182 7.182 0 0 1-4.256 1.318 7.806 7.806 0 0 1-.595-.03c-.08-.008-.16-.021-.242-.031a8.004 8.004 0 0 1-.458-.071c-.094-.018-.185-.042-.276-.063a7.743 7.743 0 0 1-.439-.113c-.068-.022-.136-.047-.205-.07a7.03 7.03 0 0 1-.492-.181c-.037-.015-.072-.032-.108-.049a7.295 7.295 0 0 1-.554-.269l-.025-.012a7.347 7.347 0 0 1-2.111-1.753c-.03-.036-.057-.074-.086-.11a7.305 7.305 0 0 1-1.594-4.557h1.686a.123.123 0 0 0 .108-.064.119.119 0 0 0-.006-.125L5.684 9.532a.123.123 0 0 0-.103-.056.123.123 0 0 0-.102.056l-2.834 4.276a.121.121 0 0 0-.005.125c.022.04.064.064.107.064h1.687c0 2.025.627 3.902 1.693 5.454.013.021.022.044.037.066.11.159.233.305.352.455.043.057.085.116.13.171.175.213.36.413.55.61.02.018.036.038.054.055a9.447 9.447 0 0 0 2.91 1.996c.058.026.115.054.175.079.202.084.41.158.619.228.098.034.196.069.296.1.183.054.37.1.558.145.125.029.249.06.376.085.052.01.102.027.155.035.177.032.355.05.533.071.064.007.128.018.19.026.32.03.639.052.956.052a9.46 9.46 0 0 0 5.47-1.746 1.16 1.16 0 0 0 .282-1.608 1.143 1.143 0 0 0-1.6-.283zm5.397-5.991a9.604 9.604 0 0 0-1.685-5.441c-.016-.027-.026-.054-.043-.078-.132-.19-.276-.366-.419-.543-.017-.022-.032-.044-.05-.065a9.467 9.467 0 0 0-3.571-2.7l-.114-.051a11.2 11.2 0 0 0-.673-.248c-.082-.027-.163-.057-.247-.082a9.188 9.188 0 0 0-.6-.156c-.113-.026-.224-.055-.337-.077-.057-.011-.109-.028-.164-.037-.151-.027-.304-.039-.455-.058-.104-.013-.208-.03-.313-.04a10.05 10.05 0 0 0-.759-.039c-.045 0-.09-.007-.136-.007l-.025.003a9.45 9.45 0 0 0-5.46 1.737 1.16 1.16 0 0 0-.284 1.608c.363.523 1.08.65 1.6.284a7.182 7.182 0 0 1 4.222-1.32c.217.002.429.013.639.033.065.007.129.017.193.025.173.021.344.046.513.08.075.014.149.033.221.05.166.037.331.077.494.127l.152.051c.185.061.366.127.545.201l.054.025a7.308 7.308 0 0 1 2.741 2.067l.013.018a7.302 7.302 0 0 1 1.652 4.633h-1.686a.123.123 0 0 0-.108.064.12.12 0 0 0 .006.124l2.834 4.277c.022.033.06.054.103.054.042 0 .08-.021.102-.054l2.833-4.277a.12.12 0 0 0 .005-.124.123.123 0 0 0-.108-.064h-1.685z"/>\n</svg>\n'},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("s_screenShot",(function(){var e=this,t=i.default.util;if(e.config.screenShot){var n=e.lang.SCREENSHOT,a=t.createDom("xg-screenshot",'<p class="name"><span>'+n+"</span></p>",{tabindex:11},"xgplayer-screenshot");e.once("ready",(function(){e.controls.appendChild(a)})),["click","touchend"].forEach((function(t){a.addEventListener(t,(function(t){t.preventDefault(),t.stopPropagation(),e.emit("screenShotBtnClick")}))}))}}))},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("s_textTrack",(function(){if(this.config.textTrack){var e=this,t=e.root,n=i.default.util,a=(i.default.sniffer,e.controls,n.createDom("xg-texttrack","",{tabindex:7},"xgplayer-texttrack")),r=e.config.textTrack;r&&Array.isArray(r)&&r.length>0&&(n.addClass(e.root,"xgplayer-is-texttrack"),e.once("canplay",(function(){var i=this,o=["<ul>"];o.push("<li class='"+(this.textTrackShowDefault?"":"selected")+"'}'>"+e.lang.OFF+"</li>"),r.forEach((function(e){o.push("<li class='"+(e.default&&i.textTrackShowDefault?"selected":"")+"'>"+e.label+"</li>")}));var l=e.lang.TEXTTRACK;o.push('</ul><p class="name">'+l+"</p>");var s=t.querySelector(".xgplayer-texttrack");if(s){s.innerHTML=o.join("");var u=s.querySelector(".name");e.config.textTrackActive&&"hover"!==e.config.textTrackActive||u.addEventListener("mouseenter",(function(e){e.preventDefault(),e.stopPropagation(),n.addClass(t,"xgplayer-texttrack-active"),s.focus()}))}else{a.innerHTML=o.join("");var c=a.querySelector(".name");e.config.textTrackActive&&"hover"!==e.config.textTrackActive||c.addEventListener("mouseenter",(function(t){t.preventDefault(),t.stopPropagation(),n.addClass(e.root,"xgplayer-texttrack-active"),a.focus()})),e.controls.appendChild(a)}}))),["touchend","click"].forEach((function(t){a.addEventListener(t,(function(t){t.preventDefault(),t.stopPropagation();var i=t.target||t.srcElement;if(i&&"li"===i.tagName.toLocaleLowerCase()){Array.prototype.forEach.call(i.parentNode.childNodes,(function(e){n.removeClass(e,"selected")})),n.addClass(i,"selected");var o=e.root.getElementsByTagName("Track");i.innerHTML===e.lang.OFF?(o[0].track.mode="hidden",o[0].src="",n.removeClass(e.root,"xgplayer-texttrack-active")):(o[0].style.display="block",n.addClass(e.root,"xgplayer-texttrack-active"),o[0].track.mode="showing",r.some((function(e){if(e.label===i.innerHTML)return o[0].src=e.src,e.kind&&(o[0].kind=e.kind),o[0].label=e.label,e.srclang&&(o[0].srclang=e.srclang),!0})),e.emit("textTrackChange",i.innerHTML))}else"click"!==e.config.textTrackActive||!i||"p"!==i.tagName.toLocaleLowerCase()&&"em"!==i.tagName.toLocaleLowerCase()||(n.addClass(e.root,"xgplayer-texttrack-active"),a.focus())}),!1)})),e.on("play",(function(){var a=t.querySelector(".xgplayer-texttrack ul"),i=t.getElementsByTagName("Track");e.hls&&a&&i&&(i[0].src="",Array.prototype.forEach.call(a.childNodes,(function(t){n.hasClass(t,"selected")&&(t.innerHTML===e.lang.OFF?(i[0].track.mode="hidden",i[0].src=""):(i[0].track.mode="hidden",r.some((function(e){if(e.label!==t.innerHTML)return i[0].src=e.src,e.kind&&(i[0].kind=e.kind),i[0].label=e.label,e.srclang&&(i[0].srclang=e.srclang),!0})),r.some((function(e){if(e.label===t.innerHTML)return setTimeout((function(){i[0].src=e.src,e.kind&&(i[0].kind=e.kind),i[0].label=e.label,e.srclang&&(i[0].srclang=e.srclang),i[0].track.mode="showing"})),!0}))))})),n.removeClass(e.root,"xgplayer-texttrack-active"))})),a.addEventListener("mouseleave",(function(t){t.preventDefault(),t.stopPropagation(),n.removeClass(e.root,"xgplayer-texttrack-active")}))}}))},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("s_error",(function(){var e=this,t=e.root,n=i.default.util,a=n.createDom("xg-error",'<span class="xgplayer-error-text">请<span class="xgplayer-error-refresh">刷新</span>试试</span>',{},"xgplayer-error");e.once("ready",(function(){t.appendChild(a)}));var r=a.querySelector(".xgplayer-error-text"),o=null;function l(){e.config.lang&&"zh-cn"===e.config.lang?r.innerHTML=e.config.errorTips||'请<span class="xgplayer-error-refresh">刷新</span>试试':r.innerHTML=e.config.errorTips||'please try to <span class="xgplayer-error-refresh">refresh</span>',n.addClass(e.root,"xgplayer-is-error"),(o=a.querySelector(".xgplayer-error-refresh"))&&["touchend","click"].forEach((function(t){o.addEventListener(t,(function(t){t.preventDefault(),t.stopPropagation(),e.autoplay=!0,e.once("playing",(function(){n.removeClass(e.root,"xgplayer-is-error")})),e.src=e.config.url}))}))}e.on("error",l),e.once("destroy",(function t(){e.off("error",l),e.off("destroy",t)}))}))},function(e,t,n){"use strict";var a,r=n(0),i=(a=r)&&a.__esModule?a:{default:a};i.default.install("s_memoryPlay",(function(){var e=this,t=i.default.util,n=e.config.lastPlayTime||0,a=e.config.lastPlayTimeHideDelay||3,r=null;if(!(n<=0)){(r=t.createDom("xg-memoryplay",'<div class="xgplayer-memoryplay-spot"><div class="xgplayer-progress-tip">您上次观看到 <span class="xgplayer-lasttime">'+t.format(n)+'</span> ,为您自动续播 <span class="btn-close"><svg viewBox="64 64 896 896" focusable="false" class="" data-icon="close" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M563.8 512l262.5-312.9c4.4-5.2.7-13.1-6.1-13.1h-79.8c-4.7 0-9.2 2.1-12.3 5.7L511.6 449.8 295.1 191.7c-3-3.6-7.5-5.7-12.3-5.7H203c-6.8 0-10.5 7.9-6.1 13.1L459.4 512 196.9 824.9A7.95 7.95 0 0 0 203 838h79.8c4.7 0 9.2-2.1 12.3-5.7l216.5-258.1 216.5 258.1c3 3.6 7.5 5.7 12.3 5.7h79.8c6.8 0 10.5-7.9 6.1-13.1L563.8 512z"></path></svg></span></div></div>',{},"xgplayer-memoryplay")).addEventListener("mouseover",(function(e){e.stopPropagation()}));var o=function(){r&&r.parentNode.removeChild(r),r=null};r.querySelector(".xgplayer-progress-tip .btn-close").addEventListener("click",o);e.once("play",(function(){e.root.appendChild(r),e.emit("memoryPlayStart",n),a>0&&setTimeout((function(){o()}),1e3*a)})),e.once("ended",o)}}))}])}));
  302. //# sourceMappingURL=index.js.map
  303. /***/ }),
  304. /***/ "5692":
  305. /***/ (function(module, exports, __webpack_require__) {
  306. var IS_PURE = __webpack_require__("c430");
  307. var store = __webpack_require__("c6cd");
  308. (module.exports = function (key, value) {
  309. return store[key] || (store[key] = value !== undefined ? value : {});
  310. })('versions', []).push({
  311. version: '3.6.5',
  312. mode: IS_PURE ? 'pure' : 'global',
  313. copyright: '© 2020 Denis Pushkarev (zloirock.ru)'
  314. });
  315. /***/ }),
  316. /***/ "56ef":
  317. /***/ (function(module, exports, __webpack_require__) {
  318. var getBuiltIn = __webpack_require__("d066");
  319. var getOwnPropertyNamesModule = __webpack_require__("241c");
  320. var getOwnPropertySymbolsModule = __webpack_require__("7418");
  321. var anObject = __webpack_require__("825a");
  322. // all object keys, includes non-enumerable and symbols
  323. module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
  324. var keys = getOwnPropertyNamesModule.f(anObject(it));
  325. var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
  326. return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;
  327. };
  328. /***/ }),
  329. /***/ "5c6c":
  330. /***/ (function(module, exports) {
  331. module.exports = function (bitmap, value) {
  332. return {
  333. enumerable: !(bitmap & 1),
  334. configurable: !(bitmap & 2),
  335. writable: !(bitmap & 4),
  336. value: value
  337. };
  338. };
  339. /***/ }),
  340. /***/ "60da":
  341. /***/ (function(module, exports, __webpack_require__) {
  342. "use strict";
  343. var DESCRIPTORS = __webpack_require__("83ab");
  344. var fails = __webpack_require__("d039");
  345. var objectKeys = __webpack_require__("df75");
  346. var getOwnPropertySymbolsModule = __webpack_require__("7418");
  347. var propertyIsEnumerableModule = __webpack_require__("d1e7");
  348. var toObject = __webpack_require__("7b0b");
  349. var IndexedObject = __webpack_require__("44ad");
  350. var nativeAssign = Object.assign;
  351. var defineProperty = Object.defineProperty;
  352. // `Object.assign` method
  353. // https://tc39.github.io/ecma262/#sec-object.assign
  354. module.exports = !nativeAssign || fails(function () {
  355. // should have correct order of operations (Edge bug)
  356. if (DESCRIPTORS && nativeAssign({ b: 1 }, nativeAssign(defineProperty({}, 'a', {
  357. enumerable: true,
  358. get: function () {
  359. defineProperty(this, 'b', {
  360. value: 3,
  361. enumerable: false
  362. });
  363. }
  364. }), { b: 2 })).b !== 1) return true;
  365. // should work with symbols and should have deterministic property order (V8 bug)
  366. var A = {};
  367. var B = {};
  368. // eslint-disable-next-line no-undef
  369. var symbol = Symbol();
  370. var alphabet = 'abcdefghijklmnopqrst';
  371. A[symbol] = 7;
  372. alphabet.split('').forEach(function (chr) { B[chr] = chr; });
  373. return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet;
  374. }) ? function assign(target, source) { // eslint-disable-line no-unused-vars
  375. var T = toObject(target);
  376. var argumentsLength = arguments.length;
  377. var index = 1;
  378. var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
  379. var propertyIsEnumerable = propertyIsEnumerableModule.f;
  380. while (argumentsLength > index) {
  381. var S = IndexedObject(arguments[index++]);
  382. var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S);
  383. var length = keys.length;
  384. var j = 0;
  385. var key;
  386. while (length > j) {
  387. key = keys[j++];
  388. if (!DESCRIPTORS || propertyIsEnumerable.call(S, key)) T[key] = S[key];
  389. }
  390. } return T;
  391. } : nativeAssign;
  392. /***/ }),
  393. /***/ "69f3":
  394. /***/ (function(module, exports, __webpack_require__) {
  395. var NATIVE_WEAK_MAP = __webpack_require__("7f9a");
  396. var global = __webpack_require__("da84");
  397. var isObject = __webpack_require__("861d");
  398. var createNonEnumerableProperty = __webpack_require__("9112");
  399. var objectHas = __webpack_require__("5135");
  400. var sharedKey = __webpack_require__("f772");
  401. var hiddenKeys = __webpack_require__("d012");
  402. var WeakMap = global.WeakMap;
  403. var set, get, has;
  404. var enforce = function (it) {
  405. return has(it) ? get(it) : set(it, {});
  406. };
  407. var getterFor = function (TYPE) {
  408. return function (it) {
  409. var state;
  410. if (!isObject(it) || (state = get(it)).type !== TYPE) {
  411. throw TypeError('Incompatible receiver, ' + TYPE + ' required');
  412. } return state;
  413. };
  414. };
  415. if (NATIVE_WEAK_MAP) {
  416. var store = new WeakMap();
  417. var wmget = store.get;
  418. var wmhas = store.has;
  419. var wmset = store.set;
  420. set = function (it, metadata) {
  421. wmset.call(store, it, metadata);
  422. return metadata;
  423. };
  424. get = function (it) {
  425. return wmget.call(store, it) || {};
  426. };
  427. has = function (it) {
  428. return wmhas.call(store, it);
  429. };
  430. } else {
  431. var STATE = sharedKey('state');
  432. hiddenKeys[STATE] = true;
  433. set = function (it, metadata) {
  434. createNonEnumerableProperty(it, STATE, metadata);
  435. return metadata;
  436. };
  437. get = function (it) {
  438. return objectHas(it, STATE) ? it[STATE] : {};
  439. };
  440. has = function (it) {
  441. return objectHas(it, STATE);
  442. };
  443. }
  444. module.exports = {
  445. set: set,
  446. get: get,
  447. has: has,
  448. enforce: enforce,
  449. getterFor: getterFor
  450. };
  451. /***/ }),
  452. /***/ "6eeb":
  453. /***/ (function(module, exports, __webpack_require__) {
  454. var global = __webpack_require__("da84");
  455. var createNonEnumerableProperty = __webpack_require__("9112");
  456. var has = __webpack_require__("5135");
  457. var setGlobal = __webpack_require__("ce4e");
  458. var inspectSource = __webpack_require__("8925");
  459. var InternalStateModule = __webpack_require__("69f3");
  460. var getInternalState = InternalStateModule.get;
  461. var enforceInternalState = InternalStateModule.enforce;
  462. var TEMPLATE = String(String).split('String');
  463. (module.exports = function (O, key, value, options) {
  464. var unsafe = options ? !!options.unsafe : false;
  465. var simple = options ? !!options.enumerable : false;
  466. var noTargetGet = options ? !!options.noTargetGet : false;
  467. if (typeof value == 'function') {
  468. if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key);
  469. enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : '');
  470. }
  471. if (O === global) {
  472. if (simple) O[key] = value;
  473. else setGlobal(key, value);
  474. return;
  475. } else if (!unsafe) {
  476. delete O[key];
  477. } else if (!noTargetGet && O[key]) {
  478. simple = true;
  479. }
  480. if (simple) O[key] = value;
  481. else createNonEnumerableProperty(O, key, value);
  482. // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
  483. })(Function.prototype, 'toString', function toString() {
  484. return typeof this == 'function' && getInternalState(this).source || inspectSource(this);
  485. });
  486. /***/ }),
  487. /***/ "7418":
  488. /***/ (function(module, exports) {
  489. exports.f = Object.getOwnPropertySymbols;
  490. /***/ }),
  491. /***/ "7839":
  492. /***/ (function(module, exports) {
  493. // IE8- don't enum bug keys
  494. module.exports = [
  495. 'constructor',
  496. 'hasOwnProperty',
  497. 'isPrototypeOf',
  498. 'propertyIsEnumerable',
  499. 'toLocaleString',
  500. 'toString',
  501. 'valueOf'
  502. ];
  503. /***/ }),
  504. /***/ "7b0b":
  505. /***/ (function(module, exports, __webpack_require__) {
  506. var requireObjectCoercible = __webpack_require__("1d80");
  507. // `ToObject` abstract operation
  508. // https://tc39.github.io/ecma262/#sec-toobject
  509. module.exports = function (argument) {
  510. return Object(requireObjectCoercible(argument));
  511. };
  512. /***/ }),
  513. /***/ "7f9a":
  514. /***/ (function(module, exports, __webpack_require__) {
  515. var global = __webpack_require__("da84");
  516. var inspectSource = __webpack_require__("8925");
  517. var WeakMap = global.WeakMap;
  518. module.exports = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap));
  519. /***/ }),
  520. /***/ "825a":
  521. /***/ (function(module, exports, __webpack_require__) {
  522. var isObject = __webpack_require__("861d");
  523. module.exports = function (it) {
  524. if (!isObject(it)) {
  525. throw TypeError(String(it) + ' is not an object');
  526. } return it;
  527. };
  528. /***/ }),
  529. /***/ "83ab":
  530. /***/ (function(module, exports, __webpack_require__) {
  531. var fails = __webpack_require__("d039");
  532. // Thank's IE8 for his funny defineProperty
  533. module.exports = !fails(function () {
  534. return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;
  535. });
  536. /***/ }),
  537. /***/ "861d":
  538. /***/ (function(module, exports) {
  539. module.exports = function (it) {
  540. return typeof it === 'object' ? it !== null : typeof it === 'function';
  541. };
  542. /***/ }),
  543. /***/ "8875":
  544. /***/ (function(module, exports, __webpack_require__) {
  545. var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// addapted from the document.currentScript polyfill by Adam Miller
  546. // MIT license
  547. // source: https://github.com/amiller-gh/currentScript-polyfill
  548. // added support for Firefox https://bugzilla.mozilla.org/show_bug.cgi?id=1620505
  549. (function (root, factory) {
  550. if (true) {
  551. !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
  552. __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
  553. (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
  554. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  555. } else {}
  556. }(typeof self !== 'undefined' ? self : this, function () {
  557. function getCurrentScript () {
  558. var descriptor = Object.getOwnPropertyDescriptor(document, 'currentScript')
  559. // for chrome
  560. if (!descriptor && 'currentScript' in document && document.currentScript) {
  561. return document.currentScript
  562. }
  563. // for other browsers with native support for currentScript
  564. if (descriptor && descriptor.get !== getCurrentScript && document.currentScript) {
  565. return document.currentScript
  566. }
  567. // IE 8-10 support script readyState
  568. // IE 11+ & Firefox support stack trace
  569. try {
  570. throw new Error();
  571. }
  572. catch (err) {
  573. // Find the second match for the "at" string to get file src url from stack.
  574. var ieStackRegExp = /.*at [^(]*\((.*):(.+):(.+)\)$/ig,
  575. ffStackRegExp = /@([^@]*):(\d+):(\d+)\s*$/ig,
  576. stackDetails = ieStackRegExp.exec(err.stack) || ffStackRegExp.exec(err.stack),
  577. scriptLocation = (stackDetails && stackDetails[1]) || false,
  578. line = (stackDetails && stackDetails[2]) || false,
  579. currentLocation = document.location.href.replace(document.location.hash, ''),
  580. pageSource,
  581. inlineScriptSourceRegExp,
  582. inlineScriptSource,
  583. scripts = document.getElementsByTagName('script'); // Live NodeList collection
  584. if (scriptLocation === currentLocation) {
  585. pageSource = document.documentElement.outerHTML;
  586. inlineScriptSourceRegExp = new RegExp('(?:[^\\n]+?\\n){0,' + (line - 2) + '}[^<]*<script>([\\d\\D]*?)<\\/script>[\\d\\D]*', 'i');
  587. inlineScriptSource = pageSource.replace(inlineScriptSourceRegExp, '$1').trim();
  588. }
  589. for (var i = 0; i < scripts.length; i++) {
  590. // If ready state is interactive, return the script tag
  591. if (scripts[i].readyState === 'interactive') {
  592. return scripts[i];
  593. }
  594. // If src matches, return the script tag
  595. if (scripts[i].src === scriptLocation) {
  596. return scripts[i];
  597. }
  598. // If inline source matches, return the script tag
  599. if (
  600. scriptLocation === currentLocation &&
  601. scripts[i].innerHTML &&
  602. scripts[i].innerHTML.trim() === inlineScriptSource
  603. ) {
  604. return scripts[i];
  605. }
  606. }
  607. // If no match, return null
  608. return null;
  609. }
  610. };
  611. return getCurrentScript
  612. }));
  613. /***/ }),
  614. /***/ "8925":
  615. /***/ (function(module, exports, __webpack_require__) {
  616. var store = __webpack_require__("c6cd");
  617. var functionToString = Function.toString;
  618. // this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper
  619. if (typeof store.inspectSource != 'function') {
  620. store.inspectSource = function (it) {
  621. return functionToString.call(it);
  622. };
  623. }
  624. module.exports = store.inspectSource;
  625. /***/ }),
  626. /***/ "9000":
  627. /***/ (function(module, exports, __webpack_require__) {
  628. (function webpackUniversalModuleDefinition(root, factory) {
  629. if(true)
  630. module.exports = factory(__webpack_require__("5392"));
  631. else {}
  632. })(window, function(__WEBPACK_EXTERNAL_MODULE__33__) {
  633. return /******/ (function(modules) { // webpackBootstrap
  634. /******/ // The module cache
  635. /******/ var installedModules = {};
  636. /******/
  637. /******/ // The require function
  638. /******/ function __webpack_require__(moduleId) {
  639. /******/
  640. /******/ // Check if module is in cache
  641. /******/ if(installedModules[moduleId]) {
  642. /******/ return installedModules[moduleId].exports;
  643. /******/ }
  644. /******/ // Create a new module (and put it into the cache)
  645. /******/ var module = installedModules[moduleId] = {
  646. /******/ i: moduleId,
  647. /******/ l: false,
  648. /******/ exports: {}
  649. /******/ };
  650. /******/
  651. /******/ // Execute the module function
  652. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  653. /******/
  654. /******/ // Flag the module as loaded
  655. /******/ module.l = true;
  656. /******/
  657. /******/ // Return the exports of the module
  658. /******/ return module.exports;
  659. /******/ }
  660. /******/
  661. /******/
  662. /******/ // expose the modules object (__webpack_modules__)
  663. /******/ __webpack_require__.m = modules;
  664. /******/
  665. /******/ // expose the module cache
  666. /******/ __webpack_require__.c = installedModules;
  667. /******/
  668. /******/ // define getter function for harmony exports
  669. /******/ __webpack_require__.d = function(exports, name, getter) {
  670. /******/ if(!__webpack_require__.o(exports, name)) {
  671. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  672. /******/ }
  673. /******/ };
  674. /******/
  675. /******/ // define __esModule on exports
  676. /******/ __webpack_require__.r = function(exports) {
  677. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  678. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  679. /******/ }
  680. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  681. /******/ };
  682. /******/
  683. /******/ // create a fake namespace object
  684. /******/ // mode & 1: value is a module id, require it
  685. /******/ // mode & 2: merge all properties of value into the ns
  686. /******/ // mode & 4: return value when already ns object
  687. /******/ // mode & 8|1: behave like require
  688. /******/ __webpack_require__.t = function(value, mode) {
  689. /******/ if(mode & 1) value = __webpack_require__(value);
  690. /******/ if(mode & 8) return value;
  691. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  692. /******/ var ns = Object.create(null);
  693. /******/ __webpack_require__.r(ns);
  694. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  695. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  696. /******/ return ns;
  697. /******/ };
  698. /******/
  699. /******/ // getDefaultExport function for compatibility with non-harmony modules
  700. /******/ __webpack_require__.n = function(module) {
  701. /******/ var getter = module && module.__esModule ?
  702. /******/ function getDefault() { return module['default']; } :
  703. /******/ function getModuleExports() { return module; };
  704. /******/ __webpack_require__.d(getter, 'a', getter);
  705. /******/ return getter;
  706. /******/ };
  707. /******/
  708. /******/ // Object.prototype.hasOwnProperty.call
  709. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  710. /******/
  711. /******/ // __webpack_public_path__
  712. /******/ __webpack_require__.p = "";
  713. /******/
  714. /******/
  715. /******/ // Load entry module and return exports
  716. /******/ return __webpack_require__(__webpack_require__.s = 31);
  717. /******/ })
  718. /************************************************************************/
  719. /******/ ([
  720. /* 0 */
  721. /***/ (function(module, exports, __webpack_require__) {
  722. "use strict";
  723. Object.defineProperty(exports, "__esModule", {
  724. value: true
  725. });
  726. exports.logger = exports.enableLogs = undefined;
  727. 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; };
  728. var _getSelfScope = __webpack_require__(5);
  729. function noop() {}
  730. var fakeLogger = {
  731. trace: noop,
  732. debug: noop,
  733. log: noop,
  734. warn: noop,
  735. info: noop,
  736. error: noop
  737. };
  738. var exportedLogger = fakeLogger;
  739. // let lastCallTime;
  740. // function formatMsgWithTimeInfo(type, msg) {
  741. // const now = Date.now();
  742. // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
  743. // lastCallTime = now;
  744. // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
  745. // return msg;
  746. // }
  747. function formatMsg(type, msg) {
  748. msg = '[' + type + '] > ' + msg;
  749. return msg;
  750. }
  751. var global = (0, _getSelfScope.getSelfScope)();
  752. function consolePrintFn(type) {
  753. var func = global.console[type];
  754. if (func) {
  755. return function () {
  756. for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  757. args[_key] = arguments[_key];
  758. }
  759. if (args[0]) {
  760. args[0] = formatMsg(type, args[0]);
  761. }
  762. func.apply(global.console, args);
  763. };
  764. }
  765. return noop;
  766. }
  767. function exportLoggerFunctions(debugConfig) {
  768. for (var _len2 = arguments.length, functions = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  769. functions[_key2 - 1] = arguments[_key2];
  770. }
  771. functions.forEach(function (type) {
  772. exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
  773. });
  774. }
  775. var enableLogs = exports.enableLogs = function enableLogs(debugConfig) {
  776. if (debugConfig === true || (typeof debugConfig === 'undefined' ? 'undefined' : _typeof(debugConfig)) === 'object') {
  777. exportLoggerFunctions(debugConfig,
  778. // Remove out from list here to hard-disable a log-level
  779. // 'trace',
  780. 'debug', 'log', 'info', 'warn', 'error');
  781. // Some browsers don't allow to use bind on console object anyway
  782. // fallback to default if needed
  783. try {
  784. exportedLogger.log();
  785. } catch (e) {
  786. exportedLogger = fakeLogger;
  787. }
  788. } else {
  789. exportedLogger = fakeLogger;
  790. }
  791. };
  792. var logger = exports.logger = exportedLogger;
  793. /***/ }),
  794. /* 1 */
  795. /***/ (function(module, exports, __webpack_require__) {
  796. "use strict";
  797. Object.defineProperty(exports, "__esModule", {
  798. value: true
  799. });
  800. /**
  801. * @readonly
  802. * @enum {string}
  803. */
  804. var HlsEvents = {
  805. // fired before MediaSource is attaching to media element - data: { media }
  806. MEDIA_ATTACHING: 'hlsMediaAttaching',
  807. // fired when MediaSource has been succesfully attached to media element - data: { }
  808. MEDIA_ATTACHED: 'hlsMediaAttached',
  809. // fired before detaching MediaSource from media element - data: { }
  810. MEDIA_DETACHING: 'hlsMediaDetaching',
  811. // fired when MediaSource has been detached from media element - data: { }
  812. MEDIA_DETACHED: 'hlsMediaDetached',
  813. // fired when we buffer is going to be reset - data: { }
  814. BUFFER_RESET: 'hlsBufferReset',
  815. // fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}
  816. BUFFER_CODECS: 'hlsBufferCodecs',
  817. // fired when sourcebuffers have been created - data: { tracks : tracks }
  818. BUFFER_CREATED: 'hlsBufferCreated',
  819. // fired when we append a segment to the buffer - data: { segment: segment object }
  820. BUFFER_APPENDING: 'hlsBufferAppending',
  821. // fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent}
  822. BUFFER_APPENDED: 'hlsBufferAppended',
  823. // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }
  824. BUFFER_EOS: 'hlsBufferEos',
  825. // fired when the media buffer should be flushed - data { startOffset, endOffset }
  826. BUFFER_FLUSHING: 'hlsBufferFlushing',
  827. // fired when the media buffer has been flushed - data: { }
  828. BUFFER_FLUSHED: 'hlsBufferFlushed',
  829. // fired to signal that a manifest loading starts - data: { url : manifestURL}
  830. MANIFEST_LOADING: 'hlsManifestLoading',
  831. // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}}
  832. MANIFEST_LOADED: 'hlsManifestLoaded',
  833. // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}
  834. MANIFEST_PARSED: 'hlsManifestParsed',
  835. // fired when a level switch is requested - data: { level : id of new level }
  836. LEVEL_SWITCHING: 'hlsLevelSwitching',
  837. // fired when a level switch is effective - data: { level : id of new level }
  838. LEVEL_SWITCHED: 'hlsLevelSwitched',
  839. // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}
  840. LEVEL_LOADING: 'hlsLevelLoading',
  841. // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }
  842. LEVEL_LOADED: 'hlsLevelLoaded',
  843. // fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level }
  844. LEVEL_UPDATED: 'hlsLevelUpdated',
  845. // fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }
  846. LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',
  847. // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }
  848. AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated',
  849. // fired when an audio track switching is requested - data: { id : audio track id }
  850. AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching',
  851. // fired when an audio track switch actually occurs - data: { id : audio track id }
  852. AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched',
  853. // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }
  854. AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading',
  855. // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } }
  856. AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded',
  857. // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }
  858. SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated',
  859. // fired when an subtitle track switch occurs - data: { id : subtitle track id }
  860. SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch',
  861. // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }
  862. SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading',
  863. // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } }
  864. SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded',
  865. // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }
  866. SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed',
  867. // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object }
  868. INIT_PTS_FOUND: 'hlsInitPtsFound',
  869. // fired when a fragment loading starts - data: { frag : fragment object }
  870. FRAG_LOADING: 'hlsFragLoading',
  871. // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }
  872. FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',
  873. // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }
  874. FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',
  875. // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } }
  876. FRAG_LOADED: 'hlsFragLoaded',
  877. // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }
  878. FRAG_DECRYPTED: 'hlsFragDecrypted',
  879. // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }
  880. FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',
  881. // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }
  882. FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',
  883. // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }
  884. FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',
  885. // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}
  886. FRAG_PARSING_DATA: 'hlsFragParsingData',
  887. // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }
  888. FRAG_PARSED: 'hlsFragParsed',
  889. // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length, bwEstimate } }
  890. FRAG_BUFFERED: 'hlsFragBuffered',
  891. // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }
  892. FRAG_CHANGED: 'hlsFragChanged',
  893. // Identifier for a FPS drop event - data: { curentDropped, currentDecoded, totalDroppedFrames }
  894. FPS_DROP: 'hlsFpsDrop',
  895. // triggered when FPS drop triggers auto level capping - data: { level, droppedlevel }
  896. FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',
  897. // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }
  898. ERROR: 'hlsError',
  899. // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }
  900. DESTROYING: 'hlsDestroying',
  901. // fired when a decrypt key loading starts - data: { frag : fragment object }
  902. KEY_LOADING: 'hlsKeyLoading',
  903. // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length } }
  904. KEY_LOADED: 'hlsKeyLoaded',
  905. // fired upon stream controller state transitions - data: { previousState, nextState }
  906. STREAM_STATE_TRANSITION: 'hlsStreamStateTransition'
  907. };
  908. exports.default = HlsEvents;
  909. module.exports = exports['default'];
  910. /***/ }),
  911. /* 2 */
  912. /***/ (function(module, exports, __webpack_require__) {
  913. "use strict";
  914. Object.defineProperty(exports, "__esModule", {
  915. value: true
  916. });
  917. var ErrorTypes = exports.ErrorTypes = {
  918. // Identifier for a network error (loading error / timeout ...)
  919. NETWORK_ERROR: 'networkError',
  920. // Identifier for a media Error (video/parsing/mediasource error)
  921. MEDIA_ERROR: 'mediaError',
  922. // EME (encrypted media extensions) errors
  923. KEY_SYSTEM_ERROR: 'keySystemError',
  924. // Identifier for a mux Error (demuxing/remuxing)
  925. MUX_ERROR: 'muxError',
  926. // Identifier for all other errors
  927. OTHER_ERROR: 'otherError'
  928. };
  929. /**
  930. * @enum {ErrorDetails}
  931. * @typedef {string} ErrorDetail
  932. */
  933. var ErrorDetails = exports.ErrorDetails = {
  934. KEY_SYSTEM_NO_KEYS: 'keySystemNoKeys',
  935. KEY_SYSTEM_NO_ACCESS: 'keySystemNoAccess',
  936. KEY_SYSTEM_NO_SESSION: 'keySystemNoSession',
  937. KEY_SYSTEM_LICENSE_REQUEST_FAILED: 'keySystemLicenseRequestFailed',
  938. // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  939. MANIFEST_LOAD_ERROR: 'manifestLoadError',
  940. // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  941. MANIFEST_LOAD_TIMEOUT: 'manifestLoadTimeOut',
  942. // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}
  943. MANIFEST_PARSING_ERROR: 'manifestParsingError',
  944. // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}
  945. MANIFEST_INCOMPATIBLE_CODECS_ERROR: 'manifestIncompatibleCodecsError',
  946. // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  947. LEVEL_LOAD_ERROR: 'levelLoadError',
  948. // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  949. LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut',
  950. // Identifier for a level switch error - data: { level : faulty level Id, event : error description}
  951. LEVEL_SWITCH_ERROR: 'levelSwitchError',
  952. // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  953. AUDIO_TRACK_LOAD_ERROR: 'audioTrackLoadError',
  954. // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  955. AUDIO_TRACK_LOAD_TIMEOUT: 'audioTrackLoadTimeOut',
  956. // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  957. FRAG_LOAD_ERROR: 'fragLoadError',
  958. // Identifier for fragment load timeout error - data: { frag : fragment object}
  959. FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut',
  960. // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }
  961. FRAG_DECRYPT_ERROR: 'fragDecryptError',
  962. // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }
  963. // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release
  964. FRAG_PARSING_ERROR: 'fragParsingError',
  965. // Identifier for a remux alloc error event - data: { id : demuxer Id, frag : fragment object, bytes : nb of bytes on which allocation failed , reason : error text }
  966. REMUX_ALLOC_ERROR: 'remuxAllocError',
  967. // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  968. KEY_LOAD_ERROR: 'keyLoadError',
  969. // Identifier for decrypt key load timeout error - data: { frag : fragment object}
  970. KEY_LOAD_TIMEOUT: 'keyLoadTimeOut',
  971. // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { err : exception , mimeType : mimeType }
  972. BUFFER_ADD_CODEC_ERROR: 'bufferAddCodecError',
  973. // Identifier for a buffer append error - data: append error description
  974. BUFFER_APPEND_ERROR: 'bufferAppendError',
  975. // Identifier for a buffer appending error event - data: appending error description
  976. BUFFER_APPENDING_ERROR: 'bufferAppendingError',
  977. // Identifier for a buffer stalled error event
  978. BUFFER_STALLED_ERROR: 'bufferStalledError',
  979. // Identifier for a buffer full event
  980. BUFFER_FULL_ERROR: 'bufferFullError',
  981. // Identifier for a buffer seek over hole event
  982. BUFFER_SEEK_OVER_HOLE: 'bufferSeekOverHole',
  983. // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)
  984. BUFFER_NUDGE_ON_STALL: 'bufferNudgeOnStall',
  985. // Identifier for an internal exception happening inside hls.js while handling an event
  986. INTERNAL_EXCEPTION: 'internalException'
  987. };
  988. /***/ }),
  989. /* 3 */
  990. /***/ (function(module, exports, __webpack_require__) {
  991. "use strict";
  992. Object.defineProperty(exports, "__esModule", {
  993. value: true
  994. });
  995. 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; };
  996. 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; }; }(); /*
  997. *
  998. * All objects in the event handling chain should inherit from this class
  999. *
  1000. */
  1001. var _logger = __webpack_require__(0);
  1002. var _errors = __webpack_require__(2);
  1003. var _events = __webpack_require__(1);
  1004. var _events2 = _interopRequireDefault(_events);
  1005. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1006. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1007. var FORBIDDEN_EVENT_NAMES = {
  1008. 'hlsEventGeneric': true,
  1009. 'hlsHandlerDestroying': true,
  1010. 'hlsHandlerDestroyed': true
  1011. };
  1012. var EventHandler = function () {
  1013. function EventHandler(hls) {
  1014. _classCallCheck(this, EventHandler);
  1015. this.hls = hls;
  1016. this.onEvent = this.onEvent.bind(this);
  1017. for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  1018. events[_key - 1] = arguments[_key];
  1019. }
  1020. this.handledEvents = events;
  1021. this.useGenericHandler = true;
  1022. this.registerListeners();
  1023. }
  1024. _createClass(EventHandler, [{
  1025. key: 'destroy',
  1026. value: function destroy() {
  1027. this.onHandlerDestroying();
  1028. this.unregisterListeners();
  1029. this.onHandlerDestroyed();
  1030. }
  1031. }, {
  1032. key: 'onHandlerDestroying',
  1033. value: function onHandlerDestroying() {}
  1034. }, {
  1035. key: 'onHandlerDestroyed',
  1036. value: function onHandlerDestroyed() {}
  1037. }, {
  1038. key: 'isEventHandler',
  1039. value: function isEventHandler() {
  1040. return _typeof(this.handledEvents) === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';
  1041. }
  1042. }, {
  1043. key: 'registerListeners',
  1044. value: function registerListeners() {
  1045. if (this.isEventHandler()) {
  1046. this.handledEvents.forEach(function (event) {
  1047. if (FORBIDDEN_EVENT_NAMES[event]) {
  1048. throw new Error('Forbidden event-name: ' + event);
  1049. }
  1050. this.hls.on(event, this.onEvent);
  1051. }, this);
  1052. }
  1053. }
  1054. }, {
  1055. key: 'unregisterListeners',
  1056. value: function unregisterListeners() {
  1057. if (this.isEventHandler()) {
  1058. this.handledEvents.forEach(function (event) {
  1059. this.hls.off(event, this.onEvent);
  1060. }, this);
  1061. }
  1062. }
  1063. /**
  1064. * arguments: event (string), data (any)
  1065. */
  1066. }, {
  1067. key: 'onEvent',
  1068. value: function onEvent(event, data) {
  1069. this.onEventGeneric(event, data);
  1070. }
  1071. }, {
  1072. key: 'onEventGeneric',
  1073. value: function onEventGeneric(event, data) {
  1074. var eventToFunction = function eventToFunction(event, data) {
  1075. var funcName = 'on' + event.replace('hls', '');
  1076. if (typeof this[funcName] !== 'function') {
  1077. throw new Error('Event ' + event + ' has no generic handler in this ' + this.constructor.name + ' class (tried ' + funcName + ')');
  1078. }
  1079. return this[funcName].bind(this, data);
  1080. };
  1081. try {
  1082. eventToFunction.call(this, event, data).call();
  1083. } catch (err) {
  1084. _logger.logger.error('An internal error happened while handling event ' + event + '. Error message: "' + err.message + '". Here is a stacktrace:', err);
  1085. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.INTERNAL_EXCEPTION, fatal: false, event: event, err: err });
  1086. }
  1087. }
  1088. }]);
  1089. return EventHandler;
  1090. }();
  1091. exports.default = EventHandler;
  1092. module.exports = exports['default'];
  1093. /***/ }),
  1094. /* 4 */
  1095. /***/ (function(module, exports, __webpack_require__) {
  1096. "use strict";
  1097. Object.defineProperty(exports, "__esModule", {
  1098. value: true
  1099. });
  1100. 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; }; }();
  1101. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1102. /**
  1103. * @module BufferHelper
  1104. *
  1105. * Providing methods dealing with buffer length retrieval for example.
  1106. *
  1107. * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
  1108. *
  1109. * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
  1110. */
  1111. var BufferHelper = exports.BufferHelper = function () {
  1112. function BufferHelper() {
  1113. _classCallCheck(this, BufferHelper);
  1114. }
  1115. _createClass(BufferHelper, null, [{
  1116. key: "isBuffered",
  1117. /**
  1118. * Return true if `media`'s buffered include `position`
  1119. * @param {HTMLMediaElement|SourceBuffer} media
  1120. * @param {number} position
  1121. * @returns {boolean}
  1122. */
  1123. value: function isBuffered(media, position) {
  1124. try {
  1125. if (media) {
  1126. var buffered = media.buffered;
  1127. for (var i = 0; i < buffered.length; i++) {
  1128. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  1129. return true;
  1130. }
  1131. }
  1132. }
  1133. } catch (error) {
  1134. // this is to catch
  1135. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  1136. // This SourceBuffer has been removed from the parent media source
  1137. }
  1138. return false;
  1139. }
  1140. }, {
  1141. key: "bufferInfo",
  1142. value: function bufferInfo(media, pos, maxHoleDuration) {
  1143. try {
  1144. if (media) {
  1145. var vbuffered = media.buffered,
  1146. buffered = [],
  1147. i = void 0;
  1148. for (i = 0; i < vbuffered.length; i++) {
  1149. buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) });
  1150. }
  1151. return this.bufferedInfo(buffered, pos, maxHoleDuration);
  1152. }
  1153. } catch (error) {
  1154. // this is to catch
  1155. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  1156. // This SourceBuffer has been removed from the parent media source
  1157. }
  1158. return { len: 0, start: pos, end: pos, nextStart: undefined };
  1159. }
  1160. }, {
  1161. key: "bufferedInfo",
  1162. value: function bufferedInfo(buffered, pos, maxHoleDuration) {
  1163. var buffered2 = [],
  1164. // bufferStart and bufferEnd are buffer boundaries around current video position
  1165. bufferLen = void 0,
  1166. bufferStart = void 0,
  1167. bufferEnd = void 0,
  1168. bufferStartNext = void 0,
  1169. i = void 0;
  1170. // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
  1171. buffered.sort(function (a, b) {
  1172. var diff = a.start - b.start;
  1173. if (diff) {
  1174. return diff;
  1175. } else {
  1176. return b.end - a.end;
  1177. }
  1178. });
  1179. // there might be some small holes between buffer time range
  1180. // consider that holes smaller than maxHoleDuration are irrelevant and build another
  1181. // buffer time range representations that discards those holes
  1182. for (i = 0; i < buffered.length; i++) {
  1183. var buf2len = buffered2.length;
  1184. if (buf2len) {
  1185. var buf2end = buffered2[buf2len - 1].end;
  1186. // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
  1187. if (buffered[i].start - buf2end < maxHoleDuration) {
  1188. // merge overlapping time ranges
  1189. // update lastRange.end only if smaller than item.end
  1190. // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
  1191. // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
  1192. if (buffered[i].end > buf2end) {
  1193. buffered2[buf2len - 1].end = buffered[i].end;
  1194. }
  1195. } else {
  1196. // big hole
  1197. buffered2.push(buffered[i]);
  1198. }
  1199. } else {
  1200. // first value
  1201. buffered2.push(buffered[i]);
  1202. }
  1203. }
  1204. for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) {
  1205. var start = buffered2[i].start,
  1206. end = buffered2[i].end;
  1207. // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
  1208. if (pos + maxHoleDuration >= start && pos < end) {
  1209. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  1210. bufferStart = start;
  1211. bufferEnd = end;
  1212. bufferLen = bufferEnd - pos;
  1213. } else if (pos + maxHoleDuration < start) {
  1214. bufferStartNext = start;
  1215. break;
  1216. }
  1217. }
  1218. return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext };
  1219. }
  1220. }]);
  1221. return BufferHelper;
  1222. }();
  1223. /***/ }),
  1224. /* 5 */
  1225. /***/ (function(module, exports, __webpack_require__) {
  1226. "use strict";
  1227. Object.defineProperty(exports, "__esModule", {
  1228. value: true
  1229. });
  1230. exports.getSelfScope = getSelfScope;
  1231. function getSelfScope() {
  1232. // see https://stackoverflow.com/a/11237259/589493
  1233. if (typeof window === 'undefined') {
  1234. /* eslint-disable-next-line no-undef */
  1235. return self;
  1236. } else {
  1237. return window;
  1238. }
  1239. }
  1240. /***/ }),
  1241. /* 6 */
  1242. /***/ (function(module, exports, __webpack_require__) {
  1243. "use strict";
  1244. Object.defineProperty(exports, "__esModule", {
  1245. value: true
  1246. });
  1247. exports.FragmentTracker = exports.FragmentState = undefined;
  1248. 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; }; }();
  1249. 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); } };
  1250. var _eventHandler = __webpack_require__(3);
  1251. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  1252. var _events = __webpack_require__(1);
  1253. var _events2 = _interopRequireDefault(_events);
  1254. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1255. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1256. 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; }
  1257. 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; }
  1258. var FragmentState = exports.FragmentState = {
  1259. NOT_LOADED: 'NOT_LOADED',
  1260. APPENDING: 'APPENDING',
  1261. PARTIAL: 'PARTIAL',
  1262. OK: 'OK'
  1263. };
  1264. var FragmentTracker = exports.FragmentTracker = function (_EventHandler) {
  1265. _inherits(FragmentTracker, _EventHandler);
  1266. function FragmentTracker(hls) {
  1267. _classCallCheck(this, FragmentTracker);
  1268. var _this = _possibleConstructorReturn(this, (FragmentTracker.__proto__ || Object.getPrototypeOf(FragmentTracker)).call(this, hls, _events2.default.BUFFER_APPENDED, _events2.default.FRAG_BUFFERED, _events2.default.FRAG_LOADED));
  1269. _this.bufferPadding = 0.2;
  1270. _this.fragments = Object.create(null);
  1271. _this.timeRanges = Object.create(null);
  1272. _this.config = hls.config;
  1273. return _this;
  1274. }
  1275. _createClass(FragmentTracker, [{
  1276. key: 'destroy',
  1277. value: function destroy() {
  1278. this.fragments = Object.create(null);
  1279. this.timeRanges = Object.create(null);
  1280. this.config = null;
  1281. _eventHandler2.default.prototype.destroy.call(this);
  1282. _get(FragmentTracker.prototype.__proto__ || Object.getPrototypeOf(FragmentTracker.prototype), 'destroy', this).call(this);
  1283. }
  1284. /**
  1285. * Return a Fragment that match the position and levelType.
  1286. * If not found any Fragment, return null
  1287. * @param {number} position
  1288. * @param {LevelType} levelType
  1289. * @returns {Fragment|null}
  1290. */
  1291. }, {
  1292. key: 'getBufferedFrag',
  1293. value: function getBufferedFrag(position, levelType) {
  1294. var fragments = this.fragments;
  1295. var bufferedFrags = Object.keys(fragments).filter(function (key) {
  1296. var fragmentEntity = fragments[key];
  1297. if (fragmentEntity.body.type !== levelType) {
  1298. return false;
  1299. }
  1300. if (!fragmentEntity.buffered) {
  1301. return false;
  1302. }
  1303. var frag = fragmentEntity.body;
  1304. return frag.startPTS <= position && position <= frag.endPTS;
  1305. });
  1306. if (bufferedFrags.length === 0) {
  1307. return null;
  1308. } else {
  1309. // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566
  1310. var bufferedFragKey = bufferedFrags.pop();
  1311. return fragments[bufferedFragKey].body;
  1312. }
  1313. }
  1314. /**
  1315. * Partial fragments effected by coded frame eviction will be removed
  1316. * The browser will unload parts of the buffer to free up memory for new buffer data
  1317. * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)
  1318. * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)
  1319. * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer
  1320. */
  1321. }, {
  1322. key: 'detectEvictedFragments',
  1323. value: function detectEvictedFragments(elementaryStream, timeRange) {
  1324. var _this2 = this;
  1325. var fragmentTimes = void 0,
  1326. time = void 0;
  1327. // Check if any flagged fragments have been unloaded
  1328. Object.keys(this.fragments).forEach(function (key) {
  1329. var fragmentEntity = _this2.fragments[key];
  1330. if (fragmentEntity.buffered === true) {
  1331. var esData = fragmentEntity.range[elementaryStream];
  1332. if (esData) {
  1333. fragmentTimes = esData.time;
  1334. for (var i = 0; i < fragmentTimes.length; i++) {
  1335. time = fragmentTimes[i];
  1336. if (_this2.isTimeBuffered(time.startPTS, time.endPTS, timeRange) === false) {
  1337. // Unregister partial fragment as it needs to load again to be reused
  1338. _this2.removeFragment(fragmentEntity.body);
  1339. break;
  1340. }
  1341. }
  1342. }
  1343. }
  1344. });
  1345. }
  1346. /**
  1347. * Checks if the fragment passed in is loaded in the buffer properly
  1348. * Partially loaded fragments will be registered as a partial fragment
  1349. * @param {Object} fragment Check the fragment against all sourceBuffers loaded
  1350. */
  1351. }, {
  1352. key: 'detectPartialFragments',
  1353. value: function detectPartialFragments(fragment) {
  1354. var _this3 = this;
  1355. var fragKey = this.getFragmentKey(fragment);
  1356. var fragmentEntity = this.fragments[fragKey];
  1357. if (fragmentEntity) {
  1358. fragmentEntity.buffered = true;
  1359. Object.keys(this.timeRanges).forEach(function (elementaryStream) {
  1360. if (fragment.hasElementaryStream(elementaryStream)) {
  1361. var timeRange = _this3.timeRanges[elementaryStream];
  1362. // Check for malformed fragments
  1363. // Gaps need to be calculated for each elementaryStream
  1364. fragmentEntity.range[elementaryStream] = _this3.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);
  1365. }
  1366. });
  1367. }
  1368. }
  1369. }, {
  1370. key: 'getBufferedTimes',
  1371. value: function getBufferedTimes(startPTS, endPTS, timeRange) {
  1372. var fragmentTimes = [];
  1373. var startTime = void 0,
  1374. endTime = void 0;
  1375. var fragmentPartial = false;
  1376. for (var i = 0; i < timeRange.length; i++) {
  1377. startTime = timeRange.start(i) - this.bufferPadding;
  1378. endTime = timeRange.end(i) + this.bufferPadding;
  1379. if (startPTS >= startTime && endPTS <= endTime) {
  1380. // Fragment is entirely contained in buffer
  1381. // No need to check the other timeRange times since it's completely playable
  1382. fragmentTimes.push({
  1383. startPTS: Math.max(startPTS, timeRange.start(i)),
  1384. endPTS: Math.min(endPTS, timeRange.end(i))
  1385. });
  1386. break;
  1387. } else if (startPTS < endTime && endPTS > startTime) {
  1388. // Check for intersection with buffer
  1389. // Get playable sections of the fragment
  1390. fragmentTimes.push({
  1391. startPTS: Math.max(startPTS, timeRange.start(i)),
  1392. endPTS: Math.min(endPTS, timeRange.end(i))
  1393. });
  1394. fragmentPartial = true;
  1395. } else if (endPTS <= startTime) {
  1396. // No need to check the rest of the timeRange as it is in order
  1397. break;
  1398. }
  1399. }
  1400. return {
  1401. time: fragmentTimes,
  1402. partial: fragmentPartial
  1403. };
  1404. }
  1405. }, {
  1406. key: 'getFragmentKey',
  1407. value: function getFragmentKey(fragment) {
  1408. return fragment.type + '_' + fragment.level + '_' + fragment.urlId + '_' + fragment.sn;
  1409. }
  1410. /**
  1411. * Gets the partial fragment for a certain time
  1412. * @param {Number} time
  1413. * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment
  1414. */
  1415. }, {
  1416. key: 'getPartialFragment',
  1417. value: function getPartialFragment(time) {
  1418. var _this4 = this;
  1419. var timePadding = void 0,
  1420. startTime = void 0,
  1421. endTime = void 0;
  1422. var bestFragment = null;
  1423. var bestOverlap = 0;
  1424. Object.keys(this.fragments).forEach(function (key) {
  1425. var fragmentEntity = _this4.fragments[key];
  1426. if (_this4.isPartial(fragmentEntity)) {
  1427. startTime = fragmentEntity.body.startPTS - _this4.bufferPadding;
  1428. endTime = fragmentEntity.body.endPTS + _this4.bufferPadding;
  1429. if (time >= startTime && time <= endTime) {
  1430. // Use the fragment that has the most padding from start and end time
  1431. timePadding = Math.min(time - startTime, endTime - time);
  1432. if (bestOverlap <= timePadding) {
  1433. bestFragment = fragmentEntity.body;
  1434. bestOverlap = timePadding;
  1435. }
  1436. }
  1437. }
  1438. });
  1439. return bestFragment;
  1440. }
  1441. /**
  1442. * @param {Object} fragment The fragment to check
  1443. * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded
  1444. */
  1445. }, {
  1446. key: 'getState',
  1447. value: function getState(fragment) {
  1448. var fragKey = this.getFragmentKey(fragment);
  1449. var fragmentEntity = this.fragments[fragKey];
  1450. var state = FragmentState.NOT_LOADED;
  1451. if (fragmentEntity !== undefined) {
  1452. if (!fragmentEntity.buffered) {
  1453. state = FragmentState.APPENDING;
  1454. } else if (this.isPartial(fragmentEntity) === true) {
  1455. state = FragmentState.PARTIAL;
  1456. } else {
  1457. state = FragmentState.OK;
  1458. }
  1459. }
  1460. return state;
  1461. }
  1462. }, {
  1463. key: 'isPartial',
  1464. value: function isPartial(fragmentEntity) {
  1465. return fragmentEntity.buffered === true && (fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true || fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true);
  1466. }
  1467. }, {
  1468. key: 'isTimeBuffered',
  1469. value: function isTimeBuffered(startPTS, endPTS, timeRange) {
  1470. var startTime = void 0,
  1471. endTime = void 0;
  1472. for (var i = 0; i < timeRange.length; i++) {
  1473. startTime = timeRange.start(i) - this.bufferPadding;
  1474. endTime = timeRange.end(i) + this.bufferPadding;
  1475. if (startPTS >= startTime && endPTS <= endTime) {
  1476. return true;
  1477. }
  1478. if (endPTS <= startTime) {
  1479. // No need to check the rest of the timeRange as it is in order
  1480. return false;
  1481. }
  1482. }
  1483. return false;
  1484. }
  1485. /**
  1486. * Fires when a fragment loading is completed
  1487. */
  1488. }, {
  1489. key: 'onFragLoaded',
  1490. value: function onFragLoaded(e) {
  1491. var fragment = e.frag;
  1492. // don't track initsegment (for which sn is not a number)
  1493. // don't track frags used for bitrateTest, they're irrelevant.
  1494. if (!Number.isFinite(fragment.sn) || fragment.bitrateTest) {
  1495. return;
  1496. }
  1497. this.fragments[this.getFragmentKey(fragment)] = {
  1498. body: fragment,
  1499. range: Object.create(null),
  1500. buffered: false
  1501. };
  1502. }
  1503. /**
  1504. * Fires when the buffer is updated
  1505. */
  1506. }, {
  1507. key: 'onBufferAppended',
  1508. value: function onBufferAppended(e) {
  1509. var _this5 = this;
  1510. // Store the latest timeRanges loaded in the buffer
  1511. this.timeRanges = e.timeRanges;
  1512. Object.keys(this.timeRanges).forEach(function (elementaryStream) {
  1513. var timeRange = _this5.timeRanges[elementaryStream];
  1514. _this5.detectEvictedFragments(elementaryStream, timeRange);
  1515. });
  1516. }
  1517. /**
  1518. * Fires after a fragment has been loaded into the source buffer
  1519. */
  1520. }, {
  1521. key: 'onFragBuffered',
  1522. value: function onFragBuffered(e) {
  1523. this.detectPartialFragments(e.frag);
  1524. }
  1525. /**
  1526. * Return true if fragment tracker has the fragment.
  1527. * @param {Object} fragment
  1528. * @returns {boolean}
  1529. */
  1530. }, {
  1531. key: 'hasFragment',
  1532. value: function hasFragment(fragment) {
  1533. var fragKey = this.getFragmentKey(fragment);
  1534. return this.fragments[fragKey] !== undefined;
  1535. }
  1536. /**
  1537. * Remove a fragment from fragment tracker until it is loaded again
  1538. * @param {Object} fragment The fragment to remove
  1539. */
  1540. }, {
  1541. key: 'removeFragment',
  1542. value: function removeFragment(fragment) {
  1543. var fragKey = this.getFragmentKey(fragment);
  1544. delete this.fragments[fragKey];
  1545. }
  1546. /**
  1547. * Remove all fragments from fragment tracker.
  1548. */
  1549. }, {
  1550. key: 'removeAllFragments',
  1551. value: function removeAllFragments() {
  1552. this.fragments = Object.create(null);
  1553. }
  1554. }]);
  1555. return FragmentTracker;
  1556. }(_eventHandler2.default);
  1557. /***/ }),
  1558. /* 7 */
  1559. /***/ (function(module, exports, __webpack_require__) {
  1560. "use strict";
  1561. Object.defineProperty(exports, "__esModule", {
  1562. value: true
  1563. });
  1564. exports.addGroupId = addGroupId;
  1565. exports.updatePTS = updatePTS;
  1566. exports.updateFragPTSDTS = updateFragPTSDTS;
  1567. exports.mergeDetails = mergeDetails;
  1568. exports.mergeSubtitlePlaylists = mergeSubtitlePlaylists;
  1569. exports.mapFragmentIntersection = mapFragmentIntersection;
  1570. exports.adjustSliding = adjustSliding;
  1571. exports.computeReloadInterval = computeReloadInterval;
  1572. var _logger = __webpack_require__(0);
  1573. function addGroupId(level, type, id) {
  1574. switch (type) {
  1575. case 'audio':
  1576. if (!level.audioGroupIds) {
  1577. level.audioGroupIds = [];
  1578. }
  1579. level.audioGroupIds.push(id);
  1580. break;
  1581. case 'text':
  1582. if (!level.textGroupIds) {
  1583. level.textGroupIds = [];
  1584. }
  1585. level.textGroupIds.push(id);
  1586. break;
  1587. }
  1588. } /**
  1589. * @module LevelHelper
  1590. *
  1591. * Providing methods dealing with playlist sliding and drift
  1592. *
  1593. * TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner.
  1594. *
  1595. * */
  1596. function updatePTS(fragments, fromIdx, toIdx) {
  1597. var fragFrom = fragments[fromIdx],
  1598. fragTo = fragments[toIdx],
  1599. fragToPTS = fragTo.startPTS;
  1600. // if we know startPTS[toIdx]
  1601. if (Number.isFinite(fragToPTS)) {
  1602. // update fragment duration.
  1603. // it helps to fix drifts between playlist reported duration and fragment real duration
  1604. if (toIdx > fromIdx) {
  1605. fragFrom.duration = fragToPTS - fragFrom.start;
  1606. if (fragFrom.duration < 0) {
  1607. _logger.logger.warn('negative duration computed for frag ' + fragFrom.sn + ',level ' + fragFrom.level + ', there should be some duration drift between playlist and fragment!');
  1608. }
  1609. } else {
  1610. fragTo.duration = fragFrom.start - fragToPTS;
  1611. if (fragTo.duration < 0) {
  1612. _logger.logger.warn('negative duration computed for frag ' + fragTo.sn + ',level ' + fragTo.level + ', there should be some duration drift between playlist and fragment!');
  1613. }
  1614. }
  1615. } else {
  1616. // we dont know startPTS[toIdx]
  1617. if (toIdx > fromIdx) {
  1618. fragTo.start = fragFrom.start + fragFrom.duration;
  1619. } else {
  1620. fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
  1621. }
  1622. }
  1623. }
  1624. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  1625. // update frag PTS/DTS
  1626. var maxStartPTS = startPTS;
  1627. if (Number.isFinite(frag.startPTS)) {
  1628. // delta PTS between audio and video
  1629. var deltaPTS = Math.abs(frag.startPTS - startPTS);
  1630. if (!Number.isFinite(frag.deltaPTS)) {
  1631. frag.deltaPTS = deltaPTS;
  1632. } else {
  1633. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  1634. }
  1635. maxStartPTS = Math.max(startPTS, frag.startPTS);
  1636. startPTS = Math.min(startPTS, frag.startPTS);
  1637. endPTS = Math.max(endPTS, frag.endPTS);
  1638. startDTS = Math.min(startDTS, frag.startDTS);
  1639. endDTS = Math.max(endDTS, frag.endDTS);
  1640. }
  1641. var drift = startPTS - frag.start;
  1642. frag.start = frag.startPTS = startPTS;
  1643. frag.maxStartPTS = maxStartPTS;
  1644. frag.endPTS = endPTS;
  1645. frag.startDTS = startDTS;
  1646. frag.endDTS = endDTS;
  1647. frag.duration = endPTS - startPTS;
  1648. var sn = frag.sn;
  1649. // exit if sn out of range
  1650. if (!details || sn < details.startSN || sn > details.endSN) {
  1651. return 0;
  1652. }
  1653. var fragIdx = void 0,
  1654. fragments = void 0,
  1655. i = void 0;
  1656. fragIdx = sn - details.startSN;
  1657. fragments = details.fragments;
  1658. // update frag reference in fragments array
  1659. // rationale is that fragments array might not contain this frag object.
  1660. // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
  1661. // if we don't update frag, we won't be able to propagate PTS info on the playlist
  1662. // resulting in invalid sliding computation
  1663. fragments[fragIdx] = frag;
  1664. // adjust fragment PTS/duration from seqnum-1 to frag 0
  1665. for (i = fragIdx; i > 0; i--) {
  1666. updatePTS(fragments, i, i - 1);
  1667. }
  1668. // adjust fragment PTS/duration from seqnum to last frag
  1669. for (i = fragIdx; i < fragments.length - 1; i++) {
  1670. updatePTS(fragments, i, i + 1);
  1671. }
  1672. details.PTSKnown = true;
  1673. return drift;
  1674. }
  1675. function mergeDetails(oldDetails, newDetails) {
  1676. // potentially retrieve cached initsegment
  1677. if (newDetails.initSegment && oldDetails.initSegment) {
  1678. newDetails.initSegment = oldDetails.initSegment;
  1679. }
  1680. // check if old/new playlists have fragments in common
  1681. // loop through overlapping SN and update startPTS , cc, and duration if any found
  1682. var ccOffset = 0;
  1683. var PTSFrag = void 0;
  1684. mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) {
  1685. ccOffset = oldFrag.cc - newFrag.cc;
  1686. if (Number.isFinite(oldFrag.startPTS)) {
  1687. newFrag.start = newFrag.startPTS = oldFrag.startPTS;
  1688. newFrag.endPTS = oldFrag.endPTS;
  1689. newFrag.duration = oldFrag.duration;
  1690. newFrag.backtracked = oldFrag.backtracked;
  1691. newFrag.dropped = oldFrag.dropped;
  1692. PTSFrag = newFrag;
  1693. }
  1694. // PTS is known when there are overlapping segments
  1695. newDetails.PTSKnown = true;
  1696. });
  1697. if (!newDetails.PTSKnown) {
  1698. return;
  1699. }
  1700. if (ccOffset) {
  1701. _logger.logger.log('discontinuity sliding from playlist, take drift into account');
  1702. var newFragments = newDetails.fragments;
  1703. for (var i = 0; i < newFragments.length; i++) {
  1704. newFragments[i].cc += ccOffset;
  1705. }
  1706. }
  1707. // if at least one fragment contains PTS info, recompute PTS information for all fragments
  1708. if (PTSFrag) {
  1709. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  1710. } else {
  1711. // ensure that delta is within oldFragments range
  1712. // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
  1713. // in that case we also need to adjust start offset of all fragments
  1714. adjustSliding(oldDetails, newDetails);
  1715. }
  1716. // if we are here, it means we have fragments overlapping between
  1717. // old and new level. reliable PTS info is thus relying on old level
  1718. newDetails.PTSKnown = oldDetails.PTSKnown;
  1719. }
  1720. function mergeSubtitlePlaylists(oldPlaylist, newPlaylist) {
  1721. var referenceStart = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  1722. var lastIndex = -1;
  1723. mapFragmentIntersection(oldPlaylist, newPlaylist, function (oldFrag, newFrag, index) {
  1724. newFrag.start = oldFrag.start;
  1725. lastIndex = index;
  1726. });
  1727. var frags = newPlaylist.fragments;
  1728. if (lastIndex < 0) {
  1729. frags.forEach(function (frag) {
  1730. frag.start += referenceStart;
  1731. });
  1732. return;
  1733. }
  1734. for (var i = lastIndex + 1; i < frags.length; i++) {
  1735. frags[i].start = frags[i - 1].start + frags[i - 1].duration;
  1736. }
  1737. }
  1738. function mapFragmentIntersection(oldPlaylist, newPlaylist, intersectionFn) {
  1739. if (!oldPlaylist || !newPlaylist) {
  1740. return;
  1741. }
  1742. var start = Math.max(oldPlaylist.startSN, newPlaylist.startSN) - newPlaylist.startSN;
  1743. var end = Math.min(oldPlaylist.endSN, newPlaylist.endSN) - newPlaylist.startSN;
  1744. var delta = newPlaylist.startSN - oldPlaylist.startSN;
  1745. for (var i = start; i <= end; i++) {
  1746. var oldFrag = oldPlaylist.fragments[delta + i];
  1747. var newFrag = newPlaylist.fragments[i];
  1748. if (!oldFrag || !newFrag) {
  1749. break;
  1750. }
  1751. intersectionFn(oldFrag, newFrag, i);
  1752. }
  1753. }
  1754. function adjustSliding(oldPlaylist, newPlaylist) {
  1755. var delta = newPlaylist.startSN - oldPlaylist.startSN;
  1756. var oldFragments = oldPlaylist.fragments;
  1757. var newFragments = newPlaylist.fragments;
  1758. if (delta < 0 || delta > oldFragments.length) {
  1759. return;
  1760. }
  1761. for (var i = 0; i < newFragments.length; i++) {
  1762. newFragments[i].start += oldFragments[delta].start;
  1763. }
  1764. }
  1765. function computeReloadInterval(currentPlaylist, newPlaylist, lastRequestTime) {
  1766. var reloadInterval = 1000 * (newPlaylist.averagetargetduration ? newPlaylist.averagetargetduration : newPlaylist.targetduration);
  1767. var minReloadInterval = reloadInterval / 2;
  1768. if (currentPlaylist && newPlaylist.endSN === currentPlaylist.endSN) {
  1769. // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
  1770. // changed then it MUST wait for a period of one-half the target
  1771. // duration before retrying.
  1772. reloadInterval = minReloadInterval;
  1773. }
  1774. if (lastRequestTime) {
  1775. reloadInterval = Math.max(minReloadInterval, reloadInterval - (window.performance.now() - lastRequestTime));
  1776. }
  1777. // in any case, don't reload more than half of target duration
  1778. return Math.round(reloadInterval);
  1779. }
  1780. /***/ }),
  1781. /* 8 */
  1782. /***/ (function(module, exports, __webpack_require__) {
  1783. // see https://tools.ietf.org/html/rfc1808
  1784. /* jshint ignore:start */
  1785. (function(root) {
  1786. /* jshint ignore:end */
  1787. var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/\?#]*\/)*.*?)??(;.*?)?(\?.*?)?(#.*?)?$/;
  1788. var FIRST_SEGMENT_REGEX = /^([^\/?#]*)(.*)$/;
  1789. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  1790. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/g;
  1791. var URLToolkit = { // jshint ignore:line
  1792. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  1793. // E.g
  1794. // With opts.alwaysNormalize = false (default, spec compliant)
  1795. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  1796. // With opts.alwaysNormalize = true (not spec compliant)
  1797. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  1798. buildAbsoluteURL: function(baseURL, relativeURL, opts) {
  1799. opts = opts || {};
  1800. // remove any remaining space and CRLF
  1801. baseURL = baseURL.trim();
  1802. relativeURL = relativeURL.trim();
  1803. if (!relativeURL) {
  1804. // 2a) If the embedded URL is entirely empty, it inherits the
  1805. // entire base URL (i.e., is set equal to the base URL)
  1806. // and we are done.
  1807. if (!opts.alwaysNormalize) {
  1808. return baseURL;
  1809. }
  1810. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  1811. if (!basePartsForNormalise) {
  1812. throw new Error('Error trying to parse base URL.');
  1813. }
  1814. basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
  1815. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  1816. }
  1817. var relativeParts = URLToolkit.parseURL(relativeURL);
  1818. if (!relativeParts) {
  1819. throw new Error('Error trying to parse relative URL.');
  1820. }
  1821. if (relativeParts.scheme) {
  1822. // 2b) If the embedded URL starts with a scheme name, it is
  1823. // interpreted as an absolute URL and we are done.
  1824. if (!opts.alwaysNormalize) {
  1825. return relativeURL;
  1826. }
  1827. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  1828. return URLToolkit.buildURLFromParts(relativeParts);
  1829. }
  1830. var baseParts = URLToolkit.parseURL(baseURL);
  1831. if (!baseParts) {
  1832. throw new Error('Error trying to parse base URL.');
  1833. }
  1834. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  1835. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  1836. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  1837. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  1838. baseParts.netLoc = pathParts[1];
  1839. baseParts.path = pathParts[2];
  1840. }
  1841. if (baseParts.netLoc && !baseParts.path) {
  1842. baseParts.path = '/';
  1843. }
  1844. var builtParts = {
  1845. // 2c) Otherwise, the embedded URL inherits the scheme of
  1846. // the base URL.
  1847. scheme: baseParts.scheme,
  1848. netLoc: relativeParts.netLoc,
  1849. path: null,
  1850. params: relativeParts.params,
  1851. query: relativeParts.query,
  1852. fragment: relativeParts.fragment
  1853. };
  1854. if (!relativeParts.netLoc) {
  1855. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  1856. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  1857. // (if any) of the base URL.
  1858. builtParts.netLoc = baseParts.netLoc;
  1859. // 4) If the embedded URL path is preceded by a slash "/", the
  1860. // path is not relative and we skip to Step 7.
  1861. if (relativeParts.path[0] !== '/') {
  1862. if (!relativeParts.path) {
  1863. // 5) If the embedded URL path is empty (and not preceded by a
  1864. // slash), then the embedded URL inherits the base URL path
  1865. builtParts.path = baseParts.path;
  1866. // 5a) if the embedded URL's <params> is non-empty, we skip to
  1867. // step 7; otherwise, it inherits the <params> of the base
  1868. // URL (if any) and
  1869. if (!relativeParts.params) {
  1870. builtParts.params = baseParts.params;
  1871. // 5b) if the embedded URL's <query> is non-empty, we skip to
  1872. // step 7; otherwise, it inherits the <query> of the base
  1873. // URL (if any) and we skip to step 7.
  1874. if (!relativeParts.query) {
  1875. builtParts.query = baseParts.query;
  1876. }
  1877. }
  1878. } else {
  1879. // 6) The last segment of the base URL's path (anything
  1880. // following the rightmost slash "/", or the entire path if no
  1881. // slash is present) is removed and the embedded URL's path is
  1882. // appended in its place.
  1883. var baseURLPath = baseParts.path;
  1884. var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;
  1885. builtParts.path = URLToolkit.normalizePath(newPath);
  1886. }
  1887. }
  1888. }
  1889. if (builtParts.path === null) {
  1890. builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
  1891. }
  1892. return URLToolkit.buildURLFromParts(builtParts);
  1893. },
  1894. parseURL: function(url) {
  1895. var parts = URL_REGEX.exec(url);
  1896. if (!parts) {
  1897. return null;
  1898. }
  1899. return {
  1900. scheme: parts[1] || '',
  1901. netLoc: parts[2] || '',
  1902. path: parts[3] || '',
  1903. params: parts[4] || '',
  1904. query: parts[5] || '',
  1905. fragment: parts[6] || ''
  1906. };
  1907. },
  1908. normalizePath: function(path) {
  1909. // The following operations are
  1910. // then applied, in order, to the new path:
  1911. // 6a) All occurrences of "./", where "." is a complete path
  1912. // segment, are removed.
  1913. // 6b) If the path ends with "." as a complete path segment,
  1914. // that "." is removed.
  1915. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
  1916. // 6c) All occurrences of "<segment>/../", where <segment> is a
  1917. // complete path segment not equal to "..", are removed.
  1918. // Removal of these path segments is performed iteratively,
  1919. // removing the leftmost matching pattern on each iteration,
  1920. // until no matching pattern remains.
  1921. // 6d) If the path ends with "<segment>/..", where <segment> is a
  1922. // complete path segment not equal to "..", that
  1923. // "<segment>/.." is removed.
  1924. while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {} // jshint ignore:line
  1925. return path.split('').reverse().join('');
  1926. },
  1927. buildURLFromParts: function(parts) {
  1928. return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
  1929. }
  1930. };
  1931. /* jshint ignore:start */
  1932. if(true)
  1933. module.exports = URLToolkit;
  1934. else {}
  1935. })(this);
  1936. /* jshint ignore:end */
  1937. /***/ }),
  1938. /* 9 */
  1939. /***/ (function(module, exports, __webpack_require__) {
  1940. "use strict";
  1941. Object.defineProperty(exports, "__esModule", {
  1942. value: true
  1943. });
  1944. var BinarySearch = {
  1945. /**
  1946. * Searches for an item in an array which matches a certain condition.
  1947. * This requires the condition to only match one item in the array,
  1948. * and for the array to be ordered.
  1949. *
  1950. * @param {Array} list The array to search.
  1951. * @param {Function} comparisonFunction
  1952. * Called and provided a candidate item as the first argument.
  1953. * Should return:
  1954. * > -1 if the item should be located at a lower index than the provided item.
  1955. * > 1 if the item should be located at a higher index than the provided item.
  1956. * > 0 if the item is the item you're looking for.
  1957. *
  1958. * @return {*} The object if it is found or null otherwise.
  1959. */
  1960. search: function search(list, comparisonFunction) {
  1961. var minIndex = 0;
  1962. var maxIndex = list.length - 1;
  1963. var currentIndex = null;
  1964. var currentElement = null;
  1965. while (minIndex <= maxIndex) {
  1966. currentIndex = (minIndex + maxIndex) / 2 | 0;
  1967. currentElement = list[currentIndex];
  1968. var comparisonResult = comparisonFunction(currentElement);
  1969. if (comparisonResult > 0) {
  1970. minIndex = currentIndex + 1;
  1971. } else if (comparisonResult < 0) {
  1972. maxIndex = currentIndex - 1;
  1973. } else {
  1974. return currentElement;
  1975. }
  1976. }
  1977. return null;
  1978. }
  1979. };
  1980. exports.default = BinarySearch;
  1981. module.exports = exports["default"];
  1982. /***/ }),
  1983. /* 10 */
  1984. /***/ (function(module, exports, __webpack_require__) {
  1985. "use strict";
  1986. Object.defineProperty(exports, "__esModule", {
  1987. value: true
  1988. });
  1989. 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; }; }();
  1990. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1991. /**
  1992. * ID3 parser
  1993. */
  1994. var ID3 = function () {
  1995. function ID3() {
  1996. _classCallCheck(this, ID3);
  1997. }
  1998. _createClass(ID3, null, [{
  1999. key: 'isHeader',
  2000. /**
  2001. * Returns true if an ID3 header can be found at offset in data
  2002. * @param {Uint8Array} data - The data to search in
  2003. * @param {number} offset - The offset at which to start searching
  2004. * @return {boolean} - True if an ID3 header is found
  2005. */
  2006. value: function isHeader(data, offset) {
  2007. /*
  2008. * http://id3.org/id3v2.3.0
  2009. * [0] = 'I'
  2010. * [1] = 'D'
  2011. * [2] = '3'
  2012. * [3,4] = {Version}
  2013. * [5] = {Flags}
  2014. * [6-9] = {ID3 Size}
  2015. *
  2016. * An ID3v2 tag can be detected with the following pattern:
  2017. * $49 44 33 yy yy xx zz zz zz zz
  2018. * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
  2019. */
  2020. if (offset + 10 <= data.length) {
  2021. // look for 'ID3' identifier
  2022. if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
  2023. // check version is within range
  2024. if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
  2025. // check size is within range
  2026. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  2027. return true;
  2028. }
  2029. }
  2030. }
  2031. }
  2032. return false;
  2033. }
  2034. /**
  2035. * Returns true if an ID3 footer can be found at offset in data
  2036. * @param {Uint8Array} data - The data to search in
  2037. * @param {number} offset - The offset at which to start searching
  2038. * @return {boolean} - True if an ID3 footer is found
  2039. */
  2040. }, {
  2041. key: 'isFooter',
  2042. value: function isFooter(data, offset) {
  2043. /*
  2044. * The footer is a copy of the header, but with a different identifier
  2045. */
  2046. if (offset + 10 <= data.length) {
  2047. // look for '3DI' identifier
  2048. if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
  2049. // check version is within range
  2050. if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
  2051. // check size is within range
  2052. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  2053. return true;
  2054. }
  2055. }
  2056. }
  2057. }
  2058. return false;
  2059. }
  2060. /**
  2061. * Returns any adjacent ID3 tags found in data starting at offset, as one block of data
  2062. * @param {Uint8Array} data - The data to search in
  2063. * @param {number} offset - The offset at which to start searching
  2064. * @return {Uint8Array} - The block of data containing any ID3 tags found
  2065. */
  2066. }, {
  2067. key: 'getID3Data',
  2068. value: function getID3Data(data, offset) {
  2069. var front = offset;
  2070. var length = 0;
  2071. while (ID3.isHeader(data, offset)) {
  2072. // ID3 header is 10 bytes
  2073. length += 10;
  2074. var size = ID3._readSize(data, offset + 6);
  2075. length += size;
  2076. if (ID3.isFooter(data, offset + 10)) {
  2077. // ID3 footer is 10 bytes
  2078. length += 10;
  2079. }
  2080. offset += length;
  2081. }
  2082. if (length > 0) {
  2083. return data.subarray(front, front + length);
  2084. }
  2085. return undefined;
  2086. }
  2087. }, {
  2088. key: '_readSize',
  2089. value: function _readSize(data, offset) {
  2090. var size = 0;
  2091. size = (data[offset] & 0x7f) << 21;
  2092. size |= (data[offset + 1] & 0x7f) << 14;
  2093. size |= (data[offset + 2] & 0x7f) << 7;
  2094. size |= data[offset + 3] & 0x7f;
  2095. return size;
  2096. }
  2097. /**
  2098. * Searches for the Elementary Stream timestamp found in the ID3 data chunk
  2099. * @param {Uint8Array} data - Block of data containing one or more ID3 tags
  2100. * @return {number} - The timestamp
  2101. */
  2102. }, {
  2103. key: 'getTimeStamp',
  2104. value: function getTimeStamp(data) {
  2105. var frames = ID3.getID3Frames(data);
  2106. for (var i = 0; i < frames.length; i++) {
  2107. var frame = frames[i];
  2108. if (ID3.isTimeStampFrame(frame)) {
  2109. return ID3._readTimeStamp(frame);
  2110. }
  2111. }
  2112. return undefined;
  2113. }
  2114. /**
  2115. * Returns true if the ID3 frame is an Elementary Stream timestamp frame
  2116. * @param {ID3 frame} frame
  2117. */
  2118. }, {
  2119. key: 'isTimeStampFrame',
  2120. value: function isTimeStampFrame(frame) {
  2121. return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
  2122. }
  2123. }, {
  2124. key: '_getFrameData',
  2125. value: function _getFrameData(data) {
  2126. /*
  2127. Frame ID $xx xx xx xx (four characters)
  2128. Size $xx xx xx xx
  2129. Flags $xx xx
  2130. */
  2131. var type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  2132. var size = ID3._readSize(data, 4);
  2133. // skip frame id, size, and flags
  2134. var offset = 10;
  2135. return { type: type, size: size, data: data.subarray(offset, offset + size) };
  2136. }
  2137. /**
  2138. * Returns an array of ID3 frames found in all the ID3 tags in the id3Data
  2139. * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags
  2140. * @return {ID3 frame[]} - Array of ID3 frame objects
  2141. */
  2142. }, {
  2143. key: 'getID3Frames',
  2144. value: function getID3Frames(id3Data) {
  2145. var offset = 0;
  2146. var frames = [];
  2147. while (ID3.isHeader(id3Data, offset)) {
  2148. var size = ID3._readSize(id3Data, offset + 6);
  2149. // skip past ID3 header
  2150. offset += 10;
  2151. var end = offset + size;
  2152. // loop through frames in the ID3 tag
  2153. while (offset + 8 < end) {
  2154. var frameData = ID3._getFrameData(id3Data.subarray(offset));
  2155. var frame = ID3._decodeFrame(frameData);
  2156. if (frame) {
  2157. frames.push(frame);
  2158. }
  2159. // skip frame header and frame data
  2160. offset += frameData.size + 10;
  2161. }
  2162. if (ID3.isFooter(id3Data, offset)) {
  2163. offset += 10;
  2164. }
  2165. }
  2166. return frames;
  2167. }
  2168. }, {
  2169. key: '_decodeFrame',
  2170. value: function _decodeFrame(frame) {
  2171. if (frame.type === 'PRIV') {
  2172. return ID3._decodePrivFrame(frame);
  2173. } else if (frame.type[0] === 'T') {
  2174. return ID3._decodeTextFrame(frame);
  2175. } else if (frame.type[0] === 'W') {
  2176. return ID3._decodeURLFrame(frame);
  2177. }
  2178. return undefined;
  2179. }
  2180. }, {
  2181. key: '_readTimeStamp',
  2182. value: function _readTimeStamp(timeStampFrame) {
  2183. if (timeStampFrame.data.byteLength === 8) {
  2184. var data = new Uint8Array(timeStampFrame.data);
  2185. // timestamp is 33 bit expressed as a big-endian eight-octet number,
  2186. // with the upper 31 bits set to zero.
  2187. var pts33Bit = data[3] & 0x1;
  2188. var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  2189. timestamp /= 45;
  2190. if (pts33Bit) {
  2191. timestamp += 47721858.84;
  2192. } // 2^32 / 90
  2193. return Math.round(timestamp);
  2194. }
  2195. return undefined;
  2196. }
  2197. }, {
  2198. key: '_decodePrivFrame',
  2199. value: function _decodePrivFrame(frame) {
  2200. /*
  2201. Format: <text string>\0<binary data>
  2202. */
  2203. if (frame.size < 2) {
  2204. return undefined;
  2205. }
  2206. var owner = ID3._utf8ArrayToStr(frame.data, true);
  2207. var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  2208. return { key: frame.type, info: owner, data: privateData.buffer };
  2209. }
  2210. }, {
  2211. key: '_decodeTextFrame',
  2212. value: function _decodeTextFrame(frame) {
  2213. if (frame.size < 2) {
  2214. return undefined;
  2215. }
  2216. if (frame.type === 'TXXX') {
  2217. /*
  2218. Format:
  2219. [0] = {Text Encoding}
  2220. [1-?] = {Description}\0{Value}
  2221. */
  2222. var index = 1;
  2223. var description = ID3._utf8ArrayToStr(frame.data.subarray(index));
  2224. index += description.length + 1;
  2225. var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
  2226. return { key: frame.type, info: description, data: value };
  2227. } else {
  2228. /*
  2229. Format:
  2230. [0] = {Text Encoding}
  2231. [1-?] = {Value}
  2232. */
  2233. var text = ID3._utf8ArrayToStr(frame.data.subarray(1));
  2234. return { key: frame.type, data: text };
  2235. }
  2236. }
  2237. }, {
  2238. key: '_decodeURLFrame',
  2239. value: function _decodeURLFrame(frame) {
  2240. if (frame.type === 'WXXX') {
  2241. /*
  2242. Format:
  2243. [0] = {Text Encoding}
  2244. [1-?] = {Description}\0{URL}
  2245. */
  2246. if (frame.size < 2) {
  2247. return undefined;
  2248. }
  2249. var index = 1;
  2250. var description = ID3._utf8ArrayToStr(frame.data.subarray(index));
  2251. index += description.length + 1;
  2252. var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
  2253. return { key: frame.type, info: description, data: value };
  2254. } else {
  2255. /*
  2256. Format:
  2257. [0-?] = {URL}
  2258. */
  2259. var url = ID3._utf8ArrayToStr(frame.data);
  2260. return { key: frame.type, data: url };
  2261. }
  2262. }
  2263. // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
  2264. // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
  2265. /* utf.js - UTF-8 <=> UTF-16 convertion
  2266. *
  2267. * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
  2268. * Version: 1.0
  2269. * LastModified: Dec 25 1999
  2270. * This library is free. You can redistribute it and/or modify it.
  2271. */
  2272. }, {
  2273. key: '_utf8ArrayToStr',
  2274. value: function _utf8ArrayToStr(array) {
  2275. var exitOnNull = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  2276. var len = array.length;
  2277. var c = void 0;
  2278. var char2 = void 0;
  2279. var char3 = void 0;
  2280. var out = '';
  2281. var i = 0;
  2282. while (i < len) {
  2283. c = array[i++];
  2284. if (c === 0x00 && exitOnNull) {
  2285. return out;
  2286. } else if (c === 0x00 || c === 0x03) {
  2287. // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
  2288. continue;
  2289. }
  2290. switch (c >> 4) {
  2291. case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:
  2292. // 0xxxxxxx
  2293. out += String.fromCharCode(c);
  2294. break;
  2295. case 12:case 13:
  2296. // 110x xxxx 10xx xxxx
  2297. char2 = array[i++];
  2298. out += String.fromCharCode((c & 0x1F) << 6 | char2 & 0x3F);
  2299. break;
  2300. case 14:
  2301. // 1110 xxxx 10xx xxxx 10xx xxxx
  2302. char2 = array[i++];
  2303. char3 = array[i++];
  2304. out += String.fromCharCode((c & 0x0F) << 12 | (char2 & 0x3F) << 6 | (char3 & 0x3F) << 0);
  2305. break;
  2306. default:
  2307. }
  2308. }
  2309. return out;
  2310. }
  2311. }]);
  2312. return ID3;
  2313. }();
  2314. var utf8ArrayToStr = ID3._utf8ArrayToStr;
  2315. exports.default = ID3;
  2316. exports.utf8ArrayToStr = utf8ArrayToStr;
  2317. /***/ }),
  2318. /* 11 */
  2319. /***/ (function(module, exports, __webpack_require__) {
  2320. "use strict";
  2321. Object.defineProperty(exports, "__esModule", {
  2322. value: true
  2323. });
  2324. 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; }; }();
  2325. var _urlToolkit = __webpack_require__(8);
  2326. var URLToolkit = _interopRequireWildcard(_urlToolkit);
  2327. var _levelKey = __webpack_require__(17);
  2328. var _levelKey2 = _interopRequireDefault(_levelKey);
  2329. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2330. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  2331. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  2332. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2333. var Fragment = function () {
  2334. function Fragment() {
  2335. var _elementaryStreams;
  2336. _classCallCheck(this, Fragment);
  2337. this._url = null;
  2338. this._byteRange = null;
  2339. this._decryptdata = null;
  2340. this.tagList = [];
  2341. this.programDateTime = null;
  2342. this.rawProgramDateTime = null;
  2343. // Holds the types of data this fragment supports
  2344. this._elementaryStreams = (_elementaryStreams = {}, _defineProperty(_elementaryStreams, Fragment.ElementaryStreamTypes.AUDIO, false), _defineProperty(_elementaryStreams, Fragment.ElementaryStreamTypes.VIDEO, false), _elementaryStreams);
  2345. }
  2346. /**
  2347. * `type` property for this._elementaryStreams
  2348. *
  2349. * @enum
  2350. */
  2351. _createClass(Fragment, [{
  2352. key: 'addElementaryStream',
  2353. /**
  2354. * @param {ElementaryStreamType} type
  2355. */
  2356. value: function addElementaryStream(type) {
  2357. this._elementaryStreams[type] = true;
  2358. }
  2359. /**
  2360. * @param {ElementaryStreamType} type
  2361. */
  2362. }, {
  2363. key: 'hasElementaryStream',
  2364. value: function hasElementaryStream(type) {
  2365. return this._elementaryStreams[type] === true;
  2366. }
  2367. /**
  2368. * Utility method for parseLevelPlaylist to create an initialization vector for a given segment
  2369. * @returns {Uint8Array}
  2370. */
  2371. }, {
  2372. key: 'createInitializationVector',
  2373. value: function createInitializationVector(segmentNumber) {
  2374. var uint8View = new Uint8Array(16);
  2375. for (var i = 12; i < 16; i++) {
  2376. uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
  2377. }
  2378. return uint8View;
  2379. }
  2380. /**
  2381. * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data
  2382. * @param levelkey - a playlist's encryption info
  2383. * @param segmentNumber - the fragment's segment number
  2384. * @returns {*} - an object to be applied as a fragment's decryptdata
  2385. */
  2386. }, {
  2387. key: 'fragmentDecryptdataFromLevelkey',
  2388. value: function fragmentDecryptdataFromLevelkey(levelkey, segmentNumber) {
  2389. var decryptdata = levelkey;
  2390. if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) {
  2391. decryptdata = new _levelKey2.default();
  2392. decryptdata.method = levelkey.method;
  2393. decryptdata.baseuri = levelkey.baseuri;
  2394. decryptdata.reluri = levelkey.reluri;
  2395. decryptdata.iv = this.createInitializationVector(segmentNumber);
  2396. }
  2397. return decryptdata;
  2398. }
  2399. }, {
  2400. key: 'url',
  2401. get: function get() {
  2402. if (!this._url && this.relurl) {
  2403. this._url = URLToolkit.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });
  2404. }
  2405. return this._url;
  2406. },
  2407. set: function set(value) {
  2408. this._url = value;
  2409. }
  2410. }, {
  2411. key: 'byteRange',
  2412. get: function get() {
  2413. if (!this._byteRange && !this.rawByteRange) {
  2414. return [];
  2415. }
  2416. if (this._byteRange) {
  2417. return this._byteRange;
  2418. }
  2419. var byteRange = [];
  2420. if (this.rawByteRange) {
  2421. var params = this.rawByteRange.split('@', 2);
  2422. if (params.length === 1) {
  2423. var lastByteRangeEndOffset = this.lastByteRangeEndOffset;
  2424. byteRange[0] = lastByteRangeEndOffset || 0;
  2425. } else {
  2426. byteRange[0] = parseInt(params[1]);
  2427. }
  2428. byteRange[1] = parseInt(params[0]) + byteRange[0];
  2429. this._byteRange = byteRange;
  2430. }
  2431. return byteRange;
  2432. }
  2433. /**
  2434. * @type {number}
  2435. */
  2436. }, {
  2437. key: 'byteRangeStartOffset',
  2438. get: function get() {
  2439. return this.byteRange[0];
  2440. }
  2441. }, {
  2442. key: 'byteRangeEndOffset',
  2443. get: function get() {
  2444. return this.byteRange[1];
  2445. }
  2446. }, {
  2447. key: 'decryptdata',
  2448. get: function get() {
  2449. if (!this._decryptdata) {
  2450. this._decryptdata = this.fragmentDecryptdataFromLevelkey(this.levelkey, this.sn);
  2451. }
  2452. return this._decryptdata;
  2453. }
  2454. }, {
  2455. key: 'endProgramDateTime',
  2456. get: function get() {
  2457. if (!Number.isFinite(this.programDateTime)) {
  2458. return null;
  2459. }
  2460. var duration = !Number.isFinite(this.duration) ? 0 : this.duration;
  2461. return this.programDateTime + duration * 1000;
  2462. }
  2463. }, {
  2464. key: 'encrypted',
  2465. get: function get() {
  2466. return !!(this.decryptdata && this.decryptdata.uri !== null && this.decryptdata.key === null);
  2467. }
  2468. }], [{
  2469. key: 'ElementaryStreamTypes',
  2470. get: function get() {
  2471. return {
  2472. AUDIO: 'audio',
  2473. VIDEO: 'video'
  2474. };
  2475. }
  2476. }]);
  2477. return Fragment;
  2478. }();
  2479. exports.default = Fragment;
  2480. module.exports = exports['default'];
  2481. /***/ }),
  2482. /* 12 */
  2483. /***/ (function(module, exports, __webpack_require__) {
  2484. "use strict";
  2485. Object.defineProperty(exports, "__esModule", {
  2486. value: true
  2487. });
  2488. 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; }; }();
  2489. var _aesCrypto = __webpack_require__(42);
  2490. var _aesCrypto2 = _interopRequireDefault(_aesCrypto);
  2491. var _fastAesKey = __webpack_require__(43);
  2492. var _fastAesKey2 = _interopRequireDefault(_fastAesKey);
  2493. var _aesDecryptor = __webpack_require__(44);
  2494. var _aesDecryptor2 = _interopRequireDefault(_aesDecryptor);
  2495. var _errors = __webpack_require__(2);
  2496. var _logger = __webpack_require__(0);
  2497. var _events = __webpack_require__(1);
  2498. var _events2 = _interopRequireDefault(_events);
  2499. var _getSelfScope = __webpack_require__(5);
  2500. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2501. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2502. // see https://stackoverflow.com/a/11237259/589493
  2503. var global = (0, _getSelfScope.getSelfScope)(); // safeguard for code that might run both on worker and main thread
  2504. var Decrypter = function () {
  2505. function Decrypter(observer, config) {
  2506. var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
  2507. _ref$removePKCS7Paddi = _ref.removePKCS7Padding,
  2508. removePKCS7Padding = _ref$removePKCS7Paddi === undefined ? true : _ref$removePKCS7Paddi;
  2509. _classCallCheck(this, Decrypter);
  2510. this.logEnabled = true;
  2511. this.observer = observer;
  2512. this.config = config;
  2513. this.removePKCS7Padding = removePKCS7Padding;
  2514. // built in decryptor expects PKCS7 padding
  2515. if (removePKCS7Padding) {
  2516. try {
  2517. var browserCrypto = global.crypto;
  2518. if (browserCrypto) {
  2519. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  2520. }
  2521. } catch (e) {}
  2522. }
  2523. this.disableWebCrypto = !this.subtle;
  2524. }
  2525. _createClass(Decrypter, [{
  2526. key: 'isSync',
  2527. value: function isSync() {
  2528. return this.disableWebCrypto && this.config.enableSoftwareAES;
  2529. }
  2530. }, {
  2531. key: 'decrypt',
  2532. value: function decrypt(data, key, iv, callback) {
  2533. var _this = this;
  2534. if (this.disableWebCrypto && this.config.enableSoftwareAES) {
  2535. if (this.logEnabled) {
  2536. _logger.logger.log('JS AES decrypt');
  2537. this.logEnabled = false;
  2538. }
  2539. var decryptor = this.decryptor;
  2540. if (!decryptor) {
  2541. this.decryptor = decryptor = new _aesDecryptor2.default();
  2542. }
  2543. decryptor.expandKey(key);
  2544. callback(decryptor.decrypt(data, 0, iv, this.removePKCS7Padding));
  2545. } else {
  2546. if (this.logEnabled) {
  2547. _logger.logger.log('WebCrypto AES decrypt');
  2548. this.logEnabled = false;
  2549. }
  2550. var subtle = this.subtle;
  2551. if (this.key !== key) {
  2552. this.key = key;
  2553. this.fastAesKey = new _fastAesKey2.default(subtle, key);
  2554. }
  2555. this.fastAesKey.expandKey().then(function (aesKey) {
  2556. // decrypt using web crypto
  2557. var crypto = new _aesCrypto2.default(subtle, iv);
  2558. crypto.decrypt(data, aesKey).catch(function (err) {
  2559. _this.onWebCryptoError(err, data, key, iv, callback);
  2560. }).then(function (result) {
  2561. callback(result);
  2562. });
  2563. }).catch(function (err) {
  2564. _this.onWebCryptoError(err, data, key, iv, callback);
  2565. });
  2566. }
  2567. }
  2568. }, {
  2569. key: 'onWebCryptoError',
  2570. value: function onWebCryptoError(err, data, key, iv, callback) {
  2571. if (this.config.enableSoftwareAES) {
  2572. _logger.logger.log('WebCrypto Error, disable WebCrypto API');
  2573. this.disableWebCrypto = true;
  2574. this.logEnabled = true;
  2575. this.decrypt(data, key, iv, callback);
  2576. } else {
  2577. _logger.logger.error('decrypting error : ' + err.message);
  2578. this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_DECRYPT_ERROR, fatal: true, reason: err.message });
  2579. }
  2580. }
  2581. }, {
  2582. key: 'destroy',
  2583. value: function destroy() {
  2584. var decryptor = this.decryptor;
  2585. if (decryptor) {
  2586. decryptor.destroy();
  2587. this.decryptor = undefined;
  2588. }
  2589. }
  2590. }]);
  2591. return Decrypter;
  2592. }();
  2593. exports.default = Decrypter;
  2594. module.exports = exports['default'];
  2595. /***/ }),
  2596. /* 13 */
  2597. /***/ (function(module, exports, __webpack_require__) {
  2598. "use strict";
  2599. Object.defineProperty(exports, "__esModule", {
  2600. value: true
  2601. });
  2602. exports.getMediaSource = getMediaSource;
  2603. /**
  2604. * MediaSource helper
  2605. */
  2606. function getMediaSource() {
  2607. if (typeof window !== 'undefined') {
  2608. return window.MediaSource || window.WebKitMediaSource;
  2609. }
  2610. }
  2611. /***/ }),
  2612. /* 14 */
  2613. /***/ (function(module, exports, __webpack_require__) {
  2614. "use strict";
  2615. Object.defineProperty(exports, "__esModule", {
  2616. value: true
  2617. });
  2618. exports.State = undefined;
  2619. 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; }; }();
  2620. 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); } };
  2621. var _taskLoop = __webpack_require__(28);
  2622. var _taskLoop2 = _interopRequireDefault(_taskLoop);
  2623. var _fragmentTracker = __webpack_require__(6);
  2624. var _bufferHelper = __webpack_require__(4);
  2625. var _logger = __webpack_require__(0);
  2626. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2627. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2628. 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; }
  2629. 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; }
  2630. var State = exports.State = {
  2631. STOPPED: 'STOPPED',
  2632. STARTING: 'STARTING',
  2633. IDLE: 'IDLE',
  2634. PAUSED: 'PAUSED',
  2635. KEY_LOADING: 'KEY_LOADING',
  2636. FRAG_LOADING: 'FRAG_LOADING',
  2637. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  2638. WAITING_TRACK: 'WAITING_TRACK',
  2639. PARSING: 'PARSING',
  2640. PARSED: 'PARSED',
  2641. BUFFER_FLUSHING: 'BUFFER_FLUSHING',
  2642. ENDED: 'ENDED',
  2643. ERROR: 'ERROR',
  2644. WAITING_INIT_PTS: 'WAITING_INIT_PTS',
  2645. WAITING_LEVEL: 'WAITING_LEVEL'
  2646. };
  2647. var BaseStreamController = function (_TaskLoop) {
  2648. _inherits(BaseStreamController, _TaskLoop);
  2649. function BaseStreamController() {
  2650. _classCallCheck(this, BaseStreamController);
  2651. return _possibleConstructorReturn(this, (BaseStreamController.__proto__ || Object.getPrototypeOf(BaseStreamController)).apply(this, arguments));
  2652. }
  2653. _createClass(BaseStreamController, [{
  2654. key: 'doTick',
  2655. value: function doTick() {}
  2656. }, {
  2657. key: 'startLoad',
  2658. value: function startLoad() {}
  2659. }, {
  2660. key: 'stopLoad',
  2661. value: function stopLoad() {
  2662. var frag = this.fragCurrent;
  2663. if (frag) {
  2664. if (frag.loader) {
  2665. frag.loader.abort();
  2666. }
  2667. this.fragmentTracker.removeFragment(frag);
  2668. }
  2669. if (this.demuxer) {
  2670. this.demuxer.destroy();
  2671. this.demuxer = null;
  2672. }
  2673. this.fragCurrent = null;
  2674. this.fragPrevious = null;
  2675. this.clearInterval();
  2676. this.clearNextTick();
  2677. this.state = State.STOPPED;
  2678. }
  2679. }, {
  2680. key: '_streamEnded',
  2681. value: function _streamEnded(bufferInfo, levelDetails) {
  2682. var fragCurrent = this.fragCurrent,
  2683. fragmentTracker = this.fragmentTracker;
  2684. // we just got done loading the final fragment and there is no other buffered range after ...
  2685. // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
  2686. // so we should not switch to ENDED in that case, to be able to buffer them
  2687. // dont switch to ENDED if we need to backtrack last fragment
  2688. if (!levelDetails.live && fragCurrent && !fragCurrent.backtracked && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) {
  2689. var fragState = fragmentTracker.getState(fragCurrent);
  2690. return fragState === _fragmentTracker.FragmentState.PARTIAL || fragState === _fragmentTracker.FragmentState.OK;
  2691. }
  2692. return false;
  2693. }
  2694. }, {
  2695. key: 'onMediaSeeking',
  2696. value: function onMediaSeeking() {
  2697. var config = this.config,
  2698. media = this.media,
  2699. mediaBuffer = this.mediaBuffer,
  2700. state = this.state;
  2701. var currentTime = media ? media.currentTime : null;
  2702. var bufferInfo = _bufferHelper.BufferHelper.bufferInfo(mediaBuffer || media, currentTime, this.config.maxBufferHole);
  2703. if (Number.isFinite(currentTime)) {
  2704. _logger.logger.log('media seeking to ' + currentTime.toFixed(3));
  2705. }
  2706. if (state === State.FRAG_LOADING) {
  2707. var fragCurrent = this.fragCurrent;
  2708. // check if we are seeking to a unbuffered area AND if frag loading is in progress
  2709. if (bufferInfo.len === 0 && fragCurrent) {
  2710. var tolerance = config.maxFragLookUpTolerance;
  2711. var fragStartOffset = fragCurrent.start - tolerance;
  2712. var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  2713. // check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything
  2714. if (currentTime < fragStartOffset || currentTime > fragEndOffset) {
  2715. if (fragCurrent.loader) {
  2716. _logger.logger.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
  2717. fragCurrent.loader.abort();
  2718. }
  2719. this.fragCurrent = null;
  2720. this.fragPrevious = null;
  2721. // switch to IDLE state to load new fragment
  2722. this.state = State.IDLE;
  2723. } else {
  2724. _logger.logger.log('seeking outside of buffer but within currently loaded fragment range');
  2725. }
  2726. }
  2727. } else if (state === State.ENDED) {
  2728. // if seeking to unbuffered area, clean up fragPrevious
  2729. if (bufferInfo.len === 0) {
  2730. this.fragPrevious = null;
  2731. this.fragCurrent = null;
  2732. }
  2733. // switch to IDLE state to check for potential new fragment
  2734. this.state = State.IDLE;
  2735. }
  2736. if (media) {
  2737. this.lastCurrentTime = currentTime;
  2738. }
  2739. // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
  2740. if (!this.loadedmetadata) {
  2741. this.nextLoadPosition = this.startPosition = currentTime;
  2742. }
  2743. // tick to speed up processing
  2744. this.tick();
  2745. }
  2746. }, {
  2747. key: 'onMediaEnded',
  2748. value: function onMediaEnded() {
  2749. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  2750. this.startPosition = this.lastCurrentTime = 0;
  2751. }
  2752. }, {
  2753. key: 'onHandlerDestroying',
  2754. value: function onHandlerDestroying() {
  2755. this.stopLoad();
  2756. _get(BaseStreamController.prototype.__proto__ || Object.getPrototypeOf(BaseStreamController.prototype), 'onHandlerDestroying', this).call(this);
  2757. }
  2758. }, {
  2759. key: 'onHandlerDestroyed',
  2760. value: function onHandlerDestroyed() {
  2761. this.state = State.STOPPED;
  2762. this.fragmentTracker = null;
  2763. }
  2764. }]);
  2765. return BaseStreamController;
  2766. }(_taskLoop2.default);
  2767. exports.default = BaseStreamController;
  2768. /***/ }),
  2769. /* 15 */
  2770. /***/ (function(module, exports, __webpack_require__) {
  2771. "use strict";
  2772. Object.defineProperty(exports, "__esModule", {
  2773. value: true
  2774. });
  2775. 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; }; }();
  2776. 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); } };
  2777. var _events = __webpack_require__(1);
  2778. var _events2 = _interopRequireDefault(_events);
  2779. var _eventHandler = __webpack_require__(3);
  2780. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  2781. var _errors = __webpack_require__(2);
  2782. var _logger = __webpack_require__(0);
  2783. var _mp4demuxer = __webpack_require__(16);
  2784. var _mp4demuxer2 = _interopRequireDefault(_mp4demuxer);
  2785. var _m3u8Parser = __webpack_require__(35);
  2786. var _m3u8Parser2 = _interopRequireDefault(_m3u8Parser);
  2787. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2788. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2789. 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; }
  2790. 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; } /**
  2791. * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.
  2792. *
  2793. * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.
  2794. *
  2795. * Uses loader(s) set in config to do actual internal loading of resource tasks.
  2796. *
  2797. * @module
  2798. *
  2799. */
  2800. var _window = window,
  2801. performance = _window.performance;
  2802. /**
  2803. * `type` property values for this loaders' context object
  2804. * @enum
  2805. *
  2806. */
  2807. var ContextType = {
  2808. MANIFEST: 'manifest',
  2809. LEVEL: 'level',
  2810. AUDIO_TRACK: 'audioTrack',
  2811. SUBTITLE_TRACK: 'subtitleTrack'
  2812. };
  2813. /**
  2814. * @enum {string}
  2815. */
  2816. var LevelType = {
  2817. MAIN: 'main',
  2818. AUDIO: 'audio',
  2819. SUBTITLE: 'subtitle'
  2820. };
  2821. /**
  2822. * @constructor
  2823. */
  2824. var PlaylistLoader = function (_EventHandler) {
  2825. _inherits(PlaylistLoader, _EventHandler);
  2826. /**
  2827. * @constructs
  2828. * @param {Hls} hls
  2829. */
  2830. function PlaylistLoader(hls) {
  2831. _classCallCheck(this, PlaylistLoader);
  2832. var _this = _possibleConstructorReturn(this, (PlaylistLoader.__proto__ || Object.getPrototypeOf(PlaylistLoader)).call(this, hls, _events2.default.MANIFEST_LOADING, _events2.default.LEVEL_LOADING, _events2.default.AUDIO_TRACK_LOADING, _events2.default.SUBTITLE_TRACK_LOADING));
  2833. _this.loaders = {};
  2834. return _this;
  2835. }
  2836. _createClass(PlaylistLoader, [{
  2837. key: 'createInternalLoader',
  2838. /**
  2839. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  2840. * Default loader is XHRLoader (see utils)
  2841. * @param {object} context
  2842. * @returns {XHRLoader} or other compatible configured overload
  2843. */
  2844. value: function createInternalLoader(context) {
  2845. var config = this.hls.config;
  2846. var PLoader = config.pLoader;
  2847. var Loader = config.loader;
  2848. var InternalLoader = PLoader || Loader;
  2849. var loader = new InternalLoader(config);
  2850. context.loader = loader;
  2851. this.loaders[context.type] = loader;
  2852. return loader;
  2853. }
  2854. }, {
  2855. key: 'getInternalLoader',
  2856. value: function getInternalLoader(context) {
  2857. return this.loaders[context.type];
  2858. }
  2859. }, {
  2860. key: 'resetInternalLoader',
  2861. value: function resetInternalLoader(contextType) {
  2862. if (this.loaders[contextType]) {
  2863. delete this.loaders[contextType];
  2864. }
  2865. }
  2866. /**
  2867. * Call `destroy` on all internal loader instances mapped (one per context type)
  2868. */
  2869. }, {
  2870. key: 'destroyInternalLoaders',
  2871. value: function destroyInternalLoaders() {
  2872. for (var contextType in this.loaders) {
  2873. var loader = this.loaders[contextType];
  2874. if (loader) {
  2875. loader.destroy();
  2876. }
  2877. this.resetInternalLoader(contextType);
  2878. }
  2879. }
  2880. }, {
  2881. key: 'destroy',
  2882. value: function destroy() {
  2883. this.destroyInternalLoaders();
  2884. _get(PlaylistLoader.prototype.__proto__ || Object.getPrototypeOf(PlaylistLoader.prototype), 'destroy', this).call(this);
  2885. }
  2886. }, {
  2887. key: 'onManifestLoading',
  2888. value: function onManifestLoading(data) {
  2889. this.load(data.url, { type: ContextType.MANIFEST, level: 0, id: null });
  2890. }
  2891. }, {
  2892. key: 'onLevelLoading',
  2893. value: function onLevelLoading(data) {
  2894. this.load(data.url, { type: ContextType.LEVEL, level: data.level, id: data.id });
  2895. }
  2896. }, {
  2897. key: 'onAudioTrackLoading',
  2898. value: function onAudioTrackLoading(data) {
  2899. this.load(data.url, { type: ContextType.AUDIO_TRACK, level: null, id: data.id });
  2900. }
  2901. }, {
  2902. key: 'onSubtitleTrackLoading',
  2903. value: function onSubtitleTrackLoading(data) {
  2904. this.load(data.url, { type: ContextType.SUBTITLE_TRACK, level: null, id: data.id });
  2905. }
  2906. }, {
  2907. key: 'load',
  2908. value: function load(url, context) {
  2909. var config = this.hls.config;
  2910. _logger.logger.debug('Loading playlist of type ' + context.type + ', level: ' + context.level + ', id: ' + context.id);
  2911. // Check if a loader for this context already exists
  2912. var loader = this.getInternalLoader(context);
  2913. if (loader) {
  2914. var loaderContext = loader.context;
  2915. if (loaderContext && loaderContext.url === url) {
  2916. // same URL can't overlap
  2917. _logger.logger.trace('playlist request ongoing');
  2918. return false;
  2919. } else {
  2920. _logger.logger.warn('aborting previous loader for type: ' + context.type);
  2921. loader.abort();
  2922. }
  2923. }
  2924. var maxRetry = void 0,
  2925. timeout = void 0,
  2926. retryDelay = void 0,
  2927. maxRetryDelay = void 0;
  2928. // apply different configs for retries depending on
  2929. // context (manifest, level, audio/subs playlist)
  2930. switch (context.type) {
  2931. case ContextType.MANIFEST:
  2932. maxRetry = config.manifestLoadingMaxRetry;
  2933. timeout = config.manifestLoadingTimeOut;
  2934. retryDelay = config.manifestLoadingRetryDelay;
  2935. maxRetryDelay = config.manifestLoadingMaxRetryTimeout;
  2936. break;
  2937. case ContextType.LEVEL:
  2938. // Disable internal loader retry logic, since we are managing retries in Level Controller
  2939. maxRetry = 0;
  2940. timeout = config.levelLoadingTimeOut;
  2941. // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config
  2942. break;
  2943. default:
  2944. maxRetry = config.levelLoadingMaxRetry;
  2945. timeout = config.levelLoadingTimeOut;
  2946. retryDelay = config.levelLoadingRetryDelay;
  2947. maxRetryDelay = config.levelLoadingMaxRetryTimeout;
  2948. break;
  2949. }
  2950. loader = this.createInternalLoader(context);
  2951. context.url = url;
  2952. context.responseType = context.responseType || ''; // FIXME: (should not be necessary to do this)
  2953. var loaderConfig = {
  2954. timeout: timeout,
  2955. maxRetry: maxRetry,
  2956. retryDelay: retryDelay,
  2957. maxRetryDelay: maxRetryDelay
  2958. };
  2959. var loaderCallbacks = {
  2960. onSuccess: this.loadsuccess.bind(this),
  2961. onError: this.loaderror.bind(this),
  2962. onTimeout: this.loadtimeout.bind(this)
  2963. };
  2964. _logger.logger.debug('Calling internal loader delegate for URL: ' + url);
  2965. loader.load(context, loaderConfig, loaderCallbacks);
  2966. return true;
  2967. }
  2968. }, {
  2969. key: 'loadsuccess',
  2970. value: function loadsuccess(response, stats, context) {
  2971. var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  2972. if (context.isSidxRequest) {
  2973. this._handleSidxRequest(response, context);
  2974. this._handlePlaylistLoaded(response, stats, context, networkDetails);
  2975. return;
  2976. }
  2977. this.resetInternalLoader(context.type);
  2978. var string = response.data;
  2979. stats.tload = performance.now();
  2980. // stats.mtime = new Date(target.getResponseHeader('Last-Modified'));
  2981. // Validate if it is an M3U8 at all
  2982. if (string.indexOf('#EXTM3U') !== 0) {
  2983. this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);
  2984. return;
  2985. }
  2986. // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)
  2987. if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {
  2988. this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);
  2989. } else {
  2990. this._handleMasterPlaylist(response, stats, context, networkDetails);
  2991. }
  2992. }
  2993. }, {
  2994. key: 'loaderror',
  2995. value: function loaderror(response, context) {
  2996. var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  2997. this._handleNetworkError(context, networkDetails, false, response);
  2998. }
  2999. }, {
  3000. key: 'loadtimeout',
  3001. value: function loadtimeout(stats, context) {
  3002. var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  3003. this._handleNetworkError(context, networkDetails, true);
  3004. }
  3005. }, {
  3006. key: '_handleMasterPlaylist',
  3007. value: function _handleMasterPlaylist(response, stats, context, networkDetails) {
  3008. var hls = this.hls;
  3009. var string = response.data;
  3010. var url = PlaylistLoader.getResponseUrl(response, context);
  3011. var levels = _m3u8Parser2.default.parseMasterPlaylist(string, url);
  3012. if (!levels.length) {
  3013. this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);
  3014. return;
  3015. }
  3016. // multi level playlist, parse level info
  3017. var audioGroups = levels.map(function (level) {
  3018. return {
  3019. id: level.attrs.AUDIO,
  3020. codec: level.audioCodec
  3021. };
  3022. });
  3023. var audioTracks = _m3u8Parser2.default.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);
  3024. var subtitles = _m3u8Parser2.default.parseMasterPlaylistMedia(string, url, 'SUBTITLES');
  3025. if (audioTracks.length) {
  3026. // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
  3027. var embeddedAudioFound = false;
  3028. audioTracks.forEach(function (audioTrack) {
  3029. if (!audioTrack.url) {
  3030. embeddedAudioFound = true;
  3031. }
  3032. });
  3033. // if no embedded audio track defined, but audio codec signaled in quality level,
  3034. // we need to signal this main audio track this could happen with playlists with
  3035. // alt audio rendition in which quality levels (main)
  3036. // contains both audio+video. but with mixed audio track not signaled
  3037. if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  3038. _logger.logger.log('audio codec signaled in quality level, but no embedded audio track signaled, create one');
  3039. audioTracks.unshift({
  3040. type: 'main',
  3041. name: 'main'
  3042. });
  3043. }
  3044. }
  3045. hls.trigger(_events2.default.MANIFEST_LOADED, {
  3046. levels: levels,
  3047. audioTracks: audioTracks,
  3048. subtitles: subtitles,
  3049. url: url,
  3050. stats: stats,
  3051. networkDetails: networkDetails
  3052. });
  3053. }
  3054. }, {
  3055. key: '_handleTrackOrLevelPlaylist',
  3056. value: function _handleTrackOrLevelPlaylist(response, stats, context, networkDetails) {
  3057. var hls = this.hls;
  3058. var id = context.id,
  3059. level = context.level,
  3060. type = context.type;
  3061. var url = PlaylistLoader.getResponseUrl(response, context);
  3062. var levelUrlId = Number.isFinite(id) ? id : 0;
  3063. var levelId = Number.isFinite(level) ? level : levelUrlId;
  3064. var levelType = PlaylistLoader.mapContextToLevelType(context);
  3065. var levelDetails = _m3u8Parser2.default.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);
  3066. // set stats on level structure
  3067. levelDetails.tload = stats.tload;
  3068. // We have done our first request (Manifest-type) and receive
  3069. // not a master playlist but a chunk-list (track/level)
  3070. // We fire the manifest-loaded event anyway with the parsed level-details
  3071. // by creating a single-level structure for it.
  3072. if (type === ContextType.MANIFEST) {
  3073. var singleLevel = {
  3074. url: url,
  3075. details: levelDetails
  3076. };
  3077. hls.trigger(_events2.default.MANIFEST_LOADED, {
  3078. levels: [singleLevel],
  3079. audioTracks: [],
  3080. url: url,
  3081. stats: stats,
  3082. networkDetails: networkDetails
  3083. });
  3084. }
  3085. // save parsing time
  3086. stats.tparsed = performance.now();
  3087. // in case we need SIDX ranges
  3088. // return early after calling load for
  3089. // the SIDX box.
  3090. if (levelDetails.needSidxRanges) {
  3091. var sidxUrl = levelDetails.initSegment.url;
  3092. this.load(sidxUrl, {
  3093. isSidxRequest: true,
  3094. type: type,
  3095. level: level,
  3096. levelDetails: levelDetails,
  3097. id: id,
  3098. rangeStart: 0,
  3099. rangeEnd: 2048,
  3100. responseType: 'arraybuffer'
  3101. });
  3102. return;
  3103. }
  3104. // extend the context with the new levelDetails property
  3105. context.levelDetails = levelDetails;
  3106. this._handlePlaylistLoaded(response, stats, context, networkDetails);
  3107. }
  3108. }, {
  3109. key: '_handleSidxRequest',
  3110. value: function _handleSidxRequest(response, context) {
  3111. var sidxInfo = _mp4demuxer2.default.parseSegmentIndex(new Uint8Array(response.data));
  3112. // if provided fragment does not contain sidx, early return
  3113. if (!sidxInfo) {
  3114. return;
  3115. }
  3116. var sidxReferences = sidxInfo.references;
  3117. var levelDetails = context.levelDetails;
  3118. sidxReferences.forEach(function (segmentRef, index) {
  3119. var segRefInfo = segmentRef.info;
  3120. var frag = levelDetails.fragments[index];
  3121. if (frag.byteRange.length === 0) {
  3122. frag.rawByteRange = String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start);
  3123. }
  3124. });
  3125. levelDetails.initSegment.rawByteRange = String(sidxInfo.moovEndOffset) + '@0';
  3126. }
  3127. }, {
  3128. key: '_handleManifestParsingError',
  3129. value: function _handleManifestParsingError(response, context, reason, networkDetails) {
  3130. this.hls.trigger(_events2.default.ERROR, {
  3131. type: _errors.ErrorTypes.NETWORK_ERROR,
  3132. details: _errors.ErrorDetails.MANIFEST_PARSING_ERROR,
  3133. fatal: true,
  3134. url: response.url,
  3135. reason: reason,
  3136. networkDetails: networkDetails
  3137. });
  3138. }
  3139. }, {
  3140. key: '_handleNetworkError',
  3141. value: function _handleNetworkError(context, networkDetails) {
  3142. var timeout = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  3143. var response = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  3144. _logger.logger.info('A network error occured while loading a ' + context.type + '-type playlist');
  3145. var details = void 0;
  3146. var fatal = void 0;
  3147. var loader = this.getInternalLoader(context);
  3148. switch (context.type) {
  3149. case ContextType.MANIFEST:
  3150. details = timeout ? _errors.ErrorDetails.MANIFEST_LOAD_TIMEOUT : _errors.ErrorDetails.MANIFEST_LOAD_ERROR;
  3151. fatal = true;
  3152. break;
  3153. case ContextType.LEVEL:
  3154. details = timeout ? _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT : _errors.ErrorDetails.LEVEL_LOAD_ERROR;
  3155. fatal = false;
  3156. break;
  3157. case ContextType.AUDIO_TRACK:
  3158. details = timeout ? _errors.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : _errors.ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  3159. fatal = false;
  3160. break;
  3161. default:
  3162. // details = ...?
  3163. fatal = false;
  3164. }
  3165. if (loader) {
  3166. loader.abort();
  3167. this.resetInternalLoader(context.type);
  3168. }
  3169. var errorData = {
  3170. type: _errors.ErrorTypes.NETWORK_ERROR,
  3171. details: details,
  3172. fatal: fatal,
  3173. url: loader.url,
  3174. loader: loader,
  3175. context: context,
  3176. networkDetails: networkDetails
  3177. };
  3178. if (response) {
  3179. errorData.response = response;
  3180. }
  3181. this.hls.trigger(_events2.default.ERROR, errorData);
  3182. }
  3183. }, {
  3184. key: '_handlePlaylistLoaded',
  3185. value: function _handlePlaylistLoaded(response, stats, context, networkDetails) {
  3186. var type = context.type,
  3187. level = context.level,
  3188. id = context.id,
  3189. levelDetails = context.levelDetails;
  3190. if (!levelDetails.targetduration) {
  3191. this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails);
  3192. return;
  3193. }
  3194. var canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type);
  3195. if (canHaveLevels) {
  3196. this.hls.trigger(_events2.default.LEVEL_LOADED, {
  3197. details: levelDetails,
  3198. level: level || 0,
  3199. id: id || 0,
  3200. stats: stats,
  3201. networkDetails: networkDetails
  3202. });
  3203. } else {
  3204. switch (type) {
  3205. case ContextType.AUDIO_TRACK:
  3206. this.hls.trigger(_events2.default.AUDIO_TRACK_LOADED, {
  3207. details: levelDetails,
  3208. id: id,
  3209. stats: stats,
  3210. networkDetails: networkDetails
  3211. });
  3212. break;
  3213. case ContextType.SUBTITLE_TRACK:
  3214. this.hls.trigger(_events2.default.SUBTITLE_TRACK_LOADED, {
  3215. details: levelDetails,
  3216. id: id,
  3217. stats: stats,
  3218. networkDetails: networkDetails
  3219. });
  3220. break;
  3221. }
  3222. }
  3223. }
  3224. }], [{
  3225. key: 'canHaveQualityLevels',
  3226. /**
  3227. * @param {ContextType} type
  3228. * @returns {boolean}
  3229. */
  3230. value: function canHaveQualityLevels(type) {
  3231. return type !== ContextType.AUDIO_TRACK && type !== ContextType.SUBTITLE_TRACK;
  3232. }
  3233. /**
  3234. * Map context.type to LevelType
  3235. * @param {{type: ContextType}} context
  3236. * @returns {LevelType}
  3237. */
  3238. }, {
  3239. key: 'mapContextToLevelType',
  3240. value: function mapContextToLevelType(context) {
  3241. var type = context.type;
  3242. switch (type) {
  3243. case ContextType.AUDIO_TRACK:
  3244. return LevelType.AUDIO;
  3245. case ContextType.SUBTITLE_TRACK:
  3246. return LevelType.SUBTITLE;
  3247. default:
  3248. return LevelType.MAIN;
  3249. }
  3250. }
  3251. }, {
  3252. key: 'getResponseUrl',
  3253. value: function getResponseUrl(response, context) {
  3254. var url = response.url;
  3255. // responseURL not supported on some browsers (it is used to detect URL redirection)
  3256. // data-uri mode also not supported (but no need to detect redirection)
  3257. if (url === undefined || url.indexOf('data:') === 0) {
  3258. // fallback to initial URL
  3259. url = context.url;
  3260. }
  3261. return url;
  3262. }
  3263. }, {
  3264. key: 'ContextType',
  3265. get: function get() {
  3266. return ContextType;
  3267. }
  3268. }, {
  3269. key: 'LevelType',
  3270. get: function get() {
  3271. return LevelType;
  3272. }
  3273. }]);
  3274. return PlaylistLoader;
  3275. }(_eventHandler2.default);
  3276. exports.default = PlaylistLoader;
  3277. module.exports = exports['default'];
  3278. /***/ }),
  3279. /* 16 */
  3280. /***/ (function(module, exports, __webpack_require__) {
  3281. "use strict";
  3282. Object.defineProperty(exports, "__esModule", {
  3283. value: true
  3284. });
  3285. 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; }; }(); /**
  3286. * MP4 demuxer
  3287. */
  3288. var _logger = __webpack_require__(0);
  3289. var _events = __webpack_require__(1);
  3290. var _events2 = _interopRequireDefault(_events);
  3291. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  3292. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3293. var UINT32_MAX = Math.pow(2, 32) - 1;
  3294. var MP4Demuxer = function () {
  3295. function MP4Demuxer(observer, remuxer) {
  3296. _classCallCheck(this, MP4Demuxer);
  3297. this.observer = observer;
  3298. this.remuxer = remuxer;
  3299. }
  3300. _createClass(MP4Demuxer, [{
  3301. key: 'resetTimeStamp',
  3302. value: function resetTimeStamp(initPTS) {
  3303. this.initPTS = initPTS;
  3304. }
  3305. }, {
  3306. key: 'resetInitSegment',
  3307. value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  3308. // jshint unused:false
  3309. if (initSegment && initSegment.byteLength) {
  3310. var initData = this.initData = MP4Demuxer.parseInitSegment(initSegment);
  3311. // default audio codec if nothing specified
  3312. // TODO : extract that from initsegment
  3313. if (audioCodec == null) {
  3314. audioCodec = 'mp4a.40.5';
  3315. }
  3316. if (videoCodec == null) {
  3317. videoCodec = 'avc1.42e01e';
  3318. }
  3319. var tracks = {};
  3320. if (initData.audio && initData.video) {
  3321. tracks.audiovideo = { container: 'video/mp4', codec: audioCodec + ',' + videoCodec, initSegment: duration ? initSegment : null };
  3322. } else {
  3323. if (initData.audio) {
  3324. tracks.audio = { container: 'audio/mp4', codec: audioCodec, initSegment: duration ? initSegment : null };
  3325. }
  3326. if (initData.video) {
  3327. tracks.video = { container: 'video/mp4', codec: videoCodec, initSegment: duration ? initSegment : null };
  3328. }
  3329. }
  3330. this.observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, { tracks: tracks });
  3331. } else {
  3332. if (audioCodec) {
  3333. this.audioCodec = audioCodec;
  3334. }
  3335. if (videoCodec) {
  3336. this.videoCodec = videoCodec;
  3337. }
  3338. }
  3339. }
  3340. }, {
  3341. key: 'append',
  3342. // feed incoming data to the front of the parsing pipeline
  3343. value: function append(data, timeOffset, contiguous, accurateTimeOffset) {
  3344. var initData = this.initData;
  3345. if (!initData) {
  3346. this.resetInitSegment(data, this.audioCodec, this.videoCodec, false);
  3347. initData = this.initData;
  3348. }
  3349. var startDTS = void 0,
  3350. initPTS = this.initPTS;
  3351. if (initPTS === undefined) {
  3352. var _startDTS = MP4Demuxer.getStartDTS(initData, data);
  3353. this.initPTS = initPTS = _startDTS - timeOffset;
  3354. this.observer.trigger(_events2.default.INIT_PTS_FOUND, { initPTS: initPTS });
  3355. }
  3356. MP4Demuxer.offsetStartDTS(initData, data, initPTS);
  3357. startDTS = MP4Demuxer.getStartDTS(initData, data);
  3358. this.remuxer.remux(initData.audio, initData.video, null, null, startDTS, contiguous, accurateTimeOffset, data);
  3359. }
  3360. }, {
  3361. key: 'destroy',
  3362. value: function destroy() {}
  3363. }], [{
  3364. key: 'probe',
  3365. value: function probe(data) {
  3366. // ensure we find a moof box in the first 16 kB
  3367. return MP4Demuxer.findBox({ data: data, start: 0, end: Math.min(data.length, 16384) }, ['moof']).length > 0;
  3368. }
  3369. }, {
  3370. key: 'bin2str',
  3371. value: function bin2str(buffer) {
  3372. return String.fromCharCode.apply(null, buffer);
  3373. }
  3374. }, {
  3375. key: 'readUint16',
  3376. value: function readUint16(buffer, offset) {
  3377. if (buffer.data) {
  3378. offset += buffer.start;
  3379. buffer = buffer.data;
  3380. }
  3381. var val = buffer[offset] << 8 | buffer[offset + 1];
  3382. return val < 0 ? 65536 + val : val;
  3383. }
  3384. }, {
  3385. key: 'readUint32',
  3386. value: function readUint32(buffer, offset) {
  3387. if (buffer.data) {
  3388. offset += buffer.start;
  3389. buffer = buffer.data;
  3390. }
  3391. var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
  3392. return val < 0 ? 4294967296 + val : val;
  3393. }
  3394. }, {
  3395. key: 'writeUint32',
  3396. value: function writeUint32(buffer, offset, value) {
  3397. if (buffer.data) {
  3398. offset += buffer.start;
  3399. buffer = buffer.data;
  3400. }
  3401. buffer[offset] = value >> 24;
  3402. buffer[offset + 1] = value >> 16 & 0xff;
  3403. buffer[offset + 2] = value >> 8 & 0xff;
  3404. buffer[offset + 3] = value & 0xff;
  3405. }
  3406. // Find the data for a box specified by its path
  3407. }, {
  3408. key: 'findBox',
  3409. value: function findBox(data, path) {
  3410. var results = [],
  3411. i = void 0,
  3412. size = void 0,
  3413. type = void 0,
  3414. end = void 0,
  3415. subresults = void 0,
  3416. start = void 0,
  3417. endbox = void 0;
  3418. if (data.data) {
  3419. start = data.start;
  3420. end = data.end;
  3421. data = data.data;
  3422. } else {
  3423. start = 0;
  3424. end = data.byteLength;
  3425. }
  3426. if (!path.length) {
  3427. // short-circuit the search for empty paths
  3428. return null;
  3429. }
  3430. for (i = start; i < end;) {
  3431. size = MP4Demuxer.readUint32(data, i);
  3432. type = MP4Demuxer.bin2str(data.subarray(i + 4, i + 8));
  3433. endbox = size > 1 ? i + size : end;
  3434. if (type === path[0]) {
  3435. if (path.length === 1) {
  3436. // this is the end of the path and we've found the box we were
  3437. // looking for
  3438. results.push({ data: data, start: i + 8, end: endbox });
  3439. } else {
  3440. // recursively search for the next box along the path
  3441. subresults = MP4Demuxer.findBox({ data: data, start: i + 8, end: endbox }, path.slice(1));
  3442. if (subresults.length) {
  3443. results = results.concat(subresults);
  3444. }
  3445. }
  3446. }
  3447. i = endbox;
  3448. }
  3449. // we've finished searching all of data
  3450. return results;
  3451. }
  3452. }, {
  3453. key: 'parseSegmentIndex',
  3454. value: function parseSegmentIndex(initSegment) {
  3455. var moov = MP4Demuxer.findBox(initSegment, ['moov'])[0];
  3456. var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data
  3457. var index = 0;
  3458. var sidx = MP4Demuxer.findBox(initSegment, ['sidx']);
  3459. var references = void 0;
  3460. if (!sidx || !sidx[0]) {
  3461. return null;
  3462. }
  3463. references = [];
  3464. sidx = sidx[0];
  3465. var version = sidx.data[0];
  3466. // set initial offset, we skip the reference ID (not needed)
  3467. index = version === 0 ? 8 : 16;
  3468. var timescale = MP4Demuxer.readUint32(sidx, index);
  3469. index += 4;
  3470. // TODO: parse earliestPresentationTime and firstOffset
  3471. // usually zero in our case
  3472. var earliestPresentationTime = 0;
  3473. var firstOffset = 0;
  3474. if (version === 0) {
  3475. index += 8;
  3476. } else {
  3477. index += 16;
  3478. }
  3479. // skip reserved
  3480. index += 2;
  3481. var startByte = sidx.end + firstOffset;
  3482. var referencesCount = MP4Demuxer.readUint16(sidx, index);
  3483. index += 2;
  3484. for (var i = 0; i < referencesCount; i++) {
  3485. var referenceIndex = index;
  3486. var referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex);
  3487. referenceIndex += 4;
  3488. var referenceSize = referenceInfo & 0x7FFFFFFF;
  3489. var referenceType = (referenceInfo & 0x80000000) >>> 31;
  3490. if (referenceType === 1) {
  3491. console.warn('SIDX has hierarchical references (not supported)');
  3492. return;
  3493. }
  3494. var subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex);
  3495. referenceIndex += 4;
  3496. references.push({
  3497. referenceSize: referenceSize,
  3498. subsegmentDuration: subsegmentDuration, // unscaled
  3499. info: {
  3500. duration: subsegmentDuration / timescale,
  3501. start: startByte,
  3502. end: startByte + referenceSize - 1
  3503. }
  3504. });
  3505. startByte += referenceSize;
  3506. // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
  3507. // for |sapDelta|.
  3508. referenceIndex += 4;
  3509. // skip to next ref
  3510. index = referenceIndex;
  3511. }
  3512. return {
  3513. earliestPresentationTime: earliestPresentationTime,
  3514. timescale: timescale,
  3515. version: version,
  3516. referencesCount: referencesCount,
  3517. references: references,
  3518. moovEndOffset: moovEndOffset
  3519. };
  3520. }
  3521. /**
  3522. * Parses an MP4 initialization segment and extracts stream type and
  3523. * timescale values for any declared tracks. Timescale values indicate the
  3524. * number of clock ticks per second to assume for time-based values
  3525. * elsewhere in the MP4.
  3526. *
  3527. * To determine the start time of an MP4, you need two pieces of
  3528. * information: the timescale unit and the earliest base media decode
  3529. * time. Multiple timescales can be specified within an MP4 but the
  3530. * base media decode time is always expressed in the timescale from
  3531. * the media header box for the track:
  3532. * ```
  3533. * moov > trak > mdia > mdhd.timescale
  3534. * moov > trak > mdia > hdlr
  3535. * ```
  3536. * @param init {Uint8Array} the bytes of the init segment
  3537. * @return {object} a hash of track type to timescale values or null if
  3538. * the init segment is malformed.
  3539. */
  3540. }, {
  3541. key: 'parseInitSegment',
  3542. value: function parseInitSegment(initSegment) {
  3543. var result = [];
  3544. var traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']);
  3545. traks.forEach(function (trak) {
  3546. var tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0];
  3547. if (tkhd) {
  3548. var version = tkhd.data[tkhd.start];
  3549. var index = version === 0 ? 12 : 20;
  3550. var trackId = MP4Demuxer.readUint32(tkhd, index);
  3551. var mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0];
  3552. if (mdhd) {
  3553. version = mdhd.data[mdhd.start];
  3554. index = version === 0 ? 12 : 20;
  3555. var timescale = MP4Demuxer.readUint32(mdhd, index);
  3556. var hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0];
  3557. if (hdlr) {
  3558. var hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));
  3559. var type = { 'soun': 'audio', 'vide': 'video' }[hdlrType];
  3560. if (type) {
  3561. // extract codec info. TODO : parse codec details to be able to build MIME type
  3562. var codecBox = MP4Demuxer.findBox(trak, ['mdia', 'minf', 'stbl', 'stsd']);
  3563. if (codecBox.length) {
  3564. codecBox = codecBox[0];
  3565. var codecType = MP4Demuxer.bin2str(codecBox.data.subarray(codecBox.start + 12, codecBox.start + 16));
  3566. _logger.logger.log('MP4Demuxer:' + type + ':' + codecType + ' found');
  3567. }
  3568. result[trackId] = { timescale: timescale, type: type };
  3569. result[type] = { timescale: timescale, id: trackId };
  3570. }
  3571. }
  3572. }
  3573. }
  3574. });
  3575. return result;
  3576. }
  3577. /**
  3578. * Determine the base media decode start time, in seconds, for an MP4
  3579. * fragment. If multiple fragments are specified, the earliest time is
  3580. * returned.
  3581. *
  3582. * The base media decode time can be parsed from track fragment
  3583. * metadata:
  3584. * ```
  3585. * moof > traf > tfdt.baseMediaDecodeTime
  3586. * ```
  3587. * It requires the timescale value from the mdhd to interpret.
  3588. *
  3589. * @param timescale {object} a hash of track ids to timescale values.
  3590. * @return {number} the earliest base media decode start time for the
  3591. * fragment, in seconds
  3592. */
  3593. }, {
  3594. key: 'getStartDTS',
  3595. value: function getStartDTS(initData, fragment) {
  3596. var trafs = void 0,
  3597. baseTimes = void 0,
  3598. result = void 0;
  3599. // we need info from two childrend of each track fragment box
  3600. trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']);
  3601. // determine the start times for each track
  3602. baseTimes = [].concat.apply([], trafs.map(function (traf) {
  3603. return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
  3604. var id = void 0,
  3605. scale = void 0,
  3606. baseTime = void 0;
  3607. // get the track id from the tfhd
  3608. id = MP4Demuxer.readUint32(tfhd, 4);
  3609. // assume a 90kHz clock if no timescale was specified
  3610. scale = initData[id].timescale || 90e3;
  3611. // get the base media decode time from the tfdt
  3612. baseTime = MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
  3613. var version = void 0,
  3614. result = void 0;
  3615. version = tfdt.data[tfdt.start];
  3616. result = MP4Demuxer.readUint32(tfdt, 4);
  3617. if (version === 1) {
  3618. result *= Math.pow(2, 32);
  3619. result += MP4Demuxer.readUint32(tfdt, 8);
  3620. }
  3621. return result;
  3622. })[0];
  3623. // convert base time to seconds
  3624. return baseTime / scale;
  3625. });
  3626. }));
  3627. // return the minimum
  3628. result = Math.min.apply(null, baseTimes);
  3629. return isFinite(result) ? result : 0;
  3630. }
  3631. }, {
  3632. key: 'offsetStartDTS',
  3633. value: function offsetStartDTS(initData, fragment, timeOffset) {
  3634. MP4Demuxer.findBox(fragment, ['moof', 'traf']).map(function (traf) {
  3635. return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
  3636. // get the track id from the tfhd
  3637. var id = MP4Demuxer.readUint32(tfhd, 4);
  3638. // assume a 90kHz clock if no timescale was specified
  3639. var timescale = initData[id].timescale || 90e3;
  3640. // get the base media decode time from the tfdt
  3641. MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
  3642. var version = tfdt.data[tfdt.start];
  3643. var baseMediaDecodeTime = MP4Demuxer.readUint32(tfdt, 4);
  3644. if (version === 0) {
  3645. MP4Demuxer.writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);
  3646. } else {
  3647. baseMediaDecodeTime *= Math.pow(2, 32);
  3648. baseMediaDecodeTime += MP4Demuxer.readUint32(tfdt, 8);
  3649. baseMediaDecodeTime -= timeOffset * timescale;
  3650. baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
  3651. var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  3652. var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  3653. MP4Demuxer.writeUint32(tfdt, 4, upper);
  3654. MP4Demuxer.writeUint32(tfdt, 8, lower);
  3655. }
  3656. });
  3657. });
  3658. });
  3659. }
  3660. }]);
  3661. return MP4Demuxer;
  3662. }();
  3663. exports.default = MP4Demuxer;
  3664. module.exports = exports['default'];
  3665. /***/ }),
  3666. /* 17 */
  3667. /***/ (function(module, exports, __webpack_require__) {
  3668. "use strict";
  3669. Object.defineProperty(exports, "__esModule", {
  3670. value: true
  3671. });
  3672. 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; }; }();
  3673. var _urlToolkit = __webpack_require__(8);
  3674. var URLToolkit = _interopRequireWildcard(_urlToolkit);
  3675. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  3676. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3677. var LevelKey = function () {
  3678. function LevelKey() {
  3679. _classCallCheck(this, LevelKey);
  3680. this.method = null;
  3681. this.key = null;
  3682. this.iv = null;
  3683. this._uri = null;
  3684. }
  3685. _createClass(LevelKey, [{
  3686. key: 'uri',
  3687. get: function get() {
  3688. if (!this._uri && this.reluri) {
  3689. this._uri = URLToolkit.buildAbsoluteURL(this.baseuri, this.reluri, { alwaysNormalize: true });
  3690. }
  3691. return this._uri;
  3692. }
  3693. }]);
  3694. return LevelKey;
  3695. }();
  3696. exports.default = LevelKey;
  3697. module.exports = exports['default'];
  3698. /***/ }),
  3699. /* 18 */
  3700. /***/ (function(module, exports, __webpack_require__) {
  3701. "use strict";
  3702. Object.defineProperty(exports, "__esModule", {
  3703. value: true
  3704. });
  3705. // from http://mp4ra.org/codecs.html
  3706. var sampleEntryCodesISO = {
  3707. audio: {
  3708. 'a3ds': true,
  3709. 'ac-3': true,
  3710. 'ac-4': true,
  3711. 'alac': true,
  3712. 'alaw': true,
  3713. 'dra1': true,
  3714. 'dts+': true,
  3715. 'dts-': true,
  3716. 'dtsc': true,
  3717. 'dtse': true,
  3718. 'dtsh': true,
  3719. 'ec-3': true,
  3720. 'enca': true,
  3721. 'g719': true,
  3722. 'g726': true,
  3723. 'm4ae': true,
  3724. 'mha1': true,
  3725. 'mha2': true,
  3726. 'mhm1': true,
  3727. 'mhm2': true,
  3728. 'mlpa': true,
  3729. 'mp4a': true,
  3730. 'raw ': true,
  3731. 'Opus': true,
  3732. 'samr': true,
  3733. 'sawb': true,
  3734. 'sawp': true,
  3735. 'sevc': true,
  3736. 'sqcp': true,
  3737. 'ssmv': true,
  3738. 'twos': true,
  3739. 'ulaw': true
  3740. },
  3741. video: {
  3742. 'avc1': true,
  3743. 'avc2': true,
  3744. 'avc3': true,
  3745. 'avc4': true,
  3746. 'avcp': true,
  3747. 'drac': true,
  3748. 'dvav': true,
  3749. 'dvhe': true,
  3750. 'encv': true,
  3751. 'hev1': true,
  3752. 'hvc1': true,
  3753. 'mjp2': true,
  3754. 'mp4v': true,
  3755. 'mvc1': true,
  3756. 'mvc2': true,
  3757. 'mvc3': true,
  3758. 'mvc4': true,
  3759. 'resv': true,
  3760. 'rv60': true,
  3761. 's263': true,
  3762. 'svc1': true,
  3763. 'svc2': true,
  3764. 'vc-1': true,
  3765. 'vp08': true,
  3766. 'vp09': true
  3767. }
  3768. };
  3769. function isCodecType(codec, type) {
  3770. var typeCodes = sampleEntryCodesISO[type];
  3771. return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;
  3772. }
  3773. function isCodecSupportedInMp4(codec, type) {
  3774. return window.MediaSource.isTypeSupported((type || 'video') + '/mp4;codecs="' + codec + '"');
  3775. }
  3776. exports.isCodecType = isCodecType;
  3777. exports.isCodecSupportedInMp4 = isCodecSupportedInMp4;
  3778. /***/ }),
  3779. /* 19 */
  3780. /***/ (function(module, exports, __webpack_require__) {
  3781. "use strict";
  3782. Object.defineProperty(exports, "__esModule", {
  3783. value: true
  3784. });
  3785. 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; }; }();
  3786. var _events = __webpack_require__(20);
  3787. var _webworkifyWebpack = __webpack_require__(41);
  3788. var work = _interopRequireWildcard(_webworkifyWebpack);
  3789. var _events2 = __webpack_require__(1);
  3790. var _events3 = _interopRequireDefault(_events2);
  3791. var _demuxerInline = __webpack_require__(21);
  3792. var _demuxerInline2 = _interopRequireDefault(_demuxerInline);
  3793. var _logger = __webpack_require__(0);
  3794. var _errors = __webpack_require__(2);
  3795. var _mediasourceHelper = __webpack_require__(13);
  3796. var _getSelfScope = __webpack_require__(5);
  3797. var _observer = __webpack_require__(24);
  3798. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  3799. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  3800. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3801. // see https://stackoverflow.com/a/11237259/589493
  3802. var global = (0, _getSelfScope.getSelfScope)(); // safeguard for code that might run both on worker and main thread
  3803. var MediaSource = (0, _mediasourceHelper.getMediaSource)();
  3804. var Demuxer = function () {
  3805. function Demuxer(hls, id) {
  3806. var _this = this;
  3807. _classCallCheck(this, Demuxer);
  3808. this.hls = hls;
  3809. this.id = id;
  3810. var observer = this.observer = new _observer.Observer();
  3811. var config = hls.config;
  3812. var forwardMessage = function forwardMessage(ev, data) {
  3813. data = data || {};
  3814. data.frag = _this.frag;
  3815. data.id = _this.id;
  3816. hls.trigger(ev, data);
  3817. };
  3818. // forward events to main thread
  3819. observer.on(_events3.default.FRAG_DECRYPTED, forwardMessage);
  3820. observer.on(_events3.default.FRAG_PARSING_INIT_SEGMENT, forwardMessage);
  3821. observer.on(_events3.default.FRAG_PARSING_DATA, forwardMessage);
  3822. observer.on(_events3.default.FRAG_PARSED, forwardMessage);
  3823. observer.on(_events3.default.ERROR, forwardMessage);
  3824. observer.on(_events3.default.FRAG_PARSING_METADATA, forwardMessage);
  3825. observer.on(_events3.default.FRAG_PARSING_USERDATA, forwardMessage);
  3826. observer.on(_events3.default.INIT_PTS_FOUND, forwardMessage);
  3827. var typeSupported = {
  3828. mp4: MediaSource.isTypeSupported('video/mp4'),
  3829. mpeg: MediaSource.isTypeSupported('audio/mpeg'),
  3830. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"')
  3831. };
  3832. // navigator.vendor is not always available in Web Worker
  3833. // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator
  3834. var vendor = navigator.vendor;
  3835. if (config.enableWorker && typeof Worker !== 'undefined') {
  3836. _logger.logger.log('demuxing in webworker');
  3837. var w = void 0;
  3838. try {
  3839. w = this.w = work(/*require.resolve*/(55));
  3840. this.onwmsg = this.onWorkerMessage.bind(this);
  3841. w.addEventListener('message', this.onwmsg);
  3842. w.onerror = function (event) {
  3843. hls.trigger(_events3.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.INTERNAL_EXCEPTION, fatal: true, event: 'demuxerWorker', err: { message: event.message + ' (' + event.filename + ':' + event.lineno + ')' } });
  3844. };
  3845. w.postMessage({ cmd: 'init', typeSupported: typeSupported, vendor: vendor, id: id, config: JSON.stringify(config) });
  3846. } catch (err) {
  3847. _logger.logger.warn('Error in worker:', err);
  3848. _logger.logger.error('Error while initializing DemuxerWorker, fallback on DemuxerInline');
  3849. if (w) {
  3850. // revoke the Object URL that was used to create demuxer worker, so as not to leak it
  3851. global.URL.revokeObjectURL(w.objectURL);
  3852. }
  3853. this.demuxer = new _demuxerInline2.default(observer, typeSupported, config, vendor);
  3854. this.w = undefined;
  3855. }
  3856. } else {
  3857. this.demuxer = new _demuxerInline2.default(observer, typeSupported, config, vendor);
  3858. }
  3859. }
  3860. _createClass(Demuxer, [{
  3861. key: 'destroy',
  3862. value: function destroy() {
  3863. var w = this.w;
  3864. if (w) {
  3865. w.removeEventListener('message', this.onwmsg);
  3866. w.terminate();
  3867. this.w = null;
  3868. } else {
  3869. var demuxer = this.demuxer;
  3870. if (demuxer) {
  3871. demuxer.destroy();
  3872. this.demuxer = null;
  3873. }
  3874. }
  3875. var observer = this.observer;
  3876. if (observer) {
  3877. observer.removeAllListeners();
  3878. this.observer = null;
  3879. }
  3880. }
  3881. }, {
  3882. key: 'push',
  3883. value: function push(data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) {
  3884. var w = this.w;
  3885. var timeOffset = Number.isFinite(frag.startPTS) ? frag.startPTS : frag.start;
  3886. var decryptdata = frag.decryptdata;
  3887. var lastFrag = this.frag;
  3888. var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  3889. var trackSwitch = !(lastFrag && frag.level === lastFrag.level);
  3890. var nextSN = lastFrag && frag.sn === lastFrag.sn + 1;
  3891. var contiguous = !trackSwitch && nextSN;
  3892. if (discontinuity) {
  3893. _logger.logger.log(this.id + ':discontinuity detected');
  3894. }
  3895. if (trackSwitch) {
  3896. _logger.logger.log(this.id + ':switch detected');
  3897. }
  3898. this.frag = frag;
  3899. if (w) {
  3900. // post fragment payload as transferable objects for ArrayBuffer (no copy)
  3901. w.postMessage({ cmd: 'demux', data: data, decryptdata: decryptdata, initSegment: initSegment, audioCodec: audioCodec, videoCodec: videoCodec, timeOffset: timeOffset, discontinuity: discontinuity, trackSwitch: trackSwitch, contiguous: contiguous, duration: duration, accurateTimeOffset: accurateTimeOffset, defaultInitPTS: defaultInitPTS }, data instanceof ArrayBuffer ? [data] : []);
  3902. } else {
  3903. var demuxer = this.demuxer;
  3904. if (demuxer) {
  3905. demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  3906. }
  3907. }
  3908. }
  3909. }, {
  3910. key: 'onWorkerMessage',
  3911. value: function onWorkerMessage(ev) {
  3912. var data = ev.data,
  3913. hls = this.hls;
  3914. switch (data.event) {
  3915. case 'init':
  3916. // revoke the Object URL that was used to create demuxer worker, so as not to leak it
  3917. global.URL.revokeObjectURL(this.w.objectURL);
  3918. break;
  3919. // special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects
  3920. case _events3.default.FRAG_PARSING_DATA:
  3921. data.data.data1 = new Uint8Array(data.data1);
  3922. if (data.data2) {
  3923. data.data.data2 = new Uint8Array(data.data2);
  3924. }
  3925. /* falls through */
  3926. default:
  3927. data.data = data.data || {};
  3928. data.data.frag = this.frag;
  3929. data.data.id = this.id;
  3930. hls.trigger(data.event, data.data);
  3931. break;
  3932. }
  3933. }
  3934. }]);
  3935. return Demuxer;
  3936. }();
  3937. exports.default = Demuxer;
  3938. module.exports = exports['default'];
  3939. /***/ }),
  3940. /* 20 */
  3941. /***/ (function(module, exports, __webpack_require__) {
  3942. "use strict";
  3943. // Copyright Joyent, Inc. and other Node contributors.
  3944. //
  3945. // Permission is hereby granted, free of charge, to any person obtaining a
  3946. // copy of this software and associated documentation files (the
  3947. // "Software"), to deal in the Software without restriction, including
  3948. // without limitation the rights to use, copy, modify, merge, publish,
  3949. // distribute, sublicense, and/or sell copies of the Software, and to permit
  3950. // persons to whom the Software is furnished to do so, subject to the
  3951. // following conditions:
  3952. //
  3953. // The above copyright notice and this permission notice shall be included
  3954. // in all copies or substantial portions of the Software.
  3955. //
  3956. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3957. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3958. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  3959. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  3960. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  3961. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  3962. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  3963. var R = typeof Reflect === 'object' ? Reflect : null
  3964. var ReflectApply = R && typeof R.apply === 'function'
  3965. ? R.apply
  3966. : function ReflectApply(target, receiver, args) {
  3967. return Function.prototype.apply.call(target, receiver, args);
  3968. }
  3969. var ReflectOwnKeys
  3970. if (R && typeof R.ownKeys === 'function') {
  3971. ReflectOwnKeys = R.ownKeys
  3972. } else if (Object.getOwnPropertySymbols) {
  3973. ReflectOwnKeys = function ReflectOwnKeys(target) {
  3974. return Object.getOwnPropertyNames(target)
  3975. .concat(Object.getOwnPropertySymbols(target));
  3976. };
  3977. } else {
  3978. ReflectOwnKeys = function ReflectOwnKeys(target) {
  3979. return Object.getOwnPropertyNames(target);
  3980. };
  3981. }
  3982. function ProcessEmitWarning(warning) {
  3983. if (console && console.warn) console.warn(warning);
  3984. }
  3985. var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
  3986. return value !== value;
  3987. }
  3988. function EventEmitter() {
  3989. EventEmitter.init.call(this);
  3990. }
  3991. module.exports = EventEmitter;
  3992. // Backwards-compat with node 0.10.x
  3993. EventEmitter.EventEmitter = EventEmitter;
  3994. EventEmitter.prototype._events = undefined;
  3995. EventEmitter.prototype._eventsCount = 0;
  3996. EventEmitter.prototype._maxListeners = undefined;
  3997. // By default EventEmitters will print a warning if more than 10 listeners are
  3998. // added to it. This is a useful default which helps finding memory leaks.
  3999. var defaultMaxListeners = 10;
  4000. function checkListener(listener) {
  4001. if (typeof listener !== 'function') {
  4002. throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
  4003. }
  4004. }
  4005. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  4006. enumerable: true,
  4007. get: function() {
  4008. return defaultMaxListeners;
  4009. },
  4010. set: function(arg) {
  4011. if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
  4012. throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
  4013. }
  4014. defaultMaxListeners = arg;
  4015. }
  4016. });
  4017. EventEmitter.init = function() {
  4018. if (this._events === undefined ||
  4019. this._events === Object.getPrototypeOf(this)._events) {
  4020. this._events = Object.create(null);
  4021. this._eventsCount = 0;
  4022. }
  4023. this._maxListeners = this._maxListeners || undefined;
  4024. };
  4025. // Obviously not all Emitters should be limited to 10. This function allows
  4026. // that to be increased. Set to zero for unlimited.
  4027. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  4028. if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
  4029. throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
  4030. }
  4031. this._maxListeners = n;
  4032. return this;
  4033. };
  4034. function _getMaxListeners(that) {
  4035. if (that._maxListeners === undefined)
  4036. return EventEmitter.defaultMaxListeners;
  4037. return that._maxListeners;
  4038. }
  4039. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  4040. return _getMaxListeners(this);
  4041. };
  4042. EventEmitter.prototype.emit = function emit(type) {
  4043. var args = [];
  4044. for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
  4045. var doError = (type === 'error');
  4046. var events = this._events;
  4047. if (events !== undefined)
  4048. doError = (doError && events.error === undefined);
  4049. else if (!doError)
  4050. return false;
  4051. // If there is no 'error' event listener then throw.
  4052. if (doError) {
  4053. var er;
  4054. if (args.length > 0)
  4055. er = args[0];
  4056. if (er instanceof Error) {
  4057. // Note: The comments on the `throw` lines are intentional, they show
  4058. // up in Node's output if this results in an unhandled exception.
  4059. throw er; // Unhandled 'error' event
  4060. }
  4061. // At least give some kind of context to the user
  4062. var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
  4063. err.context = er;
  4064. throw err; // Unhandled 'error' event
  4065. }
  4066. var handler = events[type];
  4067. if (handler === undefined)
  4068. return false;
  4069. if (typeof handler === 'function') {
  4070. ReflectApply(handler, this, args);
  4071. } else {
  4072. var len = handler.length;
  4073. var listeners = arrayClone(handler, len);
  4074. for (var i = 0; i < len; ++i)
  4075. ReflectApply(listeners[i], this, args);
  4076. }
  4077. return true;
  4078. };
  4079. function _addListener(target, type, listener, prepend) {
  4080. var m;
  4081. var events;
  4082. var existing;
  4083. checkListener(listener);
  4084. events = target._events;
  4085. if (events === undefined) {
  4086. events = target._events = Object.create(null);
  4087. target._eventsCount = 0;
  4088. } else {
  4089. // To avoid recursion in the case that type === "newListener"! Before
  4090. // adding it to the listeners, first emit "newListener".
  4091. if (events.newListener !== undefined) {
  4092. target.emit('newListener', type,
  4093. listener.listener ? listener.listener : listener);
  4094. // Re-assign `events` because a newListener handler could have caused the
  4095. // this._events to be assigned to a new object
  4096. events = target._events;
  4097. }
  4098. existing = events[type];
  4099. }
  4100. if (existing === undefined) {
  4101. // Optimize the case of one listener. Don't need the extra array object.
  4102. existing = events[type] = listener;
  4103. ++target._eventsCount;
  4104. } else {
  4105. if (typeof existing === 'function') {
  4106. // Adding the second element, need to change to array.
  4107. existing = events[type] =
  4108. prepend ? [listener, existing] : [existing, listener];
  4109. // If we've already got an array, just append.
  4110. } else if (prepend) {
  4111. existing.unshift(listener);
  4112. } else {
  4113. existing.push(listener);
  4114. }
  4115. // Check for listener leak
  4116. m = _getMaxListeners(target);
  4117. if (m > 0 && existing.length > m && !existing.warned) {
  4118. existing.warned = true;
  4119. // No error code for this since it is a Warning
  4120. // eslint-disable-next-line no-restricted-syntax
  4121. var w = new Error('Possible EventEmitter memory leak detected. ' +
  4122. existing.length + ' ' + String(type) + ' listeners ' +
  4123. 'added. Use emitter.setMaxListeners() to ' +
  4124. 'increase limit');
  4125. w.name = 'MaxListenersExceededWarning';
  4126. w.emitter = target;
  4127. w.type = type;
  4128. w.count = existing.length;
  4129. ProcessEmitWarning(w);
  4130. }
  4131. }
  4132. return target;
  4133. }
  4134. EventEmitter.prototype.addListener = function addListener(type, listener) {
  4135. return _addListener(this, type, listener, false);
  4136. };
  4137. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  4138. EventEmitter.prototype.prependListener =
  4139. function prependListener(type, listener) {
  4140. return _addListener(this, type, listener, true);
  4141. };
  4142. function onceWrapper() {
  4143. if (!this.fired) {
  4144. this.target.removeListener(this.type, this.wrapFn);
  4145. this.fired = true;
  4146. if (arguments.length === 0)
  4147. return this.listener.call(this.target);
  4148. return this.listener.apply(this.target, arguments);
  4149. }
  4150. }
  4151. function _onceWrap(target, type, listener) {
  4152. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  4153. var wrapped = onceWrapper.bind(state);
  4154. wrapped.listener = listener;
  4155. state.wrapFn = wrapped;
  4156. return wrapped;
  4157. }
  4158. EventEmitter.prototype.once = function once(type, listener) {
  4159. checkListener(listener);
  4160. this.on(type, _onceWrap(this, type, listener));
  4161. return this;
  4162. };
  4163. EventEmitter.prototype.prependOnceListener =
  4164. function prependOnceListener(type, listener) {
  4165. checkListener(listener);
  4166. this.prependListener(type, _onceWrap(this, type, listener));
  4167. return this;
  4168. };
  4169. // Emits a 'removeListener' event if and only if the listener was removed.
  4170. EventEmitter.prototype.removeListener =
  4171. function removeListener(type, listener) {
  4172. var list, events, position, i, originalListener;
  4173. checkListener(listener);
  4174. events = this._events;
  4175. if (events === undefined)
  4176. return this;
  4177. list = events[type];
  4178. if (list === undefined)
  4179. return this;
  4180. if (list === listener || list.listener === listener) {
  4181. if (--this._eventsCount === 0)
  4182. this._events = Object.create(null);
  4183. else {
  4184. delete events[type];
  4185. if (events.removeListener)
  4186. this.emit('removeListener', type, list.listener || listener);
  4187. }
  4188. } else if (typeof list !== 'function') {
  4189. position = -1;
  4190. for (i = list.length - 1; i >= 0; i--) {
  4191. if (list[i] === listener || list[i].listener === listener) {
  4192. originalListener = list[i].listener;
  4193. position = i;
  4194. break;
  4195. }
  4196. }
  4197. if (position < 0)
  4198. return this;
  4199. if (position === 0)
  4200. list.shift();
  4201. else {
  4202. spliceOne(list, position);
  4203. }
  4204. if (list.length === 1)
  4205. events[type] = list[0];
  4206. if (events.removeListener !== undefined)
  4207. this.emit('removeListener', type, originalListener || listener);
  4208. }
  4209. return this;
  4210. };
  4211. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  4212. EventEmitter.prototype.removeAllListeners =
  4213. function removeAllListeners(type) {
  4214. var listeners, events, i;
  4215. events = this._events;
  4216. if (events === undefined)
  4217. return this;
  4218. // not listening for removeListener, no need to emit
  4219. if (events.removeListener === undefined) {
  4220. if (arguments.length === 0) {
  4221. this._events = Object.create(null);
  4222. this._eventsCount = 0;
  4223. } else if (events[type] !== undefined) {
  4224. if (--this._eventsCount === 0)
  4225. this._events = Object.create(null);
  4226. else
  4227. delete events[type];
  4228. }
  4229. return this;
  4230. }
  4231. // emit removeListener for all listeners on all events
  4232. if (arguments.length === 0) {
  4233. var keys = Object.keys(events);
  4234. var key;
  4235. for (i = 0; i < keys.length; ++i) {
  4236. key = keys[i];
  4237. if (key === 'removeListener') continue;
  4238. this.removeAllListeners(key);
  4239. }
  4240. this.removeAllListeners('removeListener');
  4241. this._events = Object.create(null);
  4242. this._eventsCount = 0;
  4243. return this;
  4244. }
  4245. listeners = events[type];
  4246. if (typeof listeners === 'function') {
  4247. this.removeListener(type, listeners);
  4248. } else if (listeners !== undefined) {
  4249. // LIFO order
  4250. for (i = listeners.length - 1; i >= 0; i--) {
  4251. this.removeListener(type, listeners[i]);
  4252. }
  4253. }
  4254. return this;
  4255. };
  4256. function _listeners(target, type, unwrap) {
  4257. var events = target._events;
  4258. if (events === undefined)
  4259. return [];
  4260. var evlistener = events[type];
  4261. if (evlistener === undefined)
  4262. return [];
  4263. if (typeof evlistener === 'function')
  4264. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  4265. return unwrap ?
  4266. unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  4267. }
  4268. EventEmitter.prototype.listeners = function listeners(type) {
  4269. return _listeners(this, type, true);
  4270. };
  4271. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  4272. return _listeners(this, type, false);
  4273. };
  4274. EventEmitter.listenerCount = function(emitter, type) {
  4275. if (typeof emitter.listenerCount === 'function') {
  4276. return emitter.listenerCount(type);
  4277. } else {
  4278. return listenerCount.call(emitter, type);
  4279. }
  4280. };
  4281. EventEmitter.prototype.listenerCount = listenerCount;
  4282. function listenerCount(type) {
  4283. var events = this._events;
  4284. if (events !== undefined) {
  4285. var evlistener = events[type];
  4286. if (typeof evlistener === 'function') {
  4287. return 1;
  4288. } else if (evlistener !== undefined) {
  4289. return evlistener.length;
  4290. }
  4291. }
  4292. return 0;
  4293. }
  4294. EventEmitter.prototype.eventNames = function eventNames() {
  4295. return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
  4296. };
  4297. function arrayClone(arr, n) {
  4298. var copy = new Array(n);
  4299. for (var i = 0; i < n; ++i)
  4300. copy[i] = arr[i];
  4301. return copy;
  4302. }
  4303. function spliceOne(list, index) {
  4304. for (; index + 1 < list.length; index++)
  4305. list[index] = list[index + 1];
  4306. list.pop();
  4307. }
  4308. function unwrapListeners(arr) {
  4309. var ret = new Array(arr.length);
  4310. for (var i = 0; i < ret.length; ++i) {
  4311. ret[i] = arr[i].listener || arr[i];
  4312. }
  4313. return ret;
  4314. }
  4315. /***/ }),
  4316. /* 21 */
  4317. /***/ (function(module, exports, __webpack_require__) {
  4318. "use strict";
  4319. Object.defineProperty(exports, "__esModule", {
  4320. value: true
  4321. });
  4322. 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; }; }(); /**
  4323. *
  4324. * inline demuxer: probe fragments and instantiate
  4325. * appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)
  4326. *
  4327. */
  4328. var _events = __webpack_require__(1);
  4329. var _events2 = _interopRequireDefault(_events);
  4330. var _errors = __webpack_require__(2);
  4331. var _decrypter = __webpack_require__(12);
  4332. var _decrypter2 = _interopRequireDefault(_decrypter);
  4333. var _aacdemuxer = __webpack_require__(45);
  4334. var _aacdemuxer2 = _interopRequireDefault(_aacdemuxer);
  4335. var _mp4demuxer = __webpack_require__(16);
  4336. var _mp4demuxer2 = _interopRequireDefault(_mp4demuxer);
  4337. var _tsdemuxer = __webpack_require__(46);
  4338. var _tsdemuxer2 = _interopRequireDefault(_tsdemuxer);
  4339. var _mp3demuxer = __webpack_require__(49);
  4340. var _mp3demuxer2 = _interopRequireDefault(_mp3demuxer);
  4341. var _mp4Remuxer = __webpack_require__(50);
  4342. var _mp4Remuxer2 = _interopRequireDefault(_mp4Remuxer);
  4343. var _passthroughRemuxer = __webpack_require__(53);
  4344. var _passthroughRemuxer2 = _interopRequireDefault(_passthroughRemuxer);
  4345. var _getSelfScope = __webpack_require__(5);
  4346. var _logger = __webpack_require__(0);
  4347. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  4348. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4349. // see https://stackoverflow.com/a/11237259/589493
  4350. var global = (0, _getSelfScope.getSelfScope)(); // safeguard for code that might run both on worker and main thread
  4351. var now = void 0;
  4352. // performance.now() not available on WebWorker, at least on Safari Desktop
  4353. try {
  4354. now = global.performance.now.bind(global.performance);
  4355. } catch (err) {
  4356. _logger.logger.debug('Unable to use Performance API on this environment');
  4357. now = global.Date.now;
  4358. }
  4359. var DemuxerInline = function () {
  4360. function DemuxerInline(observer, typeSupported, config, vendor) {
  4361. _classCallCheck(this, DemuxerInline);
  4362. this.observer = observer;
  4363. this.typeSupported = typeSupported;
  4364. this.config = config;
  4365. this.vendor = vendor;
  4366. }
  4367. _createClass(DemuxerInline, [{
  4368. key: 'destroy',
  4369. value: function destroy() {
  4370. var demuxer = this.demuxer;
  4371. if (demuxer) {
  4372. demuxer.destroy();
  4373. }
  4374. }
  4375. }, {
  4376. key: 'push',
  4377. value: function push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
  4378. var _this = this;
  4379. if (data.byteLength > 0 && decryptdata != null && decryptdata.key != null && decryptdata.method === 'AES-128') {
  4380. var decrypter = this.decrypter;
  4381. if (decrypter == null) {
  4382. decrypter = this.decrypter = new _decrypter2.default(this.observer, this.config);
  4383. }
  4384. var startTime = now();
  4385. decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) {
  4386. var endTime = now();
  4387. _this.observer.trigger(_events2.default.FRAG_DECRYPTED, { stats: { tstart: startTime, tdecrypt: endTime } });
  4388. _this.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  4389. });
  4390. } else {
  4391. this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  4392. }
  4393. }
  4394. }, {
  4395. key: 'pushDecrypted',
  4396. value: function pushDecrypted(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
  4397. var demuxer = this.demuxer;
  4398. if (!demuxer ||
  4399. // in case of continuity change, or track switch
  4400. // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
  4401. // so let's check that current demuxer is still valid
  4402. (discontinuity || trackSwitch) && !this.probe(data)) {
  4403. var observer = this.observer;
  4404. var typeSupported = this.typeSupported;
  4405. var config = this.config;
  4406. // probing order is TS/AAC/MP3/MP4
  4407. var muxConfig = [{ demux: _tsdemuxer2.default, remux: _mp4Remuxer2.default }, { demux: _mp4demuxer2.default, remux: _passthroughRemuxer2.default }, { demux: _aacdemuxer2.default, remux: _mp4Remuxer2.default }, { demux: _mp3demuxer2.default, remux: _mp4Remuxer2.default }];
  4408. // probe for content type
  4409. for (var i = 0, len = muxConfig.length; i < len; i++) {
  4410. var mux = muxConfig[i];
  4411. var probe = mux.demux.probe;
  4412. if (probe(data)) {
  4413. var _remuxer = this.remuxer = new mux.remux(observer, config, typeSupported, this.vendor);
  4414. demuxer = new mux.demux(observer, _remuxer, config, typeSupported);
  4415. this.probe = probe;
  4416. break;
  4417. }
  4418. }
  4419. if (!demuxer) {
  4420. observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' });
  4421. return;
  4422. }
  4423. this.demuxer = demuxer;
  4424. }
  4425. var remuxer = this.remuxer;
  4426. if (discontinuity || trackSwitch) {
  4427. demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration);
  4428. remuxer.resetInitSegment();
  4429. }
  4430. if (discontinuity) {
  4431. demuxer.resetTimeStamp(defaultInitPTS);
  4432. remuxer.resetTimeStamp(defaultInitPTS);
  4433. }
  4434. if (typeof demuxer.setDecryptData === 'function') {
  4435. demuxer.setDecryptData(decryptdata);
  4436. }
  4437. demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);
  4438. }
  4439. }]);
  4440. return DemuxerInline;
  4441. }();
  4442. exports.default = DemuxerInline;
  4443. module.exports = exports['default'];
  4444. /***/ }),
  4445. /* 22 */
  4446. /***/ (function(module, exports, __webpack_require__) {
  4447. "use strict";
  4448. Object.defineProperty(exports, "__esModule", {
  4449. value: true
  4450. });
  4451. exports.getAudioConfig = getAudioConfig;
  4452. exports.isHeaderPattern = isHeaderPattern;
  4453. exports.getHeaderLength = getHeaderLength;
  4454. exports.getFullFrameLength = getFullFrameLength;
  4455. exports.isHeader = isHeader;
  4456. exports.probe = probe;
  4457. exports.initTrackConfig = initTrackConfig;
  4458. exports.getFrameDuration = getFrameDuration;
  4459. exports.parseFrameHeader = parseFrameHeader;
  4460. exports.appendFrame = appendFrame;
  4461. var _logger = __webpack_require__(0);
  4462. var _errors = __webpack_require__(2);
  4463. var _events = __webpack_require__(1);
  4464. var _events2 = _interopRequireDefault(_events);
  4465. var _getSelfScope = __webpack_require__(5);
  4466. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  4467. /**
  4468. * ADTS parser helper
  4469. */
  4470. function getAudioConfig(observer, data, offset, audioCodec) {
  4471. var adtsObjectType = void 0,
  4472. // :int
  4473. adtsSampleingIndex = void 0,
  4474. // :int
  4475. adtsExtensionSampleingIndex = void 0,
  4476. // :int
  4477. adtsChanelConfig = void 0,
  4478. // :int
  4479. config = void 0,
  4480. userAgent = navigator.userAgent.toLowerCase(),
  4481. manifestCodec = audioCodec,
  4482. adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  4483. // byte 2
  4484. adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1;
  4485. adtsSampleingIndex = (data[offset + 2] & 0x3C) >>> 2;
  4486. if (adtsSampleingIndex > adtsSampleingRates.length - 1) {
  4487. observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'invalid ADTS sampling index:' + adtsSampleingIndex });
  4488. return;
  4489. }
  4490. adtsChanelConfig = (data[offset + 2] & 0x01) << 2;
  4491. // byte 3
  4492. adtsChanelConfig |= (data[offset + 3] & 0xC0) >>> 6;
  4493. _logger.logger.log('manifest codec:' + audioCodec + ',ADTS data:type:' + adtsObjectType + ',sampleingIndex:' + adtsSampleingIndex + '[' + adtsSampleingRates[adtsSampleingIndex] + 'Hz],channelConfig:' + adtsChanelConfig);
  4494. // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
  4495. if (/firefox/i.test(userAgent)) {
  4496. if (adtsSampleingIndex >= 6) {
  4497. adtsObjectType = 5;
  4498. config = new Array(4);
  4499. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  4500. // there is a factor 2 between frame sample rate and output sample rate
  4501. // multiply frequency by 2 (see table below, equivalent to substract 3)
  4502. adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
  4503. } else {
  4504. adtsObjectType = 2;
  4505. config = new Array(2);
  4506. adtsExtensionSampleingIndex = adtsSampleingIndex;
  4507. }
  4508. // Android : always use AAC
  4509. } else if (userAgent.indexOf('android') !== -1) {
  4510. adtsObjectType = 2;
  4511. config = new Array(2);
  4512. adtsExtensionSampleingIndex = adtsSampleingIndex;
  4513. } else {
  4514. /* for other browsers (Chrome/Vivaldi/Opera ...)
  4515. always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
  4516. */
  4517. adtsObjectType = 5;
  4518. config = new Array(4);
  4519. // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
  4520. if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSampleingIndex >= 6) {
  4521. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  4522. // there is a factor 2 between frame sample rate and output sample rate
  4523. // multiply frequency by 2 (see table below, equivalent to substract 3)
  4524. adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
  4525. } else {
  4526. // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
  4527. // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
  4528. if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSampleingIndex >= 6 && adtsChanelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChanelConfig === 1) {
  4529. adtsObjectType = 2;
  4530. config = new Array(2);
  4531. }
  4532. adtsExtensionSampleingIndex = adtsSampleingIndex;
  4533. }
  4534. }
  4535. /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  4536. ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
  4537. Audio Profile / Audio Object Type
  4538. 0: Null
  4539. 1: AAC Main
  4540. 2: AAC LC (Low Complexity)
  4541. 3: AAC SSR (Scalable Sample Rate)
  4542. 4: AAC LTP (Long Term Prediction)
  4543. 5: SBR (Spectral Band Replication)
  4544. 6: AAC Scalable
  4545. sampling freq
  4546. 0: 96000 Hz
  4547. 1: 88200 Hz
  4548. 2: 64000 Hz
  4549. 3: 48000 Hz
  4550. 4: 44100 Hz
  4551. 5: 32000 Hz
  4552. 6: 24000 Hz
  4553. 7: 22050 Hz
  4554. 8: 16000 Hz
  4555. 9: 12000 Hz
  4556. 10: 11025 Hz
  4557. 11: 8000 Hz
  4558. 12: 7350 Hz
  4559. 13: Reserved
  4560. 14: Reserved
  4561. 15: frequency is written explictly
  4562. Channel Configurations
  4563. These are the channel configurations:
  4564. 0: Defined in AOT Specifc Config
  4565. 1: 1 channel: front-center
  4566. 2: 2 channels: front-left, front-right
  4567. */
  4568. // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  4569. config[0] = adtsObjectType << 3;
  4570. // samplingFrequencyIndex
  4571. config[0] |= (adtsSampleingIndex & 0x0E) >> 1;
  4572. config[1] |= (adtsSampleingIndex & 0x01) << 7;
  4573. // channelConfiguration
  4574. config[1] |= adtsChanelConfig << 3;
  4575. if (adtsObjectType === 5) {
  4576. // adtsExtensionSampleingIndex
  4577. config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1;
  4578. config[2] = (adtsExtensionSampleingIndex & 0x01) << 7;
  4579. // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
  4580. // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
  4581. config[2] |= 2 << 2;
  4582. config[3] = 0;
  4583. }
  4584. return { config: config, samplerate: adtsSampleingRates[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: 'mp4a.40.' + adtsObjectType, manifestCodec: manifestCodec };
  4585. }
  4586. function isHeaderPattern(data, offset) {
  4587. return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
  4588. }
  4589. function getHeaderLength(data, offset) {
  4590. return data[offset + 1] & 0x01 ? 7 : 9;
  4591. }
  4592. function getFullFrameLength(data, offset) {
  4593. return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;
  4594. }
  4595. function isHeader(data, offset) {
  4596. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  4597. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  4598. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  4599. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  4600. return true;
  4601. }
  4602. return false;
  4603. }
  4604. function probe(data, offset) {
  4605. // same as isHeader but we also check that ADTS frame follows last ADTS frame
  4606. // or end of data is reached
  4607. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  4608. // ADTS header Length
  4609. var headerLength = getHeaderLength(data, offset);
  4610. // ADTS frame Length
  4611. var frameLength = headerLength;
  4612. if (offset + 5 < data.length) {
  4613. frameLength = getFullFrameLength(data, offset);
  4614. }
  4615. var newOffset = offset + frameLength;
  4616. if (newOffset === data.length || newOffset + 1 < data.length && isHeaderPattern(data, newOffset)) {
  4617. return true;
  4618. }
  4619. }
  4620. return false;
  4621. }
  4622. function initTrackConfig(track, observer, data, offset, audioCodec) {
  4623. if (!track.samplerate) {
  4624. var config = getAudioConfig(observer, data, offset, audioCodec);
  4625. track.config = config.config;
  4626. track.samplerate = config.samplerate;
  4627. track.channelCount = config.channelCount;
  4628. track.codec = config.codec;
  4629. track.manifestCodec = config.manifestCodec;
  4630. _logger.logger.log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount);
  4631. }
  4632. }
  4633. function getFrameDuration(samplerate) {
  4634. return 1024 * 90000 / samplerate;
  4635. }
  4636. function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {
  4637. var headerLength = void 0,
  4638. frameLength = void 0,
  4639. stamp = void 0;
  4640. var length = data.length;
  4641. // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  4642. headerLength = getHeaderLength(data, offset);
  4643. // retrieve frame size
  4644. frameLength = getFullFrameLength(data, offset);
  4645. frameLength -= headerLength;
  4646. if (frameLength > 0 && offset + headerLength + frameLength <= length) {
  4647. stamp = pts + frameIndex * frameDuration;
  4648. // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
  4649. return { headerLength: headerLength, frameLength: frameLength, stamp: stamp };
  4650. }
  4651. return undefined;
  4652. }
  4653. function appendFrame(track, data, offset, pts, frameIndex) {
  4654. var frameDuration = getFrameDuration(track.samplerate);
  4655. var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);
  4656. if (header) {
  4657. var stamp = header.stamp;
  4658. var headerLength = header.headerLength;
  4659. var frameLength = header.frameLength;
  4660. // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
  4661. var aacSample = {
  4662. unit: data.subarray(offset + headerLength, offset + headerLength + frameLength),
  4663. pts: stamp,
  4664. dts: stamp
  4665. };
  4666. track.samples.push(aacSample);
  4667. track.len += frameLength;
  4668. return { sample: aacSample, length: frameLength + headerLength };
  4669. }
  4670. return undefined;
  4671. }
  4672. /***/ }),
  4673. /* 23 */
  4674. /***/ (function(module, exports, __webpack_require__) {
  4675. "use strict";
  4676. Object.defineProperty(exports, "__esModule", {
  4677. value: true
  4678. });
  4679. /**
  4680. * MPEG parser helper
  4681. */
  4682. var MpegAudio = {
  4683. BitratesMap: [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
  4684. SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000],
  4685. SamplesCoefficients: [
  4686. // MPEG 2.5
  4687. [0, // Reserved
  4688. 72, // Layer3
  4689. 144, // Layer2
  4690. 12 // Layer1
  4691. ],
  4692. // Reserved
  4693. [0, // Reserved
  4694. 0, // Layer3
  4695. 0, // Layer2
  4696. 0 // Layer1
  4697. ],
  4698. // MPEG 2
  4699. [0, // Reserved
  4700. 72, // Layer3
  4701. 144, // Layer2
  4702. 12 // Layer1
  4703. ],
  4704. // MPEG 1
  4705. [0, // Reserved
  4706. 144, // Layer3
  4707. 144, // Layer2
  4708. 12 // Layer1
  4709. ]],
  4710. BytesInSlot: [0, // Reserved
  4711. 1, // Layer3
  4712. 1, // Layer2
  4713. 4 // Layer1
  4714. ],
  4715. appendFrame: function appendFrame(track, data, offset, pts, frameIndex) {
  4716. // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
  4717. if (offset + 24 > data.length) {
  4718. return undefined;
  4719. }
  4720. var header = this.parseHeader(data, offset);
  4721. if (header && offset + header.frameLength <= data.length) {
  4722. var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
  4723. var stamp = pts + frameIndex * frameDuration;
  4724. var sample = { unit: data.subarray(offset, offset + header.frameLength), pts: stamp, dts: stamp };
  4725. track.config = [];
  4726. track.channelCount = header.channelCount;
  4727. track.samplerate = header.sampleRate;
  4728. track.samples.push(sample);
  4729. track.len += header.frameLength;
  4730. return { sample: sample, length: header.frameLength };
  4731. }
  4732. return undefined;
  4733. },
  4734. parseHeader: function parseHeader(data, offset) {
  4735. var headerB = data[offset + 1] >> 3 & 3;
  4736. var headerC = data[offset + 1] >> 1 & 3;
  4737. var headerE = data[offset + 2] >> 4 & 15;
  4738. var headerF = data[offset + 2] >> 2 & 3;
  4739. var headerG = data[offset + 2] >> 1 & 1;
  4740. if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {
  4741. var columnInBitrates = headerB === 3 ? 3 - headerC : headerC === 3 ? 3 : 4;
  4742. var bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;
  4743. var columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;
  4744. var sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];
  4745. var channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
  4746. var sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];
  4747. var bytesInSlot = MpegAudio.BytesInSlot[headerC];
  4748. var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  4749. var frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot;
  4750. return { sampleRate: sampleRate, channelCount: channelCount, frameLength: frameLength, samplesPerFrame: samplesPerFrame };
  4751. }
  4752. return undefined;
  4753. },
  4754. isHeaderPattern: function isHeaderPattern(data, offset) {
  4755. return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
  4756. },
  4757. isHeader: function isHeader(data, offset) {
  4758. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  4759. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  4760. // More info http://www.mp3-tech.org/programmer/frame_header.html
  4761. if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
  4762. return true;
  4763. }
  4764. return false;
  4765. },
  4766. probe: function probe(data, offset) {
  4767. // same as isHeader but we also check that MPEG frame follows last MPEG frame
  4768. // or end of data is reached
  4769. if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
  4770. // MPEG header Length
  4771. var headerLength = 4;
  4772. // MPEG frame Length
  4773. var header = this.parseHeader(data, offset);
  4774. var frameLength = headerLength;
  4775. if (header && header.frameLength) {
  4776. frameLength = header.frameLength;
  4777. }
  4778. var newOffset = offset + frameLength;
  4779. if (newOffset === data.length || newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset)) {
  4780. return true;
  4781. }
  4782. }
  4783. return false;
  4784. }
  4785. };
  4786. exports.default = MpegAudio;
  4787. module.exports = exports["default"];
  4788. /***/ }),
  4789. /* 24 */
  4790. /***/ (function(module, exports, __webpack_require__) {
  4791. "use strict";
  4792. Object.defineProperty(exports, "__esModule", {
  4793. value: true
  4794. });
  4795. exports.Observer = undefined;
  4796. 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; }; }();
  4797. var _eventemitter = __webpack_require__(54);
  4798. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4799. 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; }
  4800. 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; }
  4801. /**
  4802. * @class
  4803. *
  4804. * Simple adapter sub-class of Nodejs-like EventEmitter.
  4805. *
  4806. * We simply want to pass along the event-name itself
  4807. * in every call to a handler, which is the purpose of our `trigger` method
  4808. * extending the standard API.
  4809. *
  4810. */
  4811. var Observer = exports.Observer = function (_EventEmitter) {
  4812. _inherits(Observer, _EventEmitter);
  4813. function Observer() {
  4814. _classCallCheck(this, Observer);
  4815. return _possibleConstructorReturn(this, (Observer.__proto__ || Object.getPrototypeOf(Observer)).apply(this, arguments));
  4816. }
  4817. _createClass(Observer, [{
  4818. key: 'trigger',
  4819. /**
  4820. *
  4821. * @param {string} event
  4822. * @param {any} data
  4823. */
  4824. value: function trigger(event) {
  4825. for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4826. data[_key - 1] = arguments[_key];
  4827. }
  4828. this.emit.apply(this, [event, event].concat(data));
  4829. }
  4830. }]);
  4831. return Observer;
  4832. }(_eventemitter.EventEmitter);
  4833. /***/ }),
  4834. /* 25 */
  4835. /***/ (function(module, exports, __webpack_require__) {
  4836. "use strict";
  4837. Object.defineProperty(exports, "__esModule", {
  4838. value: true
  4839. });
  4840. /**
  4841. * TimeRanges to string helper
  4842. */
  4843. var TimeRanges = {
  4844. toString: function toString(r) {
  4845. var log = '',
  4846. len = r.length;
  4847. for (var i = 0; i < len; i++) {
  4848. log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';
  4849. }
  4850. return log;
  4851. }
  4852. };
  4853. exports.default = TimeRanges;
  4854. module.exports = exports['default'];
  4855. /***/ }),
  4856. /* 26 */
  4857. /***/ (function(module, exports, __webpack_require__) {
  4858. "use strict";
  4859. Object.defineProperty(exports, "__esModule", {
  4860. value: true
  4861. });
  4862. exports.findFirstFragWithCC = findFirstFragWithCC;
  4863. exports.findFragWithCC = findFragWithCC;
  4864. exports.shouldAlignOnDiscontinuities = shouldAlignOnDiscontinuities;
  4865. exports.findDiscontinuousReferenceFrag = findDiscontinuousReferenceFrag;
  4866. exports.adjustPts = adjustPts;
  4867. exports.alignStream = alignStream;
  4868. exports.alignDiscontinuities = alignDiscontinuities;
  4869. exports.alignPDT = alignPDT;
  4870. var _binarySearch = __webpack_require__(9);
  4871. var _binarySearch2 = _interopRequireDefault(_binarySearch);
  4872. var _logger = __webpack_require__(0);
  4873. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  4874. function findFirstFragWithCC(fragments, cc) {
  4875. var firstFrag = null;
  4876. for (var i = 0; i < fragments.length; i += 1) {
  4877. var currentFrag = fragments[i];
  4878. if (currentFrag && currentFrag.cc === cc) {
  4879. firstFrag = currentFrag;
  4880. break;
  4881. }
  4882. }
  4883. return firstFrag;
  4884. }
  4885. function findFragWithCC(fragments, CC) {
  4886. return _binarySearch2.default.search(fragments, function (candidate) {
  4887. if (candidate.cc < CC) {
  4888. return 1;
  4889. } else if (candidate.cc > CC) {
  4890. return -1;
  4891. } else {
  4892. return 0;
  4893. }
  4894. });
  4895. }
  4896. function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {
  4897. var shouldAlign = false;
  4898. if (lastLevel && lastLevel.details && details) {
  4899. if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
  4900. shouldAlign = true;
  4901. }
  4902. }
  4903. return shouldAlign;
  4904. }
  4905. // Find the first frag in the previous level which matches the CC of the first frag of the new level
  4906. function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
  4907. var prevFrags = prevDetails.fragments;
  4908. var curFrags = curDetails.fragments;
  4909. if (!curFrags.length || !prevFrags.length) {
  4910. _logger.logger.log('No fragments to align');
  4911. return;
  4912. }
  4913. var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
  4914. if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
  4915. _logger.logger.log('No frag in previous level to align on');
  4916. return;
  4917. }
  4918. return prevStartFrag;
  4919. }
  4920. function adjustPts(sliding, details) {
  4921. details.fragments.forEach(function (frag) {
  4922. if (frag) {
  4923. var start = frag.start + sliding;
  4924. frag.start = frag.startPTS = start;
  4925. frag.endPTS = start + frag.duration;
  4926. }
  4927. });
  4928. details.PTSKnown = true;
  4929. }
  4930. /**
  4931. * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
  4932. * contiguous stream with the last fragments.
  4933. * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
  4934. * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
  4935. * and an extra download.
  4936. * @param lastFrag
  4937. * @param lastLevel
  4938. * @param details
  4939. */
  4940. function alignStream(lastFrag, lastLevel, details) {
  4941. alignDiscontinuities(lastFrag, details, lastLevel);
  4942. if (!details.PTSKnown && lastLevel) {
  4943. // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
  4944. // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
  4945. // discontinuity sequence.
  4946. alignPDT(details, lastLevel.details);
  4947. }
  4948. }
  4949. /**
  4950. * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
  4951. * discontinuity sequence.
  4952. * @param lastLevel - The details of the last loaded level
  4953. * @param details - The details of the new level
  4954. */
  4955. function alignDiscontinuities(lastFrag, details, lastLevel) {
  4956. if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {
  4957. var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);
  4958. if (referenceFrag) {
  4959. _logger.logger.log('Adjusting PTS using last level due to CC increase within current level');
  4960. adjustPts(referenceFrag.start, details);
  4961. }
  4962. }
  4963. }
  4964. /**
  4965. * Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.
  4966. * @param details - The details of the new level
  4967. * @param lastDetails - The details of the last loaded level
  4968. */
  4969. function alignPDT(details, lastDetails) {
  4970. if (lastDetails && lastDetails.fragments.length) {
  4971. if (!details.hasProgramDateTime || !lastDetails.hasProgramDateTime) {
  4972. return;
  4973. }
  4974. // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM
  4975. // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM
  4976. // then we can deduce that playlist B sliding is 1000+8 = 1008s
  4977. var lastPDT = lastDetails.fragments[0].programDateTime;
  4978. var newPDT = details.fragments[0].programDateTime;
  4979. // date diff is in ms. frag.start is in seconds
  4980. var sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;
  4981. if (Number.isFinite(sliding)) {
  4982. _logger.logger.log('adjusting PTS using programDateTime delta, sliding:' + sliding.toFixed(3));
  4983. adjustPts(sliding, details);
  4984. }
  4985. }
  4986. }
  4987. /***/ }),
  4988. /* 27 */
  4989. /***/ (function(module, exports, __webpack_require__) {
  4990. "use strict";
  4991. Object.defineProperty(exports, "__esModule", {
  4992. value: true
  4993. });
  4994. exports.findFragmentByPDT = findFragmentByPDT;
  4995. exports.findFragmentByPTS = findFragmentByPTS;
  4996. exports.fragmentWithinToleranceTest = fragmentWithinToleranceTest;
  4997. exports.pdtWithinToleranceTest = pdtWithinToleranceTest;
  4998. var _binarySearch = __webpack_require__(9);
  4999. var _binarySearch2 = _interopRequireDefault(_binarySearch);
  5000. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5001. /**
  5002. * Returns first fragment whose endPdt value exceeds the given PDT.
  5003. * @param {Array<Fragment>} fragments - The array of candidate fragments
  5004. * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded
  5005. * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  5006. * @returns {*|null} fragment - The best matching fragment
  5007. */
  5008. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  5009. if (!Array.isArray(fragments) || !fragments.length || !Number.isFinite(PDTValue)) {
  5010. return null;
  5011. }
  5012. // if less than start
  5013. if (PDTValue < fragments[0].programDateTime) {
  5014. return null;
  5015. }
  5016. if (PDTValue >= fragments[fragments.length - 1].endProgramDateTime) {
  5017. return null;
  5018. }
  5019. maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
  5020. for (var seg = 0; seg < fragments.length; ++seg) {
  5021. var frag = fragments[seg];
  5022. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  5023. return frag;
  5024. }
  5025. }
  5026. return null;
  5027. }
  5028. /**
  5029. * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
  5030. * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
  5031. * breaking any traps which would cause the same fragment to be continuously selected within a small range.
  5032. * @param {*} fragPrevious - The last frag successfully appended
  5033. * @param {Array<Fragment>} fragments - The array of candidate fragments
  5034. * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within
  5035. * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  5036. * @returns {*} foundFrag - The best matching fragment
  5037. */
  5038. function findFragmentByPTS(fragPrevious, fragments) {
  5039. var bufferEnd = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  5040. var maxFragLookUpTolerance = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  5041. var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : null;
  5042. // Prefer the next fragment if it's within tolerance
  5043. if (fragNext && !fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) {
  5044. return fragNext;
  5045. }
  5046. return _binarySearch2.default.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  5047. }
  5048. /**
  5049. * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
  5050. * @param {*} candidate - The fragment to test
  5051. * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within
  5052. * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
  5053. * @returns {number} - 0 if it matches, 1 if too low, -1 if too high
  5054. */
  5055. function fragmentWithinToleranceTest() {
  5056. var bufferEnd = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  5057. var maxFragLookUpTolerance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  5058. var candidate = arguments[2];
  5059. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  5060. // this is to cope with situations like
  5061. // bufferEnd = 9.991
  5062. // frag[Ø] : [0,10]
  5063. // frag[1] : [10,20]
  5064. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  5065. // frag start frag start+duration
  5066. // |-----------------------------|
  5067. // <---> <--->
  5068. // ...--------><-----------------------------><---------....
  5069. // previous frag matching fragment next frag
  5070. // return -1 return 0 return 1
  5071. // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  5072. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  5073. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  5074. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  5075. return 1;
  5076. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  5077. // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  5078. return -1;
  5079. }
  5080. return 0;
  5081. }
  5082. /**
  5083. * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
  5084. * This function tests the candidate's program date time values, as represented in Unix time
  5085. * @param {*} candidate - The fragment to test
  5086. * @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range
  5087. * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
  5088. * @returns {boolean} True if contiguous, false otherwise
  5089. */
  5090. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  5091. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;
  5092. return candidate.endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  5093. }
  5094. /***/ }),
  5095. /* 28 */
  5096. /***/ (function(module, exports, __webpack_require__) {
  5097. "use strict";
  5098. Object.defineProperty(exports, "__esModule", {
  5099. value: true
  5100. });
  5101. 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; }; }();
  5102. var _eventHandler = __webpack_require__(3);
  5103. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  5104. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5105. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5106. 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; }
  5107. 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; }
  5108. /**
  5109. * Sub-class specialization of EventHandler base class.
  5110. *
  5111. * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
  5112. * scheduled asynchroneously, avoiding recursive calls in the same tick.
  5113. *
  5114. * The task itself is implemented in `doTick`. It can be requested and called for single execution
  5115. * using the `tick` method.
  5116. *
  5117. * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
  5118. * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
  5119. *
  5120. * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
  5121. * and cancelled with `clearNextTick`.
  5122. *
  5123. * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
  5124. *
  5125. * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
  5126. *
  5127. * Further explanations:
  5128. *
  5129. * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
  5130. * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
  5131. *
  5132. * When the task execution (`tick` method) is called in re-entrant way this is detected and
  5133. * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
  5134. * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
  5135. */
  5136. var TaskLoop = function (_EventHandler) {
  5137. _inherits(TaskLoop, _EventHandler);
  5138. function TaskLoop(hls) {
  5139. var _ref;
  5140. _classCallCheck(this, TaskLoop);
  5141. for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  5142. events[_key - 1] = arguments[_key];
  5143. }
  5144. var _this = _possibleConstructorReturn(this, (_ref = TaskLoop.__proto__ || Object.getPrototypeOf(TaskLoop)).call.apply(_ref, [this, hls].concat(events)));
  5145. _this._tickInterval = null;
  5146. _this._tickTimer = null;
  5147. _this._tickCallCount = 0;
  5148. _this._boundTick = _this.tick.bind(_this);
  5149. return _this;
  5150. }
  5151. /**
  5152. * @override
  5153. */
  5154. _createClass(TaskLoop, [{
  5155. key: 'onHandlerDestroying',
  5156. value: function onHandlerDestroying() {
  5157. // clear all timers before unregistering from event bus
  5158. this.clearNextTick();
  5159. this.clearInterval();
  5160. }
  5161. /**
  5162. * @returns {boolean}
  5163. */
  5164. }, {
  5165. key: 'hasInterval',
  5166. value: function hasInterval() {
  5167. return !!this._tickInterval;
  5168. }
  5169. /**
  5170. * @returns {boolean}
  5171. */
  5172. }, {
  5173. key: 'hasNextTick',
  5174. value: function hasNextTick() {
  5175. return !!this._tickTimer;
  5176. }
  5177. /**
  5178. * @param {number} millis Interval time (ms)
  5179. * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)
  5180. */
  5181. }, {
  5182. key: 'setInterval',
  5183. value: function (_setInterval) {
  5184. function setInterval(_x) {
  5185. return _setInterval.apply(this, arguments);
  5186. }
  5187. setInterval.toString = function () {
  5188. return _setInterval.toString();
  5189. };
  5190. return setInterval;
  5191. }(function (millis) {
  5192. if (!this._tickInterval) {
  5193. this._tickInterval = setInterval(this._boundTick, millis);
  5194. return true;
  5195. }
  5196. return false;
  5197. })
  5198. /**
  5199. * @returns {boolean} True when interval was cleared, false when none was set (no effect)
  5200. */
  5201. }, {
  5202. key: 'clearInterval',
  5203. value: function (_clearInterval) {
  5204. function clearInterval() {
  5205. return _clearInterval.apply(this, arguments);
  5206. }
  5207. clearInterval.toString = function () {
  5208. return _clearInterval.toString();
  5209. };
  5210. return clearInterval;
  5211. }(function () {
  5212. if (this._tickInterval) {
  5213. clearInterval(this._tickInterval);
  5214. this._tickInterval = null;
  5215. return true;
  5216. }
  5217. return false;
  5218. })
  5219. /**
  5220. * @returns {boolean} True when timeout was cleared, false when none was set (no effect)
  5221. */
  5222. }, {
  5223. key: 'clearNextTick',
  5224. value: function clearNextTick() {
  5225. if (this._tickTimer) {
  5226. clearTimeout(this._tickTimer);
  5227. this._tickTimer = null;
  5228. return true;
  5229. }
  5230. return false;
  5231. }
  5232. /**
  5233. * Will call the subclass doTick implementation in this main loop tick
  5234. * or in the next one (via setTimeout(,0)) in case it has already been called
  5235. * in this tick (in case this is a re-entrant call).
  5236. */
  5237. }, {
  5238. key: 'tick',
  5239. value: function tick() {
  5240. this._tickCallCount++;
  5241. if (this._tickCallCount === 1) {
  5242. this.doTick();
  5243. // re-entrant call to tick from previous doTick call stack
  5244. // -> schedule a call on the next main loop iteration to process this task processing request
  5245. if (this._tickCallCount > 1) {
  5246. // make sure only one timer exists at any time at max
  5247. this.clearNextTick();
  5248. this._tickTimer = setTimeout(this._boundTick, 0);
  5249. }
  5250. this._tickCallCount = 0;
  5251. }
  5252. }
  5253. /**
  5254. * For subclass to implement task logic
  5255. * @abstract
  5256. */
  5257. }, {
  5258. key: 'doTick',
  5259. value: function doTick() {}
  5260. }]);
  5261. return TaskLoop;
  5262. }(_eventHandler2.default);
  5263. exports.default = TaskLoop;
  5264. module.exports = exports['default'];
  5265. /***/ }),
  5266. /* 29 */
  5267. /***/ (function(module, exports, __webpack_require__) {
  5268. "use strict";
  5269. Object.defineProperty(exports, "__esModule", {
  5270. value: true
  5271. });
  5272. exports.sendAddTrackEvent = sendAddTrackEvent;
  5273. exports.clearCurrentCues = clearCurrentCues;
  5274. function sendAddTrackEvent(track, videoEl) {
  5275. var event = null;
  5276. try {
  5277. event = new window.Event('addtrack');
  5278. } catch (err) {
  5279. // for IE11
  5280. event = document.createEvent('Event');
  5281. event.initEvent('addtrack', false, false);
  5282. }
  5283. event.track = track;
  5284. videoEl.dispatchEvent(event);
  5285. }
  5286. function clearCurrentCues(track) {
  5287. if (track && track.cues) {
  5288. while (track.cues.length > 0) {
  5289. track.removeCue(track.cues[0]);
  5290. }
  5291. }
  5292. }
  5293. /***/ }),
  5294. /* 30 */
  5295. /***/ (function(module, exports, __webpack_require__) {
  5296. "use strict";
  5297. Object.defineProperty(exports, "__esModule", {
  5298. value: true
  5299. });
  5300. exports.fixLineBreaks = undefined;
  5301. var _vttcue = __webpack_require__(71);
  5302. var _vttcue2 = _interopRequireDefault(_vttcue);
  5303. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5304. var StringDecoder = function StringDecoder() {
  5305. return {
  5306. decode: function decode(data) {
  5307. if (!data) {
  5308. return '';
  5309. }
  5310. if (typeof data !== 'string') {
  5311. throw new Error('Error - expected string data.');
  5312. }
  5313. return decodeURIComponent(encodeURIComponent(data));
  5314. }
  5315. };
  5316. }; /*
  5317. * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js#L1716
  5318. */
  5319. function VTTParser() {
  5320. this.window = window;
  5321. this.state = 'INITIAL';
  5322. this.buffer = '';
  5323. this.decoder = new StringDecoder();
  5324. this.regionList = [];
  5325. }
  5326. // Try to parse input as a time stamp.
  5327. function parseTimeStamp(input) {
  5328. function computeSeconds(h, m, s, f) {
  5329. return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
  5330. }
  5331. var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);
  5332. if (!m) {
  5333. return null;
  5334. }
  5335. if (m[3]) {
  5336. // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
  5337. return computeSeconds(m[1], m[2], m[3].replace(':', ''), m[4]);
  5338. } else if (m[1] > 59) {
  5339. // Timestamp takes the form of [hours]:[minutes].[milliseconds]
  5340. // First position is hours as it's over 59.
  5341. return computeSeconds(m[1], m[2], 0, m[4]);
  5342. } else {
  5343. // Timestamp takes the form of [minutes]:[seconds].[milliseconds]
  5344. return computeSeconds(0, m[1], m[2], m[4]);
  5345. }
  5346. }
  5347. // A settings object holds key/value pairs and will ignore anything but the first
  5348. // assignment to a specific key.
  5349. function Settings() {
  5350. this.values = Object.create(null);
  5351. }
  5352. Settings.prototype = {
  5353. // Only accept the first assignment to any key.
  5354. set: function set(k, v) {
  5355. if (!this.get(k) && v !== '') {
  5356. this.values[k] = v;
  5357. }
  5358. },
  5359. // Return the value for a key, or a default value.
  5360. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  5361. // a number of possible default values as properties where 'defaultKey' is
  5362. // the key of the property that will be chosen; otherwise it's assumed to be
  5363. // a single value.
  5364. get: function get(k, dflt, defaultKey) {
  5365. if (defaultKey) {
  5366. return this.has(k) ? this.values[k] : dflt[defaultKey];
  5367. }
  5368. return this.has(k) ? this.values[k] : dflt;
  5369. },
  5370. // Check whether we have a value for a key.
  5371. has: function has(k) {
  5372. return k in this.values;
  5373. },
  5374. // Accept a setting if its one of the given alternatives.
  5375. alt: function alt(k, v, a) {
  5376. for (var n = 0; n < a.length; ++n) {
  5377. if (v === a[n]) {
  5378. this.set(k, v);
  5379. break;
  5380. }
  5381. }
  5382. },
  5383. // Accept a setting if its a valid (signed) integer.
  5384. integer: function integer(k, v) {
  5385. if (/^-?\d+$/.test(v)) {
  5386. // integer
  5387. this.set(k, parseInt(v, 10));
  5388. }
  5389. },
  5390. // Accept a setting if its a valid percentage.
  5391. percent: function percent(k, v) {
  5392. var m = void 0;
  5393. if (m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/)) {
  5394. v = parseFloat(v);
  5395. if (v >= 0 && v <= 100) {
  5396. this.set(k, v);
  5397. return true;
  5398. }
  5399. }
  5400. return false;
  5401. }
  5402. };
  5403. // Helper function to parse input into groups separated by 'groupDelim', and
  5404. // interprete each group as a key/value pair separated by 'keyValueDelim'.
  5405. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  5406. var groups = groupDelim ? input.split(groupDelim) : [input];
  5407. for (var i in groups) {
  5408. if (typeof groups[i] !== 'string') {
  5409. continue;
  5410. }
  5411. var kv = groups[i].split(keyValueDelim);
  5412. if (kv.length !== 2) {
  5413. continue;
  5414. }
  5415. var k = kv[0];
  5416. var v = kv[1];
  5417. callback(k, v);
  5418. }
  5419. }
  5420. var defaults = new _vttcue2.default(0, 0, 0);
  5421. // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244
  5422. // Safari doesn't yet support this change, but FF and Chrome do.
  5423. var center = defaults.align === 'middle' ? 'middle' : 'center';
  5424. function parseCue(input, cue, regionList) {
  5425. // Remember the original input if we need to throw an error.
  5426. var oInput = input;
  5427. // 4.1 WebVTT timestamp
  5428. function consumeTimeStamp() {
  5429. var ts = parseTimeStamp(input);
  5430. if (ts === null) {
  5431. throw new Error('Malformed timestamp: ' + oInput);
  5432. }
  5433. // Remove time stamp from input.
  5434. input = input.replace(/^[^\sa-zA-Z-]+/, '');
  5435. return ts;
  5436. }
  5437. // 4.4.2 WebVTT cue settings
  5438. function consumeCueSettings(input, cue) {
  5439. var settings = new Settings();
  5440. parseOptions(input, function (k, v) {
  5441. switch (k) {
  5442. case 'region':
  5443. // Find the last region we parsed with the same region id.
  5444. for (var i = regionList.length - 1; i >= 0; i--) {
  5445. if (regionList[i].id === v) {
  5446. settings.set(k, regionList[i].region);
  5447. break;
  5448. }
  5449. }
  5450. break;
  5451. case 'vertical':
  5452. settings.alt(k, v, ['rl', 'lr']);
  5453. break;
  5454. case 'line':
  5455. var vals = v.split(','),
  5456. vals0 = vals[0];
  5457. settings.integer(k, vals0);
  5458. if (settings.percent(k, vals0)) {
  5459. settings.set('snapToLines', false);
  5460. }
  5461. settings.alt(k, vals0, ['auto']);
  5462. if (vals.length === 2) {
  5463. settings.alt('lineAlign', vals[1], ['start', center, 'end']);
  5464. }
  5465. break;
  5466. case 'position':
  5467. vals = v.split(',');
  5468. settings.percent(k, vals[0]);
  5469. if (vals.length === 2) {
  5470. settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);
  5471. }
  5472. break;
  5473. case 'size':
  5474. settings.percent(k, v);
  5475. break;
  5476. case 'align':
  5477. settings.alt(k, v, ['start', center, 'end', 'left', 'right']);
  5478. break;
  5479. }
  5480. }, /:/, /\s/);
  5481. // Apply default values for any missing fields.
  5482. cue.region = settings.get('region', null);
  5483. cue.vertical = settings.get('vertical', '');
  5484. var line = settings.get('line', 'auto');
  5485. if (line === 'auto' && defaults.line === -1) {
  5486. // set numeric line number for Safari
  5487. line = -1;
  5488. }
  5489. cue.line = line;
  5490. cue.lineAlign = settings.get('lineAlign', 'start');
  5491. cue.snapToLines = settings.get('snapToLines', true);
  5492. cue.size = settings.get('size', 100);
  5493. cue.align = settings.get('align', center);
  5494. var position = settings.get('position', 'auto');
  5495. if (position === 'auto' && defaults.position === 50) {
  5496. // set numeric position for Safari
  5497. position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;
  5498. }
  5499. cue.position = position;
  5500. }
  5501. function skipWhitespace() {
  5502. input = input.replace(/^\s+/, '');
  5503. }
  5504. // 4.1 WebVTT cue timings.
  5505. skipWhitespace();
  5506. cue.startTime = consumeTimeStamp(); // (1) collect cue start time
  5507. skipWhitespace();
  5508. if (input.substr(0, 3) !== '-->') {
  5509. // (3) next characters must match '-->'
  5510. throw new Error('Malformed time stamp (time stamps must be separated by \'-->\'): ' + oInput);
  5511. }
  5512. input = input.substr(3);
  5513. skipWhitespace();
  5514. cue.endTime = consumeTimeStamp(); // (5) collect cue end time
  5515. // 4.1 WebVTT cue settings list.
  5516. skipWhitespace();
  5517. consumeCueSettings(input, cue);
  5518. }
  5519. function fixLineBreaks(input) {
  5520. return input.replace(/<br(?: \/)?>/gi, '\n');
  5521. }
  5522. VTTParser.prototype = {
  5523. parse: function parse(data) {
  5524. var self = this;
  5525. // If there is no data then we won't decode it, but will just try to parse
  5526. // whatever is in buffer already. This may occur in circumstances, for
  5527. // example when flush() is called.
  5528. if (data) {
  5529. // Try to decode the data that we received.
  5530. self.buffer += self.decoder.decode(data, { stream: true });
  5531. }
  5532. function collectNextLine() {
  5533. var buffer = self.buffer;
  5534. var pos = 0;
  5535. buffer = fixLineBreaks(buffer);
  5536. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  5537. ++pos;
  5538. }
  5539. var line = buffer.substr(0, pos);
  5540. // Advance the buffer early in case we fail below.
  5541. if (buffer[pos] === '\r') {
  5542. ++pos;
  5543. }
  5544. if (buffer[pos] === '\n') {
  5545. ++pos;
  5546. }
  5547. self.buffer = buffer.substr(pos);
  5548. return line;
  5549. }
  5550. // 3.2 WebVTT metadata header syntax
  5551. function parseHeader(input) {
  5552. parseOptions(input, function (k, v) {
  5553. switch (k) {
  5554. case 'Region':
  5555. // 3.3 WebVTT region metadata header syntax
  5556. // console.log('parse region', v);
  5557. // parseRegion(v);
  5558. break;
  5559. }
  5560. }, /:/);
  5561. }
  5562. // 5.1 WebVTT file parsing.
  5563. try {
  5564. var line = void 0;
  5565. if (self.state === 'INITIAL') {
  5566. // We can't start parsing until we have the first line.
  5567. if (!/\r\n|\n/.test(self.buffer)) {
  5568. return this;
  5569. }
  5570. line = collectNextLine();
  5571. // strip of UTF-8 BOM if any
  5572. // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
  5573. var m = line.match(/^()?WEBVTT([ \t].*)?$/);
  5574. if (!m || !m[0]) {
  5575. throw new Error('Malformed WebVTT signature.');
  5576. }
  5577. self.state = 'HEADER';
  5578. }
  5579. var alreadyCollectedLine = false;
  5580. while (self.buffer) {
  5581. // We can't parse a line until we have the full line.
  5582. if (!/\r\n|\n/.test(self.buffer)) {
  5583. return this;
  5584. }
  5585. if (!alreadyCollectedLine) {
  5586. line = collectNextLine();
  5587. } else {
  5588. alreadyCollectedLine = false;
  5589. }
  5590. switch (self.state) {
  5591. case 'HEADER':
  5592. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  5593. if (/:/.test(line)) {
  5594. parseHeader(line);
  5595. } else if (!line) {
  5596. // An empty line terminates the header and starts the body (cues).
  5597. self.state = 'ID';
  5598. }
  5599. continue;
  5600. case 'NOTE':
  5601. // Ignore NOTE blocks.
  5602. if (!line) {
  5603. self.state = 'ID';
  5604. }
  5605. continue;
  5606. case 'ID':
  5607. // Check for the start of NOTE blocks.
  5608. if (/^NOTE($|[ \t])/.test(line)) {
  5609. self.state = 'NOTE';
  5610. break;
  5611. }
  5612. // 19-29 - Allow any number of line terminators, then initialize new cue values.
  5613. if (!line) {
  5614. continue;
  5615. }
  5616. self.cue = new _vttcue2.default(0, 0, '');
  5617. self.state = 'CUE';
  5618. // 30-39 - Check if self line contains an optional identifier or timing data.
  5619. if (line.indexOf('-->') === -1) {
  5620. self.cue.id = line;
  5621. continue;
  5622. }
  5623. // Process line as start of a cue.
  5624. /* falls through */
  5625. case 'CUE':
  5626. // 40 - Collect cue timings and settings.
  5627. try {
  5628. parseCue(line, self.cue, self.regionList);
  5629. } catch (e) {
  5630. // In case of an error ignore rest of the cue.
  5631. self.cue = null;
  5632. self.state = 'BADCUE';
  5633. continue;
  5634. }
  5635. self.state = 'CUETEXT';
  5636. continue;
  5637. case 'CUETEXT':
  5638. var hasSubstring = line.indexOf('-->') !== -1;
  5639. // 34 - If we have an empty line then report the cue.
  5640. // 35 - If we have the special substring '-->' then report the cue,
  5641. // but do not collect the line as we need to process the current
  5642. // one as a new cue.
  5643. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  5644. // We are done parsing self cue.
  5645. if (self.oncue) {
  5646. self.oncue(self.cue);
  5647. }
  5648. self.cue = null;
  5649. self.state = 'ID';
  5650. continue;
  5651. }
  5652. if (self.cue.text) {
  5653. self.cue.text += '\n';
  5654. }
  5655. self.cue.text += line;
  5656. continue;
  5657. case 'BADCUE':
  5658. // BADCUE
  5659. // 54-62 - Collect and discard the remaining cue.
  5660. if (!line) {
  5661. self.state = 'ID';
  5662. }
  5663. continue;
  5664. }
  5665. }
  5666. } catch (e) {
  5667. // If we are currently parsing a cue, report what we have.
  5668. if (self.state === 'CUETEXT' && self.cue && self.oncue) {
  5669. self.oncue(self.cue);
  5670. }
  5671. self.cue = null;
  5672. // Enter BADWEBVTT state if header was not parsed correctly otherwise
  5673. // another exception occurred so enter BADCUE state.
  5674. self.state = self.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';
  5675. }
  5676. return this;
  5677. },
  5678. flush: function flush() {
  5679. var self = this;
  5680. try {
  5681. // Finish decoding the stream.
  5682. self.buffer += self.decoder.decode();
  5683. // Synthesize the end of the current cue or region.
  5684. if (self.cue || self.state === 'HEADER') {
  5685. self.buffer += '\n\n';
  5686. self.parse();
  5687. }
  5688. // If we've flushed, parsed, and we're still on the INITIAL state then
  5689. // that means we don't have enough of the stream to parse the first
  5690. // line.
  5691. if (self.state === 'INITIAL') {
  5692. throw new Error('Malformed WebVTT signature.');
  5693. }
  5694. } catch (e) {
  5695. throw e;
  5696. }
  5697. if (self.onflush) {
  5698. self.onflush();
  5699. }
  5700. return this;
  5701. }
  5702. };
  5703. exports.fixLineBreaks = fixLineBreaks;
  5704. exports.default = VTTParser;
  5705. /***/ }),
  5706. /* 31 */
  5707. /***/ (function(module, exports, __webpack_require__) {
  5708. module.exports = __webpack_require__(32);
  5709. /***/ }),
  5710. /* 32 */
  5711. /***/ (function(module, exports, __webpack_require__) {
  5712. "use strict";
  5713. Object.defineProperty(exports, "__esModule", {
  5714. value: true
  5715. });
  5716. 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; }; }();
  5717. 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); } };
  5718. var _xgplayer = __webpack_require__(33);
  5719. var _xgplayer2 = _interopRequireDefault(_xgplayer);
  5720. var _hls = __webpack_require__(34);
  5721. var _hls2 = _interopRequireDefault(_hls);
  5722. var _utils = __webpack_require__(80);
  5723. var _utils2 = _interopRequireDefault(_utils);
  5724. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5725. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5726. 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; }
  5727. 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; }
  5728. var HlsJsPlayer = function (_Player) {
  5729. _inherits(HlsJsPlayer, _Player);
  5730. function HlsJsPlayer(options) {
  5731. _classCallCheck(this, HlsJsPlayer);
  5732. var _this = _possibleConstructorReturn(this, (HlsJsPlayer.__proto__ || Object.getPrototypeOf(HlsJsPlayer)).call(this, options));
  5733. _this.hlsOpts = options.hlsOpts || {};
  5734. var util = _xgplayer2.default.util;
  5735. var player = _this;
  5736. player.once('complete', function () {
  5737. if (player.config.isLive) {
  5738. util.addClass(player.root, 'xgplayer-is-live');
  5739. if (!util.findDom(player.controls, '.xgplayer-live')) {
  5740. var live = util.createDom('xg-live', '正在直播', {}, 'xgplayer-live');
  5741. player.controls.appendChild(live);
  5742. }
  5743. }
  5744. });
  5745. _this.browser = _utils2.default.getBrowserVersion();
  5746. if (player.config.useHls === undefined) {
  5747. if (_xgplayer2.default.sniffer.device === 'mobile' && navigator.platform !== 'MacIntel' && navigator.platform !== 'Win32' || _this.browser.indexOf('Safari') > -1) {
  5748. return _possibleConstructorReturn(_this);
  5749. }
  5750. } else if (!player.config.useHls) {
  5751. return _possibleConstructorReturn(_this);
  5752. }
  5753. Number.isFinite = Number.isFinite || function (value) {
  5754. return typeof value === "number" && isFinite(value);
  5755. };
  5756. var hls = void 0;
  5757. hls = new _hls2.default(_this.hlsOpts);
  5758. _this.hls = hls;
  5759. Object.defineProperty(player, 'src', {
  5760. get: function get() {
  5761. return player.currentSrc;
  5762. },
  5763. set: function set(url) {
  5764. util.removeClass(player.root, 'xgplayer-is-live');
  5765. var liveDom = document.querySelector('.xgplayer-live');
  5766. if (liveDom) {
  5767. liveDom.parentNode.removeChild(liveDom);
  5768. }
  5769. // player.config.url = url
  5770. var paused = player.paused;
  5771. player.hls.stopLoad();
  5772. player.hls.detachMedia();
  5773. player.hls.destroy();
  5774. player.hls = new _hls2.default(player.hlsOpts);
  5775. player.register(url);
  5776. if (!paused) {
  5777. player.pause();
  5778. player.once('pause', function () {
  5779. player.hls.loadSource(url);
  5780. });
  5781. player.once('canplay', function () {
  5782. player.play().catch(function (err) {});
  5783. });
  5784. } else {
  5785. player.hls.loadSource(url);
  5786. }
  5787. player.hls.attachMedia(player.video);
  5788. player.once('canplay', function () {
  5789. player.currentTime = 0;
  5790. });
  5791. },
  5792. configurable: true
  5793. });
  5794. _this.register(_this.config.url);
  5795. _this.once('complete', function () {
  5796. hls.attachMedia(player.video);
  5797. player.once('canplay', function () {
  5798. player.play().catch(function (err) {});
  5799. });
  5800. });
  5801. _this.once('destroy', function () {
  5802. hls.stopLoad();
  5803. });
  5804. return _this;
  5805. }
  5806. _createClass(HlsJsPlayer, [{
  5807. key: 'register',
  5808. value: function register(url) {
  5809. var hls = this.hls;
  5810. var util = _xgplayer2.default.util;
  5811. var player = this;
  5812. hls.on(_hls2.default.Events.MEDIA_ATTACHED, function () {
  5813. hls.loadSource(url);
  5814. });
  5815. hls.on(_hls2.default.Events.LEVEL_LOADED, function (name, e) {
  5816. if (!hls.inited) {
  5817. hls.inited = true;
  5818. if (e && e.details && e.details.live) {
  5819. util.addClass(player.root, 'xgplayer-is-live');
  5820. if (!util.findDom(player.root, '.xgplayer-live')) {
  5821. var live = util.createDom('xg-live', '正在直播', {}, 'xgplayer-live');
  5822. player.controls.appendChild(live);
  5823. }
  5824. }
  5825. }
  5826. });
  5827. hls.on(_hls2.default.Events.ERROR, function (event, data) {
  5828. player.emit('HLS_ERROR', {
  5829. errorType: data.type,
  5830. errorDetails: data.details,
  5831. errorFatal: data.fatal
  5832. });
  5833. if (data.fatal) {
  5834. switch (data.type) {
  5835. case _hls2.default.ErrorTypes.NETWORK_ERROR:
  5836. hls.startLoad();
  5837. break;
  5838. case _hls2.default.ErrorTypes.MEDIA_ERROR:
  5839. hls.recoverMediaError();
  5840. break;
  5841. default:
  5842. player.emit('error', data);
  5843. }
  5844. }
  5845. });
  5846. this._statistics();
  5847. }
  5848. }, {
  5849. key: '_statistics',
  5850. value: function _statistics() {
  5851. var statsInfo = {
  5852. speed: 0,
  5853. playerType: "HlsPlayer"
  5854. };
  5855. var mediainfo = {
  5856. videoDataRate: 0,
  5857. audioDataRate: 0
  5858. };
  5859. var hls = this.hls;
  5860. var player = this;
  5861. hls.on(_hls2.default.Events.FRAG_LOAD_PROGRESS, function (flag, payload) {
  5862. statsInfo.speed = payload.stats.loaded / 1000;
  5863. });
  5864. hls.on(_hls2.default.Events.FRAG_PARSING_DATA, function (flag, payload) {
  5865. if (payload.type === 'video') {
  5866. mediainfo.fps = parseInt(payload.nb / (payload.endPTS - payload.startPTS));
  5867. }
  5868. });
  5869. hls.on(_hls2.default.Events.FRAG_PARSING_INIT_SEGMENT, function (flag, payload) {
  5870. mediainfo.hasAudio = payload.tracks && payload.tracks.audio ? true : false;
  5871. mediainfo.hasVideo = payload.tracks && payload.tracks.audio ? true : false;
  5872. if (mediainfo.hasAudio) {
  5873. var track = payload.tracks.audio;
  5874. mediainfo.audioChannelCount = track.metadata && track.metadata.channelCount ? track.metadata.channelCount : 0;
  5875. mediainfo.audioCodec = track.codec;
  5876. }
  5877. if (mediainfo.hasVideo) {
  5878. var _track = payload.tracks.video;
  5879. mediainfo.videoCodec = _track.codec;
  5880. mediainfo.width = _track.metadata && _track.metadata.width ? _track.metadata.width : 0;
  5881. mediainfo.height = _track.metadata && _track.metadata.height ? _track.metadata.height : 0;
  5882. }
  5883. mediainfo.duration = payload.frag && payload.frag.duration ? payload.frag.duration : 0;
  5884. mediainfo.level = payload.frag && payload.frag.level ? payload.frag.level : 0;
  5885. if (mediainfo.videoCodec || mediainfo.audioCodec) {
  5886. mediainfo.mimeType = 'video/hls; codecs="' + mediainfo.videoCodec + ';' + mediainfo.audioCodec + '"';
  5887. }
  5888. player.mediainfo = mediainfo;
  5889. player.emit("media_info", mediainfo);
  5890. });
  5891. this._statisticsTimmer = setInterval(function () {
  5892. player.emit("statistics_info", statsInfo);
  5893. statsInfo.speed = 0;
  5894. }, 1000);
  5895. }
  5896. }, {
  5897. key: 'destroy',
  5898. value: function destroy() {
  5899. _get(HlsJsPlayer.prototype.__proto__ || Object.getPrototypeOf(HlsJsPlayer.prototype), 'destroy', this).call(this);
  5900. clearInterval(this._statisticsTimmer);
  5901. }
  5902. }]);
  5903. return HlsJsPlayer;
  5904. }(_xgplayer2.default);
  5905. HlsJsPlayer.isSupported = _hls2.default.isSupported;
  5906. exports.default = HlsJsPlayer;
  5907. module.exports = exports['default'];
  5908. /***/ }),
  5909. /* 33 */
  5910. /***/ (function(module, exports) {
  5911. module.exports = __WEBPACK_EXTERNAL_MODULE__33__;
  5912. /***/ }),
  5913. /* 34 */
  5914. /***/ (function(module, exports, __webpack_require__) {
  5915. "use strict";
  5916. Object.defineProperty(exports, "__esModule", {
  5917. value: true
  5918. });
  5919. 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; }; }();
  5920. var _urlToolkit = __webpack_require__(8);
  5921. var URLToolkit = _interopRequireWildcard(_urlToolkit);
  5922. var _errors = __webpack_require__(2);
  5923. var _playlistLoader = __webpack_require__(15);
  5924. var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
  5925. var _fragmentLoader = __webpack_require__(38);
  5926. var _fragmentLoader2 = _interopRequireDefault(_fragmentLoader);
  5927. var _keyLoader = __webpack_require__(39);
  5928. var _keyLoader2 = _interopRequireDefault(_keyLoader);
  5929. var _fragmentTracker = __webpack_require__(6);
  5930. var _streamController = __webpack_require__(40);
  5931. var _streamController2 = _interopRequireDefault(_streamController);
  5932. var _levelController = __webpack_require__(57);
  5933. var _levelController2 = _interopRequireDefault(_levelController);
  5934. var _id3TrackController = __webpack_require__(58);
  5935. var _id3TrackController2 = _interopRequireDefault(_id3TrackController);
  5936. var _isSupported2 = __webpack_require__(59);
  5937. var _logger = __webpack_require__(0);
  5938. var _config = __webpack_require__(60);
  5939. var _events = __webpack_require__(1);
  5940. var _events2 = _interopRequireDefault(_events);
  5941. var _observer = __webpack_require__(24);
  5942. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5943. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  5944. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5945. 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; }
  5946. 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; }
  5947. /**
  5948. * @module Hls
  5949. * @class
  5950. * @constructor
  5951. */
  5952. var Hls = function (_Observer) {
  5953. _inherits(Hls, _Observer);
  5954. _createClass(Hls, null, [{
  5955. key: 'isSupported',
  5956. /**
  5957. * @type {boolean}
  5958. */
  5959. value: function isSupported() {
  5960. return (0, _isSupported2.isSupported)();
  5961. }
  5962. /**
  5963. * @type {HlsEvents}
  5964. */
  5965. }, {
  5966. key: 'version',
  5967. /**
  5968. * @type {string}
  5969. */
  5970. get: function get() {
  5971. return __VERSION__;
  5972. }
  5973. }, {
  5974. key: 'Events',
  5975. get: function get() {
  5976. return _events2.default;
  5977. }
  5978. /**
  5979. * @type {HlsErrorTypes}
  5980. */
  5981. }, {
  5982. key: 'ErrorTypes',
  5983. get: function get() {
  5984. return _errors.ErrorTypes;
  5985. }
  5986. /**
  5987. * @type {HlsErrorDetails}
  5988. */
  5989. }, {
  5990. key: 'ErrorDetails',
  5991. get: function get() {
  5992. return _errors.ErrorDetails;
  5993. }
  5994. /**
  5995. * @type {HlsConfig}
  5996. */
  5997. }, {
  5998. key: 'DefaultConfig',
  5999. get: function get() {
  6000. if (!Hls.defaultConfig) {
  6001. return _config.hlsDefaultConfig;
  6002. }
  6003. return Hls.defaultConfig;
  6004. }
  6005. /**
  6006. * @type {HlsConfig}
  6007. */
  6008. ,
  6009. set: function set(defaultConfig) {
  6010. Hls.defaultConfig = defaultConfig;
  6011. }
  6012. /**
  6013. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  6014. *
  6015. * @constructs Hls
  6016. * @param {HlsConfig} config
  6017. */
  6018. }]);
  6019. function Hls() {
  6020. var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  6021. _classCallCheck(this, Hls);
  6022. var _this = _possibleConstructorReturn(this, (Hls.__proto__ || Object.getPrototypeOf(Hls)).call(this));
  6023. var defaultConfig = Hls.DefaultConfig;
  6024. if ((config.liveSyncDurationCount || config.liveMaxLatencyDurationCount) && (config.liveSyncDuration || config.liveMaxLatencyDuration)) {
  6025. throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');
  6026. }
  6027. for (var prop in defaultConfig) {
  6028. if (prop in config) continue;
  6029. config[prop] = defaultConfig[prop];
  6030. }
  6031. if (config.liveMaxLatencyDurationCount !== undefined && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {
  6032. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');
  6033. }
  6034. if (config.liveMaxLatencyDuration !== undefined && (config.liveMaxLatencyDuration <= config.liveSyncDuration || config.liveSyncDuration === undefined)) {
  6035. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');
  6036. }
  6037. (0, _logger.enableLogs)(config.debug);
  6038. _this.config = config;
  6039. _this._autoLevelCapping = -1;
  6040. // core controllers and network loaders
  6041. /**
  6042. * @member {AbrController} abrController
  6043. */
  6044. var abrController = _this.abrController = new config.abrController(_this);
  6045. var bufferController = new config.bufferController(_this);
  6046. var capLevelController = new config.capLevelController(_this);
  6047. var fpsController = new config.fpsController(_this);
  6048. var playListLoader = new _playlistLoader2.default(_this);
  6049. var fragmentLoader = new _fragmentLoader2.default(_this);
  6050. var keyLoader = new _keyLoader2.default(_this);
  6051. var id3TrackController = new _id3TrackController2.default(_this);
  6052. // network controllers
  6053. /**
  6054. * @member {LevelController} levelController
  6055. */
  6056. var levelController = _this.levelController = new _levelController2.default(_this);
  6057. // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important
  6058. var fragmentTracker = new _fragmentTracker.FragmentTracker(_this);
  6059. /**
  6060. * @member {StreamController} streamController
  6061. */
  6062. var streamController = _this.streamController = new _streamController2.default(_this, fragmentTracker);
  6063. var networkControllers = [levelController, streamController];
  6064. // optional audio stream controller
  6065. /**
  6066. * @var {ICoreComponent | Controller}
  6067. */
  6068. var Controller = config.audioStreamController;
  6069. if (Controller) {
  6070. networkControllers.push(new Controller(_this, fragmentTracker));
  6071. }
  6072. /**
  6073. * @member {INetworkController[]} networkControllers
  6074. */
  6075. _this.networkControllers = networkControllers;
  6076. /**
  6077. * @var {ICoreComponent[]}
  6078. */
  6079. var coreComponents = [playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];
  6080. // optional audio track and subtitle controller
  6081. Controller = config.audioTrackController;
  6082. if (Controller) {
  6083. var audioTrackController = new Controller(_this);
  6084. /**
  6085. * @member {AudioTrackController} audioTrackController
  6086. */
  6087. _this.audioTrackController = audioTrackController;
  6088. coreComponents.push(audioTrackController);
  6089. }
  6090. Controller = config.subtitleTrackController;
  6091. if (Controller) {
  6092. var subtitleTrackController = new Controller(_this);
  6093. /**
  6094. * @member {SubtitleTrackController} subtitleTrackController
  6095. */
  6096. _this.subtitleTrackController = subtitleTrackController;
  6097. networkControllers.push(subtitleTrackController);
  6098. }
  6099. Controller = config.emeController;
  6100. if (Controller) {
  6101. var emeController = new Controller(_this);
  6102. /**
  6103. * @member {EMEController} emeController
  6104. */
  6105. _this.emeController = emeController;
  6106. coreComponents.push(emeController);
  6107. }
  6108. // optional subtitle controllers
  6109. Controller = config.subtitleStreamController;
  6110. if (Controller) {
  6111. networkControllers.push(new Controller(_this, fragmentTracker));
  6112. }
  6113. Controller = config.timelineController;
  6114. if (Controller) {
  6115. coreComponents.push(new Controller(_this));
  6116. }
  6117. /**
  6118. * @member {ICoreComponent[]}
  6119. */
  6120. _this.coreComponents = coreComponents;
  6121. return _this;
  6122. }
  6123. /**
  6124. * Dispose of the instance
  6125. */
  6126. _createClass(Hls, [{
  6127. key: 'destroy',
  6128. value: function destroy() {
  6129. _logger.logger.log('destroy');
  6130. this.trigger(_events2.default.DESTROYING);
  6131. this.detachMedia();
  6132. this.coreComponents.concat(this.networkControllers).forEach(function (component) {
  6133. component.destroy();
  6134. });
  6135. this.url = null;
  6136. this.removeAllListeners();
  6137. this._autoLevelCapping = -1;
  6138. }
  6139. /**
  6140. * Attach a media element
  6141. * @param {HTMLMediaElement} media
  6142. */
  6143. }, {
  6144. key: 'attachMedia',
  6145. value: function attachMedia(media) {
  6146. _logger.logger.log('attachMedia');
  6147. this.media = media;
  6148. this.trigger(_events2.default.MEDIA_ATTACHING, { media: media });
  6149. }
  6150. /**
  6151. * Detach from the media
  6152. */
  6153. }, {
  6154. key: 'detachMedia',
  6155. value: function detachMedia() {
  6156. _logger.logger.log('detachMedia');
  6157. this.trigger(_events2.default.MEDIA_DETACHING);
  6158. this.media = null;
  6159. }
  6160. /**
  6161. * Set the source URL. Can be relative or absolute.
  6162. * @param {string} url
  6163. */
  6164. }, {
  6165. key: 'loadSource',
  6166. value: function loadSource(url) {
  6167. url = URLToolkit.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true });
  6168. _logger.logger.log('loadSource:' + url);
  6169. this.url = url;
  6170. // when attaching to a source URL, trigger a playlist load
  6171. this.trigger(_events2.default.MANIFEST_LOADING, { url: url });
  6172. }
  6173. /**
  6174. * Start loading data from the stream source.
  6175. * Depending on default config, client starts loading automatically when a source is set.
  6176. *
  6177. * @param {number} startPosition Set the start position to stream from
  6178. * @default -1 None (from earliest point)
  6179. */
  6180. }, {
  6181. key: 'startLoad',
  6182. value: function startLoad() {
  6183. var startPosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1;
  6184. _logger.logger.log('startLoad(' + startPosition + ')');
  6185. this.networkControllers.forEach(function (controller) {
  6186. controller.startLoad(startPosition);
  6187. });
  6188. }
  6189. /**
  6190. * Stop loading of any stream data.
  6191. */
  6192. }, {
  6193. key: 'stopLoad',
  6194. value: function stopLoad() {
  6195. _logger.logger.log('stopLoad');
  6196. this.networkControllers.forEach(function (controller) {
  6197. controller.stopLoad();
  6198. });
  6199. }
  6200. /**
  6201. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  6202. */
  6203. }, {
  6204. key: 'swapAudioCodec',
  6205. value: function swapAudioCodec() {
  6206. _logger.logger.log('swapAudioCodec');
  6207. this.streamController.swapAudioCodec();
  6208. }
  6209. /**
  6210. * When the media-element fails, this allows to detach and then re-attach it
  6211. * as one call (convenience method).
  6212. *
  6213. * Automatic recovery of media-errors by this process is configurable.
  6214. */
  6215. }, {
  6216. key: 'recoverMediaError',
  6217. value: function recoverMediaError() {
  6218. _logger.logger.log('recoverMediaError');
  6219. var media = this.media;
  6220. this.detachMedia();
  6221. this.attachMedia(media);
  6222. }
  6223. /**
  6224. * @type {QualityLevel[]}
  6225. */
  6226. }, {
  6227. key: 'levels',
  6228. get: function get() {
  6229. return this.levelController.levels;
  6230. }
  6231. /**
  6232. * Index of quality level currently played
  6233. * @type {number}
  6234. */
  6235. }, {
  6236. key: 'currentLevel',
  6237. get: function get() {
  6238. return this.streamController.currentLevel;
  6239. }
  6240. /**
  6241. * Set quality level index immediately .
  6242. * This will flush the current buffer to replace the quality asap.
  6243. * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.
  6244. * @type {number} -1 for automatic level selection
  6245. */
  6246. ,
  6247. set: function set(newLevel) {
  6248. _logger.logger.log('set currentLevel:' + newLevel);
  6249. this.loadLevel = newLevel;
  6250. this.streamController.immediateLevelSwitch();
  6251. }
  6252. /**
  6253. * Index of next quality level loaded as scheduled by stream controller.
  6254. * @type {number}
  6255. */
  6256. }, {
  6257. key: 'nextLevel',
  6258. get: function get() {
  6259. return this.streamController.nextLevel;
  6260. }
  6261. /**
  6262. * Set quality level index for next loaded data.
  6263. * This will switch the video quality asap, without interrupting playback.
  6264. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  6265. * @type {number} -1 for automatic level selection
  6266. */
  6267. ,
  6268. set: function set(newLevel) {
  6269. _logger.logger.log('set nextLevel:' + newLevel);
  6270. this.levelController.manualLevel = newLevel;
  6271. this.streamController.nextLevelSwitch();
  6272. }
  6273. /**
  6274. * Return the quality level of the currently or last (of none is loaded currently) segment
  6275. * @type {number}
  6276. */
  6277. }, {
  6278. key: 'loadLevel',
  6279. get: function get() {
  6280. return this.levelController.level;
  6281. }
  6282. /**
  6283. * Set quality level index for next loaded data in a conservative way.
  6284. * This will switch the quality without flushing, but interrupt current loading.
  6285. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  6286. * @type {number} newLevel -1 for automatic level selection
  6287. */
  6288. ,
  6289. set: function set(newLevel) {
  6290. _logger.logger.log('set loadLevel:' + newLevel);
  6291. this.levelController.manualLevel = newLevel;
  6292. }
  6293. /**
  6294. * get next quality level loaded
  6295. * @type {number}
  6296. */
  6297. }, {
  6298. key: 'nextLoadLevel',
  6299. get: function get() {
  6300. return this.levelController.nextLoadLevel;
  6301. }
  6302. /**
  6303. * Set quality level of next loaded segment in a fully "non-destructive" way.
  6304. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  6305. * @type {number} level
  6306. */
  6307. ,
  6308. set: function set(level) {
  6309. this.levelController.nextLoadLevel = level;
  6310. }
  6311. /**
  6312. * Return "first level": like a default level, if not set,
  6313. * falls back to index of first level referenced in manifest
  6314. * @type {number}
  6315. */
  6316. }, {
  6317. key: 'firstLevel',
  6318. get: function get() {
  6319. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  6320. }
  6321. /**
  6322. * Sets "first-level", see getter.
  6323. * @type {number}
  6324. */
  6325. ,
  6326. set: function set(newLevel) {
  6327. _logger.logger.log('set firstLevel:' + newLevel);
  6328. this.levelController.firstLevel = newLevel;
  6329. }
  6330. /**
  6331. * Return start level (level of first fragment that will be played back)
  6332. * if not overrided by user, first level appearing in manifest will be used as start level
  6333. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  6334. * (determined from download of first segment)
  6335. * @type {number}
  6336. */
  6337. }, {
  6338. key: 'startLevel',
  6339. get: function get() {
  6340. return this.levelController.startLevel;
  6341. }
  6342. /**
  6343. * set start level (level of first fragment that will be played back)
  6344. * if not overrided by user, first level appearing in manifest will be used as start level
  6345. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  6346. * (determined from download of first segment)
  6347. * @type {number} newLevel
  6348. */
  6349. ,
  6350. set: function set(newLevel) {
  6351. _logger.logger.log('set startLevel:' + newLevel);
  6352. var hls = this;
  6353. // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
  6354. if (newLevel !== -1) {
  6355. newLevel = Math.max(newLevel, hls.minAutoLevel);
  6356. }
  6357. hls.levelController.startLevel = newLevel;
  6358. }
  6359. /**
  6360. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  6361. * @type {number}
  6362. */
  6363. }, {
  6364. key: 'autoLevelCapping',
  6365. get: function get() {
  6366. return this._autoLevelCapping;
  6367. }
  6368. /**
  6369. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  6370. * @type {number}
  6371. */
  6372. ,
  6373. set: function set(newLevel) {
  6374. _logger.logger.log('set autoLevelCapping:' + newLevel);
  6375. this._autoLevelCapping = newLevel;
  6376. }
  6377. /**
  6378. * True when automatic level selection enabled
  6379. * @type {boolean}
  6380. */
  6381. }, {
  6382. key: 'autoLevelEnabled',
  6383. get: function get() {
  6384. return this.levelController.manualLevel === -1;
  6385. }
  6386. /**
  6387. * Level set manually (if any)
  6388. * @type {number}
  6389. */
  6390. }, {
  6391. key: 'manualLevel',
  6392. get: function get() {
  6393. return this.levelController.manualLevel;
  6394. }
  6395. /**
  6396. * min level selectable in auto mode according to config.minAutoBitrate
  6397. * @type {number}
  6398. */
  6399. }, {
  6400. key: 'minAutoLevel',
  6401. get: function get() {
  6402. var hls = this,
  6403. levels = hls.levels,
  6404. minAutoBitrate = hls.config.minAutoBitrate,
  6405. len = levels ? levels.length : 0;
  6406. for (var i = 0; i < len; i++) {
  6407. var levelNextBitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate;
  6408. if (levelNextBitrate > minAutoBitrate) {
  6409. return i;
  6410. }
  6411. }
  6412. return 0;
  6413. }
  6414. /**
  6415. * max level selectable in auto mode according to autoLevelCapping
  6416. * @type {number}
  6417. */
  6418. }, {
  6419. key: 'maxAutoLevel',
  6420. get: function get() {
  6421. var hls = this;
  6422. var levels = hls.levels;
  6423. var autoLevelCapping = hls.autoLevelCapping;
  6424. var maxAutoLevel = void 0;
  6425. if (autoLevelCapping === -1 && levels && levels.length) {
  6426. maxAutoLevel = levels.length - 1;
  6427. } else {
  6428. maxAutoLevel = autoLevelCapping;
  6429. }
  6430. return maxAutoLevel;
  6431. }
  6432. /**
  6433. * next automatically selected quality level
  6434. * @type {number}
  6435. */
  6436. }, {
  6437. key: 'nextAutoLevel',
  6438. get: function get() {
  6439. var hls = this;
  6440. // ensure next auto level is between min and max auto level
  6441. return Math.min(Math.max(hls.abrController.nextAutoLevel, hls.minAutoLevel), hls.maxAutoLevel);
  6442. }
  6443. /**
  6444. * this setter is used to force next auto level.
  6445. * this is useful to force a switch down in auto mode:
  6446. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  6447. * forced value is valid for one fragment. upon succesful frag loading at forced level,
  6448. * this value will be resetted to -1 by ABR controller.
  6449. * @type {number}
  6450. */
  6451. ,
  6452. set: function set(nextLevel) {
  6453. var hls = this;
  6454. hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel);
  6455. }
  6456. /**
  6457. * @type {AudioTrack[]}
  6458. */
  6459. }, {
  6460. key: 'audioTracks',
  6461. get: function get() {
  6462. var audioTrackController = this.audioTrackController;
  6463. return audioTrackController ? audioTrackController.audioTracks : [];
  6464. }
  6465. /**
  6466. * index of the selected audio track (index in audio track lists)
  6467. * @type {number}
  6468. */
  6469. }, {
  6470. key: 'audioTrack',
  6471. get: function get() {
  6472. var audioTrackController = this.audioTrackController;
  6473. return audioTrackController ? audioTrackController.audioTrack : -1;
  6474. }
  6475. /**
  6476. * selects an audio track, based on its index in audio track lists
  6477. * @type {number}
  6478. */
  6479. ,
  6480. set: function set(audioTrackId) {
  6481. var audioTrackController = this.audioTrackController;
  6482. if (audioTrackController) {
  6483. audioTrackController.audioTrack = audioTrackId;
  6484. }
  6485. }
  6486. /**
  6487. * @type {Seconds}
  6488. */
  6489. }, {
  6490. key: 'liveSyncPosition',
  6491. get: function get() {
  6492. return this.streamController.liveSyncPosition;
  6493. }
  6494. /**
  6495. * get alternate subtitle tracks list from playlist
  6496. * @type {SubtitleTrack[]}
  6497. */
  6498. }, {
  6499. key: 'subtitleTracks',
  6500. get: function get() {
  6501. var subtitleTrackController = this.subtitleTrackController;
  6502. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  6503. }
  6504. /**
  6505. * index of the selected subtitle track (index in subtitle track lists)
  6506. * @type {number}
  6507. */
  6508. }, {
  6509. key: 'subtitleTrack',
  6510. get: function get() {
  6511. var subtitleTrackController = this.subtitleTrackController;
  6512. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  6513. }
  6514. /**
  6515. * select an subtitle track, based on its index in subtitle track lists
  6516. * @type{number}
  6517. */
  6518. ,
  6519. set: function set(subtitleTrackId) {
  6520. var subtitleTrackController = this.subtitleTrackController;
  6521. if (subtitleTrackController) {
  6522. subtitleTrackController.subtitleTrack = subtitleTrackId;
  6523. }
  6524. }
  6525. /**
  6526. * @type {boolean}
  6527. */
  6528. }, {
  6529. key: 'subtitleDisplay',
  6530. get: function get() {
  6531. var subtitleTrackController = this.subtitleTrackController;
  6532. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  6533. }
  6534. /**
  6535. * Enable/disable subtitle display rendering
  6536. * @type {boolean}
  6537. */
  6538. ,
  6539. set: function set(value) {
  6540. var subtitleTrackController = this.subtitleTrackController;
  6541. if (subtitleTrackController) {
  6542. subtitleTrackController.subtitleDisplay = value;
  6543. }
  6544. }
  6545. }]);
  6546. return Hls;
  6547. }(_observer.Observer);
  6548. exports.default = Hls;
  6549. module.exports = exports['default'];
  6550. /***/ }),
  6551. /* 35 */
  6552. /***/ (function(module, exports, __webpack_require__) {
  6553. "use strict";
  6554. Object.defineProperty(exports, "__esModule", {
  6555. value: true
  6556. });
  6557. 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; }; }();
  6558. var _urlToolkit = __webpack_require__(8);
  6559. var URLToolkit = _interopRequireWildcard(_urlToolkit);
  6560. var _fragment = __webpack_require__(11);
  6561. var _fragment2 = _interopRequireDefault(_fragment);
  6562. var _level = __webpack_require__(36);
  6563. var _level2 = _interopRequireDefault(_level);
  6564. var _levelKey = __webpack_require__(17);
  6565. var _levelKey2 = _interopRequireDefault(_levelKey);
  6566. var _attrList = __webpack_require__(37);
  6567. var _attrList2 = _interopRequireDefault(_attrList);
  6568. var _logger = __webpack_require__(0);
  6569. var _codecs = __webpack_require__(18);
  6570. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6571. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  6572. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6573. /**
  6574. * M3U8 parser
  6575. * @module
  6576. */
  6577. // https://regex101.com is your friend
  6578. var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g;
  6579. var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  6580. var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  6581. /|(?!#)([\S+ ?]+)/.source, // segment URI, group 3 => the URI (note newline is not eaten)
  6582. /|#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)
  6583. /|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec
  6584. /|#.*/.source // All other non-segment oriented tags will match with all groups empty
  6585. ].join(''), 'g');
  6586. var LEVEL_PLAYLIST_REGEX_SLOW = /(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)([^:]*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/;
  6587. var MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i;
  6588. var M3U8Parser = function () {
  6589. function M3U8Parser() {
  6590. _classCallCheck(this, M3U8Parser);
  6591. }
  6592. _createClass(M3U8Parser, null, [{
  6593. key: 'findGroup',
  6594. value: function findGroup(groups, mediaGroupId) {
  6595. if (!groups) {
  6596. return null;
  6597. }
  6598. var matchingGroup = null;
  6599. for (var i = 0; i < groups.length; i++) {
  6600. var group = groups[i];
  6601. if (group.id === mediaGroupId) {
  6602. matchingGroup = group;
  6603. }
  6604. }
  6605. return matchingGroup;
  6606. }
  6607. }, {
  6608. key: 'convertAVC1ToAVCOTI',
  6609. value: function convertAVC1ToAVCOTI(codec) {
  6610. var result = void 0,
  6611. avcdata = codec.split('.');
  6612. if (avcdata.length > 2) {
  6613. result = avcdata.shift() + '.';
  6614. result += parseInt(avcdata.shift()).toString(16);
  6615. result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
  6616. } else {
  6617. result = codec;
  6618. }
  6619. return result;
  6620. }
  6621. }, {
  6622. key: 'resolve',
  6623. value: function resolve(url, baseUrl) {
  6624. return URLToolkit.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });
  6625. }
  6626. }, {
  6627. key: 'parseMasterPlaylist',
  6628. value: function parseMasterPlaylist(string, baseurl) {
  6629. var levels = [],
  6630. result = void 0;
  6631. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  6632. function setCodecs(codecs, level) {
  6633. ['video', 'audio'].forEach(function (type) {
  6634. var filtered = codecs.filter(function (codec) {
  6635. return (0, _codecs.isCodecType)(codec, type);
  6636. });
  6637. if (filtered.length) {
  6638. var preferred = filtered.filter(function (codec) {
  6639. return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;
  6640. });
  6641. level[type + 'Codec'] = preferred.length > 0 ? preferred[0] : filtered[0];
  6642. // remove from list
  6643. codecs = codecs.filter(function (codec) {
  6644. return filtered.indexOf(codec) === -1;
  6645. });
  6646. }
  6647. });
  6648. level.unknownCodecs = codecs;
  6649. }
  6650. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  6651. var level = {};
  6652. var attrs = level.attrs = new _attrList2.default(result[1]);
  6653. level.url = M3U8Parser.resolve(result[2], baseurl);
  6654. var resolution = attrs.decimalResolution('RESOLUTION');
  6655. if (resolution) {
  6656. level.width = resolution.width;
  6657. level.height = resolution.height;
  6658. }
  6659. level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');
  6660. level.name = attrs.NAME;
  6661. setCodecs([].concat((attrs.CODECS || '').split(/[ ,]+/)), level);
  6662. if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {
  6663. level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);
  6664. }
  6665. levels.push(level);
  6666. }
  6667. return levels;
  6668. }
  6669. }, {
  6670. key: 'parseMasterPlaylistMedia',
  6671. value: function parseMasterPlaylistMedia(string, baseurl, type) {
  6672. var audioGroups = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
  6673. var result = void 0;
  6674. var medias = [];
  6675. var id = 0;
  6676. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  6677. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  6678. var media = {};
  6679. var attrs = new _attrList2.default(result[1]);
  6680. if (attrs.TYPE === type) {
  6681. media.groupId = attrs['GROUP-ID'];
  6682. media.name = attrs.NAME;
  6683. media.type = type;
  6684. media.default = attrs.DEFAULT === 'YES';
  6685. media.autoselect = attrs.AUTOSELECT === 'YES';
  6686. media.forced = attrs.FORCED === 'YES';
  6687. if (attrs.URI) {
  6688. media.url = M3U8Parser.resolve(attrs.URI, baseurl);
  6689. }
  6690. media.lang = attrs.LANGUAGE;
  6691. if (!media.name) {
  6692. media.name = media.lang;
  6693. }
  6694. if (audioGroups.length) {
  6695. var groupCodec = M3U8Parser.findGroup(audioGroups, media.groupId);
  6696. media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec;
  6697. }
  6698. media.id = id++;
  6699. medias.push(media);
  6700. }
  6701. }
  6702. return medias;
  6703. }
  6704. }, {
  6705. key: 'parseLevelPlaylist',
  6706. value: function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) {
  6707. var currentSN = 0;
  6708. var totalduration = 0;
  6709. var level = new _level2.default(baseurl);
  6710. var levelkey = new _levelKey2.default();
  6711. var cc = 0;
  6712. var prevFrag = null;
  6713. var frag = new _fragment2.default();
  6714. var result = void 0;
  6715. var i = void 0;
  6716. var firstPdtIndex = null;
  6717. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  6718. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  6719. var duration = result[1];
  6720. if (duration) {
  6721. // INF
  6722. frag.duration = parseFloat(duration);
  6723. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  6724. var title = (' ' + result[2]).slice(1);
  6725. frag.title = title || null;
  6726. frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
  6727. } else if (result[3]) {
  6728. // url
  6729. if (Number.isFinite(frag.duration)) {
  6730. var sn = currentSN++;
  6731. frag.type = type;
  6732. frag.start = totalduration;
  6733. frag.levelkey = levelkey;
  6734. frag.sn = sn;
  6735. frag.level = id;
  6736. frag.cc = cc;
  6737. frag.urlId = levelUrlId;
  6738. frag.baseurl = baseurl;
  6739. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  6740. frag.relurl = (' ' + result[3]).slice(1);
  6741. assignProgramDateTime(frag, prevFrag);
  6742. level.fragments.push(frag);
  6743. prevFrag = frag;
  6744. totalduration += frag.duration;
  6745. frag = new _fragment2.default();
  6746. }
  6747. } else if (result[4]) {
  6748. // X-BYTERANGE
  6749. frag.rawByteRange = (' ' + result[4]).slice(1);
  6750. if (prevFrag) {
  6751. var lastByteRangeEndOffset = prevFrag.byteRangeEndOffset;
  6752. if (lastByteRangeEndOffset) {
  6753. frag.lastByteRangeEndOffset = lastByteRangeEndOffset;
  6754. }
  6755. }
  6756. } else if (result[5]) {
  6757. // PROGRAM-DATE-TIME
  6758. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  6759. frag.rawProgramDateTime = (' ' + result[5]).slice(1);
  6760. frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
  6761. if (firstPdtIndex === null) {
  6762. firstPdtIndex = level.fragments.length;
  6763. }
  6764. } else {
  6765. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  6766. for (i = 1; i < result.length; i++) {
  6767. if (result[i] !== undefined) {
  6768. break;
  6769. }
  6770. }
  6771. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  6772. var value1 = (' ' + result[i + 1]).slice(1);
  6773. var value2 = (' ' + result[i + 2]).slice(1);
  6774. switch (result[i]) {
  6775. case '#':
  6776. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  6777. break;
  6778. case 'PLAYLIST-TYPE':
  6779. level.type = value1.toUpperCase();
  6780. break;
  6781. case 'MEDIA-SEQUENCE':
  6782. currentSN = level.startSN = parseInt(value1);
  6783. break;
  6784. case 'TARGETDURATION':
  6785. level.targetduration = parseFloat(value1);
  6786. break;
  6787. case 'VERSION':
  6788. level.version = parseInt(value1);
  6789. break;
  6790. case 'EXTM3U':
  6791. break;
  6792. case 'ENDLIST':
  6793. level.live = false;
  6794. break;
  6795. case 'DIS':
  6796. cc++;
  6797. frag.tagList.push(['DIS']);
  6798. break;
  6799. case 'DISCONTINUITY-SEQ':
  6800. cc = parseInt(value1);
  6801. break;
  6802. case 'KEY':
  6803. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4
  6804. var decryptparams = value1;
  6805. var keyAttrs = new _attrList2.default(decryptparams);
  6806. var decryptmethod = keyAttrs.enumeratedString('METHOD'),
  6807. decrypturi = keyAttrs.URI,
  6808. decryptiv = keyAttrs.hexadecimalInteger('IV');
  6809. if (decryptmethod) {
  6810. levelkey = new _levelKey2.default();
  6811. if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0) {
  6812. levelkey.method = decryptmethod;
  6813. // URI to get the key
  6814. levelkey.baseuri = baseurl;
  6815. levelkey.reluri = decrypturi;
  6816. levelkey.key = null;
  6817. // Initialization Vector (IV)
  6818. levelkey.iv = decryptiv;
  6819. }
  6820. }
  6821. break;
  6822. case 'START':
  6823. var startParams = value1;
  6824. var startAttrs = new _attrList2.default(startParams);
  6825. var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
  6826. // TIME-OFFSET can be 0
  6827. if (Number.isFinite(startTimeOffset)) {
  6828. level.startTimeOffset = startTimeOffset;
  6829. }
  6830. break;
  6831. case 'MAP':
  6832. var mapAttrs = new _attrList2.default(value1);
  6833. frag.relurl = mapAttrs.URI;
  6834. frag.rawByteRange = mapAttrs.BYTERANGE;
  6835. frag.baseurl = baseurl;
  6836. frag.level = id;
  6837. frag.type = type;
  6838. frag.sn = 'initSegment';
  6839. level.initSegment = frag;
  6840. frag = new _fragment2.default();
  6841. frag.rawProgramDateTime = level.initSegment.rawProgramDateTime;
  6842. break;
  6843. default:
  6844. _logger.logger.warn('line parsed but not handled: ' + result);
  6845. break;
  6846. }
  6847. }
  6848. }
  6849. frag = prevFrag;
  6850. // logger.log('found ' + level.fragments.length + ' fragments');
  6851. if (frag && !frag.relurl) {
  6852. level.fragments.pop();
  6853. totalduration -= frag.duration;
  6854. }
  6855. level.totalduration = totalduration;
  6856. level.averagetargetduration = totalduration / level.fragments.length;
  6857. level.endSN = currentSN - 1;
  6858. level.startCC = level.fragments[0] ? level.fragments[0].cc : 0;
  6859. level.endCC = cc;
  6860. if (!level.initSegment && level.fragments.length) {
  6861. // this is a bit lurky but HLS really has no other way to tell us
  6862. // if the fragments are TS or MP4, except if we download them :/
  6863. // but this is to be able to handle SIDX.
  6864. if (level.fragments.every(function (frag) {
  6865. return MP4_REGEX_SUFFIX.test(frag.relurl);
  6866. })) {
  6867. _logger.logger.warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');
  6868. frag = new _fragment2.default();
  6869. frag.relurl = level.fragments[0].relurl;
  6870. frag.baseurl = baseurl;
  6871. frag.level = id;
  6872. frag.type = type;
  6873. frag.sn = 'initSegment';
  6874. level.initSegment = frag;
  6875. level.needSidxRanges = true;
  6876. }
  6877. }
  6878. /**
  6879. * Backfill any missing PDT values
  6880. "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
  6881. one or more Media Segment URIs, the client SHOULD extrapolate
  6882. backward from that tag (using EXTINF durations and/or media
  6883. timestamps) to associate dates with those segments."
  6884. * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
  6885. * computed.
  6886. */
  6887. if (firstPdtIndex) {
  6888. backfillProgramDateTimes(level.fragments, firstPdtIndex);
  6889. }
  6890. return level;
  6891. }
  6892. }]);
  6893. return M3U8Parser;
  6894. }();
  6895. exports.default = M3U8Parser;
  6896. function backfillProgramDateTimes(fragments, startIndex) {
  6897. var fragPrev = fragments[startIndex];
  6898. for (var i = startIndex - 1; i >= 0; i--) {
  6899. var frag = fragments[i];
  6900. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
  6901. fragPrev = frag;
  6902. }
  6903. }
  6904. function assignProgramDateTime(frag, prevFrag) {
  6905. if (frag.rawProgramDateTime) {
  6906. frag.programDateTime = Date.parse(frag.rawProgramDateTime);
  6907. } else if (prevFrag && prevFrag.programDateTime) {
  6908. frag.programDateTime = prevFrag.endProgramDateTime;
  6909. }
  6910. if (!Number.isFinite(frag.programDateTime)) {
  6911. frag.programDateTime = null;
  6912. frag.rawProgramDateTime = null;
  6913. }
  6914. }
  6915. module.exports = exports['default'];
  6916. /***/ }),
  6917. /* 36 */
  6918. /***/ (function(module, exports, __webpack_require__) {
  6919. "use strict";
  6920. Object.defineProperty(exports, "__esModule", {
  6921. value: true
  6922. });
  6923. 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; }; }();
  6924. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6925. var Level = function () {
  6926. function Level(baseUrl) {
  6927. _classCallCheck(this, Level);
  6928. // Please keep properties in alphabetical order
  6929. this.endCC = 0;
  6930. this.endSN = 0;
  6931. this.fragments = [];
  6932. this.initSegment = null;
  6933. this.live = true;
  6934. this.needSidxRanges = false;
  6935. this.startCC = 0;
  6936. this.startSN = 0;
  6937. this.startTimeOffset = null;
  6938. this.targetduration = 0;
  6939. this.totalduration = 0;
  6940. this.type = null;
  6941. this.url = baseUrl;
  6942. this.version = null;
  6943. }
  6944. _createClass(Level, [{
  6945. key: "hasProgramDateTime",
  6946. get: function get() {
  6947. return !!(this.fragments[0] && Number.isFinite(this.fragments[0].programDateTime));
  6948. }
  6949. }]);
  6950. return Level;
  6951. }();
  6952. exports.default = Level;
  6953. module.exports = exports["default"];
  6954. /***/ }),
  6955. /* 37 */
  6956. /***/ (function(module, exports, __webpack_require__) {
  6957. "use strict";
  6958. Object.defineProperty(exports, "__esModule", {
  6959. value: true
  6960. });
  6961. 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; }; }();
  6962. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6963. var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; // eslint-disable-line no-useless-escape
  6964. var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape
  6965. // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
  6966. var AttrList = function () {
  6967. function AttrList(attrs) {
  6968. _classCallCheck(this, AttrList);
  6969. if (typeof attrs === 'string') {
  6970. attrs = AttrList.parseAttrList(attrs);
  6971. }
  6972. for (var attr in attrs) {
  6973. if (attrs.hasOwnProperty(attr)) {
  6974. this[attr] = attrs[attr];
  6975. }
  6976. }
  6977. }
  6978. _createClass(AttrList, [{
  6979. key: 'decimalInteger',
  6980. value: function decimalInteger(attrName) {
  6981. var intValue = parseInt(this[attrName], 10);
  6982. if (intValue > Number.MAX_SAFE_INTEGER) {
  6983. return Infinity;
  6984. }
  6985. return intValue;
  6986. }
  6987. }, {
  6988. key: 'hexadecimalInteger',
  6989. value: function hexadecimalInteger(attrName) {
  6990. if (this[attrName]) {
  6991. var stringValue = (this[attrName] || '0x').slice(2);
  6992. stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
  6993. var value = new Uint8Array(stringValue.length / 2);
  6994. for (var i = 0; i < stringValue.length / 2; i++) {
  6995. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  6996. }
  6997. return value;
  6998. } else {
  6999. return null;
  7000. }
  7001. }
  7002. }, {
  7003. key: 'hexadecimalIntegerAsNumber',
  7004. value: function hexadecimalIntegerAsNumber(attrName) {
  7005. var intValue = parseInt(this[attrName], 16);
  7006. if (intValue > Number.MAX_SAFE_INTEGER) {
  7007. return Infinity;
  7008. }
  7009. return intValue;
  7010. }
  7011. }, {
  7012. key: 'decimalFloatingPoint',
  7013. value: function decimalFloatingPoint(attrName) {
  7014. return parseFloat(this[attrName]);
  7015. }
  7016. }, {
  7017. key: 'enumeratedString',
  7018. value: function enumeratedString(attrName) {
  7019. return this[attrName];
  7020. }
  7021. }, {
  7022. key: 'decimalResolution',
  7023. value: function decimalResolution(attrName) {
  7024. var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  7025. if (res === null) {
  7026. return undefined;
  7027. }
  7028. return {
  7029. width: parseInt(res[1], 10),
  7030. height: parseInt(res[2], 10)
  7031. };
  7032. }
  7033. }], [{
  7034. key: 'parseAttrList',
  7035. value: function parseAttrList(input) {
  7036. var match = void 0,
  7037. attrs = {};
  7038. ATTR_LIST_REGEX.lastIndex = 0;
  7039. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  7040. var value = match[2],
  7041. quote = '"';
  7042. if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
  7043. value = value.slice(1, -1);
  7044. }
  7045. attrs[match[1]] = value;
  7046. }
  7047. return attrs;
  7048. }
  7049. }]);
  7050. return AttrList;
  7051. }();
  7052. exports.default = AttrList;
  7053. module.exports = exports['default'];
  7054. /***/ }),
  7055. /* 38 */
  7056. /***/ (function(module, exports, __webpack_require__) {
  7057. "use strict";
  7058. Object.defineProperty(exports, "__esModule", {
  7059. value: true
  7060. });
  7061. 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; }; }();
  7062. 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); } };
  7063. var _events = __webpack_require__(1);
  7064. var _events2 = _interopRequireDefault(_events);
  7065. var _eventHandler = __webpack_require__(3);
  7066. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  7067. var _errors = __webpack_require__(2);
  7068. var _logger = __webpack_require__(0);
  7069. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  7070. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7071. 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; }
  7072. 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; } /*
  7073. * Fragment Loader
  7074. */
  7075. var FragmentLoader = function (_EventHandler) {
  7076. _inherits(FragmentLoader, _EventHandler);
  7077. function FragmentLoader(hls) {
  7078. _classCallCheck(this, FragmentLoader);
  7079. var _this = _possibleConstructorReturn(this, (FragmentLoader.__proto__ || Object.getPrototypeOf(FragmentLoader)).call(this, hls, _events2.default.FRAG_LOADING));
  7080. _this.loaders = {};
  7081. return _this;
  7082. }
  7083. _createClass(FragmentLoader, [{
  7084. key: 'destroy',
  7085. value: function destroy() {
  7086. var loaders = this.loaders;
  7087. for (var loaderName in loaders) {
  7088. var loader = loaders[loaderName];
  7089. if (loader) {
  7090. loader.destroy();
  7091. }
  7092. }
  7093. this.loaders = {};
  7094. _get(FragmentLoader.prototype.__proto__ || Object.getPrototypeOf(FragmentLoader.prototype), 'destroy', this).call(this);
  7095. }
  7096. }, {
  7097. key: 'onFragLoading',
  7098. value: function onFragLoading(data) {
  7099. var frag = data.frag,
  7100. type = frag.type,
  7101. loaders = this.loaders,
  7102. config = this.hls.config,
  7103. FragmentILoader = config.fLoader,
  7104. DefaultILoader = config.loader;
  7105. // reset fragment state
  7106. frag.loaded = 0;
  7107. var loader = loaders[type];
  7108. if (loader) {
  7109. _logger.logger.warn('abort previous fragment loader for type: ' + type);
  7110. loader.abort();
  7111. }
  7112. loader = loaders[type] = frag.loader = config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);
  7113. var loaderContext = void 0,
  7114. loaderConfig = void 0,
  7115. loaderCallbacks = void 0;
  7116. loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false };
  7117. var start = frag.byteRangeStartOffset,
  7118. end = frag.byteRangeEndOffset;
  7119. if (Number.isFinite(start) && Number.isFinite(end)) {
  7120. loaderContext.rangeStart = start;
  7121. loaderContext.rangeEnd = end;
  7122. }
  7123. loaderConfig = {
  7124. timeout: config.fragLoadingTimeOut,
  7125. maxRetry: 0,
  7126. retryDelay: 0,
  7127. maxRetryDelay: config.fragLoadingMaxRetryTimeout
  7128. };
  7129. loaderCallbacks = {
  7130. onSuccess: this.loadsuccess.bind(this),
  7131. onError: this.loaderror.bind(this),
  7132. onTimeout: this.loadtimeout.bind(this),
  7133. onProgress: this.loadprogress.bind(this)
  7134. };
  7135. loader.load(loaderContext, loaderConfig, loaderCallbacks);
  7136. }
  7137. }, {
  7138. key: 'loadsuccess',
  7139. value: function loadsuccess(response, stats, context) {
  7140. var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  7141. var payload = response.data,
  7142. frag = context.frag;
  7143. // detach fragment loader on load success
  7144. frag.loader = undefined;
  7145. this.loaders[frag.type] = undefined;
  7146. this.hls.trigger(_events2.default.FRAG_LOADED, { payload: payload, frag: frag, stats: stats, networkDetails: networkDetails });
  7147. }
  7148. }, {
  7149. key: 'loaderror',
  7150. value: function loaderror(response, context) {
  7151. var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  7152. var frag = context.frag;
  7153. var loader = frag.loader;
  7154. if (loader) {
  7155. loader.abort();
  7156. }
  7157. this.loaders[frag.type] = undefined;
  7158. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.FRAG_LOAD_ERROR, fatal: false, frag: context.frag, response: response, networkDetails: networkDetails });
  7159. }
  7160. }, {
  7161. key: 'loadtimeout',
  7162. value: function loadtimeout(stats, context) {
  7163. var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  7164. var frag = context.frag;
  7165. var loader = frag.loader;
  7166. if (loader) {
  7167. loader.abort();
  7168. }
  7169. this.loaders[frag.type] = undefined;
  7170. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag, networkDetails: networkDetails });
  7171. }
  7172. // data will be used for progressive parsing
  7173. }, {
  7174. key: 'loadprogress',
  7175. value: function loadprogress(stats, context, data) {
  7176. var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  7177. // jshint ignore:line
  7178. var frag = context.frag;
  7179. frag.loaded = stats.loaded;
  7180. this.hls.trigger(_events2.default.FRAG_LOAD_PROGRESS, { frag: frag, stats: stats, networkDetails: networkDetails });
  7181. }
  7182. }]);
  7183. return FragmentLoader;
  7184. }(_eventHandler2.default);
  7185. exports.default = FragmentLoader;
  7186. module.exports = exports['default'];
  7187. /***/ }),
  7188. /* 39 */
  7189. /***/ (function(module, exports, __webpack_require__) {
  7190. "use strict";
  7191. Object.defineProperty(exports, "__esModule", {
  7192. value: true
  7193. });
  7194. 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; }; }();
  7195. var _events = __webpack_require__(1);
  7196. var _events2 = _interopRequireDefault(_events);
  7197. var _eventHandler = __webpack_require__(3);
  7198. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  7199. var _errors = __webpack_require__(2);
  7200. var _logger = __webpack_require__(0);
  7201. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  7202. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7203. 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; }
  7204. 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; } /*
  7205. * Decrypt key Loader
  7206. */
  7207. var KeyLoader = function (_EventHandler) {
  7208. _inherits(KeyLoader, _EventHandler);
  7209. function KeyLoader(hls) {
  7210. _classCallCheck(this, KeyLoader);
  7211. var _this = _possibleConstructorReturn(this, (KeyLoader.__proto__ || Object.getPrototypeOf(KeyLoader)).call(this, hls, _events2.default.KEY_LOADING));
  7212. _this.loaders = {};
  7213. _this.decryptkey = null;
  7214. _this.decrypturl = null;
  7215. return _this;
  7216. }
  7217. _createClass(KeyLoader, [{
  7218. key: 'destroy',
  7219. value: function destroy() {
  7220. for (var loaderName in this.loaders) {
  7221. var loader = this.loaders[loaderName];
  7222. if (loader) {
  7223. loader.destroy();
  7224. }
  7225. }
  7226. this.loaders = {};
  7227. _eventHandler2.default.prototype.destroy.call(this);
  7228. }
  7229. }, {
  7230. key: 'onKeyLoading',
  7231. value: function onKeyLoading(data) {
  7232. var frag = data.frag,
  7233. type = frag.type,
  7234. loader = this.loaders[type],
  7235. decryptdata = frag.decryptdata,
  7236. uri = decryptdata.uri;
  7237. // if uri is different from previous one or if decrypt key not retrieved yet
  7238. if (uri !== this.decrypturl || this.decryptkey === null) {
  7239. var config = this.hls.config;
  7240. if (loader) {
  7241. _logger.logger.warn('abort previous key loader for type:' + type);
  7242. loader.abort();
  7243. }
  7244. frag.loader = this.loaders[type] = new config.loader(config);
  7245. this.decrypturl = uri;
  7246. this.decryptkey = null;
  7247. var loaderContext = void 0,
  7248. loaderConfig = void 0,
  7249. loaderCallbacks = void 0;
  7250. loaderContext = { url: uri, frag: frag, responseType: 'arraybuffer' };
  7251. // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
  7252. // key-loader will trigger an error and rely on stream-controller to handle retry logic.
  7253. // this will also align retry logic with fragment-loader
  7254. loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: 0, retryDelay: config.fragLoadingRetryDelay, maxRetryDelay: config.fragLoadingMaxRetryTimeout };
  7255. loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) };
  7256. frag.loader.load(loaderContext, loaderConfig, loaderCallbacks);
  7257. } else if (this.decryptkey) {
  7258. // we already loaded this key, return it
  7259. decryptdata.key = this.decryptkey;
  7260. this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag });
  7261. }
  7262. }
  7263. }, {
  7264. key: 'loadsuccess',
  7265. value: function loadsuccess(response, stats, context) {
  7266. var frag = context.frag;
  7267. this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data);
  7268. // detach fragment loader on load success
  7269. frag.loader = undefined;
  7270. this.loaders[frag.type] = undefined;
  7271. this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag });
  7272. }
  7273. }, {
  7274. key: 'loaderror',
  7275. value: function loaderror(response, context) {
  7276. var frag = context.frag,
  7277. loader = frag.loader;
  7278. if (loader) {
  7279. loader.abort();
  7280. }
  7281. this.loaders[context.type] = undefined;
  7282. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: frag, response: response });
  7283. }
  7284. }, {
  7285. key: 'loadtimeout',
  7286. value: function loadtimeout(stats, context) {
  7287. var frag = context.frag,
  7288. loader = frag.loader;
  7289. if (loader) {
  7290. loader.abort();
  7291. }
  7292. this.loaders[context.type] = undefined;
  7293. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_TIMEOUT, fatal: false, frag: frag });
  7294. }
  7295. }]);
  7296. return KeyLoader;
  7297. }(_eventHandler2.default);
  7298. exports.default = KeyLoader;
  7299. module.exports = exports['default'];
  7300. /***/ }),
  7301. /* 40 */
  7302. /***/ (function(module, exports, __webpack_require__) {
  7303. "use strict";
  7304. Object.defineProperty(exports, "__esModule", {
  7305. value: true
  7306. });
  7307. 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; }; }();
  7308. 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); } };
  7309. var _binarySearch = __webpack_require__(9);
  7310. var _binarySearch2 = _interopRequireDefault(_binarySearch);
  7311. var _bufferHelper = __webpack_require__(4);
  7312. var _demuxer = __webpack_require__(19);
  7313. var _demuxer2 = _interopRequireDefault(_demuxer);
  7314. var _events = __webpack_require__(1);
  7315. var _events2 = _interopRequireDefault(_events);
  7316. var _fragmentTracker = __webpack_require__(6);
  7317. var _fragment = __webpack_require__(11);
  7318. var _fragment2 = _interopRequireDefault(_fragment);
  7319. var _playlistLoader = __webpack_require__(15);
  7320. var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
  7321. var _levelHelper = __webpack_require__(7);
  7322. var LevelHelper = _interopRequireWildcard(_levelHelper);
  7323. var _timeRanges = __webpack_require__(25);
  7324. var _timeRanges2 = _interopRequireDefault(_timeRanges);
  7325. var _errors = __webpack_require__(2);
  7326. var _logger = __webpack_require__(0);
  7327. var _discontinuities = __webpack_require__(26);
  7328. var _fragmentFinders = __webpack_require__(27);
  7329. var _gapController = __webpack_require__(56);
  7330. var _gapController2 = _interopRequireDefault(_gapController);
  7331. var _baseStreamController = __webpack_require__(14);
  7332. var _baseStreamController2 = _interopRequireDefault(_baseStreamController);
  7333. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  7334. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  7335. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7336. 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; }
  7337. 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; } /*
  7338. * Stream Controller
  7339. */
  7340. var TICK_INTERVAL = 100; // how often to tick in ms
  7341. var StreamController = function (_BaseStreamController) {
  7342. _inherits(StreamController, _BaseStreamController);
  7343. function StreamController(hls, fragmentTracker) {
  7344. _classCallCheck(this, StreamController);
  7345. var _this = _possibleConstructorReturn(this, (StreamController.__proto__ || Object.getPrototypeOf(StreamController)).call(this, hls, _events2.default.MEDIA_ATTACHED, _events2.default.MEDIA_DETACHING, _events2.default.MANIFEST_LOADING, _events2.default.MANIFEST_PARSED, _events2.default.LEVEL_LOADED, _events2.default.KEY_LOADED, _events2.default.FRAG_LOADED, _events2.default.FRAG_LOAD_EMERGENCY_ABORTED, _events2.default.FRAG_PARSING_INIT_SEGMENT, _events2.default.FRAG_PARSING_DATA, _events2.default.FRAG_PARSED, _events2.default.ERROR, _events2.default.AUDIO_TRACK_SWITCHING, _events2.default.AUDIO_TRACK_SWITCHED, _events2.default.BUFFER_CREATED, _events2.default.BUFFER_APPENDED, _events2.default.BUFFER_FLUSHED));
  7346. _this.fragmentTracker = fragmentTracker;
  7347. _this.config = hls.config;
  7348. _this.audioCodecSwap = false;
  7349. _this._state = _baseStreamController.State.STOPPED;
  7350. _this.stallReported = false;
  7351. _this.gapController = null;
  7352. return _this;
  7353. }
  7354. _createClass(StreamController, [{
  7355. key: 'startLoad',
  7356. value: function startLoad(startPosition) {
  7357. if (this.levels) {
  7358. var lastCurrentTime = this.lastCurrentTime,
  7359. hls = this.hls;
  7360. this.stopLoad();
  7361. this.setInterval(TICK_INTERVAL);
  7362. this.level = -1;
  7363. this.fragLoadError = 0;
  7364. if (!this.startFragRequested) {
  7365. // determine load level
  7366. var startLevel = hls.startLevel;
  7367. if (startLevel === -1) {
  7368. // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  7369. startLevel = 0;
  7370. this.bitrateTest = true;
  7371. }
  7372. // set new level to playlist loader : this will trigger start level load
  7373. // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  7374. this.level = hls.nextLoadLevel = startLevel;
  7375. this.loadedmetadata = false;
  7376. }
  7377. // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
  7378. if (lastCurrentTime > 0 && startPosition === -1) {
  7379. _logger.logger.log('override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3));
  7380. startPosition = lastCurrentTime;
  7381. }
  7382. this.state = _baseStreamController.State.IDLE;
  7383. this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
  7384. this.tick();
  7385. } else {
  7386. this.forceStartLoad = true;
  7387. this.state = _baseStreamController.State.STOPPED;
  7388. }
  7389. }
  7390. }, {
  7391. key: 'stopLoad',
  7392. value: function stopLoad() {
  7393. this.forceStartLoad = false;
  7394. _get(StreamController.prototype.__proto__ || Object.getPrototypeOf(StreamController.prototype), 'stopLoad', this).call(this);
  7395. }
  7396. }, {
  7397. key: 'doTick',
  7398. value: function doTick() {
  7399. switch (this.state) {
  7400. case _baseStreamController.State.BUFFER_FLUSHING:
  7401. // in buffer flushing state, reset fragLoadError counter
  7402. this.fragLoadError = 0;
  7403. break;
  7404. case _baseStreamController.State.IDLE:
  7405. this._doTickIdle();
  7406. break;
  7407. case _baseStreamController.State.WAITING_LEVEL:
  7408. var level = this.levels[this.level];
  7409. // check if playlist is already loaded
  7410. if (level && level.details) {
  7411. this.state = _baseStreamController.State.IDLE;
  7412. }
  7413. break;
  7414. case _baseStreamController.State.FRAG_LOADING_WAITING_RETRY:
  7415. var now = window.performance.now();
  7416. var retryDate = this.retryDate;
  7417. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  7418. if (!retryDate || now >= retryDate || this.media && this.media.seeking) {
  7419. _logger.logger.log('mediaController: retryDate reached, switch back to IDLE state');
  7420. this.state = _baseStreamController.State.IDLE;
  7421. }
  7422. break;
  7423. case _baseStreamController.State.ERROR:
  7424. case _baseStreamController.State.STOPPED:
  7425. case _baseStreamController.State.FRAG_LOADING:
  7426. case _baseStreamController.State.PARSING:
  7427. case _baseStreamController.State.PARSED:
  7428. case _baseStreamController.State.ENDED:
  7429. break;
  7430. default:
  7431. break;
  7432. }
  7433. // check buffer
  7434. this._checkBuffer();
  7435. // check/update current fragment
  7436. this._checkFragmentChanged();
  7437. }
  7438. // Ironically the "idle" state is the on we do the most logic in it seems ....
  7439. // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently
  7440. // played segment, or on pause/play/seek instead of naively checking every 100ms?
  7441. }, {
  7442. key: '_doTickIdle',
  7443. value: function _doTickIdle() {
  7444. var hls = this.hls,
  7445. config = hls.config,
  7446. media = this.media;
  7447. // if start level not parsed yet OR
  7448. // if video not attached AND start fragment already requested OR start frag prefetch disable
  7449. // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
  7450. if (this.levelLastLoaded === undefined || !media && (this.startFragRequested || !config.startFragPrefetch)) {
  7451. return;
  7452. }
  7453. // if we have not yet loaded any fragment, start loading from start position
  7454. var pos = void 0;
  7455. if (this.loadedmetadata) {
  7456. pos = media.currentTime;
  7457. } else {
  7458. pos = this.nextLoadPosition;
  7459. }
  7460. // determine next load level
  7461. var level = hls.nextLoadLevel,
  7462. levelInfo = this.levels[level];
  7463. if (!levelInfo) {
  7464. return;
  7465. }
  7466. var levelBitrate = levelInfo.bitrate,
  7467. maxBufLen = void 0;
  7468. // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s
  7469. if (levelBitrate) {
  7470. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  7471. } else {
  7472. maxBufLen = config.maxBufferLength;
  7473. }
  7474. maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);
  7475. // determine next candidate fragment to be loaded, based on current position and end of buffer position
  7476. // ensure up to `config.maxMaxBufferLength` of buffer upfront
  7477. var bufferInfo = _bufferHelper.BufferHelper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, config.maxBufferHole),
  7478. bufferLen = bufferInfo.len;
  7479. // Stay idle if we are still with buffer margins
  7480. if (bufferLen >= maxBufLen) {
  7481. return;
  7482. }
  7483. // if buffer length is less than maxBufLen try to load a new fragment ...
  7484. _logger.logger.trace('buffer length of ' + bufferLen.toFixed(3) + ' is below max of ' + maxBufLen.toFixed(3) + '. checking for more payload ...');
  7485. // set next load level : this will trigger a playlist load if needed
  7486. this.level = hls.nextLoadLevel = level;
  7487. var levelDetails = levelInfo.details;
  7488. // if level info not retrieved yet, switch state and wait for level retrieval
  7489. // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  7490. // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  7491. if (!levelDetails || levelDetails.live && this.levelLastLoaded !== level) {
  7492. this.state = _baseStreamController.State.WAITING_LEVEL;
  7493. return;
  7494. }
  7495. if (this._streamEnded(bufferInfo, levelDetails)) {
  7496. var data = {};
  7497. if (this.altAudio) {
  7498. data.type = 'video';
  7499. }
  7500. this.hls.trigger(_events2.default.BUFFER_EOS, data);
  7501. this.state = _baseStreamController.State.ENDED;
  7502. return;
  7503. }
  7504. // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)
  7505. this._fetchPayloadOrEos(pos, bufferInfo, levelDetails);
  7506. }
  7507. }, {
  7508. key: '_fetchPayloadOrEos',
  7509. value: function _fetchPayloadOrEos(pos, bufferInfo, levelDetails) {
  7510. var fragPrevious = this.fragPrevious,
  7511. level = this.level,
  7512. fragments = levelDetails.fragments,
  7513. fragLen = fragments.length;
  7514. // empty playlist
  7515. if (fragLen === 0) {
  7516. return;
  7517. }
  7518. // find fragment index, contiguous with end of buffer position
  7519. var start = fragments[0].start,
  7520. end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
  7521. bufferEnd = bufferInfo.end,
  7522. frag = void 0;
  7523. if (levelDetails.initSegment && !levelDetails.initSegment.data) {
  7524. frag = levelDetails.initSegment;
  7525. } else {
  7526. // in case of live playlist we need to ensure that requested position is not located before playlist start
  7527. if (levelDetails.live) {
  7528. var initialLiveManifestSize = this.config.initialLiveManifestSize;
  7529. if (fragLen < initialLiveManifestSize) {
  7530. _logger.logger.warn('Can not start playback of a level, reason: not enough fragments ' + fragLen + ' < ' + initialLiveManifestSize);
  7531. return;
  7532. }
  7533. frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen);
  7534. // if it explicitely returns null don't load any fragment and exit function now
  7535. if (frag === null) {
  7536. return;
  7537. }
  7538. } else {
  7539. // VoD playlist: if bufferEnd before start of playlist, load first fragment
  7540. if (bufferEnd < start) {
  7541. frag = fragments[0];
  7542. }
  7543. }
  7544. }
  7545. if (!frag) {
  7546. frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);
  7547. }
  7548. if (frag) {
  7549. if (frag.encrypted) {
  7550. _logger.logger.log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level);
  7551. this._loadKey(frag);
  7552. } else {
  7553. _logger.logger.log('Loading ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level + ', currentTime:' + pos.toFixed(3) + ',bufferEnd:' + bufferEnd.toFixed(3));
  7554. this._loadFragment(frag);
  7555. }
  7556. }
  7557. }
  7558. }, {
  7559. key: '_ensureFragmentAtLivePoint',
  7560. value: function _ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen) {
  7561. var config = this.hls.config,
  7562. media = this.media;
  7563. var frag = void 0;
  7564. // check if requested position is within seekable boundaries :
  7565. // logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);
  7566. var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  7567. if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {
  7568. var liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);
  7569. _logger.logger.log('buffer end: ' + bufferEnd.toFixed(3) + ' is located too far from the end of live sliding playlist, reset currentTime to : ' + liveSyncPosition.toFixed(3));
  7570. bufferEnd = liveSyncPosition;
  7571. if (media && media.readyState && media.duration > liveSyncPosition) {
  7572. media.currentTime = liveSyncPosition;
  7573. }
  7574. this.nextLoadPosition = liveSyncPosition;
  7575. }
  7576. // if end of buffer greater than live edge, don't load any fragment
  7577. // this could happen if live playlist intermittently slides in the past.
  7578. // level 1 loaded [182580161,182580167]
  7579. // level 1 loaded [182580162,182580169]
  7580. // Loading 182580168 of [182580162 ,182580169],level 1 ..
  7581. // Loading 182580169 of [182580162 ,182580169],level 1 ..
  7582. // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168
  7583. // level 1 loaded [182580164,182580171]
  7584. //
  7585. // don't return null in case media not loaded yet (readystate === 0)
  7586. if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {
  7587. return null;
  7588. }
  7589. if (this.startFragRequested && !levelDetails.PTSKnown) {
  7590. /* we are switching level on live playlist, but we don't have any PTS info for that quality level ...
  7591. try to load frag matching with next SN.
  7592. even if SN are not synchronized between playlists, loading this frag will help us
  7593. compute playlist sliding and find the right one after in case it was not the right consecutive one */
  7594. if (fragPrevious) {
  7595. if (levelDetails.hasProgramDateTime) {
  7596. // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)
  7597. _logger.logger.log('live playlist, switching playlist, load frag with same PDT: ' + fragPrevious.programDateTime);
  7598. frag = (0, _fragmentFinders.findFragmentByPDT)(fragments, fragPrevious.endProgramDateTime, config.maxFragLookUpTolerance);
  7599. } else {
  7600. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  7601. var targetSN = fragPrevious.sn + 1;
  7602. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  7603. var fragNext = fragments[targetSN - levelDetails.startSN];
  7604. if (fragPrevious.cc === fragNext.cc) {
  7605. frag = fragNext;
  7606. _logger.logger.log('live playlist, switching playlist, load frag with next SN: ' + frag.sn);
  7607. }
  7608. }
  7609. // next frag SN not available (or not with same continuity counter)
  7610. // look for a frag sharing the same CC
  7611. if (!frag) {
  7612. frag = _binarySearch2.default.search(fragments, function (frag) {
  7613. return fragPrevious.cc - frag.cc;
  7614. });
  7615. if (frag) {
  7616. _logger.logger.log('live playlist, switching playlist, load frag with same CC: ' + frag.sn);
  7617. }
  7618. }
  7619. }
  7620. }
  7621. if (!frag) {
  7622. /* we have no idea about which fragment should be loaded.
  7623. so let's load mid fragment. it will help computing playlist sliding and find the right one
  7624. */
  7625. frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))];
  7626. _logger.logger.log('live playlist, switching playlist, unknown, load middle frag : ' + frag.sn);
  7627. }
  7628. }
  7629. return frag;
  7630. }
  7631. }, {
  7632. key: '_findFragment',
  7633. value: function _findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails) {
  7634. var config = this.hls.config;
  7635. var frag = void 0;
  7636. if (bufferEnd < end) {
  7637. var lookupTolerance = bufferEnd > end - config.maxFragLookUpTolerance ? 0 : config.maxFragLookUpTolerance;
  7638. // Remove the tolerance if it would put the bufferEnd past the actual end of stream
  7639. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  7640. frag = (0, _fragmentFinders.findFragmentByPTS)(fragPrevious, fragments, bufferEnd, lookupTolerance);
  7641. } else {
  7642. // reach end of playlist
  7643. frag = fragments[fragLen - 1];
  7644. }
  7645. if (frag) {
  7646. var curSNIdx = frag.sn - levelDetails.startSN;
  7647. var sameLevel = fragPrevious && frag.level === fragPrevious.level;
  7648. var prevFrag = fragments[curSNIdx - 1];
  7649. var nextFrag = fragments[curSNIdx + 1];
  7650. // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
  7651. if (fragPrevious && frag.sn === fragPrevious.sn) {
  7652. if (sameLevel && !frag.backtracked) {
  7653. if (frag.sn < levelDetails.endSN) {
  7654. var deltaPTS = fragPrevious.deltaPTS;
  7655. // if there is a significant delta between audio and video, larger than max allowed hole,
  7656. // and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)
  7657. // let's try to load previous fragment again to get last keyframe
  7658. // then we will reload again current fragment (that way we should be able to fill the buffer hole ...)
  7659. if (deltaPTS && deltaPTS > config.maxBufferHole && fragPrevious.dropped && curSNIdx) {
  7660. frag = prevFrag;
  7661. _logger.logger.warn('SN just loaded, with large PTS gap between audio and video, maybe frag is not starting with a keyframe ? load previous one to try to overcome this');
  7662. } else {
  7663. frag = nextFrag;
  7664. _logger.logger.log('SN just loaded, load next one: ' + frag.sn, frag);
  7665. }
  7666. } else {
  7667. frag = null;
  7668. }
  7669. } else if (frag.backtracked) {
  7670. // Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes
  7671. if (nextFrag && nextFrag.backtracked) {
  7672. _logger.logger.warn('Already backtracked from fragment ' + nextFrag.sn + ', will not backtrack to fragment ' + frag.sn + '. Loading fragment ' + nextFrag.sn);
  7673. frag = nextFrag;
  7674. } else {
  7675. // If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe
  7676. // Reset the dropped count now since it won't be reset until we parse the fragment again, which prevents infinite backtracking on the same segment
  7677. _logger.logger.warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');
  7678. frag.dropped = 0;
  7679. if (prevFrag) {
  7680. frag = prevFrag;
  7681. frag.backtracked = true;
  7682. } else if (curSNIdx) {
  7683. // can't backtrack on very first fragment
  7684. frag = null;
  7685. }
  7686. }
  7687. }
  7688. }
  7689. }
  7690. return frag;
  7691. }
  7692. }, {
  7693. key: '_loadKey',
  7694. value: function _loadKey(frag) {
  7695. this.state = _baseStreamController.State.KEY_LOADING;
  7696. this.hls.trigger(_events2.default.KEY_LOADING, { frag: frag });
  7697. }
  7698. }, {
  7699. key: '_loadFragment',
  7700. value: function _loadFragment(frag) {
  7701. // Check if fragment is not loaded
  7702. var fragState = this.fragmentTracker.getState(frag);
  7703. this.fragCurrent = frag;
  7704. this.startFragRequested = true;
  7705. // Don't update nextLoadPosition for fragments which are not buffered
  7706. if (Number.isFinite(frag.sn) && !frag.bitrateTest) {
  7707. this.nextLoadPosition = frag.start + frag.duration;
  7708. }
  7709. // Allow backtracked fragments to load
  7710. if (frag.backtracked || fragState === _fragmentTracker.FragmentState.NOT_LOADED || fragState === _fragmentTracker.FragmentState.PARTIAL) {
  7711. frag.autoLevel = this.hls.autoLevelEnabled;
  7712. frag.bitrateTest = this.bitrateTest;
  7713. this.hls.trigger(_events2.default.FRAG_LOADING, { frag: frag });
  7714. // lazy demuxer init, as this could take some time ... do it during frag loading
  7715. if (!this.demuxer) {
  7716. this.demuxer = new _demuxer2.default(this.hls, 'main');
  7717. }
  7718. this.state = _baseStreamController.State.FRAG_LOADING;
  7719. } else if (fragState === _fragmentTracker.FragmentState.APPENDING) {
  7720. // Lower the buffer size and try again
  7721. if (this._reduceMaxBufferLength(frag.duration)) {
  7722. this.fragmentTracker.removeFragment(frag);
  7723. }
  7724. }
  7725. }
  7726. }, {
  7727. key: 'getBufferedFrag',
  7728. value: function getBufferedFrag(position) {
  7729. return this.fragmentTracker.getBufferedFrag(position, _playlistLoader2.default.LevelType.MAIN);
  7730. }
  7731. }, {
  7732. key: 'followingBufferedFrag',
  7733. value: function followingBufferedFrag(frag) {
  7734. if (frag) {
  7735. // try to get range of next fragment (500ms after this range)
  7736. return this.getBufferedFrag(frag.endPTS + 0.5);
  7737. }
  7738. return null;
  7739. }
  7740. }, {
  7741. key: '_checkFragmentChanged',
  7742. value: function _checkFragmentChanged() {
  7743. var fragPlayingCurrent = void 0,
  7744. currentTime = void 0,
  7745. video = this.media;
  7746. if (video && video.readyState && video.seeking === false) {
  7747. currentTime = video.currentTime;
  7748. /* if video element is in seeked state, currentTime can only increase.
  7749. (assuming that playback rate is positive ...)
  7750. As sometimes currentTime jumps back to zero after a
  7751. media decode error, check this, to avoid seeking back to
  7752. wrong position after a media decode error
  7753. */
  7754. if (currentTime > this.lastCurrentTime) {
  7755. this.lastCurrentTime = currentTime;
  7756. }
  7757. if (_bufferHelper.BufferHelper.isBuffered(video, currentTime)) {
  7758. fragPlayingCurrent = this.getBufferedFrag(currentTime);
  7759. } else if (_bufferHelper.BufferHelper.isBuffered(video, currentTime + 0.1)) {
  7760. /* ensure that FRAG_CHANGED event is triggered at startup,
  7761. when first video frame is displayed and playback is paused.
  7762. add a tolerance of 100ms, in case current position is not buffered,
  7763. check if current pos+100ms is buffered and use that buffer range
  7764. for FRAG_CHANGED event reporting */
  7765. fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1);
  7766. }
  7767. if (fragPlayingCurrent) {
  7768. var fragPlaying = fragPlayingCurrent;
  7769. if (fragPlaying !== this.fragPlaying) {
  7770. this.hls.trigger(_events2.default.FRAG_CHANGED, { frag: fragPlaying });
  7771. var fragPlayingLevel = fragPlaying.level;
  7772. if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {
  7773. this.hls.trigger(_events2.default.LEVEL_SWITCHED, { level: fragPlayingLevel });
  7774. }
  7775. this.fragPlaying = fragPlaying;
  7776. }
  7777. }
  7778. }
  7779. }
  7780. /*
  7781. on immediate level switch :
  7782. - pause playback if playing
  7783. - cancel any pending load request
  7784. - and trigger a buffer flush
  7785. */
  7786. }, {
  7787. key: 'immediateLevelSwitch',
  7788. value: function immediateLevelSwitch() {
  7789. _logger.logger.log('immediateLevelSwitch');
  7790. if (!this.immediateSwitch) {
  7791. this.immediateSwitch = true;
  7792. var media = this.media,
  7793. previouslyPaused = void 0;
  7794. if (media) {
  7795. previouslyPaused = media.paused;
  7796. media.pause();
  7797. } else {
  7798. // don't restart playback after instant level switch in case media not attached
  7799. previouslyPaused = true;
  7800. }
  7801. this.previouslyPaused = previouslyPaused;
  7802. }
  7803. var fragCurrent = this.fragCurrent;
  7804. if (fragCurrent && fragCurrent.loader) {
  7805. fragCurrent.loader.abort();
  7806. }
  7807. this.fragCurrent = null;
  7808. // flush everything
  7809. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  7810. }
  7811. /**
  7812. * on immediate level switch end, after new fragment has been buffered:
  7813. * - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)
  7814. * - resume the playback if needed
  7815. */
  7816. }, {
  7817. key: 'immediateLevelSwitchEnd',
  7818. value: function immediateLevelSwitchEnd() {
  7819. var media = this.media;
  7820. if (media && media.buffered.length) {
  7821. this.immediateSwitch = false;
  7822. if (_bufferHelper.BufferHelper.isBuffered(media, media.currentTime)) {
  7823. // only nudge if currentTime is buffered
  7824. media.currentTime -= 0.0001;
  7825. }
  7826. if (!this.previouslyPaused) {
  7827. media.play();
  7828. }
  7829. }
  7830. }
  7831. /**
  7832. * try to switch ASAP without breaking video playback:
  7833. * in order to ensure smooth but quick level switching,
  7834. * we need to find the next flushable buffer range
  7835. * we should take into account new segment fetch time
  7836. */
  7837. }, {
  7838. key: 'nextLevelSwitch',
  7839. value: function nextLevelSwitch() {
  7840. var media = this.media;
  7841. // ensure that media is defined and that metadata are available (to retrieve currentTime)
  7842. if (media && media.readyState) {
  7843. var fetchdelay = void 0,
  7844. fragPlayingCurrent = void 0,
  7845. nextBufferedFrag = void 0;
  7846. fragPlayingCurrent = this.getBufferedFrag(media.currentTime);
  7847. if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) {
  7848. // flush buffer preceding current fragment (flush until current fragment start offset)
  7849. // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  7850. this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1);
  7851. }
  7852. if (!media.paused) {
  7853. // add a safety delay of 1s
  7854. var nextLevelId = this.hls.nextLoadLevel,
  7855. nextLevel = this.levels[nextLevelId],
  7856. fragLastKbps = this.fragLastKbps;
  7857. if (fragLastKbps && this.fragCurrent) {
  7858. fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;
  7859. } else {
  7860. fetchdelay = 0;
  7861. }
  7862. } else {
  7863. fetchdelay = 0;
  7864. }
  7865. // logger.log('fetchdelay:'+fetchdelay);
  7866. // find buffer range that will be reached once new fragment will be fetched
  7867. nextBufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  7868. if (nextBufferedFrag) {
  7869. // we can flush buffer range following this one without stalling playback
  7870. nextBufferedFrag = this.followingBufferedFrag(nextBufferedFrag);
  7871. if (nextBufferedFrag) {
  7872. // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  7873. var fragCurrent = this.fragCurrent;
  7874. if (fragCurrent && fragCurrent.loader) {
  7875. fragCurrent.loader.abort();
  7876. }
  7877. this.fragCurrent = null;
  7878. // start flush position is the start PTS of next buffered frag.
  7879. // we use frag.naxStartPTS which is max(audio startPTS, video startPTS).
  7880. // in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment
  7881. this.flushMainBuffer(nextBufferedFrag.maxStartPTS, Number.POSITIVE_INFINITY);
  7882. }
  7883. }
  7884. }
  7885. }
  7886. }, {
  7887. key: 'flushMainBuffer',
  7888. value: function flushMainBuffer(startOffset, endOffset) {
  7889. this.state = _baseStreamController.State.BUFFER_FLUSHING;
  7890. var flushScope = { startOffset: startOffset, endOffset: endOffset };
  7891. // if alternate audio tracks are used, only flush video, otherwise flush everything
  7892. if (this.altAudio) {
  7893. flushScope.type = 'video';
  7894. }
  7895. this.hls.trigger(_events2.default.BUFFER_FLUSHING, flushScope);
  7896. }
  7897. }, {
  7898. key: 'onMediaAttached',
  7899. value: function onMediaAttached(data) {
  7900. var media = this.media = this.mediaBuffer = data.media;
  7901. this.onvseeking = this.onMediaSeeking.bind(this);
  7902. this.onvseeked = this.onMediaSeeked.bind(this);
  7903. this.onvended = this.onMediaEnded.bind(this);
  7904. media.addEventListener('seeking', this.onvseeking);
  7905. media.addEventListener('seeked', this.onvseeked);
  7906. media.addEventListener('ended', this.onvended);
  7907. var config = this.config;
  7908. if (this.levels && config.autoStartLoad) {
  7909. this.hls.startLoad(config.startPosition);
  7910. }
  7911. this.gapController = new _gapController2.default(config, media, this.fragmentTracker, this.hls);
  7912. }
  7913. }, {
  7914. key: 'onMediaDetaching',
  7915. value: function onMediaDetaching() {
  7916. var media = this.media;
  7917. if (media && media.ended) {
  7918. _logger.logger.log('MSE detaching and video ended, reset startPosition');
  7919. this.startPosition = this.lastCurrentTime = 0;
  7920. }
  7921. // reset fragment backtracked flag
  7922. var levels = this.levels;
  7923. if (levels) {
  7924. levels.forEach(function (level) {
  7925. if (level.details) {
  7926. level.details.fragments.forEach(function (fragment) {
  7927. fragment.backtracked = undefined;
  7928. });
  7929. }
  7930. });
  7931. }
  7932. // remove video listeners
  7933. if (media) {
  7934. media.removeEventListener('seeking', this.onvseeking);
  7935. media.removeEventListener('seeked', this.onvseeked);
  7936. media.removeEventListener('ended', this.onvended);
  7937. this.onvseeking = this.onvseeked = this.onvended = null;
  7938. }
  7939. this.media = this.mediaBuffer = null;
  7940. this.loadedmetadata = false;
  7941. this.stopLoad();
  7942. }
  7943. }, {
  7944. key: 'onMediaSeeked',
  7945. value: function onMediaSeeked() {
  7946. var media = this.media,
  7947. currentTime = media ? media.currentTime : undefined;
  7948. if (Number.isFinite(currentTime)) {
  7949. _logger.logger.log('media seeked to ' + currentTime.toFixed(3));
  7950. }
  7951. // tick to speed up FRAGMENT_PLAYING triggering
  7952. this.tick();
  7953. }
  7954. }, {
  7955. key: 'onManifestLoading',
  7956. value: function onManifestLoading() {
  7957. // reset buffer on manifest loading
  7958. _logger.logger.log('trigger BUFFER_RESET');
  7959. this.hls.trigger(_events2.default.BUFFER_RESET);
  7960. this.fragmentTracker.removeAllFragments();
  7961. this.stalled = false;
  7962. this.startPosition = this.lastCurrentTime = 0;
  7963. }
  7964. }, {
  7965. key: 'onManifestParsed',
  7966. value: function onManifestParsed(data) {
  7967. var aac = false,
  7968. heaac = false,
  7969. codec = void 0;
  7970. data.levels.forEach(function (level) {
  7971. // detect if we have different kind of audio codecs used amongst playlists
  7972. codec = level.audioCodec;
  7973. if (codec) {
  7974. if (codec.indexOf('mp4a.40.2') !== -1) {
  7975. aac = true;
  7976. }
  7977. if (codec.indexOf('mp4a.40.5') !== -1) {
  7978. heaac = true;
  7979. }
  7980. }
  7981. });
  7982. this.audioCodecSwitch = aac && heaac;
  7983. if (this.audioCodecSwitch) {
  7984. _logger.logger.log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  7985. }
  7986. this.levels = data.levels;
  7987. this.startFragRequested = false;
  7988. var config = this.config;
  7989. if (config.autoStartLoad || this.forceStartLoad) {
  7990. this.hls.startLoad(config.startPosition);
  7991. }
  7992. }
  7993. }, {
  7994. key: 'onLevelLoaded',
  7995. value: function onLevelLoaded(data) {
  7996. var newDetails = data.details;
  7997. var newLevelId = data.level;
  7998. var lastLevel = this.levels[this.levelLastLoaded];
  7999. var curLevel = this.levels[newLevelId];
  8000. var duration = newDetails.totalduration;
  8001. var sliding = 0;
  8002. _logger.logger.log('level ' + newLevelId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration);
  8003. if (newDetails.live) {
  8004. var curDetails = curLevel.details;
  8005. if (curDetails && newDetails.fragments.length > 0) {
  8006. // we already have details for that level, merge them
  8007. LevelHelper.mergeDetails(curDetails, newDetails);
  8008. sliding = newDetails.fragments[0].start;
  8009. this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
  8010. if (newDetails.PTSKnown && Number.isFinite(sliding)) {
  8011. _logger.logger.log('live playlist sliding:' + sliding.toFixed(3));
  8012. } else {
  8013. _logger.logger.log('live playlist - outdated PTS, unknown sliding');
  8014. (0, _discontinuities.alignStream)(this.fragPrevious, lastLevel, newDetails);
  8015. }
  8016. } else {
  8017. _logger.logger.log('live playlist - first load, unknown sliding');
  8018. newDetails.PTSKnown = false;
  8019. (0, _discontinuities.alignStream)(this.fragPrevious, lastLevel, newDetails);
  8020. }
  8021. } else {
  8022. newDetails.PTSKnown = false;
  8023. }
  8024. // override level info
  8025. curLevel.details = newDetails;
  8026. this.levelLastLoaded = newLevelId;
  8027. this.hls.trigger(_events2.default.LEVEL_UPDATED, { details: newDetails, level: newLevelId });
  8028. if (this.startFragRequested === false) {
  8029. // compute start position if set to -1. use it straight away if value is defined
  8030. if (this.startPosition === -1 || this.lastCurrentTime === -1) {
  8031. // first, check if start time offset has been set in playlist, if yes, use this value
  8032. var startTimeOffset = newDetails.startTimeOffset;
  8033. if (Number.isFinite(startTimeOffset)) {
  8034. if (startTimeOffset < 0) {
  8035. _logger.logger.log('negative start time offset ' + startTimeOffset + ', count from end of last fragment');
  8036. startTimeOffset = sliding + duration + startTimeOffset;
  8037. }
  8038. _logger.logger.log('start time offset found in playlist, adjust startPosition to ' + startTimeOffset);
  8039. this.startPosition = startTimeOffset;
  8040. } else {
  8041. // if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)
  8042. if (newDetails.live) {
  8043. this.startPosition = this.computeLivePosition(sliding, newDetails);
  8044. _logger.logger.log('configure startPosition to ' + this.startPosition);
  8045. } else {
  8046. this.startPosition = 0;
  8047. }
  8048. }
  8049. this.lastCurrentTime = this.startPosition;
  8050. }
  8051. this.nextLoadPosition = this.startPosition;
  8052. }
  8053. // only switch batck to IDLE state if we were waiting for level to start downloading a new fragment
  8054. if (this.state === _baseStreamController.State.WAITING_LEVEL) {
  8055. this.state = _baseStreamController.State.IDLE;
  8056. }
  8057. // trigger handler right now
  8058. this.tick();
  8059. }
  8060. }, {
  8061. key: 'onKeyLoaded',
  8062. value: function onKeyLoaded() {
  8063. if (this.state === _baseStreamController.State.KEY_LOADING) {
  8064. this.state = _baseStreamController.State.IDLE;
  8065. this.tick();
  8066. }
  8067. }
  8068. }, {
  8069. key: 'onFragLoaded',
  8070. value: function onFragLoaded(data) {
  8071. var fragCurrent = this.fragCurrent,
  8072. hls = this.hls,
  8073. levels = this.levels,
  8074. media = this.media;
  8075. var fragLoaded = data.frag;
  8076. if (this.state === _baseStreamController.State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'main' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
  8077. var stats = data.stats;
  8078. var currentLevel = levels[fragCurrent.level];
  8079. var details = currentLevel.details;
  8080. // reset frag bitrate test in any case after frag loaded event
  8081. // if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0
  8082. // then this means that we should be able to load a fragment at a higher quality level
  8083. this.bitrateTest = false;
  8084. this.stats = stats;
  8085. _logger.logger.log('Loaded ' + fragCurrent.sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + fragCurrent.level);
  8086. if (fragLoaded.bitrateTest && hls.nextLoadLevel) {
  8087. // switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo
  8088. this.state = _baseStreamController.State.IDLE;
  8089. this.startFragRequested = false;
  8090. stats.tparsed = stats.tbuffered = window.performance.now();
  8091. hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
  8092. this.tick();
  8093. } else if (fragLoaded.sn === 'initSegment') {
  8094. this.state = _baseStreamController.State.IDLE;
  8095. stats.tparsed = stats.tbuffered = window.performance.now();
  8096. details.initSegment.data = data.payload;
  8097. hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
  8098. this.tick();
  8099. } else {
  8100. _logger.logger.log('Parsing ' + fragCurrent.sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + fragCurrent.level + ', cc ' + fragCurrent.cc);
  8101. this.state = _baseStreamController.State.PARSING;
  8102. this.pendingBuffering = true;
  8103. this.appended = false;
  8104. // Bitrate test frags are not usually buffered so the fragment tracker ignores them. If Hls.js decides to buffer
  8105. // it (and therefore ends up at this line), then the fragment tracker needs to be manually informed.
  8106. if (fragLoaded.bitrateTest) {
  8107. fragLoaded.bitrateTest = false;
  8108. this.fragmentTracker.onFragLoaded({
  8109. frag: fragLoaded
  8110. });
  8111. }
  8112. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) and if media is not seeking (this is to overcome potential timestamp drifts between playlists and fragments)
  8113. var accurateTimeOffset = !(media && media.seeking) && (details.PTSKnown || !details.live);
  8114. var initSegmentData = details.initSegment ? details.initSegment.data : [];
  8115. var audioCodec = this._getAudioCodec(currentLevel);
  8116. // transmux the MPEG-TS data to ISO-BMFF segments
  8117. var demuxer = this.demuxer = this.demuxer || new _demuxer2.default(this.hls, 'main');
  8118. demuxer.push(data.payload, initSegmentData, audioCodec, currentLevel.videoCodec, fragCurrent, details.totalduration, accurateTimeOffset);
  8119. }
  8120. }
  8121. this.fragLoadError = 0;
  8122. }
  8123. }, {
  8124. key: 'onFragParsingInitSegment',
  8125. value: function onFragParsingInitSegment(data) {
  8126. var fragCurrent = this.fragCurrent;
  8127. var fragNew = data.frag;
  8128. if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === _baseStreamController.State.PARSING) {
  8129. var tracks = data.tracks,
  8130. trackName = void 0,
  8131. track = void 0;
  8132. // if audio track is expected to come from audio stream controller, discard any coming from main
  8133. if (tracks.audio && this.altAudio) {
  8134. delete tracks.audio;
  8135. }
  8136. // include levelCodec in audio and video tracks
  8137. track = tracks.audio;
  8138. if (track) {
  8139. var audioCodec = this.levels[this.level].audioCodec,
  8140. ua = navigator.userAgent.toLowerCase();
  8141. if (audioCodec && this.audioCodecSwap) {
  8142. _logger.logger.log('swapping playlist audio codec');
  8143. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  8144. audioCodec = 'mp4a.40.2';
  8145. } else {
  8146. audioCodec = 'mp4a.40.5';
  8147. }
  8148. }
  8149. // in case AAC and HE-AAC audio codecs are signalled in manifest
  8150. // force HE-AAC , as it seems that most browsers prefers that way,
  8151. // except for mono streams OR on FF
  8152. // these conditions might need to be reviewed ...
  8153. if (this.audioCodecSwitch) {
  8154. // don't force HE-AAC if mono stream
  8155. if (track.metadata.channelCount !== 1 &&
  8156. // don't force HE-AAC if firefox
  8157. ua.indexOf('firefox') === -1) {
  8158. audioCodec = 'mp4a.40.5';
  8159. }
  8160. }
  8161. // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  8162. if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') {
  8163. // Exclude mpeg audio
  8164. audioCodec = 'mp4a.40.2';
  8165. _logger.logger.log('Android: force audio codec to ' + audioCodec);
  8166. }
  8167. track.levelCodec = audioCodec;
  8168. track.id = data.id;
  8169. }
  8170. track = tracks.video;
  8171. if (track) {
  8172. track.levelCodec = this.levels[this.level].videoCodec;
  8173. track.id = data.id;
  8174. }
  8175. this.hls.trigger(_events2.default.BUFFER_CODECS, tracks);
  8176. // loop through tracks that are going to be provided to bufferController
  8177. for (trackName in tracks) {
  8178. track = tracks[trackName];
  8179. _logger.logger.log('main track:' + trackName + ',container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']');
  8180. var initSegment = track.initSegment;
  8181. if (initSegment) {
  8182. this.appended = true;
  8183. // arm pending Buffering flag before appending a segment
  8184. this.pendingBuffering = true;
  8185. this.hls.trigger(_events2.default.BUFFER_APPENDING, { type: trackName, data: initSegment, parent: 'main', content: 'initSegment' });
  8186. }
  8187. }
  8188. // trigger handler right now
  8189. this.tick();
  8190. }
  8191. }
  8192. }, {
  8193. key: 'onFragParsingData',
  8194. value: function onFragParsingData(data) {
  8195. var _this2 = this;
  8196. var fragCurrent = this.fragCurrent;
  8197. var fragNew = data.frag;
  8198. if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && !(data.type === 'audio' && this.altAudio) && // filter out main audio if audio track is loaded through audio stream controller
  8199. this.state === _baseStreamController.State.PARSING) {
  8200. var level = this.levels[this.level],
  8201. frag = fragCurrent;
  8202. if (!Number.isFinite(data.endPTS)) {
  8203. data.endPTS = data.startPTS + fragCurrent.duration;
  8204. data.endDTS = data.startDTS + fragCurrent.duration;
  8205. }
  8206. if (data.hasAudio === true) {
  8207. frag.addElementaryStream(_fragment2.default.ElementaryStreamTypes.AUDIO);
  8208. }
  8209. if (data.hasVideo === true) {
  8210. frag.addElementaryStream(_fragment2.default.ElementaryStreamTypes.VIDEO);
  8211. }
  8212. _logger.logger.log('Parsed ' + data.type + ',PTS:[' + data.startPTS.toFixed(3) + ',' + data.endPTS.toFixed(3) + '],DTS:[' + data.startDTS.toFixed(3) + '/' + data.endDTS.toFixed(3) + '],nb:' + data.nb + ',dropped:' + (data.dropped || 0));
  8213. // Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments)
  8214. if (data.type === 'video') {
  8215. frag.dropped = data.dropped;
  8216. if (frag.dropped) {
  8217. if (!frag.backtracked) {
  8218. var levelDetails = level.details;
  8219. if (levelDetails && frag.sn === levelDetails.startSN) {
  8220. _logger.logger.warn('missing video frame(s) on first frag, appending with gap', frag.sn);
  8221. } else {
  8222. _logger.logger.warn('missing video frame(s), backtracking fragment', frag.sn);
  8223. // Return back to the IDLE state without appending to buffer
  8224. // Causes findFragments to backtrack a segment and find the keyframe
  8225. // Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment
  8226. this.fragmentTracker.removeFragment(frag);
  8227. frag.backtracked = true;
  8228. this.nextLoadPosition = data.startPTS;
  8229. this.state = _baseStreamController.State.IDLE;
  8230. this.fragPrevious = frag;
  8231. this.tick();
  8232. return;
  8233. }
  8234. } else {
  8235. _logger.logger.warn('Already backtracked on this fragment, appending with the gap', frag.sn);
  8236. }
  8237. } else {
  8238. // Only reset the backtracked flag if we've loaded the frag without any dropped frames
  8239. frag.backtracked = false;
  8240. }
  8241. }
  8242. var drift = LevelHelper.updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS),
  8243. hls = this.hls;
  8244. hls.trigger(_events2.default.LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS });
  8245. // has remuxer dropped video frames located before first keyframe ?
  8246. [data.data1, data.data2].forEach(function (buffer) {
  8247. // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
  8248. // in that case it is useless to append following segments
  8249. if (buffer && buffer.length && _this2.state === _baseStreamController.State.PARSING) {
  8250. _this2.appended = true;
  8251. // arm pending Buffering flag before appending a segment
  8252. _this2.pendingBuffering = true;
  8253. hls.trigger(_events2.default.BUFFER_APPENDING, { type: data.type, data: buffer, parent: 'main', content: 'data' });
  8254. }
  8255. });
  8256. // trigger handler right now
  8257. this.tick();
  8258. }
  8259. }
  8260. }, {
  8261. key: 'onFragParsed',
  8262. value: function onFragParsed(data) {
  8263. var fragCurrent = this.fragCurrent;
  8264. var fragNew = data.frag;
  8265. if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === _baseStreamController.State.PARSING) {
  8266. this.stats.tparsed = window.performance.now();
  8267. this.state = _baseStreamController.State.PARSED;
  8268. this._checkAppendedParsed();
  8269. }
  8270. }
  8271. }, {
  8272. key: 'onAudioTrackSwitching',
  8273. value: function onAudioTrackSwitching(data) {
  8274. // if any URL found on new audio track, it is an alternate audio track
  8275. var altAudio = !!data.url,
  8276. trackId = data.id;
  8277. // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
  8278. // don't do anything if we switch to alt audio: audio stream controller is handling it.
  8279. // we will just have to change buffer scheduling on audioTrackSwitched
  8280. if (!altAudio) {
  8281. if (this.mediaBuffer !== this.media) {
  8282. _logger.logger.log('switching on main audio, use media.buffered to schedule main fragment loading');
  8283. this.mediaBuffer = this.media;
  8284. var fragCurrent = this.fragCurrent;
  8285. // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
  8286. if (fragCurrent.loader) {
  8287. _logger.logger.log('switching to main audio track, cancel main fragment load');
  8288. fragCurrent.loader.abort();
  8289. }
  8290. this.fragCurrent = null;
  8291. this.fragPrevious = null;
  8292. // destroy demuxer to force init segment generation (following audio switch)
  8293. if (this.demuxer) {
  8294. this.demuxer.destroy();
  8295. this.demuxer = null;
  8296. }
  8297. // switch to IDLE state to load new fragment
  8298. this.state = _baseStreamController.State.IDLE;
  8299. }
  8300. var hls = this.hls;
  8301. // switching to main audio, flush all audio and trigger track switched
  8302. hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
  8303. hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: trackId });
  8304. this.altAudio = false;
  8305. }
  8306. }
  8307. }, {
  8308. key: 'onAudioTrackSwitched',
  8309. value: function onAudioTrackSwitched(data) {
  8310. var trackId = data.id,
  8311. altAudio = !!this.hls.audioTracks[trackId].url;
  8312. if (altAudio) {
  8313. var videoBuffer = this.videoBuffer;
  8314. // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
  8315. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  8316. _logger.logger.log('switching on alternate audio, use video.buffered to schedule main fragment loading');
  8317. this.mediaBuffer = videoBuffer;
  8318. }
  8319. }
  8320. this.altAudio = altAudio;
  8321. this.tick();
  8322. }
  8323. }, {
  8324. key: 'onBufferCreated',
  8325. value: function onBufferCreated(data) {
  8326. var tracks = data.tracks,
  8327. mediaTrack = void 0,
  8328. name = void 0,
  8329. alternate = false;
  8330. for (var type in tracks) {
  8331. var track = tracks[type];
  8332. if (track.id === 'main') {
  8333. name = type;
  8334. mediaTrack = track;
  8335. // keep video source buffer reference
  8336. if (type === 'video') {
  8337. this.videoBuffer = tracks[type].buffer;
  8338. }
  8339. } else {
  8340. alternate = true;
  8341. }
  8342. }
  8343. if (alternate && mediaTrack) {
  8344. _logger.logger.log('alternate track found, use ' + name + '.buffered to schedule main fragment loading');
  8345. this.mediaBuffer = mediaTrack.buffer;
  8346. } else {
  8347. this.mediaBuffer = this.media;
  8348. }
  8349. }
  8350. }, {
  8351. key: 'onBufferAppended',
  8352. value: function onBufferAppended(data) {
  8353. if (data.parent === 'main') {
  8354. var state = this.state;
  8355. if (state === _baseStreamController.State.PARSING || state === _baseStreamController.State.PARSED) {
  8356. // check if all buffers have been appended
  8357. this.pendingBuffering = data.pending > 0;
  8358. this._checkAppendedParsed();
  8359. }
  8360. }
  8361. }
  8362. }, {
  8363. key: '_checkAppendedParsed',
  8364. value: function _checkAppendedParsed() {
  8365. // trigger handler right now
  8366. if (this.state === _baseStreamController.State.PARSED && (!this.appended || !this.pendingBuffering)) {
  8367. var frag = this.fragCurrent;
  8368. if (frag) {
  8369. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  8370. _logger.logger.log('main buffered : ' + _timeRanges2.default.toString(media.buffered));
  8371. this.fragPrevious = frag;
  8372. var stats = this.stats;
  8373. stats.tbuffered = window.performance.now();
  8374. // we should get rid of this.fragLastKbps
  8375. this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));
  8376. this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' });
  8377. this.state = _baseStreamController.State.IDLE;
  8378. }
  8379. this.tick();
  8380. }
  8381. }
  8382. }, {
  8383. key: 'onError',
  8384. value: function onError(data) {
  8385. var frag = data.frag || this.fragCurrent;
  8386. // don't handle frag error not related to main fragment
  8387. if (frag && frag.type !== 'main') {
  8388. return;
  8389. }
  8390. // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  8391. var mediaBuffered = !!this.media && _bufferHelper.BufferHelper.isBuffered(this.media, this.media.currentTime) && _bufferHelper.BufferHelper.isBuffered(this.media, this.media.currentTime + 0.5);
  8392. switch (data.details) {
  8393. case _errors.ErrorDetails.FRAG_LOAD_ERROR:
  8394. case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
  8395. case _errors.ErrorDetails.KEY_LOAD_ERROR:
  8396. case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
  8397. if (!data.fatal) {
  8398. // keep retrying until the limit will be reached
  8399. if (this.fragLoadError + 1 <= this.config.fragLoadingMaxRetry) {
  8400. // exponential backoff capped to config.fragLoadingMaxRetryTimeout
  8401. var delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);
  8402. _logger.logger.warn('mediaController: frag loading failed, retry in ' + delay + ' ms');
  8403. this.retryDate = window.performance.now() + delay;
  8404. // retry loading state
  8405. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  8406. // in that case, reset startFragRequested flag
  8407. if (!this.loadedmetadata) {
  8408. this.startFragRequested = false;
  8409. this.nextLoadPosition = this.startPosition;
  8410. }
  8411. this.fragLoadError++;
  8412. this.state = _baseStreamController.State.FRAG_LOADING_WAITING_RETRY;
  8413. } else {
  8414. _logger.logger.error('mediaController: ' + data.details + ' reaches max retry, redispatch as fatal ...');
  8415. // switch error to fatal
  8416. data.fatal = true;
  8417. this.state = _baseStreamController.State.ERROR;
  8418. }
  8419. }
  8420. break;
  8421. case _errors.ErrorDetails.LEVEL_LOAD_ERROR:
  8422. case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT:
  8423. if (this.state !== _baseStreamController.State.ERROR) {
  8424. if (data.fatal) {
  8425. // if fatal error, stop processing
  8426. this.state = _baseStreamController.State.ERROR;
  8427. _logger.logger.warn('streamController: ' + data.details + ',switch to ' + this.state + ' state ...');
  8428. } else {
  8429. // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE
  8430. if (!data.levelRetry && this.state === _baseStreamController.State.WAITING_LEVEL) {
  8431. this.state = _baseStreamController.State.IDLE;
  8432. }
  8433. }
  8434. }
  8435. break;
  8436. case _errors.ErrorDetails.BUFFER_FULL_ERROR:
  8437. // if in appending state
  8438. if (data.parent === 'main' && (this.state === _baseStreamController.State.PARSING || this.state === _baseStreamController.State.PARSED)) {
  8439. // reduce max buf len if current position is buffered
  8440. if (mediaBuffered) {
  8441. this._reduceMaxBufferLength(this.config.maxBufferLength);
  8442. this.state = _baseStreamController.State.IDLE;
  8443. } else {
  8444. // current position is not buffered, but browser is still complaining about buffer full error
  8445. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  8446. // in that case flush the whole buffer to recover
  8447. _logger.logger.warn('buffer full error also media.currentTime is not buffered, flush everything');
  8448. this.fragCurrent = null;
  8449. // flush everything
  8450. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  8451. }
  8452. }
  8453. break;
  8454. default:
  8455. break;
  8456. }
  8457. }
  8458. }, {
  8459. key: '_reduceMaxBufferLength',
  8460. value: function _reduceMaxBufferLength(minLength) {
  8461. var config = this.config;
  8462. if (config.maxMaxBufferLength >= minLength) {
  8463. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  8464. config.maxMaxBufferLength /= 2;
  8465. _logger.logger.warn('main:reduce max buffer length to ' + config.maxMaxBufferLength + 's');
  8466. return true;
  8467. }
  8468. return false;
  8469. }
  8470. /**
  8471. * Checks the health of the buffer and attempts to resolve playback stalls.
  8472. * @private
  8473. */
  8474. }, {
  8475. key: '_checkBuffer',
  8476. value: function _checkBuffer() {
  8477. var media = this.media;
  8478. if (!media || media.readyState === 0) {
  8479. // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0)
  8480. return;
  8481. }
  8482. var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;
  8483. var buffered = mediaBuffer.buffered;
  8484. if (!this.loadedmetadata && buffered.length) {
  8485. this.loadedmetadata = true;
  8486. this._seekToStartPos();
  8487. } else if (this.immediateSwitch) {
  8488. this.immediateLevelSwitchEnd();
  8489. } else {
  8490. this.gapController.poll(this.lastCurrentTime, buffered);
  8491. }
  8492. }
  8493. }, {
  8494. key: 'onFragLoadEmergencyAborted',
  8495. value: function onFragLoadEmergencyAborted() {
  8496. this.state = _baseStreamController.State.IDLE;
  8497. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  8498. // in that case, reset startFragRequested flag
  8499. if (!this.loadedmetadata) {
  8500. this.startFragRequested = false;
  8501. this.nextLoadPosition = this.startPosition;
  8502. }
  8503. this.tick();
  8504. }
  8505. }, {
  8506. key: 'onBufferFlushed',
  8507. value: function onBufferFlushed() {
  8508. /* after successful buffer flushing, filter flushed fragments from bufferedFrags
  8509. use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)
  8510. */
  8511. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  8512. if (media) {
  8513. // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams
  8514. this.fragmentTracker.detectEvictedFragments(_fragment2.default.ElementaryStreamTypes.VIDEO, media.buffered);
  8515. }
  8516. // move to IDLE once flush complete. this should trigger new fragment loading
  8517. this.state = _baseStreamController.State.IDLE;
  8518. // reset reference to frag
  8519. this.fragPrevious = null;
  8520. }
  8521. }, {
  8522. key: 'swapAudioCodec',
  8523. value: function swapAudioCodec() {
  8524. this.audioCodecSwap = !this.audioCodecSwap;
  8525. }
  8526. }, {
  8527. key: 'computeLivePosition',
  8528. value: function computeLivePosition(sliding, levelDetails) {
  8529. var targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration;
  8530. return sliding + Math.max(0, levelDetails.totalduration - targetLatency);
  8531. }
  8532. /**
  8533. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  8534. * @private
  8535. */
  8536. }, {
  8537. key: '_seekToStartPos',
  8538. value: function _seekToStartPos() {
  8539. var media = this.media;
  8540. var currentTime = media.currentTime;
  8541. // only adjust currentTime if different from startPosition or if startPosition not buffered
  8542. // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
  8543. var startPosition = media.seeking ? currentTime : this.startPosition;
  8544. // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered
  8545. if (currentTime !== startPosition) {
  8546. // if startPosition not buffered, let's seek to buffered.start(0)
  8547. _logger.logger.log('target start position not buffered, seek to buffered.start(0) ' + startPosition + ' from current time ' + currentTime + ' ');
  8548. media.currentTime = startPosition;
  8549. }
  8550. }
  8551. }, {
  8552. key: '_getAudioCodec',
  8553. value: function _getAudioCodec(currentLevel) {
  8554. var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  8555. if (this.audioCodecSwap) {
  8556. _logger.logger.log('swapping playlist audio codec');
  8557. if (audioCodec) {
  8558. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  8559. audioCodec = 'mp4a.40.2';
  8560. } else {
  8561. audioCodec = 'mp4a.40.5';
  8562. }
  8563. }
  8564. }
  8565. return audioCodec;
  8566. }
  8567. }, {
  8568. key: 'state',
  8569. set: function set(nextState) {
  8570. if (this.state !== nextState) {
  8571. var previousState = this.state;
  8572. this._state = nextState;
  8573. _logger.logger.log('main stream:' + previousState + '->' + nextState);
  8574. this.hls.trigger(_events2.default.STREAM_STATE_TRANSITION, { previousState: previousState, nextState: nextState });
  8575. }
  8576. },
  8577. get: function get() {
  8578. return this._state;
  8579. }
  8580. }, {
  8581. key: 'currentLevel',
  8582. get: function get() {
  8583. var media = this.media;
  8584. if (media) {
  8585. var frag = this.getBufferedFrag(media.currentTime);
  8586. if (frag) {
  8587. return frag.level;
  8588. }
  8589. }
  8590. return -1;
  8591. }
  8592. }, {
  8593. key: 'nextBufferedFrag',
  8594. get: function get() {
  8595. var media = this.media;
  8596. if (media) {
  8597. // first get end range of current fragment
  8598. return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime));
  8599. } else {
  8600. return null;
  8601. }
  8602. }
  8603. }, {
  8604. key: 'nextLevel',
  8605. get: function get() {
  8606. var frag = this.nextBufferedFrag;
  8607. if (frag) {
  8608. return frag.level;
  8609. } else {
  8610. return -1;
  8611. }
  8612. }
  8613. }, {
  8614. key: 'liveSyncPosition',
  8615. get: function get() {
  8616. return this._liveSyncPosition;
  8617. },
  8618. set: function set(value) {
  8619. this._liveSyncPosition = value;
  8620. }
  8621. }]);
  8622. return StreamController;
  8623. }(_baseStreamController2.default);
  8624. exports.default = StreamController;
  8625. module.exports = exports['default'];
  8626. /***/ }),
  8627. /* 41 */
  8628. /***/ (function(module, exports, __webpack_require__) {
  8629. function webpackBootstrapFunc (modules) {
  8630. /******/ // The module cache
  8631. /******/ var installedModules = {};
  8632. /******/ // The require function
  8633. /******/ function __webpack_require__(moduleId) {
  8634. /******/ // Check if module is in cache
  8635. /******/ if(installedModules[moduleId])
  8636. /******/ return installedModules[moduleId].exports;
  8637. /******/ // Create a new module (and put it into the cache)
  8638. /******/ var module = installedModules[moduleId] = {
  8639. /******/ i: moduleId,
  8640. /******/ l: false,
  8641. /******/ exports: {}
  8642. /******/ };
  8643. /******/ // Execute the module function
  8644. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  8645. /******/ // Flag the module as loaded
  8646. /******/ module.l = true;
  8647. /******/ // Return the exports of the module
  8648. /******/ return module.exports;
  8649. /******/ }
  8650. /******/ // expose the modules object (__webpack_modules__)
  8651. /******/ __webpack_require__.m = modules;
  8652. /******/ // expose the module cache
  8653. /******/ __webpack_require__.c = installedModules;
  8654. /******/ // identity function for calling harmony imports with the correct context
  8655. /******/ __webpack_require__.i = function(value) { return value; };
  8656. /******/ // define getter function for harmony exports
  8657. /******/ __webpack_require__.d = function(exports, name, getter) {
  8658. /******/ if(!__webpack_require__.o(exports, name)) {
  8659. /******/ Object.defineProperty(exports, name, {
  8660. /******/ configurable: false,
  8661. /******/ enumerable: true,
  8662. /******/ get: getter
  8663. /******/ });
  8664. /******/ }
  8665. /******/ };
  8666. /******/ // define __esModule on exports
  8667. /******/ __webpack_require__.r = function(exports) {
  8668. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  8669. /******/ };
  8670. /******/ // getDefaultExport function for compatibility with non-harmony modules
  8671. /******/ __webpack_require__.n = function(module) {
  8672. /******/ var getter = module && module.__esModule ?
  8673. /******/ function getDefault() { return module['default']; } :
  8674. /******/ function getModuleExports() { return module; };
  8675. /******/ __webpack_require__.d(getter, 'a', getter);
  8676. /******/ return getter;
  8677. /******/ };
  8678. /******/ // Object.prototype.hasOwnProperty.call
  8679. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  8680. /******/ // __webpack_public_path__
  8681. /******/ __webpack_require__.p = "/";
  8682. /******/ // on error function for async loading
  8683. /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };
  8684. var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE)
  8685. return f.default || f // try to call default if defined to also support babel esmodule exports
  8686. }
  8687. var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+'
  8688. var dependencyRegExp = '\\(\\s*(\/\\*.*?\\*\/)?\\s*.*?(' + moduleNameReqExp + ').*?\\)' // additional chars when output.pathinfo is true
  8689. // http://stackoverflow.com/a/2593661/130442
  8690. function quoteRegExp (str) {
  8691. return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&')
  8692. }
  8693. function isNumeric(n) {
  8694. return !isNaN(1 * n); // 1 * n converts integers, integers as string ("123"), 1e3 and "1e3" to integers and strings to NaN
  8695. }
  8696. function getModuleDependencies (sources, module, queueName) {
  8697. var retval = {}
  8698. retval[queueName] = []
  8699. var fnString = module.toString()
  8700. var wrapperSignature = fnString.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/)
  8701. if (!wrapperSignature) return retval
  8702. var webpackRequireName = wrapperSignature[1]
  8703. // main bundle deps
  8704. var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')
  8705. var match
  8706. while ((match = re.exec(fnString))) {
  8707. if (match[3] === 'dll-reference') continue
  8708. retval[queueName].push(match[3])
  8709. }
  8710. // dll deps
  8711. re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g')
  8712. while ((match = re.exec(fnString))) {
  8713. if (!sources[match[2]]) {
  8714. retval[queueName].push(match[1])
  8715. sources[match[2]] = __webpack_require__(match[1]).m
  8716. }
  8717. retval[match[2]] = retval[match[2]] || []
  8718. retval[match[2]].push(match[4])
  8719. }
  8720. // convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3
  8721. var keys = Object.keys(retval);
  8722. for (var i = 0; i < keys.length; i++) {
  8723. for (var j = 0; j < retval[keys[i]].length; j++) {
  8724. if (isNumeric(retval[keys[i]][j])) {
  8725. retval[keys[i]][j] = 1 * retval[keys[i]][j];
  8726. }
  8727. }
  8728. }
  8729. return retval
  8730. }
  8731. function hasValuesInQueues (queues) {
  8732. var keys = Object.keys(queues)
  8733. return keys.reduce(function (hasValues, key) {
  8734. return hasValues || queues[key].length > 0
  8735. }, false)
  8736. }
  8737. function getRequiredModules (sources, moduleId) {
  8738. var modulesQueue = {
  8739. main: [moduleId]
  8740. }
  8741. var requiredModules = {
  8742. main: []
  8743. }
  8744. var seenModules = {
  8745. main: {}
  8746. }
  8747. while (hasValuesInQueues(modulesQueue)) {
  8748. var queues = Object.keys(modulesQueue)
  8749. for (var i = 0; i < queues.length; i++) {
  8750. var queueName = queues[i]
  8751. var queue = modulesQueue[queueName]
  8752. var moduleToCheck = queue.pop()
  8753. seenModules[queueName] = seenModules[queueName] || {}
  8754. if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue
  8755. seenModules[queueName][moduleToCheck] = true
  8756. requiredModules[queueName] = requiredModules[queueName] || []
  8757. requiredModules[queueName].push(moduleToCheck)
  8758. var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)
  8759. var newModulesKeys = Object.keys(newModules)
  8760. for (var j = 0; j < newModulesKeys.length; j++) {
  8761. modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []
  8762. modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])
  8763. }
  8764. }
  8765. }
  8766. return requiredModules
  8767. }
  8768. module.exports = function (moduleId, options) {
  8769. options = options || {}
  8770. var sources = {
  8771. main: __webpack_require__.m
  8772. }
  8773. var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId)
  8774. var src = ''
  8775. Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {
  8776. var entryModule = 0
  8777. while (requiredModules[module][entryModule]) {
  8778. entryModule++
  8779. }
  8780. requiredModules[module].push(entryModule)
  8781. sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'
  8782. src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\n'
  8783. })
  8784. src = src + 'new ((' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[id].toString() }).join(',') + '}))(self);'
  8785. var blob = new window.Blob([src], { type: 'text/javascript' })
  8786. if (options.bare) { return blob }
  8787. var URL = window.URL || window.webkitURL || window.mozURL || window.msURL
  8788. var workerUrl = URL.createObjectURL(blob)
  8789. var worker = new window.Worker(workerUrl)
  8790. worker.objectURL = workerUrl
  8791. return worker
  8792. }
  8793. /***/ }),
  8794. /* 42 */
  8795. /***/ (function(module, exports, __webpack_require__) {
  8796. "use strict";
  8797. Object.defineProperty(exports, "__esModule", {
  8798. value: true
  8799. });
  8800. 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; }; }();
  8801. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8802. var AESCrypto = function () {
  8803. function AESCrypto(subtle, iv) {
  8804. _classCallCheck(this, AESCrypto);
  8805. this.subtle = subtle;
  8806. this.aesIV = iv;
  8807. }
  8808. _createClass(AESCrypto, [{
  8809. key: 'decrypt',
  8810. value: function decrypt(data, key) {
  8811. return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data);
  8812. }
  8813. }]);
  8814. return AESCrypto;
  8815. }();
  8816. exports.default = AESCrypto;
  8817. module.exports = exports['default'];
  8818. /***/ }),
  8819. /* 43 */
  8820. /***/ (function(module, exports, __webpack_require__) {
  8821. "use strict";
  8822. Object.defineProperty(exports, "__esModule", {
  8823. value: true
  8824. });
  8825. 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; }; }();
  8826. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8827. var FastAESKey = function () {
  8828. function FastAESKey(subtle, key) {
  8829. _classCallCheck(this, FastAESKey);
  8830. this.subtle = subtle;
  8831. this.key = key;
  8832. }
  8833. _createClass(FastAESKey, [{
  8834. key: 'expandKey',
  8835. value: function expandKey() {
  8836. return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']);
  8837. }
  8838. }]);
  8839. return FastAESKey;
  8840. }();
  8841. exports.default = FastAESKey;
  8842. module.exports = exports['default'];
  8843. /***/ }),
  8844. /* 44 */
  8845. /***/ (function(module, exports, __webpack_require__) {
  8846. "use strict";
  8847. Object.defineProperty(exports, "__esModule", {
  8848. value: true
  8849. });
  8850. 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; }; }();
  8851. exports.removePadding = removePadding;
  8852. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8853. // PKCS7
  8854. function removePadding(buffer) {
  8855. var outputBytes = buffer.byteLength;
  8856. var paddingBytes = outputBytes && new DataView(buffer).getUint8(outputBytes - 1);
  8857. if (paddingBytes) {
  8858. return buffer.slice(0, outputBytes - paddingBytes);
  8859. } else {
  8860. return buffer;
  8861. }
  8862. }
  8863. var AESDecryptor = function () {
  8864. function AESDecryptor() {
  8865. _classCallCheck(this, AESDecryptor);
  8866. // Static after running initTable
  8867. this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  8868. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  8869. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  8870. this.sBox = new Uint32Array(256);
  8871. this.invSBox = new Uint32Array(256);
  8872. // Changes during runtime
  8873. this.key = new Uint32Array(0);
  8874. this.initTable();
  8875. }
  8876. // Using view.getUint32() also swaps the byte order.
  8877. _createClass(AESDecryptor, [{
  8878. key: 'uint8ArrayToUint32Array_',
  8879. value: function uint8ArrayToUint32Array_(arrayBuffer) {
  8880. var view = new DataView(arrayBuffer);
  8881. var newArray = new Uint32Array(4);
  8882. for (var i = 0; i < 4; i++) {
  8883. newArray[i] = view.getUint32(i * 4);
  8884. }
  8885. return newArray;
  8886. }
  8887. }, {
  8888. key: 'initTable',
  8889. value: function initTable() {
  8890. var sBox = this.sBox;
  8891. var invSBox = this.invSBox;
  8892. var subMix = this.subMix;
  8893. var subMix0 = subMix[0];
  8894. var subMix1 = subMix[1];
  8895. var subMix2 = subMix[2];
  8896. var subMix3 = subMix[3];
  8897. var invSubMix = this.invSubMix;
  8898. var invSubMix0 = invSubMix[0];
  8899. var invSubMix1 = invSubMix[1];
  8900. var invSubMix2 = invSubMix[2];
  8901. var invSubMix3 = invSubMix[3];
  8902. var d = new Uint32Array(256);
  8903. var x = 0;
  8904. var xi = 0;
  8905. var i = 0;
  8906. for (i = 0; i < 256; i++) {
  8907. if (i < 128) {
  8908. d[i] = i << 1;
  8909. } else {
  8910. d[i] = i << 1 ^ 0x11b;
  8911. }
  8912. }
  8913. for (i = 0; i < 256; i++) {
  8914. var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  8915. sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
  8916. sBox[x] = sx;
  8917. invSBox[sx] = x;
  8918. // Compute multiplication
  8919. var x2 = d[x];
  8920. var x4 = d[x2];
  8921. var x8 = d[x4];
  8922. // Compute sub/invSub bytes, mix columns tables
  8923. var t = d[sx] * 0x101 ^ sx * 0x1010100;
  8924. subMix0[x] = t << 24 | t >>> 8;
  8925. subMix1[x] = t << 16 | t >>> 16;
  8926. subMix2[x] = t << 8 | t >>> 24;
  8927. subMix3[x] = t;
  8928. // Compute inv sub bytes, inv mix columns tables
  8929. t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  8930. invSubMix0[sx] = t << 24 | t >>> 8;
  8931. invSubMix1[sx] = t << 16 | t >>> 16;
  8932. invSubMix2[sx] = t << 8 | t >>> 24;
  8933. invSubMix3[sx] = t;
  8934. // Compute next counter
  8935. if (!x) {
  8936. x = xi = 1;
  8937. } else {
  8938. x = x2 ^ d[d[d[x8 ^ x2]]];
  8939. xi ^= d[d[xi]];
  8940. }
  8941. }
  8942. }
  8943. }, {
  8944. key: 'expandKey',
  8945. value: function expandKey(keyBuffer) {
  8946. // convert keyBuffer to Uint32Array
  8947. var key = this.uint8ArrayToUint32Array_(keyBuffer);
  8948. var sameKey = true;
  8949. var offset = 0;
  8950. while (offset < key.length && sameKey) {
  8951. sameKey = key[offset] === this.key[offset];
  8952. offset++;
  8953. }
  8954. if (sameKey) {
  8955. return;
  8956. }
  8957. this.key = key;
  8958. var keySize = this.keySize = key.length;
  8959. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  8960. throw new Error('Invalid aes key size=' + keySize);
  8961. }
  8962. var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  8963. var ksRow = void 0;
  8964. var invKsRow = void 0;
  8965. var keySchedule = this.keySchedule = new Uint32Array(ksRows);
  8966. var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  8967. var sbox = this.sBox;
  8968. var rcon = this.rcon;
  8969. var invSubMix = this.invSubMix;
  8970. var invSubMix0 = invSubMix[0];
  8971. var invSubMix1 = invSubMix[1];
  8972. var invSubMix2 = invSubMix[2];
  8973. var invSubMix3 = invSubMix[3];
  8974. var prev = void 0;
  8975. var t = void 0;
  8976. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  8977. if (ksRow < keySize) {
  8978. prev = keySchedule[ksRow] = key[ksRow];
  8979. continue;
  8980. }
  8981. t = prev;
  8982. if (ksRow % keySize === 0) {
  8983. // Rot word
  8984. t = t << 8 | t >>> 24;
  8985. // Sub word
  8986. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  8987. // Mix Rcon
  8988. t ^= rcon[ksRow / keySize | 0] << 24;
  8989. } else if (keySize > 6 && ksRow % keySize === 4) {
  8990. // Sub word
  8991. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  8992. }
  8993. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  8994. }
  8995. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  8996. ksRow = ksRows - invKsRow;
  8997. if (invKsRow & 3) {
  8998. t = keySchedule[ksRow];
  8999. } else {
  9000. t = keySchedule[ksRow - 4];
  9001. }
  9002. if (invKsRow < 4 || ksRow <= 4) {
  9003. invKeySchedule[invKsRow] = t;
  9004. } else {
  9005. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
  9006. }
  9007. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  9008. }
  9009. }
  9010. // Adding this as a method greatly improves performance.
  9011. }, {
  9012. key: 'networkToHostOrderSwap',
  9013. value: function networkToHostOrderSwap(word) {
  9014. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  9015. }
  9016. }, {
  9017. key: 'decrypt',
  9018. value: function decrypt(inputArrayBuffer, offset, aesIV, removePKCS7Padding) {
  9019. var nRounds = this.keySize + 6;
  9020. var invKeySchedule = this.invKeySchedule;
  9021. var invSBOX = this.invSBox;
  9022. var invSubMix = this.invSubMix;
  9023. var invSubMix0 = invSubMix[0];
  9024. var invSubMix1 = invSubMix[1];
  9025. var invSubMix2 = invSubMix[2];
  9026. var invSubMix3 = invSubMix[3];
  9027. var initVector = this.uint8ArrayToUint32Array_(aesIV);
  9028. var initVector0 = initVector[0];
  9029. var initVector1 = initVector[1];
  9030. var initVector2 = initVector[2];
  9031. var initVector3 = initVector[3];
  9032. var inputInt32 = new Int32Array(inputArrayBuffer);
  9033. var outputInt32 = new Int32Array(inputInt32.length);
  9034. var t0 = void 0,
  9035. t1 = void 0,
  9036. t2 = void 0,
  9037. t3 = void 0;
  9038. var s0 = void 0,
  9039. s1 = void 0,
  9040. s2 = void 0,
  9041. s3 = void 0;
  9042. var inputWords0 = void 0,
  9043. inputWords1 = void 0,
  9044. inputWords2 = void 0,
  9045. inputWords3 = void 0;
  9046. var ksRow = void 0,
  9047. i = void 0;
  9048. var swapWord = this.networkToHostOrderSwap;
  9049. while (offset < inputInt32.length) {
  9050. inputWords0 = swapWord(inputInt32[offset]);
  9051. inputWords1 = swapWord(inputInt32[offset + 1]);
  9052. inputWords2 = swapWord(inputInt32[offset + 2]);
  9053. inputWords3 = swapWord(inputInt32[offset + 3]);
  9054. s0 = inputWords0 ^ invKeySchedule[0];
  9055. s1 = inputWords3 ^ invKeySchedule[1];
  9056. s2 = inputWords2 ^ invKeySchedule[2];
  9057. s3 = inputWords1 ^ invKeySchedule[3];
  9058. ksRow = 4;
  9059. // Iterate through the rounds of decryption
  9060. for (i = 1; i < nRounds; i++) {
  9061. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
  9062. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  9063. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  9064. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  9065. // Update state
  9066. s0 = t0;
  9067. s1 = t1;
  9068. s2 = t2;
  9069. s3 = t3;
  9070. ksRow = ksRow + 4;
  9071. }
  9072. // Shift rows, sub bytes, add round key
  9073. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
  9074. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  9075. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  9076. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  9077. ksRow = ksRow + 3;
  9078. // Write
  9079. outputInt32[offset] = swapWord(t0 ^ initVector0);
  9080. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  9081. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  9082. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  9083. // reset initVector to last 4 unsigned int
  9084. initVector0 = inputWords0;
  9085. initVector1 = inputWords1;
  9086. initVector2 = inputWords2;
  9087. initVector3 = inputWords3;
  9088. offset = offset + 4;
  9089. }
  9090. return removePKCS7Padding ? removePadding(outputInt32.buffer) : outputInt32.buffer;
  9091. }
  9092. }, {
  9093. key: 'destroy',
  9094. value: function destroy() {
  9095. this.key = undefined;
  9096. this.keySize = undefined;
  9097. this.ksRows = undefined;
  9098. this.sBox = undefined;
  9099. this.invSBox = undefined;
  9100. this.subMix = undefined;
  9101. this.invSubMix = undefined;
  9102. this.keySchedule = undefined;
  9103. this.invKeySchedule = undefined;
  9104. this.rcon = undefined;
  9105. }
  9106. }]);
  9107. return AESDecryptor;
  9108. }();
  9109. exports.default = AESDecryptor;
  9110. /***/ }),
  9111. /* 45 */
  9112. /***/ (function(module, exports, __webpack_require__) {
  9113. "use strict";
  9114. Object.defineProperty(exports, "__esModule", {
  9115. value: true
  9116. });
  9117. 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; }; }(); /**
  9118. * AAC demuxer
  9119. */
  9120. var _adts = __webpack_require__(22);
  9121. var ADTS = _interopRequireWildcard(_adts);
  9122. var _logger = __webpack_require__(0);
  9123. var _id = __webpack_require__(10);
  9124. var _id2 = _interopRequireDefault(_id);
  9125. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9126. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  9127. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9128. var AACDemuxer = function () {
  9129. function AACDemuxer(observer, remuxer, config) {
  9130. _classCallCheck(this, AACDemuxer);
  9131. this.observer = observer;
  9132. this.config = config;
  9133. this.remuxer = remuxer;
  9134. }
  9135. _createClass(AACDemuxer, [{
  9136. key: 'resetInitSegment',
  9137. value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  9138. this._audioTrack = { container: 'audio/adts', type: 'audio', id: 0, sequenceNumber: 0, isAAC: true, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };
  9139. }
  9140. }, {
  9141. key: 'resetTimeStamp',
  9142. value: function resetTimeStamp() {}
  9143. }, {
  9144. key: 'append',
  9145. // feed incoming data to the front of the parsing pipeline
  9146. value: function append(data, timeOffset, contiguous, accurateTimeOffset) {
  9147. var track = this._audioTrack;
  9148. var id3Data = _id2.default.getID3Data(data, 0) || [];
  9149. var timestamp = _id2.default.getTimeStamp(id3Data);
  9150. var pts = Number.isFinite(timestamp) ? timestamp * 90 : timeOffset * 90000;
  9151. var frameIndex = 0;
  9152. var stamp = pts;
  9153. var length = data.length;
  9154. var offset = id3Data.length;
  9155. var id3Samples = [{ pts: stamp, dts: stamp, data: id3Data }];
  9156. while (offset < length - 1) {
  9157. if (ADTS.isHeader(data, offset) && offset + 5 < length) {
  9158. ADTS.initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  9159. var frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);
  9160. if (frame) {
  9161. offset += frame.length;
  9162. stamp = frame.sample.pts;
  9163. frameIndex++;
  9164. } else {
  9165. _logger.logger.log('Unable to parse AAC frame');
  9166. break;
  9167. }
  9168. } else if (_id2.default.isHeader(data, offset)) {
  9169. id3Data = _id2.default.getID3Data(data, offset);
  9170. id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });
  9171. offset += id3Data.length;
  9172. } else {
  9173. // nothing found, keep looking
  9174. offset++;
  9175. }
  9176. }
  9177. this.remuxer.remux(track, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset);
  9178. }
  9179. }, {
  9180. key: 'destroy',
  9181. value: function destroy() {}
  9182. }], [{
  9183. key: 'probe',
  9184. value: function probe(data) {
  9185. if (!data) {
  9186. return false;
  9187. }
  9188. // Check for the ADTS sync word
  9189. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  9190. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  9191. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  9192. var id3Data = _id2.default.getID3Data(data, 0) || [];
  9193. var offset = id3Data.length;
  9194. for (var length = data.length; offset < length; offset++) {
  9195. if (ADTS.probe(data, offset)) {
  9196. _logger.logger.log('ADTS sync word found !');
  9197. return true;
  9198. }
  9199. }
  9200. return false;
  9201. }
  9202. }]);
  9203. return AACDemuxer;
  9204. }();
  9205. exports.default = AACDemuxer;
  9206. module.exports = exports['default'];
  9207. /***/ }),
  9208. /* 46 */
  9209. /***/ (function(module, exports, __webpack_require__) {
  9210. "use strict";
  9211. Object.defineProperty(exports, "__esModule", {
  9212. value: true
  9213. });
  9214. 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; }; }(); /**
  9215. * highly optimized TS demuxer:
  9216. * parse PAT, PMT
  9217. * extract PES packet from audio and video PIDs
  9218. * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet
  9219. * trigger the remuxer upon parsing completion
  9220. * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.
  9221. * it also controls the remuxing process :
  9222. * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.
  9223. */
  9224. // import Hex from '../utils/hex';
  9225. var _adts = __webpack_require__(22);
  9226. var ADTS = _interopRequireWildcard(_adts);
  9227. var _mpegaudio = __webpack_require__(23);
  9228. var _mpegaudio2 = _interopRequireDefault(_mpegaudio);
  9229. var _events = __webpack_require__(1);
  9230. var _events2 = _interopRequireDefault(_events);
  9231. var _expGolomb = __webpack_require__(47);
  9232. var _expGolomb2 = _interopRequireDefault(_expGolomb);
  9233. var _sampleAes = __webpack_require__(48);
  9234. var _sampleAes2 = _interopRequireDefault(_sampleAes);
  9235. var _logger = __webpack_require__(0);
  9236. var _errors = __webpack_require__(2);
  9237. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9238. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  9239. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9240. // We are using fixed track IDs for driving the MP4 remuxer
  9241. // instead of following the TS PIDs.
  9242. // There is no reason not to do this and some browsers/SourceBuffer-demuxers
  9243. // may not like if there are TrackID "switches"
  9244. // See https://github.com/video-dev/hls.js/issues/1331
  9245. // Here we are mapping our internal track types to constant MP4 track IDs
  9246. // With MSE currently one can only have one track of each, and we are muxing
  9247. // whatever video/audio rendition in them.
  9248. var RemuxerTrackIdConfig = {
  9249. video: 1,
  9250. audio: 2,
  9251. id3: 3,
  9252. text: 4
  9253. };
  9254. var TSDemuxer = function () {
  9255. function TSDemuxer(observer, remuxer, config, typeSupported) {
  9256. _classCallCheck(this, TSDemuxer);
  9257. this.observer = observer;
  9258. this.config = config;
  9259. this.typeSupported = typeSupported;
  9260. this.remuxer = remuxer;
  9261. this.sampleAes = null;
  9262. }
  9263. _createClass(TSDemuxer, [{
  9264. key: 'setDecryptData',
  9265. value: function setDecryptData(decryptdata) {
  9266. if (decryptdata != null && decryptdata.key != null && decryptdata.method === 'SAMPLE-AES') {
  9267. this.sampleAes = new _sampleAes2.default(this.observer, this.config, decryptdata, this.discardEPB);
  9268. } else {
  9269. this.sampleAes = null;
  9270. }
  9271. }
  9272. }, {
  9273. key: 'resetInitSegment',
  9274. /**
  9275. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  9276. * Resets all internal track instances of the demuxer.
  9277. *
  9278. * @override Implements generic demuxing/remuxing interface (see DemuxerInline)
  9279. * @param {object} initSegment
  9280. * @param {string} audioCodec
  9281. * @param {string} videoCodec
  9282. * @param {number} duration (in TS timescale = 90kHz)
  9283. */
  9284. value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  9285. this.pmtParsed = false;
  9286. this._pmtId = -1;
  9287. this._avcTrack = TSDemuxer.createTrack('video', duration);
  9288. this._audioTrack = TSDemuxer.createTrack('audio', duration);
  9289. this._id3Track = TSDemuxer.createTrack('id3', duration);
  9290. this._txtTrack = TSDemuxer.createTrack('text', duration);
  9291. // flush any partial content
  9292. this.aacOverFlow = null;
  9293. this.aacLastPTS = null;
  9294. this.avcSample = null;
  9295. this.audioCodec = audioCodec;
  9296. this.videoCodec = videoCodec;
  9297. this._duration = duration;
  9298. }
  9299. /**
  9300. *
  9301. * @override
  9302. */
  9303. }, {
  9304. key: 'resetTimeStamp',
  9305. value: function resetTimeStamp() {}
  9306. // feed incoming data to the front of the parsing pipeline
  9307. }, {
  9308. key: 'append',
  9309. value: function append(data, timeOffset, contiguous, accurateTimeOffset) {
  9310. var start = void 0,
  9311. len = data.length,
  9312. stt = void 0,
  9313. pid = void 0,
  9314. atf = void 0,
  9315. offset = void 0,
  9316. pes = void 0,
  9317. unknownPIDs = false;
  9318. this.contiguous = contiguous;
  9319. var pmtParsed = this.pmtParsed,
  9320. avcTrack = this._avcTrack,
  9321. audioTrack = this._audioTrack,
  9322. id3Track = this._id3Track,
  9323. avcId = avcTrack.pid,
  9324. audioId = audioTrack.pid,
  9325. id3Id = id3Track.pid,
  9326. pmtId = this._pmtId,
  9327. avcData = avcTrack.pesData,
  9328. audioData = audioTrack.pesData,
  9329. id3Data = id3Track.pesData,
  9330. parsePAT = this._parsePAT,
  9331. parsePMT = this._parsePMT,
  9332. parsePES = this._parsePES,
  9333. parseAVCPES = this._parseAVCPES.bind(this),
  9334. parseAACPES = this._parseAACPES.bind(this),
  9335. parseMPEGPES = this._parseMPEGPES.bind(this),
  9336. parseID3PES = this._parseID3PES.bind(this);
  9337. var syncOffset = TSDemuxer._syncOffset(data);
  9338. // don't parse last TS packet if incomplete
  9339. len -= (len + syncOffset) % 188;
  9340. // loop through TS packets
  9341. for (start = syncOffset; start < len; start += 188) {
  9342. if (data[start] === 0x47) {
  9343. stt = !!(data[start + 1] & 0x40);
  9344. // pid is a 13-bit field starting at the last bit of TS[1]
  9345. pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
  9346. atf = (data[start + 3] & 0x30) >> 4;
  9347. // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
  9348. if (atf > 1) {
  9349. offset = start + 5 + data[start + 4];
  9350. // continue if there is only adaptation field
  9351. if (offset === start + 188) {
  9352. continue;
  9353. }
  9354. } else {
  9355. offset = start + 4;
  9356. }
  9357. switch (pid) {
  9358. case avcId:
  9359. if (stt) {
  9360. if (avcData && (pes = parsePES(avcData)) && pes.pts !== undefined) {
  9361. parseAVCPES(pes, false);
  9362. }
  9363. avcData = { data: [], size: 0 };
  9364. }
  9365. if (avcData) {
  9366. avcData.data.push(data.subarray(offset, start + 188));
  9367. avcData.size += start + 188 - offset;
  9368. }
  9369. break;
  9370. case audioId:
  9371. if (stt) {
  9372. if (audioData && (pes = parsePES(audioData)) && pes.pts !== undefined) {
  9373. if (audioTrack.isAAC) {
  9374. parseAACPES(pes);
  9375. } else {
  9376. parseMPEGPES(pes);
  9377. }
  9378. }
  9379. audioData = { data: [], size: 0 };
  9380. }
  9381. if (audioData) {
  9382. audioData.data.push(data.subarray(offset, start + 188));
  9383. audioData.size += start + 188 - offset;
  9384. }
  9385. break;
  9386. case id3Id:
  9387. if (stt) {
  9388. if (id3Data && (pes = parsePES(id3Data)) && pes.pts !== undefined) {
  9389. parseID3PES(pes);
  9390. }
  9391. id3Data = { data: [], size: 0 };
  9392. }
  9393. if (id3Data) {
  9394. id3Data.data.push(data.subarray(offset, start + 188));
  9395. id3Data.size += start + 188 - offset;
  9396. }
  9397. break;
  9398. case 0:
  9399. if (stt) {
  9400. offset += data[offset] + 1;
  9401. }
  9402. pmtId = this._pmtId = parsePAT(data, offset);
  9403. break;
  9404. case pmtId:
  9405. if (stt) {
  9406. offset += data[offset] + 1;
  9407. }
  9408. var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, this.sampleAes != null);
  9409. // only update track id if track PID found while parsing PMT
  9410. // this is to avoid resetting the PID to -1 in case
  9411. // track PID transiently disappears from the stream
  9412. // this could happen in case of transient missing audio samples for example
  9413. // NOTE this is only the PID of the track as found in TS,
  9414. // but we are not using this for MP4 track IDs.
  9415. avcId = parsedPIDs.avc;
  9416. if (avcId > 0) {
  9417. avcTrack.pid = avcId;
  9418. }
  9419. audioId = parsedPIDs.audio;
  9420. if (audioId > 0) {
  9421. audioTrack.pid = audioId;
  9422. audioTrack.isAAC = parsedPIDs.isAAC;
  9423. }
  9424. id3Id = parsedPIDs.id3;
  9425. if (id3Id > 0) {
  9426. id3Track.pid = id3Id;
  9427. }
  9428. if (unknownPIDs && !pmtParsed) {
  9429. _logger.logger.log('reparse from beginning');
  9430. unknownPIDs = false;
  9431. // we set it to -188, the += 188 in the for loop will reset start to 0
  9432. start = syncOffset - 188;
  9433. }
  9434. pmtParsed = this.pmtParsed = true;
  9435. break;
  9436. case 17:
  9437. case 0x1fff:
  9438. break;
  9439. default:
  9440. unknownPIDs = true;
  9441. break;
  9442. }
  9443. } else {
  9444. this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47' });
  9445. }
  9446. }
  9447. // try to parse last PES packets
  9448. if (avcData && (pes = parsePES(avcData)) && pes.pts !== undefined) {
  9449. parseAVCPES(pes, true);
  9450. avcTrack.pesData = null;
  9451. } else {
  9452. // either avcData null or PES truncated, keep it for next frag parsing
  9453. avcTrack.pesData = avcData;
  9454. }
  9455. if (audioData && (pes = parsePES(audioData)) && pes.pts !== undefined) {
  9456. if (audioTrack.isAAC) {
  9457. parseAACPES(pes);
  9458. } else {
  9459. parseMPEGPES(pes);
  9460. }
  9461. audioTrack.pesData = null;
  9462. } else {
  9463. if (audioData && audioData.size) {
  9464. _logger.logger.log('last AAC PES packet truncated,might overlap between fragments');
  9465. }
  9466. // either audioData null or PES truncated, keep it for next frag parsing
  9467. audioTrack.pesData = audioData;
  9468. }
  9469. if (id3Data && (pes = parsePES(id3Data)) && pes.pts !== undefined) {
  9470. parseID3PES(pes);
  9471. id3Track.pesData = null;
  9472. } else {
  9473. // either id3Data null or PES truncated, keep it for next frag parsing
  9474. id3Track.pesData = id3Data;
  9475. }
  9476. if (this.sampleAes == null) {
  9477. this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
  9478. } else {
  9479. this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
  9480. }
  9481. }
  9482. }, {
  9483. key: 'decryptAndRemux',
  9484. value: function decryptAndRemux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  9485. if (audioTrack.samples && audioTrack.isAAC) {
  9486. var localthis = this;
  9487. this.sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
  9488. localthis.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  9489. });
  9490. } else {
  9491. this.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  9492. }
  9493. }
  9494. }, {
  9495. key: 'decryptAndRemuxAvc',
  9496. value: function decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  9497. if (videoTrack.samples) {
  9498. var localthis = this;
  9499. this.sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
  9500. localthis.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  9501. });
  9502. } else {
  9503. this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  9504. }
  9505. }
  9506. }, {
  9507. key: 'destroy',
  9508. value: function destroy() {
  9509. this._initPTS = this._initDTS = undefined;
  9510. this._duration = 0;
  9511. }
  9512. }, {
  9513. key: '_parsePAT',
  9514. value: function _parsePAT(data, offset) {
  9515. // skip the PSI header and parse the first PMT entry
  9516. return (data[offset + 10] & 0x1F) << 8 | data[offset + 11];
  9517. // logger.log('PMT PID:' + this._pmtId);
  9518. }
  9519. }, {
  9520. key: '_parsePMT',
  9521. value: function _parsePMT(data, offset, mpegSupported, isSampleAes) {
  9522. var sectionLength = void 0,
  9523. tableEnd = void 0,
  9524. programInfoLength = void 0,
  9525. pid = void 0,
  9526. result = { audio: -1, avc: -1, id3: -1, isAAC: true };
  9527. sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
  9528. tableEnd = offset + 3 + sectionLength - 4;
  9529. // to determine where the table is, we have to figure out how
  9530. // long the program info descriptors are
  9531. programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
  9532. // advance the offset to the first entry in the mapping table
  9533. offset += 12 + programInfoLength;
  9534. while (offset < tableEnd) {
  9535. pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];
  9536. switch (data[offset]) {
  9537. case 0xcf:
  9538. // SAMPLE-AES AAC
  9539. if (!isSampleAes) {
  9540. _logger.logger.log('unkown stream type:' + data[offset]);
  9541. break;
  9542. }
  9543. /* falls through */
  9544. // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
  9545. case 0x0f:
  9546. // logger.log('AAC PID:' + pid);
  9547. if (result.audio === -1) {
  9548. result.audio = pid;
  9549. }
  9550. break;
  9551. // Packetized metadata (ID3)
  9552. case 0x15:
  9553. // logger.log('ID3 PID:' + pid);
  9554. if (result.id3 === -1) {
  9555. result.id3 = pid;
  9556. }
  9557. break;
  9558. case 0xdb:
  9559. // SAMPLE-AES AVC
  9560. if (!isSampleAes) {
  9561. _logger.logger.log('unkown stream type:' + data[offset]);
  9562. break;
  9563. }
  9564. /* falls through */
  9565. // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
  9566. case 0x1b:
  9567. // logger.log('AVC PID:' + pid);
  9568. if (result.avc === -1) {
  9569. result.avc = pid;
  9570. }
  9571. break;
  9572. // ISO/IEC 11172-3 (MPEG-1 audio)
  9573. // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
  9574. case 0x03:
  9575. case 0x04:
  9576. // logger.log('MPEG PID:' + pid);
  9577. if (!mpegSupported) {
  9578. _logger.logger.log('MPEG audio found, not supported in this browser for now');
  9579. } else if (result.audio === -1) {
  9580. result.audio = pid;
  9581. result.isAAC = false;
  9582. }
  9583. break;
  9584. case 0x24:
  9585. _logger.logger.warn('HEVC stream type found, not supported for now');
  9586. break;
  9587. default:
  9588. _logger.logger.log('unkown stream type:' + data[offset]);
  9589. break;
  9590. }
  9591. // move to the next table entry
  9592. // skip past the elementary stream descriptors, if present
  9593. offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;
  9594. }
  9595. return result;
  9596. }
  9597. }, {
  9598. key: '_parsePES',
  9599. value: function _parsePES(stream) {
  9600. var i = 0,
  9601. frag = void 0,
  9602. pesFlags = void 0,
  9603. pesPrefix = void 0,
  9604. pesLen = void 0,
  9605. pesHdrLen = void 0,
  9606. pesData = void 0,
  9607. pesPts = void 0,
  9608. pesDts = void 0,
  9609. payloadStartOffset = void 0,
  9610. data = stream.data;
  9611. // safety check
  9612. if (!stream || stream.size === 0) {
  9613. return null;
  9614. }
  9615. // we might need up to 19 bytes to read PES header
  9616. // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
  9617. // usually only one merge is needed (and this is rare ...)
  9618. while (data[0].length < 19 && data.length > 1) {
  9619. var newData = new Uint8Array(data[0].length + data[1].length);
  9620. newData.set(data[0]);
  9621. newData.set(data[1], data[0].length);
  9622. data[0] = newData;
  9623. data.splice(1, 1);
  9624. }
  9625. // retrieve PTS/DTS from first fragment
  9626. frag = data[0];
  9627. pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  9628. if (pesPrefix === 1) {
  9629. pesLen = (frag[4] << 8) + frag[5];
  9630. // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
  9631. // minus 6 : PES header size
  9632. if (pesLen && pesLen > stream.size - 6) {
  9633. return null;
  9634. }
  9635. pesFlags = frag[7];
  9636. if (pesFlags & 0xC0) {
  9637. /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  9638. as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
  9639. as Bitwise operators treat their operands as a sequence of 32 bits */
  9640. pesPts = (frag[9] & 0x0E) * 536870912 + // 1 << 29
  9641. (frag[10] & 0xFF) * 4194304 + // 1 << 22
  9642. (frag[11] & 0xFE) * 16384 + // 1 << 14
  9643. (frag[12] & 0xFF) * 128 + // 1 << 7
  9644. (frag[13] & 0xFE) / 2;
  9645. // check if greater than 2^32 -1
  9646. if (pesPts > 4294967295) {
  9647. // decrement 2^33
  9648. pesPts -= 8589934592;
  9649. }
  9650. if (pesFlags & 0x40) {
  9651. pesDts = (frag[14] & 0x0E) * 536870912 + // 1 << 29
  9652. (frag[15] & 0xFF) * 4194304 + // 1 << 22
  9653. (frag[16] & 0xFE) * 16384 + // 1 << 14
  9654. (frag[17] & 0xFF) * 128 + // 1 << 7
  9655. (frag[18] & 0xFE) / 2;
  9656. // check if greater than 2^32 -1
  9657. if (pesDts > 4294967295) {
  9658. // decrement 2^33
  9659. pesDts -= 8589934592;
  9660. }
  9661. if (pesPts - pesDts > 60 * 90000) {
  9662. _logger.logger.warn(Math.round((pesPts - pesDts) / 90000) + 's delta between PTS and DTS, align them');
  9663. pesPts = pesDts;
  9664. }
  9665. } else {
  9666. pesDts = pesPts;
  9667. }
  9668. }
  9669. pesHdrLen = frag[8];
  9670. // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
  9671. payloadStartOffset = pesHdrLen + 9;
  9672. stream.size -= payloadStartOffset;
  9673. // reassemble PES packet
  9674. pesData = new Uint8Array(stream.size);
  9675. for (var j = 0, dataLen = data.length; j < dataLen; j++) {
  9676. frag = data[j];
  9677. var len = frag.byteLength;
  9678. if (payloadStartOffset) {
  9679. if (payloadStartOffset > len) {
  9680. // trim full frag if PES header bigger than frag
  9681. payloadStartOffset -= len;
  9682. continue;
  9683. } else {
  9684. // trim partial frag if PES header smaller than frag
  9685. frag = frag.subarray(payloadStartOffset);
  9686. len -= payloadStartOffset;
  9687. payloadStartOffset = 0;
  9688. }
  9689. }
  9690. pesData.set(frag, i);
  9691. i += len;
  9692. }
  9693. if (pesLen) {
  9694. // payload size : remove PES header + PES extension
  9695. pesLen -= pesHdrLen + 3;
  9696. }
  9697. return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen };
  9698. } else {
  9699. return null;
  9700. }
  9701. }
  9702. }, {
  9703. key: 'pushAccesUnit',
  9704. value: function pushAccesUnit(avcSample, avcTrack) {
  9705. if (avcSample.units.length && avcSample.frame) {
  9706. var samples = avcTrack.samples;
  9707. var nbSamples = samples.length;
  9708. // only push AVC sample if starting with a keyframe is not mandatory OR
  9709. // if keyframe already found in this fragment OR
  9710. // keyframe found in last fragment (track.sps) AND
  9711. // samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous
  9712. if (!this.config.forceKeyFrameOnDiscontinuity || avcSample.key === true || avcTrack.sps && (nbSamples || this.contiguous)) {
  9713. avcSample.id = nbSamples;
  9714. samples.push(avcSample);
  9715. } else {
  9716. // dropped samples, track it
  9717. avcTrack.dropped++;
  9718. }
  9719. }
  9720. if (avcSample.debug.length) {
  9721. _logger.logger.log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);
  9722. }
  9723. }
  9724. }, {
  9725. key: '_parseAVCPES',
  9726. value: function _parseAVCPES(pes, last) {
  9727. var _this = this;
  9728. // logger.log('parse new PES');
  9729. var track = this._avcTrack,
  9730. units = this._parseAVCNALu(pes.data),
  9731. debug = false,
  9732. expGolombDecoder = void 0,
  9733. avcSample = this.avcSample,
  9734. push = void 0,
  9735. spsfound = false,
  9736. i = void 0,
  9737. pushAccesUnit = this.pushAccesUnit.bind(this),
  9738. createAVCSample = function createAVCSample(key, pts, dts, debug) {
  9739. return { key: key, pts: pts, dts: dts, units: [], debug: debug };
  9740. };
  9741. // free pes.data to save up some memory
  9742. pes.data = null;
  9743. // if new NAL units found and last sample still there, let's push ...
  9744. // this helps parsing streams with missing AUD (only do this if AUD never found)
  9745. if (avcSample && units.length && !track.audFound) {
  9746. pushAccesUnit(avcSample, track);
  9747. avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');
  9748. }
  9749. units.forEach(function (unit) {
  9750. switch (unit.type) {
  9751. // NDR
  9752. case 1:
  9753. push = true;
  9754. if (!avcSample) {
  9755. avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
  9756. }
  9757. if (debug) {
  9758. avcSample.debug += 'NDR ';
  9759. }
  9760. avcSample.frame = true;
  9761. var data = unit.data;
  9762. // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
  9763. if (spsfound && data.length > 4) {
  9764. // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
  9765. var sliceType = new _expGolomb2.default(data).readSliceType();
  9766. // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
  9767. // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
  9768. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
  9769. // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
  9770. // if (sliceType === 2 || sliceType === 7) {
  9771. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  9772. avcSample.key = true;
  9773. }
  9774. }
  9775. break;
  9776. // IDR
  9777. case 5:
  9778. push = true;
  9779. // handle PES not starting with AUD
  9780. if (!avcSample) {
  9781. avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
  9782. }
  9783. if (debug) {
  9784. avcSample.debug += 'IDR ';
  9785. }
  9786. avcSample.key = true;
  9787. avcSample.frame = true;
  9788. break;
  9789. // SEI
  9790. case 6:
  9791. push = true;
  9792. if (debug && avcSample) {
  9793. avcSample.debug += 'SEI ';
  9794. }
  9795. expGolombDecoder = new _expGolomb2.default(_this.discardEPB(unit.data));
  9796. // skip frameType
  9797. expGolombDecoder.readUByte();
  9798. var payloadType = 0;
  9799. var payloadSize = 0;
  9800. var endOfCaptions = false;
  9801. var b = 0;
  9802. while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {
  9803. payloadType = 0;
  9804. do {
  9805. b = expGolombDecoder.readUByte();
  9806. payloadType += b;
  9807. } while (b === 0xFF);
  9808. // Parse payload size.
  9809. payloadSize = 0;
  9810. do {
  9811. b = expGolombDecoder.readUByte();
  9812. payloadSize += b;
  9813. } while (b === 0xFF);
  9814. // TODO: there can be more than one payload in an SEI packet...
  9815. // TODO: need to read type and size in a while loop to get them all
  9816. if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {
  9817. endOfCaptions = true;
  9818. var countryCode = expGolombDecoder.readUByte();
  9819. if (countryCode === 181) {
  9820. var providerCode = expGolombDecoder.readUShort();
  9821. if (providerCode === 49) {
  9822. var userStructure = expGolombDecoder.readUInt();
  9823. if (userStructure === 0x47413934) {
  9824. var userDataType = expGolombDecoder.readUByte();
  9825. // Raw CEA-608 bytes wrapped in CEA-708 packet
  9826. if (userDataType === 3) {
  9827. var firstByte = expGolombDecoder.readUByte();
  9828. var secondByte = expGolombDecoder.readUByte();
  9829. var totalCCs = 31 & firstByte;
  9830. var byteArray = [firstByte, secondByte];
  9831. for (i = 0; i < totalCCs; i++) {
  9832. // 3 bytes per CC
  9833. byteArray.push(expGolombDecoder.readUByte());
  9834. byteArray.push(expGolombDecoder.readUByte());
  9835. byteArray.push(expGolombDecoder.readUByte());
  9836. }
  9837. _this._insertSampleInOrder(_this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray });
  9838. }
  9839. }
  9840. }
  9841. }
  9842. } else if (payloadSize < expGolombDecoder.bytesAvailable) {
  9843. for (i = 0; i < payloadSize; i++) {
  9844. expGolombDecoder.readUByte();
  9845. }
  9846. }
  9847. }
  9848. break;
  9849. // SPS
  9850. case 7:
  9851. push = true;
  9852. spsfound = true;
  9853. if (debug && avcSample) {
  9854. avcSample.debug += 'SPS ';
  9855. }
  9856. if (!track.sps) {
  9857. expGolombDecoder = new _expGolomb2.default(unit.data);
  9858. var config = expGolombDecoder.readSPS();
  9859. track.width = config.width;
  9860. track.height = config.height;
  9861. track.pixelRatio = config.pixelRatio;
  9862. track.sps = [unit.data];
  9863. track.duration = _this._duration;
  9864. var codecarray = unit.data.subarray(1, 4);
  9865. var codecstring = 'avc1.';
  9866. for (i = 0; i < 3; i++) {
  9867. var h = codecarray[i].toString(16);
  9868. if (h.length < 2) {
  9869. h = '0' + h;
  9870. }
  9871. codecstring += h;
  9872. }
  9873. track.codec = codecstring;
  9874. }
  9875. break;
  9876. // PPS
  9877. case 8:
  9878. push = true;
  9879. if (debug && avcSample) {
  9880. avcSample.debug += 'PPS ';
  9881. }
  9882. if (!track.pps) {
  9883. track.pps = [unit.data];
  9884. }
  9885. break;
  9886. // AUD
  9887. case 9:
  9888. push = false;
  9889. track.audFound = true;
  9890. if (avcSample) {
  9891. pushAccesUnit(avcSample, track);
  9892. }
  9893. avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');
  9894. break;
  9895. // Filler Data
  9896. case 12:
  9897. push = false;
  9898. break;
  9899. default:
  9900. push = false;
  9901. if (avcSample) {
  9902. avcSample.debug += 'unknown NAL ' + unit.type + ' ';
  9903. }
  9904. break;
  9905. }
  9906. if (avcSample && push) {
  9907. var _units = avcSample.units;
  9908. _units.push(unit);
  9909. }
  9910. });
  9911. // if last PES packet, push samples
  9912. if (last && avcSample) {
  9913. pushAccesUnit(avcSample, track);
  9914. this.avcSample = null;
  9915. }
  9916. }
  9917. }, {
  9918. key: '_insertSampleInOrder',
  9919. value: function _insertSampleInOrder(arr, data) {
  9920. var len = arr.length;
  9921. if (len > 0) {
  9922. if (data.pts >= arr[len - 1].pts) {
  9923. arr.push(data);
  9924. } else {
  9925. for (var pos = len - 1; pos >= 0; pos--) {
  9926. if (data.pts < arr[pos].pts) {
  9927. arr.splice(pos, 0, data);
  9928. break;
  9929. }
  9930. }
  9931. }
  9932. } else {
  9933. arr.push(data);
  9934. }
  9935. }
  9936. }, {
  9937. key: '_getLastNalUnit',
  9938. value: function _getLastNalUnit() {
  9939. var avcSample = this.avcSample,
  9940. lastUnit = void 0;
  9941. // try to fallback to previous sample if current one is empty
  9942. if (!avcSample || avcSample.units.length === 0) {
  9943. var track = this._avcTrack,
  9944. samples = track.samples;
  9945. avcSample = samples[samples.length - 1];
  9946. }
  9947. if (avcSample) {
  9948. var units = avcSample.units;
  9949. lastUnit = units[units.length - 1];
  9950. }
  9951. return lastUnit;
  9952. }
  9953. }, {
  9954. key: '_parseAVCNALu',
  9955. value: function _parseAVCNALu(array) {
  9956. var i = 0,
  9957. len = array.byteLength,
  9958. value = void 0,
  9959. overflow = void 0,
  9960. track = this._avcTrack,
  9961. state = track.naluState || 0,
  9962. lastState = state;
  9963. var units = [],
  9964. unit = void 0,
  9965. unitType = void 0,
  9966. lastUnitStart = -1,
  9967. lastUnitType = void 0;
  9968. // logger.log('PES:' + Hex.hexDump(array));
  9969. if (state === -1) {
  9970. // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
  9971. lastUnitStart = 0;
  9972. // NALu type is value read from offset 0
  9973. lastUnitType = array[0] & 0x1f;
  9974. state = 0;
  9975. i = 1;
  9976. }
  9977. while (i < len) {
  9978. value = array[i++];
  9979. // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
  9980. if (!state) {
  9981. state = value ? 0 : 1;
  9982. continue;
  9983. }
  9984. if (state === 1) {
  9985. state = value ? 0 : 2;
  9986. continue;
  9987. }
  9988. // here we have state either equal to 2 or 3
  9989. if (!value) {
  9990. state = 3;
  9991. } else if (value === 1) {
  9992. if (lastUnitStart >= 0) {
  9993. unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType };
  9994. // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  9995. units.push(unit);
  9996. } else {
  9997. // lastUnitStart is undefined => this is the first start code found in this PES packet
  9998. // first check if start code delimiter is overlapping between 2 PES packets,
  9999. // ie it started in last packet (lastState not zero)
  10000. // and ended at the beginning of this PES packet (i <= 4 - lastState)
  10001. var lastUnit = this._getLastNalUnit();
  10002. if (lastUnit) {
  10003. if (lastState && i <= 4 - lastState) {
  10004. // start delimiter overlapping between PES packets
  10005. // strip start delimiter bytes from the end of last NAL unit
  10006. // check if lastUnit had a state different from zero
  10007. if (lastUnit.state) {
  10008. // strip last bytes
  10009. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  10010. }
  10011. }
  10012. // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
  10013. overflow = i - state - 1;
  10014. if (overflow > 0) {
  10015. // logger.log('first NALU found with overflow:' + overflow);
  10016. var tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
  10017. tmp.set(lastUnit.data, 0);
  10018. tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
  10019. lastUnit.data = tmp;
  10020. }
  10021. }
  10022. }
  10023. // check if we can read unit type
  10024. if (i < len) {
  10025. unitType = array[i] & 0x1f;
  10026. // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
  10027. lastUnitStart = i;
  10028. lastUnitType = unitType;
  10029. state = 0;
  10030. } else {
  10031. // not enough byte to read unit type. let's read it on next PES parsing
  10032. state = -1;
  10033. }
  10034. } else {
  10035. state = 0;
  10036. }
  10037. }
  10038. if (lastUnitStart >= 0 && state >= 0) {
  10039. unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType, state: state };
  10040. units.push(unit);
  10041. // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
  10042. }
  10043. // no NALu found
  10044. if (units.length === 0) {
  10045. // append pes.data to previous NAL unit
  10046. var _lastUnit = this._getLastNalUnit();
  10047. if (_lastUnit) {
  10048. var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength);
  10049. _tmp.set(_lastUnit.data, 0);
  10050. _tmp.set(array, _lastUnit.data.byteLength);
  10051. _lastUnit.data = _tmp;
  10052. }
  10053. }
  10054. track.naluState = state;
  10055. return units;
  10056. }
  10057. /**
  10058. * remove Emulation Prevention bytes from a RBSP
  10059. */
  10060. }, {
  10061. key: 'discardEPB',
  10062. value: function discardEPB(data) {
  10063. var length = data.byteLength,
  10064. EPBPositions = [],
  10065. i = 1,
  10066. newLength = void 0,
  10067. newData = void 0;
  10068. // Find all `Emulation Prevention Bytes`
  10069. while (i < length - 2) {
  10070. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  10071. EPBPositions.push(i + 2);
  10072. i += 2;
  10073. } else {
  10074. i++;
  10075. }
  10076. }
  10077. // If no Emulation Prevention Bytes were found just return the original
  10078. // array
  10079. if (EPBPositions.length === 0) {
  10080. return data;
  10081. }
  10082. // Create a new array to hold the NAL unit data
  10083. newLength = length - EPBPositions.length;
  10084. newData = new Uint8Array(newLength);
  10085. var sourceIndex = 0;
  10086. for (i = 0; i < newLength; sourceIndex++, i++) {
  10087. if (sourceIndex === EPBPositions[0]) {
  10088. // Skip this byte
  10089. sourceIndex++;
  10090. // Remove this position index
  10091. EPBPositions.shift();
  10092. }
  10093. newData[i] = data[sourceIndex];
  10094. }
  10095. return newData;
  10096. }
  10097. }, {
  10098. key: '_parseAACPES',
  10099. value: function _parseAACPES(pes) {
  10100. var track = this._audioTrack,
  10101. data = pes.data,
  10102. pts = pes.pts,
  10103. startOffset = 0,
  10104. aacOverFlow = this.aacOverFlow,
  10105. aacLastPTS = this.aacLastPTS,
  10106. frameDuration = void 0,
  10107. frameIndex = void 0,
  10108. offset = void 0,
  10109. stamp = void 0,
  10110. len = void 0;
  10111. if (aacOverFlow) {
  10112. var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);
  10113. tmp.set(aacOverFlow, 0);
  10114. tmp.set(data, aacOverFlow.byteLength);
  10115. // logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);
  10116. data = tmp;
  10117. }
  10118. // look for ADTS header (0xFFFx)
  10119. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  10120. if (ADTS.isHeader(data, offset)) {
  10121. break;
  10122. }
  10123. }
  10124. // if ADTS header does not start straight from the beginning of the PES payload, raise an error
  10125. if (offset) {
  10126. var reason = void 0,
  10127. fatal = void 0;
  10128. if (offset < len - 1) {
  10129. reason = 'AAC PES did not start with ADTS header,offset:' + offset;
  10130. fatal = false;
  10131. } else {
  10132. reason = 'no ADTS header found in AAC PES';
  10133. fatal = true;
  10134. }
  10135. _logger.logger.warn('parsing error:' + reason);
  10136. this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: fatal, reason: reason });
  10137. if (fatal) {
  10138. return;
  10139. }
  10140. }
  10141. ADTS.initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  10142. frameIndex = 0;
  10143. frameDuration = ADTS.getFrameDuration(track.samplerate);
  10144. // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
  10145. // first sample PTS should be equal to last sample PTS + frameDuration
  10146. if (aacOverFlow && aacLastPTS) {
  10147. var newPTS = aacLastPTS + frameDuration;
  10148. if (Math.abs(newPTS - pts) > 1) {
  10149. _logger.logger.log('AAC: align PTS for overlapping frames by ' + Math.round((newPTS - pts) / 90));
  10150. pts = newPTS;
  10151. }
  10152. }
  10153. // scan for aac samples
  10154. while (offset < len) {
  10155. if (ADTS.isHeader(data, offset) && offset + 5 < len) {
  10156. var frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);
  10157. if (frame) {
  10158. // logger.log(`${Math.round(frame.sample.pts)} : AAC`);
  10159. offset += frame.length;
  10160. stamp = frame.sample.pts;
  10161. frameIndex++;
  10162. } else {
  10163. // logger.log('Unable to parse AAC frame');
  10164. break;
  10165. }
  10166. } else {
  10167. // nothing found, keep looking
  10168. offset++;
  10169. }
  10170. }
  10171. if (offset < len) {
  10172. aacOverFlow = data.subarray(offset, len);
  10173. // logger.log(`AAC: overflow detected:${len-offset}`);
  10174. } else {
  10175. aacOverFlow = null;
  10176. }
  10177. this.aacOverFlow = aacOverFlow;
  10178. this.aacLastPTS = stamp;
  10179. }
  10180. }, {
  10181. key: '_parseMPEGPES',
  10182. value: function _parseMPEGPES(pes) {
  10183. var data = pes.data;
  10184. var length = data.length;
  10185. var frameIndex = 0;
  10186. var offset = 0;
  10187. var pts = pes.pts;
  10188. while (offset < length) {
  10189. if (_mpegaudio2.default.isHeader(data, offset)) {
  10190. var frame = _mpegaudio2.default.appendFrame(this._audioTrack, data, offset, pts, frameIndex);
  10191. if (frame) {
  10192. offset += frame.length;
  10193. frameIndex++;
  10194. } else {
  10195. // logger.log('Unable to parse Mpeg audio frame');
  10196. break;
  10197. }
  10198. } else {
  10199. // nothing found, keep looking
  10200. offset++;
  10201. }
  10202. }
  10203. }
  10204. }, {
  10205. key: '_parseID3PES',
  10206. value: function _parseID3PES(pes) {
  10207. this._id3Track.samples.push(pes);
  10208. }
  10209. }], [{
  10210. key: 'probe',
  10211. value: function probe(data) {
  10212. var syncOffset = TSDemuxer._syncOffset(data);
  10213. if (syncOffset < 0) {
  10214. return false;
  10215. } else {
  10216. if (syncOffset) {
  10217. _logger.logger.warn('MPEG2-TS detected but first sync word found @ offset ' + syncOffset + ', junk ahead ?');
  10218. }
  10219. return true;
  10220. }
  10221. }
  10222. }, {
  10223. key: '_syncOffset',
  10224. value: function _syncOffset(data) {
  10225. // scan 1000 first bytes
  10226. var scanwindow = Math.min(1000, data.length - 3 * 188);
  10227. var i = 0;
  10228. while (i < scanwindow) {
  10229. // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
  10230. if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {
  10231. return i;
  10232. } else {
  10233. i++;
  10234. }
  10235. }
  10236. return -1;
  10237. }
  10238. /**
  10239. * Creates a track model internal to demuxer used to drive remuxing input
  10240. *
  10241. * @param {string} type 'audio' | 'video' | 'id3' | 'text'
  10242. * @param {number} duration
  10243. * @return {object} TSDemuxer's internal track model
  10244. */
  10245. }, {
  10246. key: 'createTrack',
  10247. value: function createTrack(type, duration) {
  10248. return {
  10249. container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
  10250. type: type,
  10251. id: RemuxerTrackIdConfig[type],
  10252. pid: -1,
  10253. inputTimeScale: 90000,
  10254. sequenceNumber: 0,
  10255. samples: [],
  10256. len: 0,
  10257. dropped: type === 'video' ? 0 : undefined,
  10258. isAAC: type === 'audio' ? true : undefined,
  10259. duration: type === 'audio' ? duration : undefined
  10260. };
  10261. }
  10262. }]);
  10263. return TSDemuxer;
  10264. }();
  10265. exports.default = TSDemuxer;
  10266. module.exports = exports['default'];
  10267. /***/ }),
  10268. /* 47 */
  10269. /***/ (function(module, exports, __webpack_require__) {
  10270. "use strict";
  10271. Object.defineProperty(exports, "__esModule", {
  10272. value: true
  10273. });
  10274. 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; }; }(); /**
  10275. * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
  10276. */
  10277. var _logger = __webpack_require__(0);
  10278. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10279. var ExpGolomb = function () {
  10280. function ExpGolomb(data) {
  10281. _classCallCheck(this, ExpGolomb);
  10282. this.data = data;
  10283. // the number of bytes left to examine in this.data
  10284. this.bytesAvailable = data.byteLength;
  10285. // the current word being examined
  10286. this.word = 0; // :uint
  10287. // the number of bits left to examine in the current word
  10288. this.bitsAvailable = 0; // :uint
  10289. }
  10290. // ():void
  10291. _createClass(ExpGolomb, [{
  10292. key: 'loadWord',
  10293. value: function loadWord() {
  10294. var data = this.data,
  10295. bytesAvailable = this.bytesAvailable,
  10296. position = data.byteLength - bytesAvailable,
  10297. workingBytes = new Uint8Array(4),
  10298. availableBytes = Math.min(4, bytesAvailable);
  10299. if (availableBytes === 0) {
  10300. throw new Error('no bytes available');
  10301. }
  10302. workingBytes.set(data.subarray(position, position + availableBytes));
  10303. this.word = new DataView(workingBytes.buffer).getUint32(0);
  10304. // track the amount of this.data that has been processed
  10305. this.bitsAvailable = availableBytes * 8;
  10306. this.bytesAvailable -= availableBytes;
  10307. }
  10308. // (count:int):void
  10309. }, {
  10310. key: 'skipBits',
  10311. value: function skipBits(count) {
  10312. var skipBytes = void 0; // :int
  10313. if (this.bitsAvailable > count) {
  10314. this.word <<= count;
  10315. this.bitsAvailable -= count;
  10316. } else {
  10317. count -= this.bitsAvailable;
  10318. skipBytes = count >> 3;
  10319. count -= skipBytes >> 3;
  10320. this.bytesAvailable -= skipBytes;
  10321. this.loadWord();
  10322. this.word <<= count;
  10323. this.bitsAvailable -= count;
  10324. }
  10325. }
  10326. // (size:int):uint
  10327. }, {
  10328. key: 'readBits',
  10329. value: function readBits(size) {
  10330. var bits = Math.min(this.bitsAvailable, size),
  10331. // :uint
  10332. valu = this.word >>> 32 - bits; // :uint
  10333. if (size > 32) {
  10334. _logger.logger.error('Cannot read more than 32 bits at a time');
  10335. }
  10336. this.bitsAvailable -= bits;
  10337. if (this.bitsAvailable > 0) {
  10338. this.word <<= bits;
  10339. } else if (this.bytesAvailable > 0) {
  10340. this.loadWord();
  10341. }
  10342. bits = size - bits;
  10343. if (bits > 0 && this.bitsAvailable) {
  10344. return valu << bits | this.readBits(bits);
  10345. } else {
  10346. return valu;
  10347. }
  10348. }
  10349. // ():uint
  10350. }, {
  10351. key: 'skipLZ',
  10352. value: function skipLZ() {
  10353. var leadingZeroCount = void 0; // :uint
  10354. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  10355. if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
  10356. // the first bit of working word is 1
  10357. this.word <<= leadingZeroCount;
  10358. this.bitsAvailable -= leadingZeroCount;
  10359. return leadingZeroCount;
  10360. }
  10361. }
  10362. // we exhausted word and still have not found a 1
  10363. this.loadWord();
  10364. return leadingZeroCount + this.skipLZ();
  10365. }
  10366. // ():void
  10367. }, {
  10368. key: 'skipUEG',
  10369. value: function skipUEG() {
  10370. this.skipBits(1 + this.skipLZ());
  10371. }
  10372. // ():void
  10373. }, {
  10374. key: 'skipEG',
  10375. value: function skipEG() {
  10376. this.skipBits(1 + this.skipLZ());
  10377. }
  10378. // ():uint
  10379. }, {
  10380. key: 'readUEG',
  10381. value: function readUEG() {
  10382. var clz = this.skipLZ(); // :uint
  10383. return this.readBits(clz + 1) - 1;
  10384. }
  10385. // ():int
  10386. }, {
  10387. key: 'readEG',
  10388. value: function readEG() {
  10389. var valu = this.readUEG(); // :int
  10390. if (0x01 & valu) {
  10391. // the number is odd if the low order bit is set
  10392. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  10393. } else {
  10394. return -1 * (valu >>> 1); // divide by two then make it negative
  10395. }
  10396. }
  10397. // Some convenience functions
  10398. // :Boolean
  10399. }, {
  10400. key: 'readBoolean',
  10401. value: function readBoolean() {
  10402. return this.readBits(1) === 1;
  10403. }
  10404. // ():int
  10405. }, {
  10406. key: 'readUByte',
  10407. value: function readUByte() {
  10408. return this.readBits(8);
  10409. }
  10410. // ():int
  10411. }, {
  10412. key: 'readUShort',
  10413. value: function readUShort() {
  10414. return this.readBits(16);
  10415. }
  10416. // ():int
  10417. }, {
  10418. key: 'readUInt',
  10419. value: function readUInt() {
  10420. return this.readBits(32);
  10421. }
  10422. /**
  10423. * Advance the ExpGolomb decoder past a scaling list. The scaling
  10424. * list is optionally transmitted as part of a sequence parameter
  10425. * set and is not relevant to transmuxing.
  10426. * @param count {number} the number of entries in this scaling list
  10427. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  10428. */
  10429. }, {
  10430. key: 'skipScalingList',
  10431. value: function skipScalingList(count) {
  10432. var lastScale = 8,
  10433. nextScale = 8,
  10434. j = void 0,
  10435. deltaScale = void 0;
  10436. for (j = 0; j < count; j++) {
  10437. if (nextScale !== 0) {
  10438. deltaScale = this.readEG();
  10439. nextScale = (lastScale + deltaScale + 256) % 256;
  10440. }
  10441. lastScale = nextScale === 0 ? lastScale : nextScale;
  10442. }
  10443. }
  10444. /**
  10445. * Read a sequence parameter set and return some interesting video
  10446. * properties. A sequence parameter set is the H264 metadata that
  10447. * describes the properties of upcoming video frames.
  10448. * @param data {Uint8Array} the bytes of a sequence parameter set
  10449. * @return {object} an object with configuration parsed from the
  10450. * sequence parameter set, including the dimensions of the
  10451. * associated video frames.
  10452. */
  10453. }, {
  10454. key: 'readSPS',
  10455. value: function readSPS() {
  10456. var frameCropLeftOffset = 0,
  10457. frameCropRightOffset = 0,
  10458. frameCropTopOffset = 0,
  10459. frameCropBottomOffset = 0,
  10460. profileIdc = void 0,
  10461. profileCompat = void 0,
  10462. levelIdc = void 0,
  10463. numRefFramesInPicOrderCntCycle = void 0,
  10464. picWidthInMbsMinus1 = void 0,
  10465. picHeightInMapUnitsMinus1 = void 0,
  10466. frameMbsOnlyFlag = void 0,
  10467. scalingListCount = void 0,
  10468. i = void 0,
  10469. readUByte = this.readUByte.bind(this),
  10470. readBits = this.readBits.bind(this),
  10471. readUEG = this.readUEG.bind(this),
  10472. readBoolean = this.readBoolean.bind(this),
  10473. skipBits = this.skipBits.bind(this),
  10474. skipEG = this.skipEG.bind(this),
  10475. skipUEG = this.skipUEG.bind(this),
  10476. skipScalingList = this.skipScalingList.bind(this);
  10477. readUByte();
  10478. profileIdc = readUByte(); // profile_idc
  10479. profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5)
  10480. skipBits(3); // reserved_zero_3bits u(3),
  10481. levelIdc = readUByte(); // level_idc u(8)
  10482. skipUEG(); // seq_parameter_set_id
  10483. // some profiles have more optional data we don't need
  10484. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  10485. var chromaFormatIdc = readUEG();
  10486. if (chromaFormatIdc === 3) {
  10487. skipBits(1);
  10488. } // separate_colour_plane_flag
  10489. skipUEG(); // bit_depth_luma_minus8
  10490. skipUEG(); // bit_depth_chroma_minus8
  10491. skipBits(1); // qpprime_y_zero_transform_bypass_flag
  10492. if (readBoolean()) {
  10493. // seq_scaling_matrix_present_flag
  10494. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  10495. for (i = 0; i < scalingListCount; i++) {
  10496. if (readBoolean()) {
  10497. // seq_scaling_list_present_flag[ i ]
  10498. if (i < 6) {
  10499. skipScalingList(16);
  10500. } else {
  10501. skipScalingList(64);
  10502. }
  10503. }
  10504. }
  10505. }
  10506. }
  10507. skipUEG(); // log2_max_frame_num_minus4
  10508. var picOrderCntType = readUEG();
  10509. if (picOrderCntType === 0) {
  10510. readUEG(); // log2_max_pic_order_cnt_lsb_minus4
  10511. } else if (picOrderCntType === 1) {
  10512. skipBits(1); // delta_pic_order_always_zero_flag
  10513. skipEG(); // offset_for_non_ref_pic
  10514. skipEG(); // offset_for_top_to_bottom_field
  10515. numRefFramesInPicOrderCntCycle = readUEG();
  10516. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  10517. skipEG();
  10518. } // offset_for_ref_frame[ i ]
  10519. }
  10520. skipUEG(); // max_num_ref_frames
  10521. skipBits(1); // gaps_in_frame_num_value_allowed_flag
  10522. picWidthInMbsMinus1 = readUEG();
  10523. picHeightInMapUnitsMinus1 = readUEG();
  10524. frameMbsOnlyFlag = readBits(1);
  10525. if (frameMbsOnlyFlag === 0) {
  10526. skipBits(1);
  10527. } // mb_adaptive_frame_field_flag
  10528. skipBits(1); // direct_8x8_inference_flag
  10529. if (readBoolean()) {
  10530. // frame_cropping_flag
  10531. frameCropLeftOffset = readUEG();
  10532. frameCropRightOffset = readUEG();
  10533. frameCropTopOffset = readUEG();
  10534. frameCropBottomOffset = readUEG();
  10535. }
  10536. var pixelRatio = [1, 1];
  10537. if (readBoolean()) {
  10538. // vui_parameters_present_flag
  10539. if (readBoolean()) {
  10540. // aspect_ratio_info_present_flag
  10541. var aspectRatioIdc = readUByte();
  10542. switch (aspectRatioIdc) {
  10543. case 1:
  10544. pixelRatio = [1, 1];break;
  10545. case 2:
  10546. pixelRatio = [12, 11];break;
  10547. case 3:
  10548. pixelRatio = [10, 11];break;
  10549. case 4:
  10550. pixelRatio = [16, 11];break;
  10551. case 5:
  10552. pixelRatio = [40, 33];break;
  10553. case 6:
  10554. pixelRatio = [24, 11];break;
  10555. case 7:
  10556. pixelRatio = [20, 11];break;
  10557. case 8:
  10558. pixelRatio = [32, 11];break;
  10559. case 9:
  10560. pixelRatio = [80, 33];break;
  10561. case 10:
  10562. pixelRatio = [18, 11];break;
  10563. case 11:
  10564. pixelRatio = [15, 11];break;
  10565. case 12:
  10566. pixelRatio = [64, 33];break;
  10567. case 13:
  10568. pixelRatio = [160, 99];break;
  10569. case 14:
  10570. pixelRatio = [4, 3];break;
  10571. case 15:
  10572. pixelRatio = [3, 2];break;
  10573. case 16:
  10574. pixelRatio = [2, 1];break;
  10575. case 255:
  10576. {
  10577. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  10578. break;
  10579. }
  10580. }
  10581. }
  10582. }
  10583. return {
  10584. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  10585. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  10586. pixelRatio: pixelRatio
  10587. };
  10588. }
  10589. }, {
  10590. key: 'readSliceType',
  10591. value: function readSliceType() {
  10592. // skip NALu type
  10593. this.readUByte();
  10594. // discard first_mb_in_slice
  10595. this.readUEG();
  10596. // return slice_type
  10597. return this.readUEG();
  10598. }
  10599. }]);
  10600. return ExpGolomb;
  10601. }();
  10602. exports.default = ExpGolomb;
  10603. module.exports = exports['default'];
  10604. /***/ }),
  10605. /* 48 */
  10606. /***/ (function(module, exports, __webpack_require__) {
  10607. "use strict";
  10608. Object.defineProperty(exports, "__esModule", {
  10609. value: true
  10610. });
  10611. 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; }; }(); /**
  10612. * SAMPLE-AES decrypter
  10613. */
  10614. var _decrypter = __webpack_require__(12);
  10615. var _decrypter2 = _interopRequireDefault(_decrypter);
  10616. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  10617. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10618. var SampleAesDecrypter = function () {
  10619. function SampleAesDecrypter(observer, config, decryptdata, discardEPB) {
  10620. _classCallCheck(this, SampleAesDecrypter);
  10621. this.decryptdata = decryptdata;
  10622. this.discardEPB = discardEPB;
  10623. this.decrypter = new _decrypter2.default(observer, config, { removePKCS7Padding: false });
  10624. }
  10625. _createClass(SampleAesDecrypter, [{
  10626. key: 'decryptBuffer',
  10627. value: function decryptBuffer(encryptedData, callback) {
  10628. this.decrypter.decrypt(encryptedData, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, callback);
  10629. }
  10630. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  10631. }, {
  10632. key: 'decryptAacSample',
  10633. value: function decryptAacSample(samples, sampleIndex, callback, sync) {
  10634. var curUnit = samples[sampleIndex].unit;
  10635. var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  10636. var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  10637. var localthis = this;
  10638. this.decryptBuffer(encryptedBuffer, function (decryptedData) {
  10639. decryptedData = new Uint8Array(decryptedData);
  10640. curUnit.set(decryptedData, 16);
  10641. if (!sync) {
  10642. localthis.decryptAacSamples(samples, sampleIndex + 1, callback);
  10643. }
  10644. });
  10645. }
  10646. }, {
  10647. key: 'decryptAacSamples',
  10648. value: function decryptAacSamples(samples, sampleIndex, callback) {
  10649. for (;; sampleIndex++) {
  10650. if (sampleIndex >= samples.length) {
  10651. callback();
  10652. return;
  10653. }
  10654. if (samples[sampleIndex].unit.length < 32) {
  10655. continue;
  10656. }
  10657. var sync = this.decrypter.isSync();
  10658. this.decryptAacSample(samples, sampleIndex, callback, sync);
  10659. if (!sync) {
  10660. return;
  10661. }
  10662. }
  10663. }
  10664. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  10665. }, {
  10666. key: 'getAvcEncryptedData',
  10667. value: function getAvcEncryptedData(decodedData) {
  10668. var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  10669. var encryptedData = new Int8Array(encryptedDataLen);
  10670. var outputPos = 0;
  10671. for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {
  10672. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  10673. }
  10674. return encryptedData;
  10675. }
  10676. }, {
  10677. key: 'getAvcDecryptedUnit',
  10678. value: function getAvcDecryptedUnit(decodedData, decryptedData) {
  10679. decryptedData = new Uint8Array(decryptedData);
  10680. var inputPos = 0;
  10681. for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {
  10682. decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos);
  10683. }
  10684. return decodedData;
  10685. }
  10686. }, {
  10687. key: 'decryptAvcSample',
  10688. value: function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {
  10689. var decodedData = this.discardEPB(curUnit.data);
  10690. var encryptedData = this.getAvcEncryptedData(decodedData);
  10691. var localthis = this;
  10692. this.decryptBuffer(encryptedData.buffer, function (decryptedData) {
  10693. curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedData);
  10694. if (!sync) {
  10695. localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  10696. }
  10697. });
  10698. }
  10699. }, {
  10700. key: 'decryptAvcSamples',
  10701. value: function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  10702. for (;; sampleIndex++, unitIndex = 0) {
  10703. if (sampleIndex >= samples.length) {
  10704. callback();
  10705. return;
  10706. }
  10707. var curUnits = samples[sampleIndex].units;
  10708. for (;; unitIndex++) {
  10709. if (unitIndex >= curUnits.length) {
  10710. break;
  10711. }
  10712. var curUnit = curUnits[unitIndex];
  10713. if (curUnit.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  10714. continue;
  10715. }
  10716. var sync = this.decrypter.isSync();
  10717. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);
  10718. if (!sync) {
  10719. return;
  10720. }
  10721. }
  10722. }
  10723. }
  10724. }]);
  10725. return SampleAesDecrypter;
  10726. }();
  10727. exports.default = SampleAesDecrypter;
  10728. module.exports = exports['default'];
  10729. /***/ }),
  10730. /* 49 */
  10731. /***/ (function(module, exports, __webpack_require__) {
  10732. "use strict";
  10733. Object.defineProperty(exports, "__esModule", {
  10734. value: true
  10735. });
  10736. 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; }; }(); /**
  10737. * MP3 demuxer
  10738. */
  10739. var _id = __webpack_require__(10);
  10740. var _id2 = _interopRequireDefault(_id);
  10741. var _logger = __webpack_require__(0);
  10742. var _mpegaudio = __webpack_require__(23);
  10743. var _mpegaudio2 = _interopRequireDefault(_mpegaudio);
  10744. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  10745. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10746. var MP3Demuxer = function () {
  10747. function MP3Demuxer(observer, remuxer, config) {
  10748. _classCallCheck(this, MP3Demuxer);
  10749. this.observer = observer;
  10750. this.config = config;
  10751. this.remuxer = remuxer;
  10752. }
  10753. _createClass(MP3Demuxer, [{
  10754. key: 'resetInitSegment',
  10755. value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  10756. this._audioTrack = { container: 'audio/mpeg', type: 'audio', id: -1, sequenceNumber: 0, isAAC: false, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };
  10757. }
  10758. }, {
  10759. key: 'resetTimeStamp',
  10760. value: function resetTimeStamp() {}
  10761. }, {
  10762. key: 'append',
  10763. // feed incoming data to the front of the parsing pipeline
  10764. value: function append(data, timeOffset, contiguous, accurateTimeOffset) {
  10765. var id3Data = _id2.default.getID3Data(data, 0);
  10766. var timestamp = _id2.default.getTimeStamp(id3Data);
  10767. var pts = timestamp ? 90 * timestamp : timeOffset * 90000;
  10768. var offset = id3Data.length;
  10769. var length = data.length;
  10770. var frameIndex = 0,
  10771. stamp = 0;
  10772. var track = this._audioTrack;
  10773. var id3Samples = [{ pts: pts, dts: pts, data: id3Data }];
  10774. while (offset < length) {
  10775. if (_mpegaudio2.default.isHeader(data, offset)) {
  10776. var frame = _mpegaudio2.default.appendFrame(track, data, offset, pts, frameIndex);
  10777. if (frame) {
  10778. offset += frame.length;
  10779. stamp = frame.sample.pts;
  10780. frameIndex++;
  10781. } else {
  10782. // logger.log('Unable to parse Mpeg audio frame');
  10783. break;
  10784. }
  10785. } else if (_id2.default.isHeader(data, offset)) {
  10786. id3Data = _id2.default.getID3Data(data, offset);
  10787. id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });
  10788. offset += id3Data.length;
  10789. } else {
  10790. // nothing found, keep looking
  10791. offset++;
  10792. }
  10793. }
  10794. this.remuxer.remux(track, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset);
  10795. }
  10796. }, {
  10797. key: 'destroy',
  10798. value: function destroy() {}
  10799. }], [{
  10800. key: 'probe',
  10801. value: function probe(data) {
  10802. // check if data contains ID3 timestamp and MPEG sync word
  10803. var offset = void 0,
  10804. length = void 0;
  10805. var id3Data = _id2.default.getID3Data(data, 0);
  10806. if (id3Data && _id2.default.getTimeStamp(id3Data) !== undefined) {
  10807. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  10808. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  10809. // More info http://www.mp3-tech.org/programmer/frame_header.html
  10810. for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) {
  10811. if (_mpegaudio2.default.probe(data, offset)) {
  10812. _logger.logger.log('MPEG Audio sync word found !');
  10813. return true;
  10814. }
  10815. }
  10816. }
  10817. return false;
  10818. }
  10819. }]);
  10820. return MP3Demuxer;
  10821. }();
  10822. exports.default = MP3Demuxer;
  10823. module.exports = exports['default'];
  10824. /***/ }),
  10825. /* 50 */
  10826. /***/ (function(module, exports, __webpack_require__) {
  10827. "use strict";
  10828. Object.defineProperty(exports, "__esModule", {
  10829. value: true
  10830. });
  10831. 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; }; }(); /**
  10832. * fMP4 remuxer
  10833. */
  10834. var _aacHelper = __webpack_require__(51);
  10835. var _aacHelper2 = _interopRequireDefault(_aacHelper);
  10836. var _mp4Generator = __webpack_require__(52);
  10837. var _mp4Generator2 = _interopRequireDefault(_mp4Generator);
  10838. var _events = __webpack_require__(1);
  10839. var _events2 = _interopRequireDefault(_events);
  10840. var _errors = __webpack_require__(2);
  10841. var _logger = __webpack_require__(0);
  10842. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  10843. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10844. // 10 seconds
  10845. var MAX_SILENT_FRAME_DURATION = 10 * 1000;
  10846. var MP4Remuxer = function () {
  10847. function MP4Remuxer(observer, config, typeSupported, vendor) {
  10848. _classCallCheck(this, MP4Remuxer);
  10849. this.observer = observer;
  10850. this.config = config;
  10851. this.typeSupported = typeSupported;
  10852. var userAgent = navigator.userAgent;
  10853. this.isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS');
  10854. this.ISGenerated = false;
  10855. }
  10856. _createClass(MP4Remuxer, [{
  10857. key: 'destroy',
  10858. value: function destroy() {}
  10859. }, {
  10860. key: 'resetTimeStamp',
  10861. value: function resetTimeStamp(defaultTimeStamp) {
  10862. this._initPTS = this._initDTS = defaultTimeStamp;
  10863. }
  10864. }, {
  10865. key: 'resetInitSegment',
  10866. value: function resetInitSegment() {
  10867. this.ISGenerated = false;
  10868. }
  10869. }, {
  10870. key: 'remux',
  10871. value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  10872. // generate Init Segment if needed
  10873. if (!this.ISGenerated) {
  10874. this.generateIS(audioTrack, videoTrack, timeOffset);
  10875. }
  10876. if (this.ISGenerated) {
  10877. var nbAudioSamples = audioTrack.samples.length;
  10878. var nbVideoSamples = videoTrack.samples.length;
  10879. var audioTimeOffset = timeOffset;
  10880. var videoTimeOffset = timeOffset;
  10881. if (nbAudioSamples && nbVideoSamples) {
  10882. // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
  10883. // if first audio DTS is not aligned with first video DTS then we need to take that into account
  10884. // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
  10885. // drift between audio and video streams
  10886. var audiovideoDeltaDts = (audioTrack.samples[0].pts - videoTrack.samples[0].pts) / videoTrack.inputTimeScale;
  10887. audioTimeOffset += Math.max(0, audiovideoDeltaDts);
  10888. videoTimeOffset += Math.max(0, -audiovideoDeltaDts);
  10889. }
  10890. // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is
  10891. // calculated in remuxAudio.
  10892. // logger.log('nb AAC samples:' + audioTrack.samples.length);
  10893. if (nbAudioSamples) {
  10894. // if initSegment was generated without video samples, regenerate it again
  10895. if (!audioTrack.timescale) {
  10896. _logger.logger.warn('regenerate InitSegment as audio detected');
  10897. this.generateIS(audioTrack, videoTrack, timeOffset);
  10898. }
  10899. var audioData = this.remuxAudio(audioTrack, audioTimeOffset, contiguous, accurateTimeOffset);
  10900. // logger.log('nb AVC samples:' + videoTrack.samples.length);
  10901. if (nbVideoSamples) {
  10902. var audioTrackLength = void 0;
  10903. if (audioData) {
  10904. audioTrackLength = audioData.endPTS - audioData.startPTS;
  10905. }
  10906. // if initSegment was generated without video samples, regenerate it again
  10907. if (!videoTrack.timescale) {
  10908. _logger.logger.warn('regenerate InitSegment as video detected');
  10909. this.generateIS(audioTrack, videoTrack, timeOffset);
  10910. }
  10911. this.remuxVideo(videoTrack, videoTimeOffset, contiguous, audioTrackLength, accurateTimeOffset);
  10912. }
  10913. } else {
  10914. // logger.log('nb AVC samples:' + videoTrack.samples.length);
  10915. if (nbVideoSamples) {
  10916. var videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, accurateTimeOffset);
  10917. if (videoData && audioTrack.codec) {
  10918. this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);
  10919. }
  10920. }
  10921. }
  10922. }
  10923. // logger.log('nb ID3 samples:' + audioTrack.samples.length);
  10924. if (id3Track.samples.length) {
  10925. this.remuxID3(id3Track, timeOffset);
  10926. }
  10927. // logger.log('nb ID3 samples:' + audioTrack.samples.length);
  10928. if (textTrack.samples.length) {
  10929. this.remuxText(textTrack, timeOffset);
  10930. }
  10931. // notify end of parsing
  10932. this.observer.trigger(_events2.default.FRAG_PARSED);
  10933. }
  10934. }, {
  10935. key: 'generateIS',
  10936. value: function generateIS(audioTrack, videoTrack, timeOffset) {
  10937. var observer = this.observer,
  10938. audioSamples = audioTrack.samples,
  10939. videoSamples = videoTrack.samples,
  10940. typeSupported = this.typeSupported,
  10941. container = 'audio/mp4',
  10942. tracks = {},
  10943. data = { tracks: tracks },
  10944. computePTSDTS = this._initPTS === undefined,
  10945. initPTS = void 0,
  10946. initDTS = void 0;
  10947. if (computePTSDTS) {
  10948. initPTS = initDTS = Infinity;
  10949. }
  10950. if (audioTrack.config && audioSamples.length) {
  10951. // let's use audio sampling rate as MP4 time scale.
  10952. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
  10953. // using audio sampling rate here helps having an integer MP4 frame duration
  10954. // this avoids potential rounding issue and AV sync issue
  10955. audioTrack.timescale = audioTrack.samplerate;
  10956. _logger.logger.log('audio sampling rate : ' + audioTrack.samplerate);
  10957. if (!audioTrack.isAAC) {
  10958. if (typeSupported.mpeg) {
  10959. // Chrome and Safari
  10960. container = 'audio/mpeg';
  10961. audioTrack.codec = '';
  10962. } else if (typeSupported.mp3) {
  10963. // Firefox
  10964. audioTrack.codec = 'mp3';
  10965. }
  10966. }
  10967. tracks.audio = {
  10968. container: container,
  10969. codec: audioTrack.codec,
  10970. initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : _mp4Generator2.default.initSegment([audioTrack]),
  10971. metadata: {
  10972. channelCount: audioTrack.channelCount
  10973. }
  10974. };
  10975. if (computePTSDTS) {
  10976. // remember first PTS of this demuxing context. for audio, PTS = DTS
  10977. initPTS = initDTS = audioSamples[0].pts - audioTrack.inputTimeScale * timeOffset;
  10978. }
  10979. }
  10980. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  10981. // let's use input time scale as MP4 video timescale
  10982. // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
  10983. var inputTimeScale = videoTrack.inputTimeScale;
  10984. videoTrack.timescale = inputTimeScale;
  10985. tracks.video = {
  10986. container: 'video/mp4',
  10987. codec: videoTrack.codec,
  10988. initSegment: _mp4Generator2.default.initSegment([videoTrack]),
  10989. metadata: {
  10990. width: videoTrack.width,
  10991. height: videoTrack.height
  10992. }
  10993. };
  10994. if (computePTSDTS) {
  10995. initPTS = Math.min(initPTS, videoSamples[0].pts - inputTimeScale * timeOffset);
  10996. initDTS = Math.min(initDTS, videoSamples[0].dts - inputTimeScale * timeOffset);
  10997. this.observer.trigger(_events2.default.INIT_PTS_FOUND, { initPTS: initPTS });
  10998. }
  10999. }
  11000. if (Object.keys(tracks).length) {
  11001. observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, data);
  11002. this.ISGenerated = true;
  11003. if (computePTSDTS) {
  11004. this._initPTS = initPTS;
  11005. this._initDTS = initDTS;
  11006. }
  11007. } else {
  11008. observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' });
  11009. }
  11010. }
  11011. }, {
  11012. key: 'remuxVideo',
  11013. value: function remuxVideo(track, timeOffset, contiguous, audioTrackLength, accurateTimeOffset) {
  11014. var offset = 8;
  11015. var mp4SampleDuration = void 0;
  11016. var mdat = void 0;
  11017. var moof = void 0;
  11018. var firstPTS = void 0;
  11019. var firstDTS = void 0;
  11020. var lastPTS = void 0;
  11021. var lastDTS = void 0;
  11022. var timeScale = track.timescale;
  11023. var inputSamples = track.samples;
  11024. var outputSamples = [];
  11025. var nbSamples = inputSamples.length;
  11026. var ptsNormalize = this._PTSNormalize;
  11027. var initPTS = this._initPTS;
  11028. // if parsed fragment is contiguous with last one, let's use last DTS value as reference
  11029. var nextAvcDts = this.nextAvcDts;
  11030. var isSafari = this.isSafari;
  11031. if (nbSamples === 0) {
  11032. return;
  11033. }
  11034. // Safari does not like overlapping DTS on consecutive fragments. let's use nextAvcDts to overcome this if fragments are consecutive
  11035. if (isSafari) {
  11036. // also consider consecutive fragments as being contiguous (even if a level switch occurs),
  11037. // for sake of clarity:
  11038. // consecutive fragments are frags with
  11039. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  11040. // - less than 200 ms PTS gaps (timeScale/5)
  11041. contiguous |= inputSamples.length && nextAvcDts && (accurateTimeOffset && Math.abs(timeOffset - nextAvcDts / timeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAvcDts - initPTS) < timeScale / 5);
  11042. }
  11043. if (!contiguous) {
  11044. // if not contiguous, let's use target timeOffset
  11045. nextAvcDts = timeOffset * timeScale;
  11046. }
  11047. // PTS is coded on 33bits, and can loop from -2^32 to 2^32
  11048. // ptsNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
  11049. inputSamples.forEach(function (sample) {
  11050. sample.pts = ptsNormalize(sample.pts - initPTS, nextAvcDts);
  11051. sample.dts = ptsNormalize(sample.dts - initPTS, nextAvcDts);
  11052. });
  11053. // sort video samples by DTS then PTS then demux id order
  11054. inputSamples.sort(function (a, b) {
  11055. var deltadts = a.dts - b.dts;
  11056. var deltapts = a.pts - b.pts;
  11057. return deltadts || deltapts || a.id - b.id;
  11058. });
  11059. // handle broken streams with PTS < DTS, tolerance up 200ms (18000 in 90kHz timescale)
  11060. var PTSDTSshift = inputSamples.reduce(function (prev, curr) {
  11061. return Math.max(Math.min(prev, curr.pts - curr.dts), -18000);
  11062. }, 0);
  11063. if (PTSDTSshift < 0) {
  11064. _logger.logger.warn('PTS < DTS detected in video samples, shifting DTS by ' + Math.round(PTSDTSshift / 90) + ' ms to overcome this issue');
  11065. for (var i = 0; i < inputSamples.length; i++) {
  11066. inputSamples[i].dts += PTSDTSshift;
  11067. }
  11068. }
  11069. // compute first DTS and last DTS, normalize them against reference value
  11070. var sample = inputSamples[0];
  11071. firstDTS = Math.max(sample.dts, 0);
  11072. firstPTS = Math.max(sample.pts, 0);
  11073. // check timestamp continuity accross consecutive fragments (this is to remove inter-fragment gap/hole)
  11074. var delta = Math.round((firstDTS - nextAvcDts) / 90);
  11075. // if fragment are contiguous, detect hole/overlapping between fragments
  11076. if (contiguous) {
  11077. if (delta) {
  11078. if (delta > 1) {
  11079. _logger.logger.log('AVC:' + delta + ' ms hole between fragments detected,filling it');
  11080. } else if (delta < -1) {
  11081. _logger.logger.log('AVC:' + -delta + ' ms overlapping between fragments detected');
  11082. }
  11083. // remove hole/gap : set DTS to next expected DTS
  11084. firstDTS = nextAvcDts;
  11085. inputSamples[0].dts = firstDTS;
  11086. // offset PTS as well, ensure that PTS is smaller or equal than new DTS
  11087. firstPTS = Math.max(firstPTS - delta, nextAvcDts);
  11088. inputSamples[0].pts = firstPTS;
  11089. _logger.logger.log('Video/PTS/DTS adjusted: ' + Math.round(firstPTS / 90) + '/' + Math.round(firstDTS / 90) + ',delta:' + delta + ' ms');
  11090. }
  11091. }
  11092. // compute lastPTS/lastDTS
  11093. sample = inputSamples[inputSamples.length - 1];
  11094. lastDTS = Math.max(sample.dts, 0);
  11095. lastPTS = Math.max(sample.pts, 0, lastDTS);
  11096. // on Safari let's signal the same sample duration for all samples
  11097. // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
  11098. // set this constant duration as being the avg delta between consecutive DTS.
  11099. if (isSafari) {
  11100. mp4SampleDuration = Math.round((lastDTS - firstDTS) / (inputSamples.length - 1));
  11101. }
  11102. var nbNalu = 0,
  11103. naluLen = 0;
  11104. for (var _i = 0; _i < nbSamples; _i++) {
  11105. // compute total/avc sample length and nb of NAL units
  11106. var _sample = inputSamples[_i],
  11107. units = _sample.units,
  11108. nbUnits = units.length,
  11109. sampleLen = 0;
  11110. for (var j = 0; j < nbUnits; j++) {
  11111. sampleLen += units[j].data.length;
  11112. }
  11113. naluLen += sampleLen;
  11114. nbNalu += nbUnits;
  11115. _sample.length = sampleLen;
  11116. // normalize PTS/DTS
  11117. if (isSafari) {
  11118. // sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples
  11119. _sample.dts = firstDTS + _i * mp4SampleDuration;
  11120. } else {
  11121. // ensure sample monotonic DTS
  11122. _sample.dts = Math.max(_sample.dts, firstDTS);
  11123. }
  11124. // ensure that computed value is greater or equal than sample DTS
  11125. _sample.pts = Math.max(_sample.pts, _sample.dts);
  11126. }
  11127. /* concatenate the video data and construct the mdat in place
  11128. (need 8 more bytes to fill length and mpdat type) */
  11129. var mdatSize = naluLen + 4 * nbNalu + 8;
  11130. try {
  11131. mdat = new Uint8Array(mdatSize);
  11132. } catch (err) {
  11133. this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MUX_ERROR, details: _errors.ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: 'fail allocating video mdat ' + mdatSize });
  11134. return;
  11135. }
  11136. var view = new DataView(mdat.buffer);
  11137. view.setUint32(0, mdatSize);
  11138. mdat.set(_mp4Generator2.default.types.mdat, 4);
  11139. for (var _i2 = 0; _i2 < nbSamples; _i2++) {
  11140. var avcSample = inputSamples[_i2],
  11141. avcSampleUnits = avcSample.units,
  11142. mp4SampleLength = 0,
  11143. compositionTimeOffset = void 0;
  11144. // convert NALU bitstream to MP4 format (prepend NALU with size field)
  11145. for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) {
  11146. var unit = avcSampleUnits[_j],
  11147. unitData = unit.data,
  11148. unitDataLen = unit.data.byteLength;
  11149. view.setUint32(offset, unitDataLen);
  11150. offset += 4;
  11151. mdat.set(unitData, offset);
  11152. offset += unitDataLen;
  11153. mp4SampleLength += 4 + unitDataLen;
  11154. }
  11155. if (!isSafari) {
  11156. // expected sample duration is the Decoding Timestamp diff of consecutive samples
  11157. if (_i2 < nbSamples - 1) {
  11158. mp4SampleDuration = inputSamples[_i2 + 1].dts - avcSample.dts;
  11159. } else {
  11160. var config = this.config,
  11161. lastFrameDuration = avcSample.dts - inputSamples[_i2 > 0 ? _i2 - 1 : _i2].dts;
  11162. if (config.stretchShortVideoTrack) {
  11163. // In some cases, a segment's audio track duration may exceed the video track duration.
  11164. // Since we've already remuxed audio, and we know how long the audio track is, we look to
  11165. // see if the delta to the next segment is longer than maxBufferHole.
  11166. // If so, playback would potentially get stuck, so we artificially inflate
  11167. // the duration of the last frame to minimize any potential gap between segments.
  11168. var maxBufferHole = config.maxBufferHole,
  11169. gapTolerance = Math.floor(maxBufferHole * timeScale),
  11170. deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;
  11171. if (deltaToFrameEnd > gapTolerance) {
  11172. // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
  11173. // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
  11174. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  11175. if (mp4SampleDuration < 0) {
  11176. mp4SampleDuration = lastFrameDuration;
  11177. }
  11178. _logger.logger.log('It is approximately ' + deltaToFrameEnd / 90 + ' ms to the next segment; using duration ' + mp4SampleDuration / 90 + ' ms for the last video frame.');
  11179. } else {
  11180. mp4SampleDuration = lastFrameDuration;
  11181. }
  11182. } else {
  11183. mp4SampleDuration = lastFrameDuration;
  11184. }
  11185. }
  11186. compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);
  11187. } else {
  11188. compositionTimeOffset = Math.max(0, mp4SampleDuration * Math.round((avcSample.pts - avcSample.dts) / mp4SampleDuration));
  11189. }
  11190. // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');
  11191. // console.log(`avcSample.dts: ${avcSample.dts / 90}, avcSample.pts: ${avcSample.pts / 90}, mp4SampleDuration: ${mp4SampleDuration / 90}`, avcSample)
  11192. outputSamples.push({
  11193. size: mp4SampleLength,
  11194. // constant duration
  11195. duration: mp4SampleDuration,
  11196. cts: compositionTimeOffset,
  11197. flags: {
  11198. isLeading: 0,
  11199. isDependedOn: 0,
  11200. hasRedundancy: 0,
  11201. degradPrio: 0,
  11202. dependsOn: avcSample.key ? 2 : 1,
  11203. isNonSync: avcSample.key ? 0 : 1
  11204. }
  11205. });
  11206. }
  11207. // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
  11208. this.nextAvcDts = lastDTS + mp4SampleDuration;
  11209. var dropped = track.dropped;
  11210. track.len = 0;
  11211. track.nbNalu = 0;
  11212. track.dropped = 0;
  11213. if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
  11214. var flags = outputSamples[0].flags;
  11215. // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue
  11216. // https://code.google.com/p/chromium/issues/detail?id=229412
  11217. flags.dependsOn = 2;
  11218. flags.isNonSync = 0;
  11219. }
  11220. track.samples = outputSamples;
  11221. moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstDTS, track);
  11222. track.samples = [];
  11223. var data = {
  11224. data1: moof,
  11225. data2: mdat,
  11226. startPTS: firstPTS / timeScale,
  11227. endPTS: (lastPTS + mp4SampleDuration) / timeScale,
  11228. startDTS: firstDTS / timeScale,
  11229. endDTS: this.nextAvcDts / timeScale,
  11230. type: 'video',
  11231. hasAudio: false,
  11232. hasVideo: true,
  11233. nb: outputSamples.length,
  11234. dropped: dropped
  11235. };
  11236. this.observer.trigger(_events2.default.FRAG_PARSING_DATA, data);
  11237. return data;
  11238. }
  11239. }, {
  11240. key: 'remuxAudio',
  11241. value: function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset) {
  11242. var inputTimeScale = track.inputTimeScale;
  11243. var mp4timeScale = track.timescale;
  11244. var scaleFactor = inputTimeScale / mp4timeScale;
  11245. var mp4SampleDuration = track.isAAC ? 1024 : 1152;
  11246. var inputSampleDuration = mp4SampleDuration * scaleFactor;
  11247. var ptsNormalize = this._PTSNormalize;
  11248. var initPTS = this._initPTS;
  11249. var rawMPEG = !track.isAAC && this.typeSupported.mpeg;
  11250. var offset = void 0,
  11251. mp4Sample = void 0,
  11252. fillFrame = void 0,
  11253. mdat = void 0,
  11254. moof = void 0,
  11255. firstPTS = void 0,
  11256. lastPTS = void 0,
  11257. inputSamples = track.samples,
  11258. outputSamples = [],
  11259. nextAudioPts = this.nextAudioPts;
  11260. // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
  11261. // for sake of clarity:
  11262. // consecutive fragments are frags with
  11263. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  11264. // - less than 20 audio frames distance
  11265. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  11266. // this helps ensuring audio continuity
  11267. // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
  11268. contiguous |= inputSamples.length && nextAudioPts && (accurateTimeOffset && Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAudioPts - initPTS) < 20 * inputSampleDuration);
  11269. // compute normalized PTS
  11270. inputSamples.forEach(function (sample) {
  11271. sample.pts = sample.dts = ptsNormalize(sample.pts - initPTS, timeOffset * inputTimeScale);
  11272. });
  11273. // filter out sample with negative PTS that are not playable anyway
  11274. // if we don't remove these negative samples, they will shift all audio samples forward.
  11275. // leading to audio overlap between current / next fragment
  11276. inputSamples = inputSamples.filter(function (sample) {
  11277. return sample.pts >= 0;
  11278. });
  11279. // in case all samples have negative PTS, and have been filtered out, return now
  11280. if (inputSamples.length === 0) {
  11281. return;
  11282. }
  11283. if (!contiguous) {
  11284. if (!accurateTimeOffset) {
  11285. // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
  11286. nextAudioPts = inputSamples[0].pts;
  11287. } else {
  11288. // if timeOffset is accurate, let's use it as predicted next audio PTS
  11289. nextAudioPts = timeOffset * inputTimeScale;
  11290. }
  11291. }
  11292. // If the audio track is missing samples, the frames seem to get "left-shifted" within the
  11293. // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
  11294. // In an effort to prevent this from happening, we inject frames here where there are gaps.
  11295. // When possible, we inject a silent frame; when that's not possible, we duplicate the last
  11296. // frame.
  11297. if (track.isAAC) {
  11298. var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  11299. for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length;) {
  11300. // First, let's see how far off this frame is from where we expect it to be
  11301. var sample = inputSamples[i],
  11302. delta;
  11303. var pts = sample.pts;
  11304. delta = pts - nextPts;
  11305. var duration = Math.abs(1000 * delta / inputTimeScale);
  11306. // If we're overlapping by more than a duration, drop this sample
  11307. if (delta <= -maxAudioFramesDrift * inputSampleDuration) {
  11308. _logger.logger.warn('Dropping 1 audio frame @ ' + (nextPts / inputTimeScale).toFixed(3) + 's due to ' + Math.round(duration) + ' ms overlap.');
  11309. inputSamples.splice(i, 1);
  11310. track.len -= sample.unit.length;
  11311. // Don't touch nextPtsNorm or i
  11312. } // eslint-disable-line brace-style
  11313. // Insert missing frames if:
  11314. // 1: We're more than maxAudioFramesDrift frame away
  11315. // 2: Not more than MAX_SILENT_FRAME_DURATION away
  11316. // 3: currentTime (aka nextPtsNorm) is not 0
  11317. else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && nextPts) {
  11318. var missing = Math.round(delta / inputSampleDuration);
  11319. _logger.logger.warn('Injecting ' + missing + ' audio frame @ ' + (nextPts / inputTimeScale).toFixed(3) + 's due to ' + Math.round(1000 * delta / inputTimeScale) + ' ms gap.');
  11320. for (var j = 0; j < missing; j++) {
  11321. var newStamp = Math.max(nextPts, 0);
  11322. fillFrame = _aacHelper2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  11323. if (!fillFrame) {
  11324. _logger.logger.log('Unable to get silent frame for given audio codec; duplicating last frame instead.');
  11325. fillFrame = sample.unit.subarray();
  11326. }
  11327. inputSamples.splice(i, 0, { unit: fillFrame, pts: newStamp, dts: newStamp });
  11328. track.len += fillFrame.length;
  11329. nextPts += inputSampleDuration;
  11330. i++;
  11331. }
  11332. // Adjust sample to next expected pts
  11333. sample.pts = sample.dts = nextPts;
  11334. nextPts += inputSampleDuration;
  11335. i++;
  11336. } else {
  11337. // Otherwise, just adjust pts
  11338. if (Math.abs(delta) > 0.1 * inputSampleDuration) {
  11339. // logger.log(`Invalid frame delta ${Math.round(delta + inputSampleDuration)} at PTS ${Math.round(pts / 90)} (should be ${Math.round(inputSampleDuration)}).`);
  11340. }
  11341. sample.pts = sample.dts = nextPts;
  11342. nextPts += inputSampleDuration;
  11343. i++;
  11344. }
  11345. }
  11346. }
  11347. for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
  11348. var audioSample = inputSamples[_j2];
  11349. var unit = audioSample.unit;
  11350. var _pts = audioSample.pts;
  11351. // logger.log(`Audio/PTS:${Math.round(pts/90)}`);
  11352. // if not first sample
  11353. if (lastPTS !== undefined) {
  11354. mp4Sample.duration = Math.round((_pts - lastPTS) / scaleFactor);
  11355. } else {
  11356. var _delta = Math.round(1000 * (_pts - nextAudioPts) / inputTimeScale),
  11357. numMissingFrames = 0;
  11358. // if fragment are contiguous, detect hole/overlapping between fragments
  11359. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  11360. if (contiguous && track.isAAC) {
  11361. // log delta
  11362. if (_delta) {
  11363. if (_delta > 0 && _delta < MAX_SILENT_FRAME_DURATION) {
  11364. numMissingFrames = Math.round((_pts - nextAudioPts) / inputSampleDuration);
  11365. _logger.logger.log(_delta + ' ms hole between AAC samples detected,filling it');
  11366. if (numMissingFrames > 0) {
  11367. fillFrame = _aacHelper2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  11368. if (!fillFrame) {
  11369. fillFrame = unit.subarray();
  11370. }
  11371. track.len += numMissingFrames * fillFrame.length;
  11372. }
  11373. // if we have frame overlap, overlapping for more than half a frame duraion
  11374. } else if (_delta < -12) {
  11375. // drop overlapping audio frames... browser will deal with it
  11376. _logger.logger.log('drop overlapping AAC sample, expected/parsed/delta:' + (nextAudioPts / inputTimeScale).toFixed(3) + 's/' + (_pts / inputTimeScale).toFixed(3) + 's/' + -_delta + 'ms');
  11377. track.len -= unit.byteLength;
  11378. continue;
  11379. }
  11380. // set PTS/DTS to expected PTS/DTS
  11381. _pts = nextAudioPts;
  11382. }
  11383. }
  11384. // remember first PTS of our audioSamples
  11385. firstPTS = _pts;
  11386. if (track.len > 0) {
  11387. /* concatenate the audio data and construct the mdat in place
  11388. (need 8 more bytes to fill length and mdat type) */
  11389. var mdatSize = rawMPEG ? track.len : track.len + 8;
  11390. offset = rawMPEG ? 0 : 8;
  11391. try {
  11392. mdat = new Uint8Array(mdatSize);
  11393. } catch (err) {
  11394. this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MUX_ERROR, details: _errors.ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: 'fail allocating audio mdat ' + mdatSize });
  11395. return;
  11396. }
  11397. if (!rawMPEG) {
  11398. var view = new DataView(mdat.buffer);
  11399. view.setUint32(0, mdatSize);
  11400. mdat.set(_mp4Generator2.default.types.mdat, 4);
  11401. }
  11402. } else {
  11403. // no audio samples
  11404. return;
  11405. }
  11406. for (var _i3 = 0; _i3 < numMissingFrames; _i3++) {
  11407. fillFrame = _aacHelper2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  11408. if (!fillFrame) {
  11409. _logger.logger.log('Unable to get silent frame for given audio codec; duplicating this frame instead.');
  11410. fillFrame = unit.subarray();
  11411. }
  11412. mdat.set(fillFrame, offset);
  11413. offset += fillFrame.byteLength;
  11414. mp4Sample = {
  11415. size: fillFrame.byteLength,
  11416. cts: 0,
  11417. duration: 1024,
  11418. flags: {
  11419. isLeading: 0,
  11420. isDependedOn: 0,
  11421. hasRedundancy: 0,
  11422. degradPrio: 0,
  11423. dependsOn: 1
  11424. }
  11425. };
  11426. outputSamples.push(mp4Sample);
  11427. }
  11428. }
  11429. mdat.set(unit, offset);
  11430. var unitLen = unit.byteLength;
  11431. offset += unitLen;
  11432. // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${audioSample.pts}/${audioSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(audioSample.pts/4294967296).toFixed(3)}');
  11433. mp4Sample = {
  11434. size: unitLen,
  11435. cts: 0,
  11436. duration: 0,
  11437. flags: {
  11438. isLeading: 0,
  11439. isDependedOn: 0,
  11440. hasRedundancy: 0,
  11441. degradPrio: 0,
  11442. dependsOn: 1
  11443. }
  11444. };
  11445. outputSamples.push(mp4Sample);
  11446. lastPTS = _pts;
  11447. }
  11448. var lastSampleDuration = 0;
  11449. var nbSamples = outputSamples.length;
  11450. // set last sample duration as being identical to previous sample
  11451. if (nbSamples >= 2) {
  11452. lastSampleDuration = outputSamples[nbSamples - 2].duration;
  11453. mp4Sample.duration = lastSampleDuration;
  11454. }
  11455. if (nbSamples) {
  11456. // next audio sample PTS should be equal to last sample PTS + duration
  11457. this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSampleDuration;
  11458. // logger.log('Audio/PTS/PTSend:' + audioSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));
  11459. track.len = 0;
  11460. track.samples = outputSamples;
  11461. if (rawMPEG) {
  11462. moof = new Uint8Array();
  11463. } else {
  11464. moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstPTS / scaleFactor, track);
  11465. }
  11466. track.samples = [];
  11467. var start = firstPTS / inputTimeScale;
  11468. var end = nextAudioPts / inputTimeScale;
  11469. var audioData = {
  11470. data1: moof,
  11471. data2: mdat,
  11472. startPTS: start,
  11473. endPTS: end,
  11474. startDTS: start,
  11475. endDTS: end,
  11476. type: 'audio',
  11477. hasAudio: true,
  11478. hasVideo: false,
  11479. nb: nbSamples
  11480. };
  11481. this.observer.trigger(_events2.default.FRAG_PARSING_DATA, audioData);
  11482. return audioData;
  11483. }
  11484. return null;
  11485. }
  11486. }, {
  11487. key: 'remuxEmptyAudio',
  11488. value: function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
  11489. var inputTimeScale = track.inputTimeScale,
  11490. mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale,
  11491. scaleFactor = inputTimeScale / mp4timeScale,
  11492. nextAudioPts = this.nextAudioPts,
  11493. // sync with video's timestamp
  11494. startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS,
  11495. endDTS = videoData.endDTS * inputTimeScale + this._initDTS,
  11496. // one sample's duration value
  11497. sampleDuration = 1024,
  11498. frameDuration = scaleFactor * sampleDuration,
  11499. // samples count of this segment's duration
  11500. nbSamples = Math.ceil((endDTS - startDTS) / frameDuration),
  11501. // silent frame
  11502. silentFrame = _aacHelper2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  11503. _logger.logger.warn('remux empty Audio');
  11504. // Can't remux if we can't generate a silent frame...
  11505. if (!silentFrame) {
  11506. _logger.logger.trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');
  11507. return;
  11508. }
  11509. var samples = [];
  11510. for (var i = 0; i < nbSamples; i++) {
  11511. var stamp = startDTS + i * frameDuration;
  11512. samples.push({ unit: silentFrame, pts: stamp, dts: stamp });
  11513. track.len += silentFrame.length;
  11514. }
  11515. track.samples = samples;
  11516. this.remuxAudio(track, timeOffset, contiguous);
  11517. }
  11518. }, {
  11519. key: 'remuxID3',
  11520. value: function remuxID3(track) {
  11521. var length = track.samples.length,
  11522. sample = void 0;
  11523. var inputTimeScale = track.inputTimeScale;
  11524. var initPTS = this._initPTS;
  11525. var initDTS = this._initDTS;
  11526. // consume samples
  11527. if (length) {
  11528. for (var index = 0; index < length; index++) {
  11529. sample = track.samples[index];
  11530. // setting id3 pts, dts to relative time
  11531. // using this._initPTS and this._initDTS to calculate relative time
  11532. sample.pts = (sample.pts - initPTS) / inputTimeScale;
  11533. sample.dts = (sample.dts - initDTS) / inputTimeScale;
  11534. }
  11535. this.observer.trigger(_events2.default.FRAG_PARSING_METADATA, {
  11536. samples: track.samples
  11537. });
  11538. }
  11539. track.samples = [];
  11540. }
  11541. }, {
  11542. key: 'remuxText',
  11543. value: function remuxText(track) {
  11544. track.samples.sort(function (a, b) {
  11545. return a.pts - b.pts;
  11546. });
  11547. var length = track.samples.length,
  11548. sample = void 0;
  11549. var inputTimeScale = track.inputTimeScale;
  11550. var initPTS = this._initPTS;
  11551. // consume samples
  11552. if (length) {
  11553. for (var index = 0; index < length; index++) {
  11554. sample = track.samples[index];
  11555. // setting text pts, dts to relative time
  11556. // using this._initPTS and this._initDTS to calculate relative time
  11557. sample.pts = (sample.pts - initPTS) / inputTimeScale;
  11558. }
  11559. this.observer.trigger(_events2.default.FRAG_PARSING_USERDATA, {
  11560. samples: track.samples
  11561. });
  11562. }
  11563. track.samples = [];
  11564. }
  11565. }, {
  11566. key: '_PTSNormalize',
  11567. value: function _PTSNormalize(value, reference) {
  11568. var offset = void 0;
  11569. if (reference === undefined) {
  11570. return value;
  11571. }
  11572. if (reference < value) {
  11573. // - 2^33
  11574. offset = -8589934592;
  11575. } else {
  11576. // + 2^33
  11577. offset = 8589934592;
  11578. }
  11579. /* PTS is 33bit (from 0 to 2^33 -1)
  11580. if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
  11581. PTS looping occured. fill the gap */
  11582. while (Math.abs(value - reference) > 4294967296) {
  11583. value += offset;
  11584. }
  11585. return value;
  11586. }
  11587. }]);
  11588. return MP4Remuxer;
  11589. }();
  11590. exports.default = MP4Remuxer;
  11591. module.exports = exports['default'];
  11592. /***/ }),
  11593. /* 51 */
  11594. /***/ (function(module, exports, __webpack_require__) {
  11595. "use strict";
  11596. Object.defineProperty(exports, "__esModule", {
  11597. value: true
  11598. });
  11599. 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; }; }();
  11600. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  11601. /**
  11602. * AAC helper
  11603. */
  11604. var AAC = function () {
  11605. function AAC() {
  11606. _classCallCheck(this, AAC);
  11607. }
  11608. _createClass(AAC, null, [{
  11609. key: 'getSilentFrame',
  11610. value: function getSilentFrame(codec, channelCount) {
  11611. switch (codec) {
  11612. case 'mp4a.40.2':
  11613. if (channelCount === 1) {
  11614. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  11615. } else if (channelCount === 2) {
  11616. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  11617. } else if (channelCount === 3) {
  11618. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  11619. } else if (channelCount === 4) {
  11620. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  11621. } else if (channelCount === 5) {
  11622. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  11623. } else if (channelCount === 6) {
  11624. 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]);
  11625. }
  11626. break;
  11627. // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
  11628. default:
  11629. if (channelCount === 1) {
  11630. // 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
  11631. 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]);
  11632. } else if (channelCount === 2) {
  11633. // 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
  11634. 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]);
  11635. } else if (channelCount === 3) {
  11636. // 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
  11637. 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]);
  11638. }
  11639. break;
  11640. }
  11641. return null;
  11642. }
  11643. }]);
  11644. return AAC;
  11645. }();
  11646. exports.default = AAC;
  11647. module.exports = exports['default'];
  11648. /***/ }),
  11649. /* 52 */
  11650. /***/ (function(module, exports, __webpack_require__) {
  11651. "use strict";
  11652. Object.defineProperty(exports, "__esModule", {
  11653. value: true
  11654. });
  11655. 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; }; }();
  11656. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  11657. /**
  11658. * Generate MP4 Box
  11659. */
  11660. var UINT32_MAX = Math.pow(2, 32) - 1;
  11661. var MP4 = function () {
  11662. function MP4() {
  11663. _classCallCheck(this, MP4);
  11664. }
  11665. _createClass(MP4, null, [{
  11666. key: 'init',
  11667. value: function init() {
  11668. MP4.types = {
  11669. avc1: [], // codingname
  11670. avcC: [],
  11671. btrt: [],
  11672. dinf: [],
  11673. dref: [],
  11674. esds: [],
  11675. ftyp: [],
  11676. hdlr: [],
  11677. mdat: [],
  11678. mdhd: [],
  11679. mdia: [],
  11680. mfhd: [],
  11681. minf: [],
  11682. moof: [],
  11683. moov: [],
  11684. mp4a: [],
  11685. '.mp3': [],
  11686. mvex: [],
  11687. mvhd: [],
  11688. pasp: [],
  11689. sdtp: [],
  11690. stbl: [],
  11691. stco: [],
  11692. stsc: [],
  11693. stsd: [],
  11694. stsz: [],
  11695. stts: [],
  11696. tfdt: [],
  11697. tfhd: [],
  11698. traf: [],
  11699. trak: [],
  11700. trun: [],
  11701. trex: [],
  11702. tkhd: [],
  11703. vmhd: [],
  11704. smhd: []
  11705. };
  11706. var i = void 0;
  11707. for (i in MP4.types) {
  11708. if (MP4.types.hasOwnProperty(i)) {
  11709. MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  11710. }
  11711. }
  11712. var videoHdlr = new Uint8Array([0x00, // version 0
  11713. 0x00, 0x00, 0x00, // flags
  11714. 0x00, 0x00, 0x00, 0x00, // pre_defined
  11715. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  11716. 0x00, 0x00, 0x00, 0x00, // reserved
  11717. 0x00, 0x00, 0x00, 0x00, // reserved
  11718. 0x00, 0x00, 0x00, 0x00, // reserved
  11719. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  11720. ]);
  11721. var audioHdlr = new Uint8Array([0x00, // version 0
  11722. 0x00, 0x00, 0x00, // flags
  11723. 0x00, 0x00, 0x00, 0x00, // pre_defined
  11724. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  11725. 0x00, 0x00, 0x00, 0x00, // reserved
  11726. 0x00, 0x00, 0x00, 0x00, // reserved
  11727. 0x00, 0x00, 0x00, 0x00, // reserved
  11728. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  11729. ]);
  11730. MP4.HDLR_TYPES = {
  11731. 'video': videoHdlr,
  11732. 'audio': audioHdlr
  11733. };
  11734. var dref = new Uint8Array([0x00, // version 0
  11735. 0x00, 0x00, 0x00, // flags
  11736. 0x00, 0x00, 0x00, 0x01, // entry_count
  11737. 0x00, 0x00, 0x00, 0x0c, // entry_size
  11738. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  11739. 0x00, // version 0
  11740. 0x00, 0x00, 0x01 // entry_flags
  11741. ]);
  11742. var stco = new Uint8Array([0x00, // version
  11743. 0x00, 0x00, 0x00, // flags
  11744. 0x00, 0x00, 0x00, 0x00 // entry_count
  11745. ]);
  11746. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  11747. MP4.STSZ = new Uint8Array([0x00, // version
  11748. 0x00, 0x00, 0x00, // flags
  11749. 0x00, 0x00, 0x00, 0x00, // sample_size
  11750. 0x00, 0x00, 0x00, 0x00 // sample_count
  11751. ]);
  11752. MP4.VMHD = new Uint8Array([0x00, // version
  11753. 0x00, 0x00, 0x01, // flags
  11754. 0x00, 0x00, // graphicsmode
  11755. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  11756. ]);
  11757. MP4.SMHD = new Uint8Array([0x00, // version
  11758. 0x00, 0x00, 0x00, // flags
  11759. 0x00, 0x00, // balance
  11760. 0x00, 0x00 // reserved
  11761. ]);
  11762. MP4.STSD = new Uint8Array([0x00, // version 0
  11763. 0x00, 0x00, 0x00, // flags
  11764. 0x00, 0x00, 0x00, 0x01]); // entry_count
  11765. var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
  11766. var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
  11767. var minorVersion = new Uint8Array([0, 0, 0, 1]);
  11768. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  11769. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  11770. }
  11771. }, {
  11772. key: 'box',
  11773. value: function box(type) {
  11774. var payload = Array.prototype.slice.call(arguments, 1),
  11775. size = 8,
  11776. i = payload.length,
  11777. len = i,
  11778. result = void 0;
  11779. // calculate the total size we need to allocate
  11780. while (i--) {
  11781. size += payload[i].byteLength;
  11782. }
  11783. result = new Uint8Array(size);
  11784. result[0] = size >> 24 & 0xff;
  11785. result[1] = size >> 16 & 0xff;
  11786. result[2] = size >> 8 & 0xff;
  11787. result[3] = size & 0xff;
  11788. result.set(type, 4);
  11789. // copy the payload into the result
  11790. for (i = 0, size = 8; i < len; i++) {
  11791. // copy payload[i] array @ offset size
  11792. result.set(payload[i], size);
  11793. size += payload[i].byteLength;
  11794. }
  11795. return result;
  11796. }
  11797. }, {
  11798. key: 'hdlr',
  11799. value: function hdlr(type) {
  11800. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  11801. }
  11802. }, {
  11803. key: 'mdat',
  11804. value: function mdat(data) {
  11805. return MP4.box(MP4.types.mdat, data);
  11806. }
  11807. }, {
  11808. key: 'mdhd',
  11809. value: function mdhd(timescale, duration) {
  11810. duration *= timescale;
  11811. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  11812. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  11813. return MP4.box(MP4.types.mdhd, new Uint8Array([0x01, // version 1
  11814. 0x00, 0x00, 0x00, // flags
  11815. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
  11816. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
  11817. timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
  11818. upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x55, 0xc4, // 'und' language (undetermined)
  11819. 0x00, 0x00]));
  11820. }
  11821. }, {
  11822. key: 'mdia',
  11823. value: function mdia(track) {
  11824. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
  11825. }
  11826. }, {
  11827. key: 'mfhd',
  11828. value: function mfhd(sequenceNumber) {
  11829. return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
  11830. sequenceNumber >> 24, sequenceNumber >> 16 & 0xFF, sequenceNumber >> 8 & 0xFF, sequenceNumber & 0xFF // sequence_number
  11831. ]));
  11832. }
  11833. }, {
  11834. key: 'minf',
  11835. value: function minf(track) {
  11836. if (track.type === 'audio') {
  11837. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  11838. } else {
  11839. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  11840. }
  11841. }
  11842. }, {
  11843. key: 'moof',
  11844. value: function moof(sn, baseMediaDecodeTime, track) {
  11845. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  11846. }
  11847. /**
  11848. * @param tracks... (optional) {array} the tracks associated with this movie
  11849. */
  11850. }, {
  11851. key: 'moov',
  11852. value: function moov(tracks) {
  11853. var i = tracks.length,
  11854. boxes = [];
  11855. while (i--) {
  11856. boxes[i] = MP4.trak(tracks[i]);
  11857. }
  11858. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
  11859. }
  11860. }, {
  11861. key: 'mvex',
  11862. value: function mvex(tracks) {
  11863. var i = tracks.length,
  11864. boxes = [];
  11865. while (i--) {
  11866. boxes[i] = MP4.trex(tracks[i]);
  11867. }
  11868. return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
  11869. }
  11870. }, {
  11871. key: 'mvhd',
  11872. value: function mvhd(timescale, duration) {
  11873. duration *= timescale;
  11874. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  11875. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  11876. var bytes = new Uint8Array([0x01, // version 1
  11877. 0x00, 0x00, 0x00, // flags
  11878. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
  11879. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
  11880. timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
  11881. upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x00, 0x01, 0x00, 0x00, // 1.0 rate
  11882. 0x01, 0x00, // 1.0 volume
  11883. 0x00, 0x00, // reserved
  11884. 0x00, 0x00, 0x00, 0x00, // reserved
  11885. 0x00, 0x00, 0x00, 0x00, // reserved
  11886. 0x00, 0x01, 0x00, 0x00, 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, // transformation: unity matrix
  11887. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  11888. 0xff, 0xff, 0xff, 0xff // next_track_ID
  11889. ]);
  11890. return MP4.box(MP4.types.mvhd, bytes);
  11891. }
  11892. }, {
  11893. key: 'sdtp',
  11894. value: function sdtp(track) {
  11895. var samples = track.samples || [],
  11896. bytes = new Uint8Array(4 + samples.length),
  11897. flags = void 0,
  11898. i = void 0;
  11899. // leave the full box header (4 bytes) all zero
  11900. // write the sample table
  11901. for (i = 0; i < samples.length; i++) {
  11902. flags = samples[i].flags;
  11903. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  11904. }
  11905. return MP4.box(MP4.types.sdtp, bytes);
  11906. }
  11907. }, {
  11908. key: 'stbl',
  11909. value: function stbl(track) {
  11910. return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));
  11911. }
  11912. }, {
  11913. key: 'avc1',
  11914. value: function avc1(track) {
  11915. var sps = [],
  11916. pps = [],
  11917. i = void 0,
  11918. data = void 0,
  11919. len = void 0;
  11920. // assemble the SPSs
  11921. for (i = 0; i < track.sps.length; i++) {
  11922. data = track.sps[i];
  11923. len = data.byteLength;
  11924. sps.push(len >>> 8 & 0xFF);
  11925. sps.push(len & 0xFF);
  11926. // SPS
  11927. sps = sps.concat(Array.prototype.slice.call(data));
  11928. }
  11929. // assemble the PPSs
  11930. for (i = 0; i < track.pps.length; i++) {
  11931. data = track.pps[i];
  11932. len = data.byteLength;
  11933. pps.push(len >>> 8 & 0xFF);
  11934. pps.push(len & 0xFF);
  11935. pps = pps.concat(Array.prototype.slice.call(data));
  11936. }
  11937. var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version
  11938. sps[3], // profile
  11939. sps[4], // profile compat
  11940. sps[5], // level
  11941. 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes
  11942. 0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
  11943. ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
  11944. ]).concat(pps))),
  11945. // "PPS"
  11946. width = track.width,
  11947. height = track.height,
  11948. hSpacing = track.pixelRatio[0],
  11949. vSpacing = track.pixelRatio[1];
  11950. return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved
  11951. 0x00, 0x00, 0x00, // reserved
  11952. 0x00, 0x01, // data_reference_index
  11953. 0x00, 0x00, // pre_defined
  11954. 0x00, 0x00, // reserved
  11955. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  11956. width >> 8 & 0xFF, width & 0xff, // width
  11957. height >> 8 & 0xFF, height & 0xff, // height
  11958. 0x00, 0x48, 0x00, 0x00, // horizresolution
  11959. 0x00, 0x48, 0x00, 0x00, // vertresolution
  11960. 0x00, 0x00, 0x00, 0x00, // reserved
  11961. 0x00, 0x01, // frame_count
  11962. 0x12, 0x64, 0x61, 0x69, 0x6C, // dailymotion/hls.js
  11963. 0x79, 0x6D, 0x6F, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x68, 0x6C, 0x73, 0x2E, 0x6A, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
  11964. 0x00, 0x18, // depth = 24
  11965. 0x11, 0x11]), // pre_defined = -1
  11966. avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  11967. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  11968. 0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate
  11969. MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24, // hSpacing
  11970. hSpacing >> 16 & 0xFF, hSpacing >> 8 & 0xFF, hSpacing & 0xFF, vSpacing >> 24, // vSpacing
  11971. vSpacing >> 16 & 0xFF, vSpacing >> 8 & 0xFF, vSpacing & 0xFF])));
  11972. }
  11973. }, {
  11974. key: 'esds',
  11975. value: function esds(track) {
  11976. var configlen = track.config.length;
  11977. return new Uint8Array([0x00, // version 0
  11978. 0x00, 0x00, 0x00, // flags
  11979. 0x03, // descriptor_type
  11980. 0x17 + configlen, // length
  11981. 0x00, 0x01, // es_id
  11982. 0x00, // stream_priority
  11983. 0x04, // descriptor_type
  11984. 0x0f + configlen, // length
  11985. 0x40, // codec : mpeg4_audio
  11986. 0x15, // stream_type
  11987. 0x00, 0x00, 0x00, // buffer_size
  11988. 0x00, 0x00, 0x00, 0x00, // maxBitrate
  11989. 0x00, 0x00, 0x00, 0x00, // avgBitrate
  11990. 0x05 // descriptor_type
  11991. ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
  11992. }
  11993. }, {
  11994. key: 'mp4a',
  11995. value: function mp4a(track) {
  11996. var samplerate = track.samplerate;
  11997. return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved
  11998. 0x00, 0x00, 0x00, // reserved
  11999. 0x00, 0x01, // data_reference_index
  12000. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  12001. 0x00, track.channelCount, // channelcount
  12002. 0x00, 0x10, // sampleSize:16bits
  12003. 0x00, 0x00, 0x00, 0x00, // reserved2
  12004. samplerate >> 8 & 0xFF, samplerate & 0xff, //
  12005. 0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
  12006. }
  12007. }, {
  12008. key: 'mp3',
  12009. value: function mp3(track) {
  12010. var samplerate = track.samplerate;
  12011. return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved
  12012. 0x00, 0x00, 0x00, // reserved
  12013. 0x00, 0x01, // data_reference_index
  12014. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  12015. 0x00, track.channelCount, // channelcount
  12016. 0x00, 0x10, // sampleSize:16bits
  12017. 0x00, 0x00, 0x00, 0x00, // reserved2
  12018. samplerate >> 8 & 0xFF, samplerate & 0xff, //
  12019. 0x00, 0x00]));
  12020. }
  12021. }, {
  12022. key: 'stsd',
  12023. value: function stsd(track) {
  12024. if (track.type === 'audio') {
  12025. if (!track.isAAC && track.codec === 'mp3') {
  12026. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  12027. }
  12028. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  12029. } else {
  12030. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  12031. }
  12032. }
  12033. }, {
  12034. key: 'tkhd',
  12035. value: function tkhd(track) {
  12036. var id = track.id,
  12037. duration = track.duration * track.timescale,
  12038. width = track.width,
  12039. height = track.height,
  12040. upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)),
  12041. lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  12042. return MP4.box(MP4.types.tkhd, new Uint8Array([0x01, // version 1
  12043. 0x00, 0x00, 0x07, // flags
  12044. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
  12045. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
  12046. id >> 24 & 0xFF, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID
  12047. 0x00, 0x00, 0x00, 0x00, // reserved
  12048. upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  12049. 0x00, 0x00, // layer
  12050. 0x00, 0x00, // alternate_group
  12051. 0x00, 0x00, // non-audio track volume
  12052. 0x00, 0x00, // reserved
  12053. 0x00, 0x01, 0x00, 0x00, 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, // transformation: unity matrix
  12054. width >> 8 & 0xFF, width & 0xFF, 0x00, 0x00, // width
  12055. height >> 8 & 0xFF, height & 0xFF, 0x00, 0x00 // height
  12056. ]));
  12057. }
  12058. }, {
  12059. key: 'traf',
  12060. value: function traf(track, baseMediaDecodeTime) {
  12061. var sampleDependencyTable = MP4.sdtp(track),
  12062. id = track.id,
  12063. upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)),
  12064. lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  12065. return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0
  12066. 0x00, 0x00, 0x00, // flags
  12067. id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF]) // track_ID
  12068. ), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1
  12069. 0x00, 0x00, 0x00, // flags
  12070. upperWordBaseMediaDecodeTime >> 24, upperWordBaseMediaDecodeTime >> 16 & 0XFF, upperWordBaseMediaDecodeTime >> 8 & 0XFF, upperWordBaseMediaDecodeTime & 0xFF, lowerWordBaseMediaDecodeTime >> 24, lowerWordBaseMediaDecodeTime >> 16 & 0XFF, lowerWordBaseMediaDecodeTime >> 8 & 0XFF, lowerWordBaseMediaDecodeTime & 0xFF])), MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd
  12071. 20 + // tfdt
  12072. 8 + // traf header
  12073. 16 + // mfhd
  12074. 8 + // moof header
  12075. 8), // mdat header
  12076. sampleDependencyTable);
  12077. }
  12078. /**
  12079. * Generate a track box.
  12080. * @param track {object} a track definition
  12081. * @return {Uint8Array} the track box
  12082. */
  12083. }, {
  12084. key: 'trak',
  12085. value: function trak(track) {
  12086. track.duration = track.duration || 0xffffffff;
  12087. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  12088. }
  12089. }, {
  12090. key: 'trex',
  12091. value: function trex(track) {
  12092. var id = track.id;
  12093. return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0
  12094. 0x00, 0x00, 0x00, // flags
  12095. id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF, // track_ID
  12096. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  12097. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  12098. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  12099. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  12100. ]));
  12101. }
  12102. }, {
  12103. key: 'trun',
  12104. value: function trun(track, offset) {
  12105. var samples = track.samples || [],
  12106. len = samples.length,
  12107. arraylen = 12 + 16 * len,
  12108. array = new Uint8Array(arraylen),
  12109. i = void 0,
  12110. sample = void 0,
  12111. duration = void 0,
  12112. size = void 0,
  12113. flags = void 0,
  12114. cts = void 0;
  12115. offset += 8 + arraylen;
  12116. array.set([0x00, // version 0
  12117. 0x00, 0x0f, 0x01, // flags
  12118. len >>> 24 & 0xFF, len >>> 16 & 0xFF, len >>> 8 & 0xFF, len & 0xFF, // sample_count
  12119. offset >>> 24 & 0xFF, offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF // data_offset
  12120. ], 0);
  12121. for (i = 0; i < len; i++) {
  12122. sample = samples[i];
  12123. duration = sample.duration;
  12124. size = sample.size;
  12125. flags = sample.flags;
  12126. cts = sample.cts;
  12127. array.set([duration >>> 24 & 0xFF, duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, // sample_duration
  12128. size >>> 24 & 0xFF, size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, // sample_size
  12129. flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xF0 << 8, flags.degradPrio & 0x0F, // sample_flags
  12130. cts >>> 24 & 0xFF, cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF // sample_composition_time_offset
  12131. ], 12 + 16 * i);
  12132. }
  12133. return MP4.box(MP4.types.trun, array);
  12134. }
  12135. }, {
  12136. key: 'initSegment',
  12137. value: function initSegment(tracks) {
  12138. if (!MP4.types) {
  12139. MP4.init();
  12140. }
  12141. var movie = MP4.moov(tracks),
  12142. result = void 0;
  12143. result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
  12144. result.set(MP4.FTYP);
  12145. result.set(movie, MP4.FTYP.byteLength);
  12146. return result;
  12147. }
  12148. }]);
  12149. return MP4;
  12150. }();
  12151. exports.default = MP4;
  12152. module.exports = exports['default'];
  12153. /***/ }),
  12154. /* 53 */
  12155. /***/ (function(module, exports, __webpack_require__) {
  12156. "use strict";
  12157. Object.defineProperty(exports, "__esModule", {
  12158. value: true
  12159. });
  12160. 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; }; }(); /**
  12161. * passthrough remuxer
  12162. */
  12163. var _events = __webpack_require__(1);
  12164. var _events2 = _interopRequireDefault(_events);
  12165. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12166. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  12167. var PassThroughRemuxer = function () {
  12168. function PassThroughRemuxer(observer) {
  12169. _classCallCheck(this, PassThroughRemuxer);
  12170. this.observer = observer;
  12171. }
  12172. _createClass(PassThroughRemuxer, [{
  12173. key: 'destroy',
  12174. value: function destroy() {}
  12175. }, {
  12176. key: 'resetTimeStamp',
  12177. value: function resetTimeStamp() {}
  12178. }, {
  12179. key: 'resetInitSegment',
  12180. value: function resetInitSegment() {}
  12181. }, {
  12182. key: 'remux',
  12183. value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset, rawData) {
  12184. var observer = this.observer;
  12185. var streamType = '';
  12186. if (audioTrack) {
  12187. streamType += 'audio';
  12188. }
  12189. if (videoTrack) {
  12190. streamType += 'video';
  12191. }
  12192. observer.trigger(_events2.default.FRAG_PARSING_DATA, {
  12193. data1: rawData,
  12194. startPTS: timeOffset,
  12195. startDTS: timeOffset,
  12196. type: streamType,
  12197. hasAudio: !!audioTrack,
  12198. hasVideo: !!videoTrack,
  12199. nb: 1,
  12200. dropped: 0
  12201. });
  12202. // notify end of parsing
  12203. observer.trigger(_events2.default.FRAG_PARSED);
  12204. }
  12205. }]);
  12206. return PassThroughRemuxer;
  12207. }();
  12208. exports.default = PassThroughRemuxer;
  12209. module.exports = exports['default'];
  12210. /***/ }),
  12211. /* 54 */
  12212. /***/ (function(module, exports, __webpack_require__) {
  12213. "use strict";
  12214. var has = Object.prototype.hasOwnProperty
  12215. , prefix = '~';
  12216. /**
  12217. * Constructor to create a storage for our `EE` objects.
  12218. * An `Events` instance is a plain object whose properties are event names.
  12219. *
  12220. * @constructor
  12221. * @private
  12222. */
  12223. function Events() {}
  12224. //
  12225. // We try to not inherit from `Object.prototype`. In some engines creating an
  12226. // instance in this way is faster than calling `Object.create(null)` directly.
  12227. // If `Object.create(null)` is not supported we prefix the event names with a
  12228. // character to make sure that the built-in object properties are not
  12229. // overridden or used as an attack vector.
  12230. //
  12231. if (Object.create) {
  12232. Events.prototype = Object.create(null);
  12233. //
  12234. // This hack is needed because the `__proto__` property is still inherited in
  12235. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  12236. //
  12237. if (!new Events().__proto__) prefix = false;
  12238. }
  12239. /**
  12240. * Representation of a single event listener.
  12241. *
  12242. * @param {Function} fn The listener function.
  12243. * @param {*} context The context to invoke the listener with.
  12244. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  12245. * @constructor
  12246. * @private
  12247. */
  12248. function EE(fn, context, once) {
  12249. this.fn = fn;
  12250. this.context = context;
  12251. this.once = once || false;
  12252. }
  12253. /**
  12254. * Add a listener for a given event.
  12255. *
  12256. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  12257. * @param {(String|Symbol)} event The event name.
  12258. * @param {Function} fn The listener function.
  12259. * @param {*} context The context to invoke the listener with.
  12260. * @param {Boolean} once Specify if the listener is a one-time listener.
  12261. * @returns {EventEmitter}
  12262. * @private
  12263. */
  12264. function addListener(emitter, event, fn, context, once) {
  12265. if (typeof fn !== 'function') {
  12266. throw new TypeError('The listener must be a function');
  12267. }
  12268. var listener = new EE(fn, context || emitter, once)
  12269. , evt = prefix ? prefix + event : event;
  12270. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  12271. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  12272. else emitter._events[evt] = [emitter._events[evt], listener];
  12273. return emitter;
  12274. }
  12275. /**
  12276. * Clear event by name.
  12277. *
  12278. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  12279. * @param {(String|Symbol)} evt The Event name.
  12280. * @private
  12281. */
  12282. function clearEvent(emitter, evt) {
  12283. if (--emitter._eventsCount === 0) emitter._events = new Events();
  12284. else delete emitter._events[evt];
  12285. }
  12286. /**
  12287. * Minimal `EventEmitter` interface that is molded against the Node.js
  12288. * `EventEmitter` interface.
  12289. *
  12290. * @constructor
  12291. * @public
  12292. */
  12293. function EventEmitter() {
  12294. this._events = new Events();
  12295. this._eventsCount = 0;
  12296. }
  12297. /**
  12298. * Return an array listing the events for which the emitter has registered
  12299. * listeners.
  12300. *
  12301. * @returns {Array}
  12302. * @public
  12303. */
  12304. EventEmitter.prototype.eventNames = function eventNames() {
  12305. var names = []
  12306. , events
  12307. , name;
  12308. if (this._eventsCount === 0) return names;
  12309. for (name in (events = this._events)) {
  12310. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  12311. }
  12312. if (Object.getOwnPropertySymbols) {
  12313. return names.concat(Object.getOwnPropertySymbols(events));
  12314. }
  12315. return names;
  12316. };
  12317. /**
  12318. * Return the listeners registered for a given event.
  12319. *
  12320. * @param {(String|Symbol)} event The event name.
  12321. * @returns {Array} The registered listeners.
  12322. * @public
  12323. */
  12324. EventEmitter.prototype.listeners = function listeners(event) {
  12325. var evt = prefix ? prefix + event : event
  12326. , handlers = this._events[evt];
  12327. if (!handlers) return [];
  12328. if (handlers.fn) return [handlers.fn];
  12329. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  12330. ee[i] = handlers[i].fn;
  12331. }
  12332. return ee;
  12333. };
  12334. /**
  12335. * Return the number of listeners listening to a given event.
  12336. *
  12337. * @param {(String|Symbol)} event The event name.
  12338. * @returns {Number} The number of listeners.
  12339. * @public
  12340. */
  12341. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  12342. var evt = prefix ? prefix + event : event
  12343. , listeners = this._events[evt];
  12344. if (!listeners) return 0;
  12345. if (listeners.fn) return 1;
  12346. return listeners.length;
  12347. };
  12348. /**
  12349. * Calls each of the listeners registered for a given event.
  12350. *
  12351. * @param {(String|Symbol)} event The event name.
  12352. * @returns {Boolean} `true` if the event had listeners, else `false`.
  12353. * @public
  12354. */
  12355. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  12356. var evt = prefix ? prefix + event : event;
  12357. if (!this._events[evt]) return false;
  12358. var listeners = this._events[evt]
  12359. , len = arguments.length
  12360. , args
  12361. , i;
  12362. if (listeners.fn) {
  12363. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  12364. switch (len) {
  12365. case 1: return listeners.fn.call(listeners.context), true;
  12366. case 2: return listeners.fn.call(listeners.context, a1), true;
  12367. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  12368. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  12369. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  12370. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  12371. }
  12372. for (i = 1, args = new Array(len -1); i < len; i++) {
  12373. args[i - 1] = arguments[i];
  12374. }
  12375. listeners.fn.apply(listeners.context, args);
  12376. } else {
  12377. var length = listeners.length
  12378. , j;
  12379. for (i = 0; i < length; i++) {
  12380. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  12381. switch (len) {
  12382. case 1: listeners[i].fn.call(listeners[i].context); break;
  12383. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  12384. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  12385. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  12386. default:
  12387. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  12388. args[j - 1] = arguments[j];
  12389. }
  12390. listeners[i].fn.apply(listeners[i].context, args);
  12391. }
  12392. }
  12393. }
  12394. return true;
  12395. };
  12396. /**
  12397. * Add a listener for a given event.
  12398. *
  12399. * @param {(String|Symbol)} event The event name.
  12400. * @param {Function} fn The listener function.
  12401. * @param {*} [context=this] The context to invoke the listener with.
  12402. * @returns {EventEmitter} `this`.
  12403. * @public
  12404. */
  12405. EventEmitter.prototype.on = function on(event, fn, context) {
  12406. return addListener(this, event, fn, context, false);
  12407. };
  12408. /**
  12409. * Add a one-time listener for a given event.
  12410. *
  12411. * @param {(String|Symbol)} event The event name.
  12412. * @param {Function} fn The listener function.
  12413. * @param {*} [context=this] The context to invoke the listener with.
  12414. * @returns {EventEmitter} `this`.
  12415. * @public
  12416. */
  12417. EventEmitter.prototype.once = function once(event, fn, context) {
  12418. return addListener(this, event, fn, context, true);
  12419. };
  12420. /**
  12421. * Remove the listeners of a given event.
  12422. *
  12423. * @param {(String|Symbol)} event The event name.
  12424. * @param {Function} fn Only remove the listeners that match this function.
  12425. * @param {*} context Only remove the listeners that have this context.
  12426. * @param {Boolean} once Only remove one-time listeners.
  12427. * @returns {EventEmitter} `this`.
  12428. * @public
  12429. */
  12430. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  12431. var evt = prefix ? prefix + event : event;
  12432. if (!this._events[evt]) return this;
  12433. if (!fn) {
  12434. clearEvent(this, evt);
  12435. return this;
  12436. }
  12437. var listeners = this._events[evt];
  12438. if (listeners.fn) {
  12439. if (
  12440. listeners.fn === fn &&
  12441. (!once || listeners.once) &&
  12442. (!context || listeners.context === context)
  12443. ) {
  12444. clearEvent(this, evt);
  12445. }
  12446. } else {
  12447. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  12448. if (
  12449. listeners[i].fn !== fn ||
  12450. (once && !listeners[i].once) ||
  12451. (context && listeners[i].context !== context)
  12452. ) {
  12453. events.push(listeners[i]);
  12454. }
  12455. }
  12456. //
  12457. // Reset the array, or remove it completely if we have no more listeners.
  12458. //
  12459. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  12460. else clearEvent(this, evt);
  12461. }
  12462. return this;
  12463. };
  12464. /**
  12465. * Remove all listeners, or those of the specified event.
  12466. *
  12467. * @param {(String|Symbol)} [event] The event name.
  12468. * @returns {EventEmitter} `this`.
  12469. * @public
  12470. */
  12471. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  12472. var evt;
  12473. if (event) {
  12474. evt = prefix ? prefix + event : event;
  12475. if (this._events[evt]) clearEvent(this, evt);
  12476. } else {
  12477. this._events = new Events();
  12478. this._eventsCount = 0;
  12479. }
  12480. return this;
  12481. };
  12482. //
  12483. // Alias methods names because people roll like that.
  12484. //
  12485. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  12486. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  12487. //
  12488. // Expose the prefix.
  12489. //
  12490. EventEmitter.prefixed = prefix;
  12491. //
  12492. // Allow `EventEmitter` to be imported as module namespace.
  12493. //
  12494. EventEmitter.EventEmitter = EventEmitter;
  12495. //
  12496. // Expose the module.
  12497. //
  12498. if (true) {
  12499. module.exports = EventEmitter;
  12500. }
  12501. /***/ }),
  12502. /* 55 */
  12503. /***/ (function(module, exports, __webpack_require__) {
  12504. "use strict";
  12505. Object.defineProperty(exports, "__esModule", {
  12506. value: true
  12507. });
  12508. var _demuxerInline = __webpack_require__(21);
  12509. var _demuxerInline2 = _interopRequireDefault(_demuxerInline);
  12510. var _events = __webpack_require__(1);
  12511. var _events2 = _interopRequireDefault(_events);
  12512. var _logger = __webpack_require__(0);
  12513. var _events3 = __webpack_require__(20);
  12514. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12515. /* demuxer web worker.
  12516. * - listen to worker message, and trigger DemuxerInline upon reception of Fragments.
  12517. * - provides MP4 Boxes back to main thread using [transferable objects](https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast) in order to minimize message passing overhead.
  12518. */
  12519. var DemuxerWorker = function DemuxerWorker(self) {
  12520. // observer setup
  12521. var observer = new _events3.EventEmitter();
  12522. observer.trigger = function trigger(event) {
  12523. for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12524. data[_key - 1] = arguments[_key];
  12525. }
  12526. observer.emit.apply(observer, [event, event].concat(data));
  12527. };
  12528. observer.off = function off(event) {
  12529. for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  12530. data[_key2 - 1] = arguments[_key2];
  12531. }
  12532. observer.removeListener.apply(observer, [event].concat(data));
  12533. };
  12534. var forwardMessage = function forwardMessage(ev, data) {
  12535. self.postMessage({ event: ev, data: data });
  12536. };
  12537. self.addEventListener('message', function (ev) {
  12538. var data = ev.data;
  12539. // console.log('demuxer cmd:' + data.cmd);
  12540. switch (data.cmd) {
  12541. case 'init':
  12542. var config = JSON.parse(data.config);
  12543. self.demuxer = new _demuxerInline2.default(observer, data.typeSupported, config, data.vendor);
  12544. (0, _logger.enableLogs)(config.debug);
  12545. // signal end of worker init
  12546. forwardMessage('init', null);
  12547. break;
  12548. case 'demux':
  12549. self.demuxer.push(data.data, data.decryptdata, data.initSegment, data.audioCodec, data.videoCodec, data.timeOffset, data.discontinuity, data.trackSwitch, data.contiguous, data.duration, data.accurateTimeOffset, data.defaultInitPTS);
  12550. break;
  12551. default:
  12552. break;
  12553. }
  12554. });
  12555. // forward events to main thread
  12556. observer.on(_events2.default.FRAG_DECRYPTED, forwardMessage);
  12557. observer.on(_events2.default.FRAG_PARSING_INIT_SEGMENT, forwardMessage);
  12558. observer.on(_events2.default.FRAG_PARSED, forwardMessage);
  12559. observer.on(_events2.default.ERROR, forwardMessage);
  12560. observer.on(_events2.default.FRAG_PARSING_METADATA, forwardMessage);
  12561. observer.on(_events2.default.FRAG_PARSING_USERDATA, forwardMessage);
  12562. observer.on(_events2.default.INIT_PTS_FOUND, forwardMessage);
  12563. // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy)
  12564. observer.on(_events2.default.FRAG_PARSING_DATA, function (ev, data) {
  12565. var transferable = [];
  12566. var message = { event: ev, data: data };
  12567. if (data.data1) {
  12568. message.data1 = data.data1.buffer;
  12569. transferable.push(data.data1.buffer);
  12570. delete data.data1;
  12571. }
  12572. if (data.data2) {
  12573. message.data2 = data.data2.buffer;
  12574. transferable.push(data.data2.buffer);
  12575. delete data.data2;
  12576. }
  12577. self.postMessage(message, transferable);
  12578. });
  12579. };
  12580. exports.default = DemuxerWorker;
  12581. module.exports = exports['default'];
  12582. /***/ }),
  12583. /* 56 */
  12584. /***/ (function(module, exports, __webpack_require__) {
  12585. "use strict";
  12586. Object.defineProperty(exports, "__esModule", {
  12587. value: true
  12588. });
  12589. 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; }; }();
  12590. var _bufferHelper = __webpack_require__(4);
  12591. var _errors = __webpack_require__(2);
  12592. var _events = __webpack_require__(1);
  12593. var _events2 = _interopRequireDefault(_events);
  12594. var _logger = __webpack_require__(0);
  12595. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12596. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  12597. var stallDebounceInterval = 1000;
  12598. var jumpThreshold = 0.5; // tolerance needed as some browsers stalls playback before reaching buffered range end
  12599. var GapController = function () {
  12600. function GapController(config, media, fragmentTracker, hls) {
  12601. _classCallCheck(this, GapController);
  12602. this.config = config;
  12603. this.media = media;
  12604. this.fragmentTracker = fragmentTracker;
  12605. this.hls = hls;
  12606. this.stallReported = false;
  12607. }
  12608. /**
  12609. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  12610. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  12611. * @param lastCurrentTime
  12612. * @param buffered
  12613. */
  12614. _createClass(GapController, [{
  12615. key: 'poll',
  12616. value: function poll(lastCurrentTime, buffered) {
  12617. var config = this.config,
  12618. media = this.media;
  12619. var currentTime = media.currentTime;
  12620. var tnow = window.performance.now();
  12621. if (currentTime !== lastCurrentTime) {
  12622. // The playhead is now moving, but was previously stalled
  12623. if (this.stallReported) {
  12624. _logger.logger.warn('playback not stuck anymore @' + currentTime + ', after ' + Math.round(tnow - this.stalled) + 'ms');
  12625. this.stallReported = false;
  12626. }
  12627. this.stalled = null;
  12628. this.nudgeRetry = 0;
  12629. return;
  12630. }
  12631. if (media.ended || !media.buffered.length || media.readyState > 2) {
  12632. return;
  12633. }
  12634. if (media.seeking && _bufferHelper.BufferHelper.isBuffered(media, currentTime)) {
  12635. return;
  12636. }
  12637. // The playhead isn't moving but it should be
  12638. // Allow some slack time to for small stalls to resolve themselves
  12639. var stalledDuration = tnow - this.stalled;
  12640. var bufferInfo = _bufferHelper.BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  12641. if (!this.stalled) {
  12642. this.stalled = tnow;
  12643. return;
  12644. } else if (stalledDuration >= stallDebounceInterval) {
  12645. // Report stalling after trying to fix
  12646. this._reportStall(bufferInfo.len);
  12647. }
  12648. this._tryFixBufferStall(bufferInfo, stalledDuration);
  12649. }
  12650. /**
  12651. * Detects and attempts to fix known buffer stalling issues.
  12652. * @param bufferInfo - The properties of the current buffer.
  12653. * @param stalledDuration - The amount of time Hls.js has been stalling for.
  12654. * @private
  12655. */
  12656. }, {
  12657. key: '_tryFixBufferStall',
  12658. value: function _tryFixBufferStall(bufferInfo, stalledDuration) {
  12659. var config = this.config,
  12660. fragmentTracker = this.fragmentTracker,
  12661. media = this.media;
  12662. var currentTime = media.currentTime;
  12663. var partial = fragmentTracker.getPartialFragment(currentTime);
  12664. if (partial) {
  12665. // Try to skip over the buffer hole caused by a partial fragment
  12666. // This method isn't limited by the size of the gap between buffered ranges
  12667. this._trySkipBufferHole(partial);
  12668. }
  12669. if (bufferInfo.len > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {
  12670. // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
  12671. // We only try to jump the hole if it's under the configured size
  12672. // Reset stalled so to rearm watchdog timer
  12673. this.stalled = null;
  12674. this._tryNudgeBuffer();
  12675. }
  12676. }
  12677. /**
  12678. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  12679. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  12680. * @private
  12681. */
  12682. }, {
  12683. key: '_reportStall',
  12684. value: function _reportStall(bufferLen) {
  12685. var hls = this.hls,
  12686. media = this.media,
  12687. stallReported = this.stallReported;
  12688. if (!stallReported) {
  12689. // Report stalled error once
  12690. this.stallReported = true;
  12691. _logger.logger.warn('Playback stalling at @' + media.currentTime + ' due to low buffer');
  12692. hls.trigger(_events2.default.ERROR, {
  12693. type: _errors.ErrorTypes.MEDIA_ERROR,
  12694. details: _errors.ErrorDetails.BUFFER_STALLED_ERROR,
  12695. fatal: false,
  12696. buffer: bufferLen
  12697. });
  12698. }
  12699. }
  12700. /**
  12701. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  12702. * @param partial - The partial fragment found at the current time (where playback is stalling).
  12703. * @private
  12704. */
  12705. }, {
  12706. key: '_trySkipBufferHole',
  12707. value: function _trySkipBufferHole(partial) {
  12708. var hls = this.hls,
  12709. media = this.media;
  12710. var currentTime = media.currentTime;
  12711. var lastEndTime = 0;
  12712. // Check if currentTime is between unbuffered regions of partial fragments
  12713. for (var i = 0; i < media.buffered.length; i++) {
  12714. var startTime = media.buffered.start(i);
  12715. if (currentTime >= lastEndTime && currentTime < startTime) {
  12716. media.currentTime = Math.max(startTime, media.currentTime + 0.1);
  12717. _logger.logger.warn('skipping hole, adjusting currentTime from ' + currentTime + ' to ' + media.currentTime);
  12718. this.stalled = null;
  12719. hls.trigger(_events2.default.ERROR, {
  12720. type: _errors.ErrorTypes.MEDIA_ERROR,
  12721. details: _errors.ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  12722. fatal: false,
  12723. reason: 'fragment loaded with buffer holes, seeking from ' + currentTime + ' to ' + media.currentTime,
  12724. frag: partial
  12725. });
  12726. return;
  12727. }
  12728. lastEndTime = media.buffered.end(i);
  12729. }
  12730. }
  12731. /**
  12732. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  12733. * @private
  12734. */
  12735. }, {
  12736. key: '_tryNudgeBuffer',
  12737. value: function _tryNudgeBuffer() {
  12738. var config = this.config,
  12739. hls = this.hls,
  12740. media = this.media;
  12741. var currentTime = media.currentTime;
  12742. var nudgeRetry = (this.nudgeRetry || 0) + 1;
  12743. this.nudgeRetry = nudgeRetry;
  12744. if (nudgeRetry < config.nudgeMaxRetry) {
  12745. var targetTime = currentTime + nudgeRetry * config.nudgeOffset;
  12746. _logger.logger.log('adjust currentTime from ' + currentTime + ' to ' + targetTime);
  12747. // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
  12748. media.currentTime = targetTime;
  12749. hls.trigger(_events2.default.ERROR, {
  12750. type: _errors.ErrorTypes.MEDIA_ERROR,
  12751. details: _errors.ErrorDetails.BUFFER_NUDGE_ON_STALL,
  12752. fatal: false
  12753. });
  12754. } else {
  12755. _logger.logger.error('still stuck in high buffer @' + currentTime + ' after ' + config.nudgeMaxRetry + ', raise fatal error');
  12756. hls.trigger(_events2.default.ERROR, {
  12757. type: _errors.ErrorTypes.MEDIA_ERROR,
  12758. details: _errors.ErrorDetails.BUFFER_STALLED_ERROR,
  12759. fatal: true
  12760. });
  12761. }
  12762. }
  12763. }]);
  12764. return GapController;
  12765. }();
  12766. exports.default = GapController;
  12767. module.exports = exports['default'];
  12768. /***/ }),
  12769. /* 57 */
  12770. /***/ (function(module, exports, __webpack_require__) {
  12771. "use strict";
  12772. Object.defineProperty(exports, "__esModule", {
  12773. value: true
  12774. });
  12775. 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; };
  12776. 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; }; }();
  12777. var _events = __webpack_require__(1);
  12778. var _events2 = _interopRequireDefault(_events);
  12779. var _eventHandler = __webpack_require__(3);
  12780. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  12781. var _logger = __webpack_require__(0);
  12782. var _errors = __webpack_require__(2);
  12783. var _codecs = __webpack_require__(18);
  12784. var _levelHelper = __webpack_require__(7);
  12785. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12786. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  12787. 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; }
  12788. 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; } /*
  12789. * Level Controller
  12790. */
  12791. var _window = window,
  12792. performance = _window.performance;
  12793. var chromeOrFirefox = void 0;
  12794. var LevelController = function (_EventHandler) {
  12795. _inherits(LevelController, _EventHandler);
  12796. function LevelController(hls) {
  12797. _classCallCheck(this, LevelController);
  12798. var _this = _possibleConstructorReturn(this, (LevelController.__proto__ || Object.getPrototypeOf(LevelController)).call(this, hls, _events2.default.MANIFEST_LOADED, _events2.default.LEVEL_LOADED, _events2.default.AUDIO_TRACK_SWITCHED, _events2.default.FRAG_LOADED, _events2.default.ERROR));
  12799. _this.canload = false;
  12800. _this.currentLevelIndex = null;
  12801. _this.manualLevelIndex = -1;
  12802. _this.timer = null;
  12803. chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());
  12804. return _this;
  12805. }
  12806. _createClass(LevelController, [{
  12807. key: 'onHandlerDestroying',
  12808. value: function onHandlerDestroying() {
  12809. this.clearTimer();
  12810. this.manualLevelIndex = -1;
  12811. }
  12812. }, {
  12813. key: 'clearTimer',
  12814. value: function clearTimer() {
  12815. if (this.timer !== null) {
  12816. clearTimeout(this.timer);
  12817. this.timer = null;
  12818. }
  12819. }
  12820. }, {
  12821. key: 'startLoad',
  12822. value: function startLoad() {
  12823. var levels = this._levels;
  12824. this.canload = true;
  12825. this.levelRetryCount = 0;
  12826. // clean up live level details to force reload them, and reset load errors
  12827. if (levels) {
  12828. levels.forEach(function (level) {
  12829. level.loadError = 0;
  12830. var levelDetails = level.details;
  12831. if (levelDetails && levelDetails.live) {
  12832. level.details = undefined;
  12833. }
  12834. });
  12835. }
  12836. // speed up live playlist refresh if timer exists
  12837. if (this.timer !== null) {
  12838. this.loadLevel();
  12839. }
  12840. }
  12841. }, {
  12842. key: 'stopLoad',
  12843. value: function stopLoad() {
  12844. this.canload = false;
  12845. }
  12846. }, {
  12847. key: 'onManifestLoaded',
  12848. value: function onManifestLoaded(data) {
  12849. var levels = [];
  12850. var audioTracks = [];
  12851. var bitrateStart = void 0;
  12852. var levelSet = {};
  12853. var levelFromSet = null;
  12854. var videoCodecFound = false;
  12855. var audioCodecFound = false;
  12856. // regroup redundant levels together
  12857. data.levels.forEach(function (level) {
  12858. var attributes = level.attrs;
  12859. level.loadError = 0;
  12860. level.fragmentError = false;
  12861. videoCodecFound = videoCodecFound || !!level.videoCodec;
  12862. audioCodecFound = audioCodecFound || !!level.audioCodec;
  12863. // erase audio codec info if browser does not support mp4a.40.34.
  12864. // demuxer will autodetect codec and fallback to mpeg/audio
  12865. if (chromeOrFirefox && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {
  12866. level.audioCodec = undefined;
  12867. }
  12868. levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here
  12869. if (!levelFromSet) {
  12870. level.url = [level.url];
  12871. level.urlId = 0;
  12872. levelSet[level.bitrate] = level;
  12873. levels.push(level);
  12874. } else {
  12875. levelFromSet.url.push(level.url);
  12876. }
  12877. if (attributes) {
  12878. if (attributes.AUDIO) {
  12879. audioCodecFound = true;
  12880. (0, _levelHelper.addGroupId)(levelFromSet || level, 'audio', attributes.AUDIO);
  12881. }
  12882. if (attributes.SUBTITLES) {
  12883. (0, _levelHelper.addGroupId)(levelFromSet || level, 'text', attributes.SUBTITLES);
  12884. }
  12885. }
  12886. });
  12887. // remove audio-only level if we also have levels with audio+video codecs signalled
  12888. if (videoCodecFound && audioCodecFound) {
  12889. levels = levels.filter(function (_ref) {
  12890. var videoCodec = _ref.videoCodec;
  12891. return !!videoCodec;
  12892. });
  12893. }
  12894. // only keep levels with supported audio/video codecs
  12895. levels = levels.filter(function (_ref2) {
  12896. var audioCodec = _ref2.audioCodec,
  12897. videoCodec = _ref2.videoCodec;
  12898. return (!audioCodec || (0, _codecs.isCodecSupportedInMp4)(audioCodec, 'audio')) && (!videoCodec || (0, _codecs.isCodecSupportedInMp4)(videoCodec, 'video'));
  12899. });
  12900. if (data.audioTracks) {
  12901. audioTracks = data.audioTracks.filter(function (track) {
  12902. return !track.audioCodec || (0, _codecs.isCodecSupportedInMp4)(track.audioCodec, 'audio');
  12903. });
  12904. // Reassign id's after filtering since they're used as array indices
  12905. audioTracks.forEach(function (track, index) {
  12906. track.id = index;
  12907. });
  12908. }
  12909. if (levels.length > 0) {
  12910. // start bitrate is the first bitrate of the manifest
  12911. bitrateStart = levels[0].bitrate;
  12912. // sort level on bitrate
  12913. levels.sort(function (a, b) {
  12914. return a.bitrate - b.bitrate;
  12915. });
  12916. this._levels = levels;
  12917. // find index of first level in sorted levels
  12918. for (var i = 0; i < levels.length; i++) {
  12919. if (levels[i].bitrate === bitrateStart) {
  12920. this._firstLevel = i;
  12921. _logger.logger.log('manifest loaded,' + levels.length + ' level(s) found, first bitrate:' + bitrateStart);
  12922. break;
  12923. }
  12924. }
  12925. // Audio is only alternate if manifest include a URI along with the audio group tag
  12926. this.hls.trigger(_events2.default.MANIFEST_PARSED, {
  12927. levels: levels,
  12928. audioTracks: audioTracks,
  12929. firstLevel: this._firstLevel,
  12930. stats: data.stats,
  12931. audio: audioCodecFound,
  12932. video: videoCodecFound,
  12933. altAudio: audioTracks.some(function (t) {
  12934. return !!t.url;
  12935. })
  12936. });
  12937. } else {
  12938. this.hls.trigger(_events2.default.ERROR, {
  12939. type: _errors.ErrorTypes.MEDIA_ERROR,
  12940. details: _errors.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  12941. fatal: true,
  12942. url: this.hls.url,
  12943. reason: 'no level with compatible codecs found in manifest'
  12944. });
  12945. }
  12946. }
  12947. }, {
  12948. key: 'setLevelInternal',
  12949. value: function setLevelInternal(newLevel) {
  12950. var levels = this._levels;
  12951. var hls = this.hls;
  12952. // check if level idx is valid
  12953. if (newLevel >= 0 && newLevel < levels.length) {
  12954. // stopping live reloading timer if any
  12955. this.clearTimer();
  12956. if (this.currentLevelIndex !== newLevel) {
  12957. _logger.logger.log('switching to level ' + newLevel);
  12958. this.currentLevelIndex = newLevel;
  12959. var levelProperties = levels[newLevel];
  12960. levelProperties.level = newLevel;
  12961. hls.trigger(_events2.default.LEVEL_SWITCHING, levelProperties);
  12962. }
  12963. var level = levels[newLevel];
  12964. var levelDetails = level.details;
  12965. // check if we need to load playlist for this level
  12966. if (!levelDetails || levelDetails.live) {
  12967. // level not retrieved yet, or live playlist we need to (re)load it
  12968. var urlId = level.urlId;
  12969. hls.trigger(_events2.default.LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId });
  12970. }
  12971. } else {
  12972. // invalid level id given, trigger error
  12973. hls.trigger(_events2.default.ERROR, {
  12974. type: _errors.ErrorTypes.OTHER_ERROR,
  12975. details: _errors.ErrorDetails.LEVEL_SWITCH_ERROR,
  12976. level: newLevel,
  12977. fatal: false,
  12978. reason: 'invalid level idx'
  12979. });
  12980. }
  12981. }
  12982. }, {
  12983. key: 'onError',
  12984. value: function onError(data) {
  12985. if (data.fatal) {
  12986. if (data.type === _errors.ErrorTypes.NETWORK_ERROR) {
  12987. this.clearTimer();
  12988. }
  12989. return;
  12990. }
  12991. var levelError = false,
  12992. fragmentError = false;
  12993. var levelIndex = void 0;
  12994. // try to recover not fatal errors
  12995. switch (data.details) {
  12996. case _errors.ErrorDetails.FRAG_LOAD_ERROR:
  12997. case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
  12998. case _errors.ErrorDetails.KEY_LOAD_ERROR:
  12999. case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
  13000. levelIndex = data.frag.level;
  13001. fragmentError = true;
  13002. break;
  13003. case _errors.ErrorDetails.LEVEL_LOAD_ERROR:
  13004. case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT:
  13005. levelIndex = data.context.level;
  13006. levelError = true;
  13007. break;
  13008. case _errors.ErrorDetails.REMUX_ALLOC_ERROR:
  13009. levelIndex = data.level;
  13010. levelError = true;
  13011. break;
  13012. }
  13013. if (levelIndex !== undefined) {
  13014. this.recoverLevel(data, levelIndex, levelError, fragmentError);
  13015. }
  13016. }
  13017. /**
  13018. * Switch to a redundant stream if any available.
  13019. * If redundant stream is not available, emergency switch down if ABR mode is enabled.
  13020. *
  13021. * @param {Object} errorEvent
  13022. * @param {Number} levelIndex current level index
  13023. * @param {Boolean} levelError
  13024. * @param {Boolean} fragmentError
  13025. */
  13026. // FIXME Find a better abstraction where fragment/level retry management is well decoupled
  13027. }, {
  13028. key: 'recoverLevel',
  13029. value: function recoverLevel(errorEvent, levelIndex, levelError, fragmentError) {
  13030. var _this2 = this;
  13031. var config = this.hls.config;
  13032. var errorDetails = errorEvent.details;
  13033. var level = this._levels[levelIndex];
  13034. var redundantLevels = void 0,
  13035. delay = void 0,
  13036. nextLevel = void 0;
  13037. level.loadError++;
  13038. level.fragmentError = fragmentError;
  13039. if (levelError) {
  13040. if (this.levelRetryCount + 1 <= config.levelLoadingMaxRetry) {
  13041. // exponential backoff capped to max retry timeout
  13042. delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);
  13043. // Schedule level reload
  13044. this.timer = setTimeout(function () {
  13045. return _this2.loadLevel();
  13046. }, delay);
  13047. // boolean used to inform stream controller not to switch back to IDLE on non fatal error
  13048. errorEvent.levelRetry = true;
  13049. this.levelRetryCount++;
  13050. _logger.logger.warn('level controller, ' + errorDetails + ', retry in ' + delay + ' ms, current retry count is ' + this.levelRetryCount);
  13051. } else {
  13052. _logger.logger.error('level controller, cannot recover from ' + errorDetails + ' error');
  13053. this.currentLevelIndex = null;
  13054. // stopping live reloading timer if any
  13055. this.clearTimer();
  13056. // switch error to fatal
  13057. errorEvent.fatal = true;
  13058. return;
  13059. }
  13060. }
  13061. // Try any redundant streams if available for both errors: level and fragment
  13062. // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down
  13063. if (levelError || fragmentError) {
  13064. redundantLevels = level.url.length;
  13065. if (redundantLevels > 1 && level.loadError < redundantLevels) {
  13066. level.urlId = (level.urlId + 1) % redundantLevels;
  13067. level.details = undefined;
  13068. _logger.logger.warn('level controller, ' + errorDetails + ' for level ' + levelIndex + ': switching to redundant URL-id ' + level.urlId);
  13069. // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
  13070. // console.log('New video quality level audio group id:', level.attrs.AUDIO);
  13071. } else {
  13072. // Search for available level
  13073. if (this.manualLevelIndex === -1) {
  13074. // When lowest level has been reached, let's start hunt from the top
  13075. nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1;
  13076. _logger.logger.warn('level controller, ' + errorDetails + ': switch to ' + nextLevel);
  13077. this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;
  13078. } else if (fragmentError) {
  13079. // Allow fragment retry as long as configuration allows.
  13080. // reset this._level so that another call to set level() will trigger again a frag load
  13081. _logger.logger.warn('level controller, ' + errorDetails + ': reload a fragment');
  13082. this.currentLevelIndex = null;
  13083. }
  13084. }
  13085. }
  13086. }
  13087. // reset errors on the successful load of a fragment
  13088. }, {
  13089. key: 'onFragLoaded',
  13090. value: function onFragLoaded(_ref3) {
  13091. var frag = _ref3.frag;
  13092. if (frag !== undefined && frag.type === 'main') {
  13093. var level = this._levels[frag.level];
  13094. if (level !== undefined) {
  13095. level.fragmentError = false;
  13096. level.loadError = 0;
  13097. this.levelRetryCount = 0;
  13098. }
  13099. }
  13100. }
  13101. }, {
  13102. key: 'onLevelLoaded',
  13103. value: function onLevelLoaded(data) {
  13104. var _this3 = this;
  13105. var level = data.level,
  13106. details = data.details;
  13107. // only process level loaded events matching with expected level
  13108. if (level !== this.currentLevelIndex) {
  13109. return;
  13110. }
  13111. var curLevel = this._levels[level];
  13112. // reset level load error counter on successful level loaded only if there is no issues with fragments
  13113. if (!curLevel.fragmentError) {
  13114. curLevel.loadError = 0;
  13115. this.levelRetryCount = 0;
  13116. }
  13117. // if current playlist is a live playlist, arm a timer to reload it
  13118. if (details.live) {
  13119. var reloadInterval = (0, _levelHelper.computeReloadInterval)(curLevel.details, details, data.stats.trequest);
  13120. _logger.logger.log('live playlist, reload in ' + Math.round(reloadInterval) + ' ms');
  13121. this.timer = setTimeout(function () {
  13122. return _this3.loadLevel();
  13123. }, reloadInterval);
  13124. } else {
  13125. this.clearTimer();
  13126. }
  13127. }
  13128. }, {
  13129. key: 'onAudioTrackSwitched',
  13130. value: function onAudioTrackSwitched(data) {
  13131. var audioGroupId = this.hls.audioTracks[data.id].groupId;
  13132. var currentLevel = this.hls.levels[this.currentLevelIndex];
  13133. if (!currentLevel) {
  13134. return;
  13135. }
  13136. if (currentLevel.audioGroupIds) {
  13137. var urlId = -1;
  13138. for (var i = 0; i < currentLevel.audioGroupIds.length; i++) {
  13139. if (currentLevel.audioGroupIds[i] === audioGroupId) {
  13140. urlId = i;
  13141. break;
  13142. }
  13143. }
  13144. if (urlId !== currentLevel.urlId) {
  13145. currentLevel.urlId = urlId;
  13146. this.startLoad();
  13147. }
  13148. }
  13149. }
  13150. }, {
  13151. key: 'loadLevel',
  13152. value: function loadLevel() {
  13153. _logger.logger.debug('call to loadLevel');
  13154. if (this.currentLevelIndex !== null && this.canload) {
  13155. var levelObject = this._levels[this.currentLevelIndex];
  13156. if ((typeof levelObject === 'undefined' ? 'undefined' : _typeof(levelObject)) === 'object' && levelObject.url.length > 0) {
  13157. var level = this.currentLevelIndex;
  13158. var id = levelObject.urlId;
  13159. var url = levelObject.url[id];
  13160. _logger.logger.log('Attempt loading level index ' + level + ' with URL-id ' + id);
  13161. // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
  13162. // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
  13163. this.hls.trigger(_events2.default.LEVEL_LOADING, { url: url, level: level, id: id });
  13164. }
  13165. }
  13166. }
  13167. }, {
  13168. key: 'levels',
  13169. get: function get() {
  13170. return this._levels;
  13171. }
  13172. }, {
  13173. key: 'level',
  13174. get: function get() {
  13175. return this.currentLevelIndex;
  13176. },
  13177. set: function set(newLevel) {
  13178. var levels = this._levels;
  13179. if (levels) {
  13180. newLevel = Math.min(newLevel, levels.length - 1);
  13181. if (this.currentLevelIndex !== newLevel || !levels[newLevel].details) {
  13182. this.setLevelInternal(newLevel);
  13183. }
  13184. }
  13185. }
  13186. }, {
  13187. key: 'manualLevel',
  13188. get: function get() {
  13189. return this.manualLevelIndex;
  13190. },
  13191. set: function set(newLevel) {
  13192. this.manualLevelIndex = newLevel;
  13193. if (this._startLevel === undefined) {
  13194. this._startLevel = newLevel;
  13195. }
  13196. if (newLevel !== -1) {
  13197. this.level = newLevel;
  13198. }
  13199. }
  13200. }, {
  13201. key: 'firstLevel',
  13202. get: function get() {
  13203. return this._firstLevel;
  13204. },
  13205. set: function set(newLevel) {
  13206. this._firstLevel = newLevel;
  13207. }
  13208. }, {
  13209. key: 'startLevel',
  13210. get: function get() {
  13211. // hls.startLevel takes precedence over config.startLevel
  13212. // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)
  13213. if (this._startLevel === undefined) {
  13214. var configStartLevel = this.hls.config.startLevel;
  13215. if (configStartLevel !== undefined) {
  13216. return configStartLevel;
  13217. } else {
  13218. return this._firstLevel;
  13219. }
  13220. } else {
  13221. return this._startLevel;
  13222. }
  13223. },
  13224. set: function set(newLevel) {
  13225. this._startLevel = newLevel;
  13226. }
  13227. }, {
  13228. key: 'nextLoadLevel',
  13229. get: function get() {
  13230. if (this.manualLevelIndex !== -1) {
  13231. return this.manualLevelIndex;
  13232. } else {
  13233. return this.hls.nextAutoLevel;
  13234. }
  13235. },
  13236. set: function set(nextLevel) {
  13237. this.level = nextLevel;
  13238. if (this.manualLevelIndex === -1) {
  13239. this.hls.nextAutoLevel = nextLevel;
  13240. }
  13241. }
  13242. }]);
  13243. return LevelController;
  13244. }(_eventHandler2.default);
  13245. exports.default = LevelController;
  13246. module.exports = exports['default'];
  13247. /***/ }),
  13248. /* 58 */
  13249. /***/ (function(module, exports, __webpack_require__) {
  13250. "use strict";
  13251. Object.defineProperty(exports, "__esModule", {
  13252. value: true
  13253. });
  13254. 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; }; }();
  13255. var _events = __webpack_require__(1);
  13256. var _events2 = _interopRequireDefault(_events);
  13257. var _eventHandler = __webpack_require__(3);
  13258. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  13259. var _id = __webpack_require__(10);
  13260. var _id2 = _interopRequireDefault(_id);
  13261. var _texttrackUtils = __webpack_require__(29);
  13262. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13263. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13264. 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; }
  13265. 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; } /*
  13266. * id3 metadata track controller
  13267. */
  13268. var ID3TrackController = function (_EventHandler) {
  13269. _inherits(ID3TrackController, _EventHandler);
  13270. function ID3TrackController(hls) {
  13271. _classCallCheck(this, ID3TrackController);
  13272. var _this = _possibleConstructorReturn(this, (ID3TrackController.__proto__ || Object.getPrototypeOf(ID3TrackController)).call(this, hls, _events2.default.MEDIA_ATTACHED, _events2.default.MEDIA_DETACHING, _events2.default.FRAG_PARSING_METADATA));
  13273. _this.id3Track = undefined;
  13274. _this.media = undefined;
  13275. return _this;
  13276. }
  13277. _createClass(ID3TrackController, [{
  13278. key: 'destroy',
  13279. value: function destroy() {
  13280. _eventHandler2.default.prototype.destroy.call(this);
  13281. }
  13282. // Add ID3 metatadata text track.
  13283. }, {
  13284. key: 'onMediaAttached',
  13285. value: function onMediaAttached(data) {
  13286. this.media = data.media;
  13287. if (!this.media) {}
  13288. }
  13289. }, {
  13290. key: 'onMediaDetaching',
  13291. value: function onMediaDetaching() {
  13292. (0, _texttrackUtils.clearCurrentCues)(this.id3Track);
  13293. this.id3Track = undefined;
  13294. this.media = undefined;
  13295. }
  13296. }, {
  13297. key: 'getID3Track',
  13298. value: function getID3Track(textTracks) {
  13299. for (var i = 0; i < textTracks.length; i++) {
  13300. var textTrack = textTracks[i];
  13301. if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
  13302. // send 'addtrack' when reusing the textTrack for metadata,
  13303. // same as what we do for captions
  13304. (0, _texttrackUtils.sendAddTrackEvent)(textTrack, this.media);
  13305. return textTrack;
  13306. }
  13307. }
  13308. return this.media.addTextTrack('metadata', 'id3');
  13309. }
  13310. }, {
  13311. key: 'onFragParsingMetadata',
  13312. value: function onFragParsingMetadata(data) {
  13313. var fragment = data.frag;
  13314. var samples = data.samples;
  13315. // create track dynamically
  13316. if (!this.id3Track) {
  13317. this.id3Track = this.getID3Track(this.media.textTracks);
  13318. this.id3Track.mode = 'hidden';
  13319. }
  13320. // Attempt to recreate Safari functionality by creating
  13321. // WebKitDataCue objects when available and store the decoded
  13322. // ID3 data in the value property of the cue
  13323. var Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;
  13324. for (var i = 0; i < samples.length; i++) {
  13325. var frames = _id2.default.getID3Frames(samples[i].data);
  13326. if (frames) {
  13327. var startTime = samples[i].pts;
  13328. var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.endPTS;
  13329. // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
  13330. if (startTime === endTime) {
  13331. endTime += 0.0001;
  13332. }
  13333. for (var j = 0; j < frames.length; j++) {
  13334. var frame = frames[j];
  13335. // Safari doesn't put the timestamp frame in the TextTrack
  13336. if (!_id2.default.isTimeStampFrame(frame)) {
  13337. var cue = new Cue(startTime, endTime, '');
  13338. cue.value = frame;
  13339. this.id3Track.addCue(cue);
  13340. }
  13341. }
  13342. }
  13343. }
  13344. }
  13345. }]);
  13346. return ID3TrackController;
  13347. }(_eventHandler2.default);
  13348. exports.default = ID3TrackController;
  13349. module.exports = exports['default'];
  13350. /***/ }),
  13351. /* 59 */
  13352. /***/ (function(module, exports, __webpack_require__) {
  13353. "use strict";
  13354. Object.defineProperty(exports, "__esModule", {
  13355. value: true
  13356. });
  13357. exports.isSupported = isSupported;
  13358. var _mediasourceHelper = __webpack_require__(13);
  13359. function isSupported() {
  13360. var mediaSource = (0, _mediasourceHelper.getMediaSource)();
  13361. var sourceBuffer = window.SourceBuffer || window.WebKitSourceBuffer;
  13362. var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
  13363. // if SourceBuffer is exposed ensure its API is valid
  13364. // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
  13365. var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
  13366. return !!isTypeSupported && !!sourceBufferValidAPI;
  13367. }
  13368. /***/ }),
  13369. /* 60 */
  13370. /***/ (function(module, exports, __webpack_require__) {
  13371. "use strict";
  13372. Object.defineProperty(exports, "__esModule", {
  13373. value: true
  13374. });
  13375. exports.hlsDefaultConfig = undefined;
  13376. var _abrController = __webpack_require__(61);
  13377. var _abrController2 = _interopRequireDefault(_abrController);
  13378. var _bufferController = __webpack_require__(64);
  13379. var _bufferController2 = _interopRequireDefault(_bufferController);
  13380. var _capLevelController = __webpack_require__(65);
  13381. var _capLevelController2 = _interopRequireDefault(_capLevelController);
  13382. var _fpsController = __webpack_require__(66);
  13383. var _fpsController2 = _interopRequireDefault(_fpsController);
  13384. var _xhrLoader = __webpack_require__(67);
  13385. var _xhrLoader2 = _interopRequireDefault(_xhrLoader);
  13386. var _audioTrackController = __webpack_require__(68);
  13387. var _audioTrackController2 = _interopRequireDefault(_audioTrackController);
  13388. var _audioStreamController = __webpack_require__(69);
  13389. var _audioStreamController2 = _interopRequireDefault(_audioStreamController);
  13390. var _cues = __webpack_require__(70);
  13391. var Cues = _interopRequireWildcard(_cues);
  13392. var _timelineController = __webpack_require__(72);
  13393. var _timelineController2 = _interopRequireDefault(_timelineController);
  13394. var _subtitleTrackController = __webpack_require__(76);
  13395. var _subtitleTrackController2 = _interopRequireDefault(_subtitleTrackController);
  13396. var _subtitleStreamController = __webpack_require__(77);
  13397. var _emeController = __webpack_require__(78);
  13398. var _emeController2 = _interopRequireDefault(_emeController);
  13399. var _mediakeysHelper = __webpack_require__(79);
  13400. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  13401. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13402. // import FetchLoader from './utils/fetch-loader';
  13403. var hlsDefaultConfig = exports.hlsDefaultConfig = {
  13404. autoStartLoad: true, // used by stream-controller
  13405. startPosition: -1, // used by stream-controller
  13406. defaultAudioCodec: undefined, // used by stream-controller
  13407. debug: false, // used by logger
  13408. capLevelOnFPSDrop: false, // used by fps-controller
  13409. capLevelToPlayerSize: false, // used by cap-level-controller
  13410. initialLiveManifestSize: 1, // used by stream-controller
  13411. maxBufferLength: 30, // used by stream-controller
  13412. maxBufferSize: 60 * 1000 * 1000, // used by stream-controller
  13413. maxBufferHole: 0.5, // used by stream-controller
  13414. lowBufferWatchdogPeriod: 0.5, // used by stream-controller
  13415. highBufferWatchdogPeriod: 3, // used by stream-controller
  13416. nudgeOffset: 0.1, // used by stream-controller
  13417. nudgeMaxRetry: 3, // used by stream-controller
  13418. maxFragLookUpTolerance: 0.25, // used by stream-controller
  13419. liveSyncDurationCount: 3, // used by stream-controller
  13420. liveMaxLatencyDurationCount: Infinity, // used by stream-controller
  13421. liveSyncDuration: undefined, // used by stream-controller
  13422. liveMaxLatencyDuration: undefined, // used by stream-controller
  13423. liveDurationInfinity: false, // used by buffer-controller
  13424. liveBackBufferLength: Infinity, // used by buffer-controller
  13425. maxMaxBufferLength: 600, // used by stream-controller
  13426. enableWorker: true, // used by demuxer
  13427. enableSoftwareAES: true, // used by decrypter
  13428. manifestLoadingTimeOut: 10000, // used by playlist-loader
  13429. manifestLoadingMaxRetry: 1, // used by playlist-loader
  13430. manifestLoadingRetryDelay: 1000, // used by playlist-loader
  13431. manifestLoadingMaxRetryTimeout: 64000, // used by playlist-loader
  13432. startLevel: undefined, // used by level-controller
  13433. levelLoadingTimeOut: 10000, // used by playlist-loader
  13434. levelLoadingMaxRetry: 4, // used by playlist-loader
  13435. levelLoadingRetryDelay: 1000, // used by playlist-loader
  13436. levelLoadingMaxRetryTimeout: 64000, // used by playlist-loader
  13437. fragLoadingTimeOut: 20000, // used by fragment-loader
  13438. fragLoadingMaxRetry: 6, // used by fragment-loader
  13439. fragLoadingRetryDelay: 1000, // used by fragment-loader
  13440. fragLoadingMaxRetryTimeout: 64000, // used by fragment-loader
  13441. startFragPrefetch: false, // used by stream-controller
  13442. fpsDroppedMonitoringPeriod: 5000, // used by fps-controller
  13443. fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller
  13444. appendErrorMaxRetry: 3, // used by buffer-controller
  13445. loader: _xhrLoader2.default,
  13446. // loader: FetchLoader,
  13447. fLoader: undefined, // used by fragment-loader
  13448. pLoader: undefined, // used by playlist-loader
  13449. xhrSetup: undefined, // used by xhr-loader
  13450. licenseXhrSetup: undefined, // used by eme-controller
  13451. // fetchSetup: undefined,
  13452. abrController: _abrController2.default,
  13453. bufferController: _bufferController2.default,
  13454. capLevelController: _capLevelController2.default,
  13455. fpsController: _fpsController2.default,
  13456. stretchShortVideoTrack: false, // used by mp4-remuxer
  13457. maxAudioFramesDrift: 1, // used by mp4-remuxer
  13458. forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer
  13459. abrEwmaFastLive: 3, // used by abr-controller
  13460. abrEwmaSlowLive: 9, // used by abr-controller
  13461. abrEwmaFastVoD: 3, // used by abr-controller
  13462. abrEwmaSlowVoD: 9, // used by abr-controller
  13463. abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller
  13464. abrBandWidthFactor: 0.95, // used by abr-controller
  13465. abrBandWidthUpFactor: 0.7, // used by abr-controller
  13466. abrMaxWithRealBitrate: false, // used by abr-controller
  13467. maxStarvationDelay: 4, // used by abr-controller
  13468. maxLoadingDelay: 4, // used by abr-controller
  13469. minAutoBitrate: 0, // used by hls
  13470. emeEnabled: false, // used by eme-controller
  13471. widevineLicenseUrl: undefined, // used by eme-controller
  13472. requestMediaKeySystemAccessFunc: _mediakeysHelper.requestMediaKeySystemAccess // used by eme-controller
  13473. }; /**
  13474. * HLS config
  13475. */
  13476. hlsDefaultConfig.subtitleStreamController = _subtitleStreamController.SubtitleStreamController;
  13477. hlsDefaultConfig.subtitleTrackController = _subtitleTrackController2.default;
  13478. hlsDefaultConfig.timelineController = _timelineController2.default;
  13479. hlsDefaultConfig.cueHandler = Cues; // used by timeline-controller
  13480. hlsDefaultConfig.enableCEA708Captions = true; // used by timeline-controller
  13481. hlsDefaultConfig.enableWebVTT = true; // used by timeline-controller
  13482. hlsDefaultConfig.captionsTextTrack1Label = 'English'; // used by timeline-controller
  13483. hlsDefaultConfig.captionsTextTrack1LanguageCode = 'en'; // used by timeline-controller
  13484. hlsDefaultConfig.captionsTextTrack2Label = 'Spanish'; // used by timeline-controller
  13485. hlsDefaultConfig.captionsTextTrack2LanguageCode = 'es'; // used by timeline-controller
  13486. hlsDefaultConfig.audioStreamController = _audioStreamController2.default;
  13487. hlsDefaultConfig.audioTrackController = _audioTrackController2.default;
  13488. hlsDefaultConfig.emeController = _emeController2.default;
  13489. /***/ }),
  13490. /* 61 */
  13491. /***/ (function(module, exports, __webpack_require__) {
  13492. "use strict";
  13493. Object.defineProperty(exports, "__esModule", {
  13494. value: true
  13495. });
  13496. 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; }; }();
  13497. var _events = __webpack_require__(1);
  13498. var _events2 = _interopRequireDefault(_events);
  13499. var _eventHandler = __webpack_require__(3);
  13500. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  13501. var _bufferHelper = __webpack_require__(4);
  13502. var _errors = __webpack_require__(2);
  13503. var _logger = __webpack_require__(0);
  13504. var _ewmaBandwidthEstimator = __webpack_require__(62);
  13505. var _ewmaBandwidthEstimator2 = _interopRequireDefault(_ewmaBandwidthEstimator);
  13506. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13507. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13508. 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; }
  13509. 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; } /*
  13510. * simple ABR Controller
  13511. * - compute next level based on last fragment bw heuristics
  13512. * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling
  13513. */
  13514. var _window = window,
  13515. performance = _window.performance;
  13516. var AbrController = function (_EventHandler) {
  13517. _inherits(AbrController, _EventHandler);
  13518. function AbrController(hls) {
  13519. _classCallCheck(this, AbrController);
  13520. var _this = _possibleConstructorReturn(this, (AbrController.__proto__ || Object.getPrototypeOf(AbrController)).call(this, hls, _events2.default.FRAG_LOADING, _events2.default.FRAG_LOADED, _events2.default.FRAG_BUFFERED, _events2.default.ERROR));
  13521. _this.lastLoadedFragLevel = 0;
  13522. _this._nextAutoLevel = -1;
  13523. _this.hls = hls;
  13524. _this.timer = null;
  13525. _this._bwEstimator = null;
  13526. _this.onCheck = _this._abandonRulesCheck.bind(_this);
  13527. return _this;
  13528. }
  13529. _createClass(AbrController, [{
  13530. key: 'destroy',
  13531. value: function destroy() {
  13532. this.clearTimer();
  13533. _eventHandler2.default.prototype.destroy.call(this);
  13534. }
  13535. }, {
  13536. key: 'onFragLoading',
  13537. value: function onFragLoading(data) {
  13538. var frag = data.frag;
  13539. if (frag.type === 'main') {
  13540. if (!this.timer) {
  13541. this.fragCurrent = frag;
  13542. this.timer = setInterval(this.onCheck, 100);
  13543. }
  13544. // lazy init of BwEstimator, rationale is that we use different params for Live/VoD
  13545. // so we need to wait for stream manifest / playlist type to instantiate it.
  13546. if (!this._bwEstimator) {
  13547. var hls = this.hls;
  13548. var config = hls.config;
  13549. var level = frag.level;
  13550. var isLive = hls.levels[level].details.live;
  13551. var ewmaFast = void 0,
  13552. ewmaSlow = void 0;
  13553. if (isLive) {
  13554. ewmaFast = config.abrEwmaFastLive;
  13555. ewmaSlow = config.abrEwmaSlowLive;
  13556. } else {
  13557. ewmaFast = config.abrEwmaFastVoD;
  13558. ewmaSlow = config.abrEwmaSlowVoD;
  13559. }
  13560. this._bwEstimator = new _ewmaBandwidthEstimator2.default(hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate);
  13561. }
  13562. }
  13563. }
  13564. }, {
  13565. key: '_abandonRulesCheck',
  13566. value: function _abandonRulesCheck() {
  13567. /*
  13568. monitor fragment retrieval time...
  13569. we compute expected time of arrival of the complete fragment.
  13570. we compare it to expected time of buffer starvation
  13571. */
  13572. var hls = this.hls;
  13573. var video = hls.media;
  13574. var frag = this.fragCurrent;
  13575. if (!frag) {
  13576. return;
  13577. }
  13578. var loader = frag.loader;
  13579. var minAutoLevel = hls.minAutoLevel;
  13580. // if loader has been destroyed or loading has been aborted, stop timer and return
  13581. if (!loader || loader.stats && loader.stats.aborted) {
  13582. _logger.logger.warn('frag loader destroy or aborted, disarm abandonRules');
  13583. this.clearTimer();
  13584. // reset forced auto level value so that next level will be selected
  13585. this._nextAutoLevel = -1;
  13586. return;
  13587. }
  13588. var stats = loader.stats;
  13589. /* only monitor frag retrieval time if
  13590. (video not paused OR first fragment being loaded(ready state === HAVE_NOTHING = 0)) AND autoswitching enabled AND not lowest level (=> means that we have several levels) */
  13591. if (video && stats && (!video.paused && video.playbackRate !== 0 || !video.readyState) && frag.autoLevel && frag.level) {
  13592. var requestDelay = performance.now() - stats.trequest,
  13593. playbackRate = Math.abs(video.playbackRate);
  13594. // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate
  13595. if (requestDelay > 500 * frag.duration / playbackRate) {
  13596. var levels = hls.levels,
  13597. loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay),
  13598. // byte/s; at least 1 byte/s to avoid division by zero
  13599. // compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size
  13600. level = levels[frag.level],
  13601. levelBitrate = level.realBitrate ? Math.max(level.realBitrate, level.bitrate) : level.bitrate,
  13602. expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8)),
  13603. pos = video.currentTime,
  13604. fragLoadedDelay = (expectedLen - stats.loaded) / loadRate,
  13605. bufferStarvationDelay = (_bufferHelper.BufferHelper.bufferInfo(video, pos, hls.config.maxBufferHole).end - pos) / playbackRate;
  13606. // consider emergency switch down only if we have less than 2 frag buffered AND
  13607. // time to finish loading current fragment is bigger than buffer starvation delay
  13608. // ie if we risk buffer starvation if bw does not increase quickly
  13609. if (bufferStarvationDelay < 2 * frag.duration / playbackRate && fragLoadedDelay > bufferStarvationDelay) {
  13610. var fragLevelNextLoadedDelay = void 0,
  13611. nextLoadLevel = void 0;
  13612. // lets iterate through lower level and try to find the biggest one that could avoid rebuffering
  13613. // we start from current level - 1 and we step down , until we find a matching level
  13614. for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  13615. // compute time to load next fragment at lower level
  13616. // 0.8 : consider only 80% of current bw to be conservative
  13617. // 8 = bits per byte (bps/Bps)
  13618. var levelNextBitrate = levels[nextLoadLevel].realBitrate ? Math.max(levels[nextLoadLevel].realBitrate, levels[nextLoadLevel].bitrate) : levels[nextLoadLevel].bitrate;
  13619. fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate);
  13620. if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
  13621. // we found a lower level that be rebuffering free with current estimated bw !
  13622. break;
  13623. }
  13624. }
  13625. // only emergency switch down if it takes less time to load new fragment at lowest level instead
  13626. // of finishing loading current one ...
  13627. if (fragLevelNextLoadedDelay < fragLoadedDelay) {
  13628. _logger.logger.warn('loading too slow, abort fragment loading and switch to level ' + nextLoadLevel + ':fragLoadedDelay[' + nextLoadLevel + ']<fragLoadedDelay[' + (frag.level - 1) + '];bufferStarvationDelay:' + fragLevelNextLoadedDelay.toFixed(1) + '<' + fragLoadedDelay.toFixed(1) + ':' + bufferStarvationDelay.toFixed(1));
  13629. // force next load level in auto mode
  13630. hls.nextLoadLevel = nextLoadLevel;
  13631. // update bw estimate for this fragment before cancelling load (this will help reducing the bw)
  13632. this._bwEstimator.sample(requestDelay, stats.loaded);
  13633. // abort fragment loading
  13634. loader.abort();
  13635. // stop abandon rules timer
  13636. this.clearTimer();
  13637. hls.trigger(_events2.default.FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag, stats: stats });
  13638. }
  13639. }
  13640. }
  13641. }
  13642. }
  13643. }, {
  13644. key: 'onFragLoaded',
  13645. value: function onFragLoaded(data) {
  13646. var frag = data.frag;
  13647. if (frag.type === 'main' && Number.isFinite(frag.sn)) {
  13648. // stop monitoring bw once frag loaded
  13649. this.clearTimer();
  13650. // store level id after successful fragment load
  13651. this.lastLoadedFragLevel = frag.level;
  13652. // reset forced auto level value so that next level will be selected
  13653. this._nextAutoLevel = -1;
  13654. // compute level average bitrate
  13655. if (this.hls.config.abrMaxWithRealBitrate) {
  13656. var level = this.hls.levels[frag.level];
  13657. var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;
  13658. var loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration;
  13659. level.loaded = { bytes: loadedBytes, duration: loadedDuration };
  13660. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  13661. }
  13662. // if fragment has been loaded to perform a bitrate test,
  13663. if (data.frag.bitrateTest) {
  13664. var stats = data.stats;
  13665. stats.tparsed = stats.tbuffered = stats.tload;
  13666. this.onFragBuffered(data);
  13667. }
  13668. }
  13669. }
  13670. }, {
  13671. key: 'onFragBuffered',
  13672. value: function onFragBuffered(data) {
  13673. var stats = data.stats;
  13674. var frag = data.frag;
  13675. // only update stats on first frag buffering
  13676. // if same frag is loaded multiple times, it might be in browser cache, and loaded quickly
  13677. // and leading to wrong bw estimation
  13678. // on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED)
  13679. if (stats.aborted !== true && frag.type === 'main' && Number.isFinite(frag.sn) && (!frag.bitrateTest || stats.tload === stats.tbuffered)) {
  13680. // use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached
  13681. // in case we use config.startFragPrefetch while media is not attached yet, fragment might be parsed while media not attached yet, but it will only be buffered on media attached
  13682. // as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation
  13683. var fragLoadingProcessingMs = stats.tparsed - stats.trequest;
  13684. _logger.logger.log('latency/loading/parsing/append/kbps:' + Math.round(stats.tfirst - stats.trequest) + '/' + Math.round(stats.tload - stats.tfirst) + '/' + Math.round(stats.tparsed - stats.tload) + '/' + Math.round(stats.tbuffered - stats.tparsed) + '/' + Math.round(8 * stats.loaded / (stats.tbuffered - stats.trequest)));
  13685. this._bwEstimator.sample(fragLoadingProcessingMs, stats.loaded);
  13686. stats.bwEstimate = this._bwEstimator.getEstimate();
  13687. // if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration
  13688. if (frag.bitrateTest) {
  13689. this.bitrateTestDelay = fragLoadingProcessingMs / 1000;
  13690. } else {
  13691. this.bitrateTestDelay = 0;
  13692. }
  13693. }
  13694. }
  13695. }, {
  13696. key: 'onError',
  13697. value: function onError(data) {
  13698. // stop timer in case of frag loading error
  13699. switch (data.details) {
  13700. case _errors.ErrorDetails.FRAG_LOAD_ERROR:
  13701. case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
  13702. this.clearTimer();
  13703. break;
  13704. default:
  13705. break;
  13706. }
  13707. }
  13708. }, {
  13709. key: 'clearTimer',
  13710. value: function clearTimer() {
  13711. clearInterval(this.timer);
  13712. this.timer = null;
  13713. }
  13714. // return next auto level
  13715. }, {
  13716. key: '_findBestLevel',
  13717. value: function _findBestLevel(currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) {
  13718. for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
  13719. var levelInfo = levels[i];
  13720. if (!levelInfo) {
  13721. continue;
  13722. }
  13723. var levelDetails = levelInfo.details,
  13724. avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration,
  13725. live = levelDetails ? levelDetails.live : false,
  13726. adjustedbw = void 0;
  13727. // follow algorithm captured from stagefright :
  13728. // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
  13729. // Pick the highest bandwidth stream below or equal to estimated bandwidth.
  13730. // consider only 80% of the available bandwidth, but if we are switching up,
  13731. // be even more conservative (70%) to avoid overestimating and immediately
  13732. // switching back.
  13733. if (i <= currentLevel) {
  13734. adjustedbw = bwFactor * currentBw;
  13735. } else {
  13736. adjustedbw = bwUpFactor * currentBw;
  13737. }
  13738. var bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate,
  13739. fetchDuration = bitrate * avgDuration / adjustedbw;
  13740. _logger.logger.trace('level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: ' + i + '/' + Math.round(adjustedbw) + '/' + bitrate + '/' + avgDuration + '/' + maxFetchDuration + '/' + fetchDuration);
  13741. // if adjusted bw is greater than level bitrate AND
  13742. if (adjustedbw > bitrate && (
  13743. // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  13744. // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...
  13745. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that _findBestLevel will return -1
  13746. !fetchDuration || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) {
  13747. // as we are looping from highest to lowest, this will return the best achievable quality level
  13748. return i;
  13749. }
  13750. }
  13751. // not enough time budget even with quality level 0 ... rebuffering might happen
  13752. return -1;
  13753. }
  13754. }, {
  13755. key: 'nextAutoLevel',
  13756. get: function get() {
  13757. var forcedAutoLevel = this._nextAutoLevel;
  13758. var bwEstimator = this._bwEstimator;
  13759. // in case next auto level has been forced, and bw not available or not reliable, return forced value
  13760. if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {
  13761. return forcedAutoLevel;
  13762. }
  13763. // compute next level using ABR logic
  13764. var nextABRAutoLevel = this._nextABRAutoLevel;
  13765. // if forced auto level has been defined, use it to cap ABR computed quality level
  13766. if (forcedAutoLevel !== -1) {
  13767. nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);
  13768. }
  13769. return nextABRAutoLevel;
  13770. },
  13771. set: function set(nextLevel) {
  13772. this._nextAutoLevel = nextLevel;
  13773. }
  13774. }, {
  13775. key: '_nextABRAutoLevel',
  13776. get: function get() {
  13777. var hls = this.hls,
  13778. maxAutoLevel = hls.maxAutoLevel,
  13779. levels = hls.levels,
  13780. config = hls.config,
  13781. minAutoLevel = hls.minAutoLevel;
  13782. var video = hls.media,
  13783. currentLevel = this.lastLoadedFragLevel,
  13784. currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0,
  13785. pos = video ? video.currentTime : 0,
  13786. // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as
  13787. // if we're playing back at the normal rate.
  13788. playbackRate = video && video.playbackRate !== 0 ? Math.abs(video.playbackRate) : 1.0,
  13789. avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate,
  13790. // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
  13791. bufferStarvationDelay = (_bufferHelper.BufferHelper.bufferInfo(video, pos, config.maxBufferHole).end - pos) / playbackRate;
  13792. // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
  13793. var bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor, levels);
  13794. if (bestLevel >= 0) {
  13795. return bestLevel;
  13796. } else {
  13797. _logger.logger.trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering');
  13798. // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering
  13799. // if no matching level found, logic will return 0
  13800. var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay,
  13801. bwFactor = config.abrBandWidthFactor,
  13802. bwUpFactor = config.abrBandWidthUpFactor;
  13803. if (bufferStarvationDelay === 0) {
  13804. // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
  13805. var bitrateTestDelay = this.bitrateTestDelay;
  13806. if (bitrateTestDelay) {
  13807. // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
  13808. // max video loading delay used in automatic start level selection :
  13809. // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
  13810. // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
  13811. // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
  13812. var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  13813. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  13814. _logger.logger.trace('bitrate test took ' + Math.round(1000 * bitrateTestDelay) + 'ms, set first fragment max fetchDuration to ' + Math.round(1000 * maxStarvationDelay) + ' ms');
  13815. // don't use conservative factor on bitrate test
  13816. bwFactor = bwUpFactor = 1;
  13817. }
  13818. }
  13819. bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor, levels);
  13820. return Math.max(bestLevel, 0);
  13821. }
  13822. }
  13823. }]);
  13824. return AbrController;
  13825. }(_eventHandler2.default);
  13826. exports.default = AbrController;
  13827. module.exports = exports['default'];
  13828. /***/ }),
  13829. /* 62 */
  13830. /***/ (function(module, exports, __webpack_require__) {
  13831. "use strict";
  13832. Object.defineProperty(exports, "__esModule", {
  13833. value: true
  13834. });
  13835. 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; }; }(); /*
  13836. * EWMA Bandwidth Estimator
  13837. * - heavily inspired from shaka-player
  13838. * Tracks bandwidth samples and estimates available bandwidth.
  13839. * Based on the minimum of two exponentially-weighted moving averages with
  13840. * different half-lives.
  13841. */
  13842. var _ewma = __webpack_require__(63);
  13843. var _ewma2 = _interopRequireDefault(_ewma);
  13844. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13845. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13846. var EwmaBandWidthEstimator = function () {
  13847. function EwmaBandWidthEstimator(hls, slow, fast, defaultEstimate) {
  13848. _classCallCheck(this, EwmaBandWidthEstimator);
  13849. this.hls = hls;
  13850. this.defaultEstimate_ = defaultEstimate;
  13851. this.minWeight_ = 0.001;
  13852. this.minDelayMs_ = 50;
  13853. this.slow_ = new _ewma2.default(slow);
  13854. this.fast_ = new _ewma2.default(fast);
  13855. }
  13856. _createClass(EwmaBandWidthEstimator, [{
  13857. key: 'sample',
  13858. value: function sample(durationMs, numBytes) {
  13859. durationMs = Math.max(durationMs, this.minDelayMs_);
  13860. var bandwidth = 8000 * numBytes / durationMs,
  13861. // console.log('instant bw:'+ Math.round(bandwidth));
  13862. // we weight sample using loading duration....
  13863. weight = durationMs / 1000;
  13864. this.fast_.sample(weight, bandwidth);
  13865. this.slow_.sample(weight, bandwidth);
  13866. }
  13867. }, {
  13868. key: 'canEstimate',
  13869. value: function canEstimate() {
  13870. var fast = this.fast_;
  13871. return fast && fast.getTotalWeight() >= this.minWeight_;
  13872. }
  13873. }, {
  13874. key: 'getEstimate',
  13875. value: function getEstimate() {
  13876. if (this.canEstimate()) {
  13877. // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
  13878. // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
  13879. // Take the minimum of these two estimates. This should have the effect of
  13880. // adapting down quickly, but up more slowly.
  13881. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  13882. } else {
  13883. return this.defaultEstimate_;
  13884. }
  13885. }
  13886. }, {
  13887. key: 'destroy',
  13888. value: function destroy() {}
  13889. }]);
  13890. return EwmaBandWidthEstimator;
  13891. }();
  13892. exports.default = EwmaBandWidthEstimator;
  13893. module.exports = exports['default'];
  13894. /***/ }),
  13895. /* 63 */
  13896. /***/ (function(module, exports, __webpack_require__) {
  13897. "use strict";
  13898. Object.defineProperty(exports, "__esModule", {
  13899. value: true
  13900. });
  13901. 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; }; }();
  13902. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13903. /*
  13904. * compute an Exponential Weighted moving average
  13905. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  13906. * - heavily inspired from shaka-player
  13907. */
  13908. var EWMA = function () {
  13909. // About half of the estimated value will be from the last |halfLife| samples by weight.
  13910. function EWMA(halfLife) {
  13911. _classCallCheck(this, EWMA);
  13912. // Larger values of alpha expire historical data more slowly.
  13913. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  13914. this.estimate_ = 0;
  13915. this.totalWeight_ = 0;
  13916. }
  13917. _createClass(EWMA, [{
  13918. key: "sample",
  13919. value: function sample(weight, value) {
  13920. var adjAlpha = Math.pow(this.alpha_, weight);
  13921. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  13922. this.totalWeight_ += weight;
  13923. }
  13924. }, {
  13925. key: "getTotalWeight",
  13926. value: function getTotalWeight() {
  13927. return this.totalWeight_;
  13928. }
  13929. }, {
  13930. key: "getEstimate",
  13931. value: function getEstimate() {
  13932. if (this.alpha_) {
  13933. var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  13934. return this.estimate_ / zeroFactor;
  13935. } else {
  13936. return this.estimate_;
  13937. }
  13938. }
  13939. }]);
  13940. return EWMA;
  13941. }();
  13942. exports.default = EWMA;
  13943. module.exports = exports["default"];
  13944. /***/ }),
  13945. /* 64 */
  13946. /***/ (function(module, exports, __webpack_require__) {
  13947. "use strict";
  13948. Object.defineProperty(exports, "__esModule", {
  13949. value: true
  13950. });
  13951. 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; }; }();
  13952. var _events = __webpack_require__(1);
  13953. var _events2 = _interopRequireDefault(_events);
  13954. var _eventHandler = __webpack_require__(3);
  13955. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  13956. var _logger = __webpack_require__(0);
  13957. var _errors = __webpack_require__(2);
  13958. var _mediasourceHelper = __webpack_require__(13);
  13959. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13960. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13961. 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; }
  13962. 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; } /*
  13963. * Buffer Controller
  13964. */
  13965. var MediaSource = (0, _mediasourceHelper.getMediaSource)();
  13966. var BufferController = function (_EventHandler) {
  13967. _inherits(BufferController, _EventHandler);
  13968. function BufferController(hls) {
  13969. _classCallCheck(this, BufferController);
  13970. // the value that we have set mediasource.duration to
  13971. // (the actual duration may be tweaked slighly by the browser)
  13972. var _this = _possibleConstructorReturn(this, (BufferController.__proto__ || Object.getPrototypeOf(BufferController)).call(this, hls, _events2.default.MEDIA_ATTACHING, _events2.default.MEDIA_DETACHING, _events2.default.MANIFEST_PARSED, _events2.default.BUFFER_RESET, _events2.default.BUFFER_APPENDING, _events2.default.BUFFER_CODECS, _events2.default.BUFFER_EOS, _events2.default.BUFFER_FLUSHING, _events2.default.LEVEL_PTS_UPDATED, _events2.default.LEVEL_UPDATED));
  13973. _this._msDuration = null;
  13974. // the value that we want to set mediaSource.duration to
  13975. _this._levelDuration = null;
  13976. // the target duration of the current media playlist
  13977. _this._levelTargetDuration = 10;
  13978. // current stream state: true - for live broadcast, false - for VoD content
  13979. _this._live = null;
  13980. // cache the self generated object url to detect hijack of video tag
  13981. _this._objectUrl = null;
  13982. // The number of BUFFER_CODEC events received before any sourceBuffers are created
  13983. _this.bufferCodecEventsExpected = 0;
  13984. // Source Buffer listeners
  13985. _this.onsbue = _this.onSBUpdateEnd.bind(_this);
  13986. _this.onsbe = _this.onSBUpdateError.bind(_this);
  13987. _this.pendingTracks = {};
  13988. _this.tracks = {};
  13989. return _this;
  13990. }
  13991. _createClass(BufferController, [{
  13992. key: 'destroy',
  13993. value: function destroy() {
  13994. _eventHandler2.default.prototype.destroy.call(this);
  13995. }
  13996. }, {
  13997. key: 'onLevelPtsUpdated',
  13998. value: function onLevelPtsUpdated(data) {
  13999. var type = data.type;
  14000. var audioTrack = this.tracks.audio;
  14001. // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
  14002. // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
  14003. // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos). At the time of change we issue
  14004. // `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend`
  14005. // event if SB is in updating state.
  14006. // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
  14007. if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') {
  14008. // Chrome audio mp3 track
  14009. var audioBuffer = this.sourceBuffer.audio;
  14010. var delta = Math.abs(audioBuffer.timestampOffset - data.start);
  14011. // adjust timestamp offset if time delta is greater than 100ms
  14012. if (delta > 0.1) {
  14013. var updating = audioBuffer.updating;
  14014. try {
  14015. audioBuffer.abort();
  14016. } catch (err) {
  14017. _logger.logger.warn('can not abort audio buffer: ' + err);
  14018. }
  14019. if (!updating) {
  14020. _logger.logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.start);
  14021. audioBuffer.timestampOffset = data.start;
  14022. } else {
  14023. this.audioTimestampOffset = data.start;
  14024. }
  14025. }
  14026. }
  14027. }
  14028. }, {
  14029. key: 'onManifestParsed',
  14030. value: function onManifestParsed(data) {
  14031. // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
  14032. // sourcebuffers will be created all at once when the expected nb of tracks will be reached
  14033. // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
  14034. // it will contain the expected nb of source buffers, no need to compute it
  14035. this.bufferCodecEventsExpected = data.altAudio ? 2 : 1;
  14036. _logger.logger.log(this.bufferCodecEventsExpected + ' bufferCodec event(s) expected');
  14037. }
  14038. }, {
  14039. key: 'onMediaAttaching',
  14040. value: function onMediaAttaching(data) {
  14041. var media = this.media = data.media;
  14042. if (media) {
  14043. // setup the media source
  14044. var ms = this.mediaSource = new MediaSource();
  14045. // Media Source listeners
  14046. this.onmso = this.onMediaSourceOpen.bind(this);
  14047. this.onmse = this.onMediaSourceEnded.bind(this);
  14048. this.onmsc = this.onMediaSourceClose.bind(this);
  14049. ms.addEventListener('sourceopen', this.onmso);
  14050. ms.addEventListener('sourceended', this.onmse);
  14051. ms.addEventListener('sourceclose', this.onmsc);
  14052. // link video and media Source
  14053. media.src = window.URL.createObjectURL(ms);
  14054. // cache the locally generated object url
  14055. this._objectUrl = media.src;
  14056. }
  14057. }
  14058. }, {
  14059. key: 'onMediaDetaching',
  14060. value: function onMediaDetaching() {
  14061. _logger.logger.log('media source detaching');
  14062. var ms = this.mediaSource;
  14063. if (ms) {
  14064. if (ms.readyState === 'open') {
  14065. try {
  14066. // endOfStream could trigger exception if any sourcebuffer is in updating state
  14067. // we don't really care about checking sourcebuffer state here,
  14068. // as we are anyway detaching the MediaSource
  14069. // let's just avoid this exception to propagate
  14070. ms.endOfStream();
  14071. } catch (err) {
  14072. _logger.logger.warn('onMediaDetaching:' + err.message + ' while calling endOfStream');
  14073. }
  14074. }
  14075. ms.removeEventListener('sourceopen', this.onmso);
  14076. ms.removeEventListener('sourceended', this.onmse);
  14077. ms.removeEventListener('sourceclose', this.onmsc);
  14078. // Detach properly the MediaSource from the HTMLMediaElement as
  14079. // suggested in https://github.com/w3c/media-source/issues/53.
  14080. if (this.media) {
  14081. window.URL.revokeObjectURL(this._objectUrl);
  14082. // clean up video tag src only if it's our own url. some external libraries might
  14083. // hijack the video tag and change its 'src' without destroying the Hls instance first
  14084. if (this.media.src === this._objectUrl) {
  14085. this.media.removeAttribute('src');
  14086. this.media.load();
  14087. } else {
  14088. _logger.logger.warn('media.src was changed by a third party - skip cleanup');
  14089. }
  14090. }
  14091. this.mediaSource = null;
  14092. this.media = null;
  14093. this._objectUrl = null;
  14094. this.pendingTracks = {};
  14095. this.tracks = {};
  14096. this.sourceBuffer = {};
  14097. this.flushRange = [];
  14098. this.segments = [];
  14099. this.appended = 0;
  14100. }
  14101. this.onmso = this.onmse = this.onmsc = null;
  14102. this.hls.trigger(_events2.default.MEDIA_DETACHED);
  14103. }
  14104. }, {
  14105. key: 'onMediaSourceOpen',
  14106. value: function onMediaSourceOpen() {
  14107. _logger.logger.log('media source opened');
  14108. this.hls.trigger(_events2.default.MEDIA_ATTACHED, { media: this.media });
  14109. var mediaSource = this.mediaSource;
  14110. if (mediaSource) {
  14111. // once received, don't listen anymore to sourceopen event
  14112. mediaSource.removeEventListener('sourceopen', this.onmso);
  14113. }
  14114. this.checkPendingTracks();
  14115. }
  14116. }, {
  14117. key: 'checkPendingTracks',
  14118. value: function checkPendingTracks() {
  14119. var bufferCodecEventsExpected = this.bufferCodecEventsExpected,
  14120. pendingTracks = this.pendingTracks;
  14121. // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
  14122. // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
  14123. // data has been appended to existing ones.
  14124. // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
  14125. var pendingTracksCount = Object.keys(pendingTracks).length;
  14126. if (pendingTracksCount && !bufferCodecEventsExpected || pendingTracksCount === 2) {
  14127. // ok, let's create them now !
  14128. this.createSourceBuffers(pendingTracks);
  14129. this.pendingTracks = {};
  14130. // append any pending segments now !
  14131. this.doAppending();
  14132. }
  14133. }
  14134. }, {
  14135. key: 'onMediaSourceClose',
  14136. value: function onMediaSourceClose() {
  14137. _logger.logger.log('media source closed');
  14138. }
  14139. }, {
  14140. key: 'onMediaSourceEnded',
  14141. value: function onMediaSourceEnded() {
  14142. _logger.logger.log('media source ended');
  14143. }
  14144. }, {
  14145. key: 'onSBUpdateEnd',
  14146. value: function onSBUpdateEnd() {
  14147. // update timestampOffset
  14148. if (this.audioTimestampOffset) {
  14149. var audioBuffer = this.sourceBuffer.audio;
  14150. _logger.logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + this.audioTimestampOffset);
  14151. audioBuffer.timestampOffset = this.audioTimestampOffset;
  14152. delete this.audioTimestampOffset;
  14153. }
  14154. if (this._needsFlush) {
  14155. this.doFlush();
  14156. }
  14157. if (this._needsEos) {
  14158. this.checkEos();
  14159. }
  14160. this.appending = false;
  14161. var parent = this.parent;
  14162. // count nb of pending segments waiting for appending on this sourcebuffer
  14163. var pending = this.segments.reduce(function (counter, segment) {
  14164. return segment.parent === parent ? counter + 1 : counter;
  14165. }, 0);
  14166. // this.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments
  14167. var timeRanges = {};
  14168. var sourceBuffer = this.sourceBuffer;
  14169. for (var streamType in sourceBuffer) {
  14170. timeRanges[streamType] = sourceBuffer[streamType].buffered;
  14171. }
  14172. // 寻找可播放的起始点。如果没有自动播放,需要手动Seek
  14173. if (this._paused === false && timeRanges["video"] && timeRanges["video"].length > 0 && timeRanges["audio"] && timeRanges["audio"].length > 0) {
  14174. if (timeRanges["video"].end(0) - timeRanges["video"].start(0) > 1 && timeRanges["audio"].end(0) - timeRanges["audio"].start(0) > 1) {
  14175. // Seek to the point that can play;
  14176. var startTime = Math.max(timeRanges["video"].start(0), timeRanges["audio"].start(0));
  14177. this.media.currentTime = startTime;
  14178. this.media.play();
  14179. delete this["_paused"];
  14180. } else {
  14181. // Try to seek more
  14182. var endTime = Math.max(timeRanges["video"].end(0), timeRanges["audio"].end(0));
  14183. this.media.currentTime = endTime;
  14184. this.media.play();
  14185. }
  14186. }
  14187. this.hls.trigger(_events2.default.BUFFER_APPENDED, { parent: parent, pending: pending, timeRanges: timeRanges });
  14188. // don't append in flushing mode
  14189. if (!this._needsFlush) {
  14190. this.doAppending();
  14191. }
  14192. this.updateMediaElementDuration();
  14193. // appending goes first
  14194. if (pending === 0) {
  14195. this.flushLiveBackBuffer();
  14196. }
  14197. }
  14198. }, {
  14199. key: 'onSBUpdateError',
  14200. value: function onSBUpdateError(event) {
  14201. _logger.logger.error('sourceBuffer error:', event);
  14202. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  14203. // this error might not always be fatal (it is fatal if decode error is set, in that case
  14204. // it will be followed by a mediaElement error ...)
  14205. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false });
  14206. // we don't need to do more than that, as accordin to the spec, updateend will be fired just after
  14207. }
  14208. }, {
  14209. key: 'onBufferReset',
  14210. value: function onBufferReset() {
  14211. var sourceBuffer = this.sourceBuffer;
  14212. for (var type in sourceBuffer) {
  14213. var sb = sourceBuffer[type];
  14214. try {
  14215. this.mediaSource.removeSourceBuffer(sb);
  14216. sb.removeEventListener('updateend', this.onsbue);
  14217. sb.removeEventListener('error', this.onsbe);
  14218. } catch (err) {}
  14219. }
  14220. this.sourceBuffer = {};
  14221. this.flushRange = [];
  14222. this.segments = [];
  14223. this.appended = 0;
  14224. }
  14225. }, {
  14226. key: 'onBufferCodecs',
  14227. value: function onBufferCodecs(tracks) {
  14228. var _this2 = this;
  14229. // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
  14230. // if sourcebuffers already created, do nothing ...
  14231. /** 需要放过tracks, 有新的track需要重新加buffer 使得画面到达时,可以播放画面
  14232. if (Object.keys(this.sourceBuffer).length) {
  14233. return;
  14234. }*/
  14235. Object.keys(tracks).forEach(function (trackName) {
  14236. _this2.pendingTracks[trackName] = tracks[trackName];
  14237. });
  14238. var mediaSource = this.mediaSource;
  14239. this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
  14240. if (mediaSource && mediaSource.readyState === 'open') {
  14241. this.checkPendingTracks();
  14242. }
  14243. }
  14244. }, {
  14245. key: 'createSourceBuffers',
  14246. value: function createSourceBuffers(tracks) {
  14247. var sourceBuffer = this.sourceBuffer,
  14248. mediaSource = this.mediaSource;
  14249. for (var trackName in tracks) {
  14250. if (!sourceBuffer[trackName]) {
  14251. var track = tracks[trackName];
  14252. // use levelCodec as first priority
  14253. var codec = track.levelCodec || track.codec;
  14254. var mimeType = track.container + ';codecs=' + codec;
  14255. _logger.logger.log('creating sourceBuffer(' + mimeType + ')');
  14256. try {
  14257. var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
  14258. sb.addEventListener('updateend', this.onsbue);
  14259. sb.addEventListener('error', this.onsbe);
  14260. this.tracks[trackName] = { codec: codec, container: track.container };
  14261. track.buffer = sb;
  14262. } catch (err) {
  14263. if (err.code == 22) {
  14264. _logger.logger.log("Found new track, try to rebuild");
  14265. this._paused = false;
  14266. // setup the media source
  14267. var ms = this.mediaSource = new MediaSource();
  14268. // Media Source listeners
  14269. this.onmso = this.onMediaSourceOpen.bind(this);
  14270. this.onmse = this.onMediaSourceEnded.bind(this);
  14271. this.onmsc = this.onMediaSourceClose.bind(this);
  14272. for (var i = 0; i < Object.keys(this.tracks).length; i++) {
  14273. var _track = this.tracks[Object.keys(this.tracks)[i]];
  14274. this.pendingTracks[Object.keys(this.tracks)[i]] = _track;
  14275. }
  14276. this.tracks = {};
  14277. this.sourceBuffer = {};
  14278. ms.addEventListener('sourceopen', this.onmso);
  14279. ms.addEventListener('sourceended', this.onmse);
  14280. ms.addEventListener('sourceclose', this.onmsc);
  14281. // link video and media Source
  14282. this.media.src = window.URL.createObjectURL(ms);
  14283. // cache the locally generated object url
  14284. this._objectUrl = media.src;
  14285. } else {
  14286. _logger.logger.error('error while trying to add sourceBuffer:' + err.message);
  14287. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType });
  14288. }
  14289. }
  14290. }
  14291. }
  14292. this.hls.trigger(_events2.default.BUFFER_CREATED, { tracks: tracks });
  14293. }
  14294. }, {
  14295. key: 'onBufferAppending',
  14296. value: function onBufferAppending(data) {
  14297. if (!this._needsFlush) {
  14298. if (!this.segments) {
  14299. this.segments = [data];
  14300. } else {
  14301. this.segments.push(data);
  14302. }
  14303. this.doAppending();
  14304. }
  14305. }
  14306. }, {
  14307. key: 'onBufferAppendFail',
  14308. value: function onBufferAppendFail(data) {
  14309. _logger.logger.error('sourceBuffer error:', data.event);
  14310. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  14311. // this error might not always be fatal (it is fatal if decode error is set, in that case
  14312. // it will be followed by a mediaElement error ...)
  14313. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false });
  14314. }
  14315. // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
  14316. }, {
  14317. key: 'onBufferEos',
  14318. value: function onBufferEos(data) {
  14319. var sb = this.sourceBuffer;
  14320. var dataType = data.type;
  14321. for (var type in sb) {
  14322. if (!dataType || type === dataType) {
  14323. if (!sb[type].ended) {
  14324. sb[type].ended = true;
  14325. _logger.logger.log(type + ' sourceBuffer now EOS');
  14326. }
  14327. }
  14328. }
  14329. this.checkEos();
  14330. }
  14331. // if all source buffers are marked as ended, signal endOfStream() to MediaSource.
  14332. }, {
  14333. key: 'checkEos',
  14334. value: function checkEos() {
  14335. var sb = this.sourceBuffer,
  14336. mediaSource = this.mediaSource;
  14337. if (!mediaSource || mediaSource.readyState !== 'open') {
  14338. this._needsEos = false;
  14339. return;
  14340. }
  14341. for (var type in sb) {
  14342. var sbobj = sb[type];
  14343. if (!sbobj.ended) {
  14344. return;
  14345. }
  14346. if (sbobj.updating) {
  14347. this._needsEos = true;
  14348. return;
  14349. }
  14350. }
  14351. _logger.logger.log('all media data are available, signal endOfStream() to MediaSource and stop loading fragment');
  14352. // Notify the media element that it now has all of the media data
  14353. try {
  14354. mediaSource.endOfStream();
  14355. } catch (e) {
  14356. _logger.logger.warn('exception while calling mediaSource.endOfStream()');
  14357. }
  14358. this._needsEos = false;
  14359. }
  14360. }, {
  14361. key: 'onBufferFlushing',
  14362. value: function onBufferFlushing(data) {
  14363. this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });
  14364. // attempt flush immediately
  14365. this.flushBufferCounter = 0;
  14366. this.doFlush();
  14367. }
  14368. }, {
  14369. key: 'flushLiveBackBuffer',
  14370. value: function flushLiveBackBuffer() {
  14371. // clear back buffer for live only
  14372. if (!this._live) {
  14373. return;
  14374. }
  14375. var liveBackBufferLength = this.hls.config.liveBackBufferLength;
  14376. if (!isFinite(liveBackBufferLength) || liveBackBufferLength < 0) {
  14377. return;
  14378. }
  14379. var currentTime = this.media.currentTime;
  14380. var sourceBuffer = this.sourceBuffer;
  14381. var bufferTypes = Object.keys(sourceBuffer);
  14382. var targetBackBufferPosition = currentTime - Math.max(liveBackBufferLength, this._levelTargetDuration);
  14383. for (var index = bufferTypes.length - 1; index >= 0; index--) {
  14384. var bufferType = bufferTypes[index],
  14385. buffered = sourceBuffer[bufferType].buffered;
  14386. // when target buffer start exceeds actual buffer start
  14387. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  14388. // remove buffer up until current time minus minimum back buffer length (removing buffer too close to current
  14389. // time will lead to playback freezing)
  14390. // credits for level target duration - https://github.com/videojs/http-streaming/blob/3132933b6aa99ddefab29c10447624efd6fd6e52/src/segment-loader.js#L91
  14391. this.removeBufferRange(bufferType, sourceBuffer[bufferType], 0, targetBackBufferPosition);
  14392. }
  14393. }
  14394. }
  14395. }, {
  14396. key: 'onLevelUpdated',
  14397. value: function onLevelUpdated(_ref) {
  14398. var details = _ref.details;
  14399. if (details.fragments.length > 0) {
  14400. this._levelDuration = details.totalduration + details.fragments[0].start;
  14401. this._levelTargetDuration = details.averagetargetduration || details.targetduration || 10;
  14402. this._live = details.live;
  14403. this.updateMediaElementDuration();
  14404. }
  14405. }
  14406. /**
  14407. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  14408. * 'liveDurationInfinity` is set to `true`
  14409. * More details: https://github.com/video-dev/hls.js/issues/355
  14410. */
  14411. }, {
  14412. key: 'updateMediaElementDuration',
  14413. value: function updateMediaElementDuration() {
  14414. var config = this.hls.config;
  14415. var duration = void 0;
  14416. if (this._levelDuration === null || !this.media || !this.mediaSource || !this.sourceBuffer || this.media.readyState === 0 || this.mediaSource.readyState !== 'open') {
  14417. return;
  14418. }
  14419. for (var type in this.sourceBuffer) {
  14420. if (this.sourceBuffer[type].updating === true) {
  14421. // can't set duration whilst a buffer is updating
  14422. return;
  14423. }
  14424. }
  14425. duration = this.media.duration;
  14426. // initialise to the value that the media source is reporting
  14427. if (this._msDuration === null) {
  14428. this._msDuration = this.mediaSource.duration;
  14429. }
  14430. if (this._live === true && config.liveDurationInfinity === true) {
  14431. // Override duration to Infinity
  14432. _logger.logger.log('Media Source duration is set to Infinity');
  14433. this._msDuration = this.mediaSource.duration = Infinity;
  14434. } else if (this._levelDuration > this._msDuration && this._levelDuration > duration || !Number.isFinite(duration)) {
  14435. // levelDuration was the last value we set.
  14436. // not using mediaSource.duration as the browser may tweak this value
  14437. // only update Media Source duration if its value increase, this is to avoid
  14438. // flushing already buffered portion when switching between quality level
  14439. _logger.logger.log('Updating Media Source duration to ' + this._levelDuration.toFixed(3));
  14440. this._msDuration = this.mediaSource.duration = this._levelDuration;
  14441. }
  14442. }
  14443. }, {
  14444. key: 'doFlush',
  14445. value: function doFlush() {
  14446. // loop through all buffer ranges to flush
  14447. while (this.flushRange.length) {
  14448. var range = this.flushRange[0];
  14449. // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer
  14450. if (this.flushBuffer(range.start, range.end, range.type)) {
  14451. // range flushed, remove from flush array
  14452. this.flushRange.shift();
  14453. this.flushBufferCounter = 0;
  14454. } else {
  14455. this._needsFlush = true;
  14456. // avoid looping, wait for SB update end to retrigger a flush
  14457. return;
  14458. }
  14459. }
  14460. if (this.flushRange.length === 0) {
  14461. // everything flushed
  14462. this._needsFlush = false;
  14463. // let's recompute this.appended, which is used to avoid flush looping
  14464. var appended = 0;
  14465. var sourceBuffer = this.sourceBuffer;
  14466. try {
  14467. for (var type in sourceBuffer) {
  14468. appended += sourceBuffer[type].buffered.length;
  14469. }
  14470. } catch (error) {
  14471. // error could be thrown while accessing buffered, in case sourcebuffer has already been removed from MediaSource
  14472. // this is harmess at this stage, catch this to avoid reporting an internal exception
  14473. _logger.logger.error('error while accessing sourceBuffer.buffered');
  14474. }
  14475. this.appended = appended;
  14476. this.hls.trigger(_events2.default.BUFFER_FLUSHED);
  14477. }
  14478. }
  14479. }, {
  14480. key: 'doAppending',
  14481. value: function doAppending() {
  14482. var hls = this.hls,
  14483. segments = this.segments,
  14484. sourceBuffer = this.sourceBuffer;
  14485. if (Object.keys(sourceBuffer).length) {
  14486. if (this.media.error) {
  14487. this.segments = [];
  14488. _logger.logger.error('trying to append although a media error occured, flush segment and abort');
  14489. return;
  14490. }
  14491. if (this.appending) {
  14492. // logger.log(`sb appending in progress`);
  14493. return;
  14494. }
  14495. if (segments && segments.length) {
  14496. var segment = segments.shift();
  14497. try {
  14498. var type = segment.type,
  14499. sb = sourceBuffer[type];
  14500. if (sb) {
  14501. if (!sb.updating) {
  14502. // reset sourceBuffer ended flag before appending segment
  14503. sb.ended = false;
  14504. // logger.log(`appending ${segment.content} ${type} SB, size:${segment.data.length}, ${segment.parent}`);
  14505. this.parent = segment.parent;
  14506. // console.log('append buffer ', segment)
  14507. sb.appendBuffer(segment.data);
  14508. this.appendError = 0;
  14509. this.appended++;
  14510. this.appending = true;
  14511. } else {
  14512. segments.unshift(segment);
  14513. }
  14514. } else {
  14515. // in case we don't have any source buffer matching with this segment type,
  14516. // it means that Mediasource fails to create sourcebuffer
  14517. // discard this segment, and trigger update end
  14518. this.onSBUpdateEnd();
  14519. }
  14520. } catch (err) {
  14521. // in case any error occured while appending, put back segment in segments table
  14522. _logger.logger.error('error while trying to append buffer:' + err.message);
  14523. segments.unshift(segment);
  14524. var event = { type: _errors.ErrorTypes.MEDIA_ERROR, parent: segment.parent };
  14525. if (err.code !== 22) {
  14526. if (this.appendError) {
  14527. this.appendError++;
  14528. } else {
  14529. this.appendError = 1;
  14530. }
  14531. event.details = _errors.ErrorDetails.BUFFER_APPEND_ERROR;
  14532. /* with UHD content, we could get loop of quota exceeded error until
  14533. browser is able to evict some data from sourcebuffer. retrying help recovering this
  14534. */
  14535. if (this.appendError > hls.config.appendErrorMaxRetry) {
  14536. _logger.logger.log('fail ' + hls.config.appendErrorMaxRetry + ' times to append segment in sourceBuffer');
  14537. this.segments = [];
  14538. event.fatal = true;
  14539. hls.trigger(_events2.default.ERROR, event);
  14540. } else {
  14541. event.fatal = false;
  14542. hls.trigger(_events2.default.ERROR, event);
  14543. }
  14544. } else {
  14545. // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
  14546. // let's stop appending any segments, and report BUFFER_FULL_ERROR error
  14547. this.segments = [];
  14548. event.details = _errors.ErrorDetails.BUFFER_FULL_ERROR;
  14549. event.fatal = false;
  14550. hls.trigger(_events2.default.ERROR, event);
  14551. }
  14552. }
  14553. }
  14554. }
  14555. }
  14556. /*
  14557. flush specified buffered range,
  14558. return true once range has been flushed.
  14559. as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end
  14560. */
  14561. }, {
  14562. key: 'flushBuffer',
  14563. value: function flushBuffer(startOffset, endOffset, typeIn) {
  14564. var sb = void 0;
  14565. var sourceBuffer = this.sourceBuffer;
  14566. if (Object.keys(sourceBuffer).length) {
  14567. _logger.logger.log('flushBuffer,pos/start/end: ' + this.media.currentTime.toFixed(3) + '/' + startOffset + '/' + endOffset);
  14568. // safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments
  14569. if (this.flushBufferCounter < this.appended) {
  14570. for (var type in sourceBuffer) {
  14571. // check if sourcebuffer type is defined (typeIn): if yes, let's only flush this one
  14572. // if no, let's flush all sourcebuffers
  14573. if (typeIn && type !== typeIn) {
  14574. continue;
  14575. }
  14576. sb = sourceBuffer[type];
  14577. // we are going to flush buffer, mark source buffer as 'not ended'
  14578. sb.ended = false;
  14579. if (!sb.updating) {
  14580. if (this.removeBufferRange(type, sb, startOffset, endOffset)) {
  14581. this.flushBufferCounter++;
  14582. return false;
  14583. }
  14584. } else {
  14585. _logger.logger.warn('cannot flush, sb updating in progress');
  14586. return false;
  14587. }
  14588. }
  14589. } else {
  14590. _logger.logger.warn('abort flushing too many retries');
  14591. }
  14592. _logger.logger.log('buffer flushed');
  14593. }
  14594. // everything flushed !
  14595. return true;
  14596. }
  14597. /**
  14598. * Removes first buffered range from provided source buffer that lies within given start and end offsets.
  14599. *
  14600. * @param type Type of the source buffer, logging purposes only.
  14601. * @param sb Target SourceBuffer instance.
  14602. * @param startOffset
  14603. * @param endOffset
  14604. *
  14605. * @returns {boolean} True when source buffer remove requested.
  14606. */
  14607. }, {
  14608. key: 'removeBufferRange',
  14609. value: function removeBufferRange(type, sb, startOffset, endOffset) {
  14610. try {
  14611. for (var i = 0; i < sb.buffered.length; i++) {
  14612. var bufStart = sb.buffered.start(i);
  14613. var bufEnd = sb.buffered.end(i);
  14614. var removeStart = Math.max(bufStart, startOffset);
  14615. var removeEnd = Math.min(bufEnd, endOffset);
  14616. /* sometimes sourcebuffer.remove() does not flush
  14617. the exact expected time range.
  14618. to avoid rounding issues/infinite loop,
  14619. only flush buffer range of length greater than 500ms.
  14620. */
  14621. if (Math.min(removeEnd, bufEnd) - removeStart > 0.5) {
  14622. _logger.logger.log('sb remove ' + type + ' [' + removeStart + ',' + removeEnd + '], of [' + bufStart + ',' + bufEnd + '], pos:' + this.media.currentTime);
  14623. sb.remove(removeStart, removeEnd);
  14624. return true;
  14625. }
  14626. }
  14627. } catch (error) {
  14628. _logger.logger.warn('removeBufferRange failed', error);
  14629. }
  14630. return false;
  14631. }
  14632. }]);
  14633. return BufferController;
  14634. }(_eventHandler2.default);
  14635. exports.default = BufferController;
  14636. module.exports = exports['default'];
  14637. /***/ }),
  14638. /* 65 */
  14639. /***/ (function(module, exports, __webpack_require__) {
  14640. "use strict";
  14641. Object.defineProperty(exports, "__esModule", {
  14642. value: true
  14643. });
  14644. 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; }; }();
  14645. var _events = __webpack_require__(1);
  14646. var _events2 = _interopRequireDefault(_events);
  14647. var _eventHandler = __webpack_require__(3);
  14648. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  14649. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  14650. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  14651. 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; }
  14652. 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; } /*
  14653. * cap stream level to media size dimension controller
  14654. */
  14655. var CapLevelController = function (_EventHandler) {
  14656. _inherits(CapLevelController, _EventHandler);
  14657. function CapLevelController(hls) {
  14658. _classCallCheck(this, CapLevelController);
  14659. var _this = _possibleConstructorReturn(this, (CapLevelController.__proto__ || Object.getPrototypeOf(CapLevelController)).call(this, hls, _events2.default.FPS_DROP_LEVEL_CAPPING, _events2.default.MEDIA_ATTACHING, _events2.default.MANIFEST_PARSED, _events2.default.BUFFER_CODECS, _events2.default.MEDIA_DETACHING));
  14660. _this.autoLevelCapping = Number.POSITIVE_INFINITY;
  14661. _this.firstLevel = null;
  14662. _this.levels = [];
  14663. _this.media = null;
  14664. _this.restrictedLevels = [];
  14665. _this.timer = null;
  14666. return _this;
  14667. }
  14668. _createClass(CapLevelController, [{
  14669. key: 'destroy',
  14670. value: function destroy() {
  14671. if (this.hls.config.capLevelToPlayerSize) {
  14672. this.media = null;
  14673. this._stopCapping();
  14674. }
  14675. }
  14676. }, {
  14677. key: 'onFpsDropLevelCapping',
  14678. value: function onFpsDropLevelCapping(data) {
  14679. // Don't add a restricted level more than once
  14680. if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {
  14681. this.restrictedLevels.push(data.droppedLevel);
  14682. }
  14683. }
  14684. }, {
  14685. key: 'onMediaAttaching',
  14686. value: function onMediaAttaching(data) {
  14687. this.media = data.media instanceof window.HTMLVideoElement ? data.media : null;
  14688. }
  14689. }, {
  14690. key: 'onManifestParsed',
  14691. value: function onManifestParsed(data) {
  14692. var hls = this.hls;
  14693. this.restrictedLevels = [];
  14694. this.levels = data.levels;
  14695. this.firstLevel = data.firstLevel;
  14696. if (hls.config.capLevelToPlayerSize && data.video) {
  14697. // Start capping immediately if the manifest has signaled video codecs
  14698. this._startCapping();
  14699. }
  14700. }
  14701. // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  14702. // to the first level
  14703. }, {
  14704. key: 'onBufferCodecs',
  14705. value: function onBufferCodecs(data) {
  14706. var hls = this.hls;
  14707. if (hls.config.capLevelToPlayerSize && data.video) {
  14708. // If the manifest did not signal a video codec capping has been deferred until we're certain video is present
  14709. this._startCapping();
  14710. }
  14711. }
  14712. }, {
  14713. key: 'onLevelsUpdated',
  14714. value: function onLevelsUpdated(data) {
  14715. this.levels = data.levels;
  14716. }
  14717. }, {
  14718. key: 'onMediaDetaching',
  14719. value: function onMediaDetaching() {
  14720. this._stopCapping();
  14721. }
  14722. }, {
  14723. key: 'detectPlayerSize',
  14724. value: function detectPlayerSize() {
  14725. if (this.media) {
  14726. var levelsLength = this.levels ? this.levels.length : 0;
  14727. if (levelsLength) {
  14728. var hls = this.hls;
  14729. hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);
  14730. if (hls.autoLevelCapping > this.autoLevelCapping) {
  14731. // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
  14732. // usually happen when the user go to the fullscreen mode.
  14733. hls.streamController.nextLevelSwitch();
  14734. }
  14735. this.autoLevelCapping = hls.autoLevelCapping;
  14736. }
  14737. }
  14738. }
  14739. /*
  14740. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  14741. */
  14742. }, {
  14743. key: 'getMaxLevel',
  14744. value: function getMaxLevel(capLevelIndex) {
  14745. var _this2 = this;
  14746. if (!this.levels) {
  14747. return -1;
  14748. }
  14749. var validLevels = this.levels.filter(function (level, index) {
  14750. return CapLevelController.isLevelAllowed(index, _this2.restrictedLevels) && index <= capLevelIndex;
  14751. });
  14752. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  14753. }
  14754. }, {
  14755. key: '_startCapping',
  14756. value: function _startCapping() {
  14757. if (this.timer) {
  14758. // Don't reset capping if started twice; this can happen if the manifest signals a video codec
  14759. return;
  14760. }
  14761. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  14762. this.hls.firstLevel = this.getMaxLevel(this.firstLevel);
  14763. clearInterval(this.timer);
  14764. this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);
  14765. this.detectPlayerSize();
  14766. }
  14767. }, {
  14768. key: '_stopCapping',
  14769. value: function _stopCapping() {
  14770. this.restrictedLevels = [];
  14771. this.firstLevel = null;
  14772. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  14773. if (this.timer) {
  14774. this.timer = clearInterval(this.timer);
  14775. this.timer = null;
  14776. }
  14777. }
  14778. }, {
  14779. key: 'mediaWidth',
  14780. get: function get() {
  14781. var width = void 0;
  14782. var media = this.media;
  14783. if (media) {
  14784. width = media.width || media.clientWidth || media.offsetWidth;
  14785. width *= CapLevelController.contentScaleFactor;
  14786. }
  14787. return width;
  14788. }
  14789. }, {
  14790. key: 'mediaHeight',
  14791. get: function get() {
  14792. var height = void 0;
  14793. var media = this.media;
  14794. if (media) {
  14795. height = media.height || media.clientHeight || media.offsetHeight;
  14796. height *= CapLevelController.contentScaleFactor;
  14797. }
  14798. return height;
  14799. }
  14800. }], [{
  14801. key: 'isLevelAllowed',
  14802. value: function isLevelAllowed(level) {
  14803. var restrictedLevels = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  14804. return restrictedLevels.indexOf(level) === -1;
  14805. }
  14806. }, {
  14807. key: 'getMaxLevelByMediaSize',
  14808. value: function getMaxLevelByMediaSize(levels, width, height) {
  14809. if (!levels || levels && !levels.length) {
  14810. return -1;
  14811. }
  14812. // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
  14813. // to determine whether we've chosen the greatest bandwidth for the media's dimensions
  14814. var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) {
  14815. if (!nextLevel) {
  14816. return true;
  14817. }
  14818. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  14819. };
  14820. // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
  14821. // the max level
  14822. var maxLevelIndex = levels.length - 1;
  14823. for (var i = 0; i < levels.length; i += 1) {
  14824. var level = levels[i];
  14825. if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {
  14826. maxLevelIndex = i;
  14827. break;
  14828. }
  14829. }
  14830. return maxLevelIndex;
  14831. }
  14832. }, {
  14833. key: 'contentScaleFactor',
  14834. get: function get() {
  14835. var pixelRatio = 1;
  14836. try {
  14837. pixelRatio = window.devicePixelRatio;
  14838. } catch (e) {}
  14839. return pixelRatio;
  14840. }
  14841. }]);
  14842. return CapLevelController;
  14843. }(_eventHandler2.default);
  14844. exports.default = CapLevelController;
  14845. module.exports = exports['default'];
  14846. /***/ }),
  14847. /* 66 */
  14848. /***/ (function(module, exports, __webpack_require__) {
  14849. "use strict";
  14850. Object.defineProperty(exports, "__esModule", {
  14851. value: true
  14852. });
  14853. 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; }; }();
  14854. var _events = __webpack_require__(1);
  14855. var _events2 = _interopRequireDefault(_events);
  14856. var _eventHandler = __webpack_require__(3);
  14857. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  14858. var _logger = __webpack_require__(0);
  14859. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  14860. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  14861. 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; }
  14862. 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; } /*
  14863. * FPS Controller
  14864. */
  14865. var _window = window,
  14866. performance = _window.performance;
  14867. var FPSController = function (_EventHandler) {
  14868. _inherits(FPSController, _EventHandler);
  14869. function FPSController(hls) {
  14870. _classCallCheck(this, FPSController);
  14871. return _possibleConstructorReturn(this, (FPSController.__proto__ || Object.getPrototypeOf(FPSController)).call(this, hls, _events2.default.MEDIA_ATTACHING));
  14872. }
  14873. _createClass(FPSController, [{
  14874. key: 'destroy',
  14875. value: function destroy() {
  14876. if (this.timer) {
  14877. clearInterval(this.timer);
  14878. }
  14879. this.isVideoPlaybackQualityAvailable = false;
  14880. }
  14881. }, {
  14882. key: 'onMediaAttaching',
  14883. value: function onMediaAttaching(data) {
  14884. var config = this.hls.config;
  14885. if (config.capLevelOnFPSDrop) {
  14886. var video = this.video = data.media instanceof window.HTMLVideoElement ? data.media : null;
  14887. if (typeof video.getVideoPlaybackQuality === 'function') {
  14888. this.isVideoPlaybackQualityAvailable = true;
  14889. }
  14890. clearInterval(this.timer);
  14891. this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  14892. }
  14893. }
  14894. }, {
  14895. key: 'checkFPS',
  14896. value: function checkFPS(video, decodedFrames, droppedFrames) {
  14897. var currentTime = performance.now();
  14898. if (decodedFrames) {
  14899. if (this.lastTime) {
  14900. var currentPeriod = currentTime - this.lastTime,
  14901. currentDropped = droppedFrames - this.lastDroppedFrames,
  14902. currentDecoded = decodedFrames - this.lastDecodedFrames,
  14903. droppedFPS = 1000 * currentDropped / currentPeriod,
  14904. hls = this.hls;
  14905. hls.trigger(_events2.default.FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames });
  14906. if (droppedFPS > 0) {
  14907. // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
  14908. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  14909. var currentLevel = hls.currentLevel;
  14910. _logger.logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
  14911. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  14912. currentLevel = currentLevel - 1;
  14913. hls.trigger(_events2.default.FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: hls.currentLevel });
  14914. hls.autoLevelCapping = currentLevel;
  14915. hls.streamController.nextLevelSwitch();
  14916. }
  14917. }
  14918. }
  14919. }
  14920. this.lastTime = currentTime;
  14921. this.lastDroppedFrames = droppedFrames;
  14922. this.lastDecodedFrames = decodedFrames;
  14923. }
  14924. }
  14925. }, {
  14926. key: 'checkFPSInterval',
  14927. value: function checkFPSInterval() {
  14928. var video = this.video;
  14929. if (video) {
  14930. if (this.isVideoPlaybackQualityAvailable) {
  14931. var videoPlaybackQuality = video.getVideoPlaybackQuality();
  14932. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  14933. } else {
  14934. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  14935. }
  14936. }
  14937. }
  14938. }]);
  14939. return FPSController;
  14940. }(_eventHandler2.default);
  14941. exports.default = FPSController;
  14942. module.exports = exports['default'];
  14943. /***/ }),
  14944. /* 67 */
  14945. /***/ (function(module, exports, __webpack_require__) {
  14946. "use strict";
  14947. Object.defineProperty(exports, "__esModule", {
  14948. value: true
  14949. });
  14950. 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; }; }(); /**
  14951. * XHR based logger
  14952. */
  14953. var _logger = __webpack_require__(0);
  14954. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  14955. var _window = window,
  14956. performance = _window.performance,
  14957. XMLHttpRequest = _window.XMLHttpRequest;
  14958. var XhrLoader = function () {
  14959. function XhrLoader(config) {
  14960. _classCallCheck(this, XhrLoader);
  14961. if (config && config.xhrSetup) {
  14962. this.xhrSetup = config.xhrSetup;
  14963. }
  14964. }
  14965. _createClass(XhrLoader, [{
  14966. key: 'destroy',
  14967. value: function destroy() {
  14968. this.abort();
  14969. this.loader = null;
  14970. }
  14971. }, {
  14972. key: 'abort',
  14973. value: function abort() {
  14974. var loader = this.loader;
  14975. if (loader && loader.readyState !== 4) {
  14976. this.stats.aborted = true;
  14977. loader.abort();
  14978. }
  14979. window.clearTimeout(this.requestTimeout);
  14980. this.requestTimeout = null;
  14981. window.clearTimeout(this.retryTimeout);
  14982. this.retryTimeout = null;
  14983. }
  14984. }, {
  14985. key: 'load',
  14986. value: function load(context, config, callbacks) {
  14987. this.context = context;
  14988. this.config = config;
  14989. this.callbacks = callbacks;
  14990. this.stats = { trequest: performance.now(), retry: 0 };
  14991. this.retryDelay = config.retryDelay;
  14992. this.loadInternal();
  14993. }
  14994. }, {
  14995. key: 'loadInternal',
  14996. value: function loadInternal() {
  14997. var xhr = void 0,
  14998. context = this.context;
  14999. xhr = this.loader = new XMLHttpRequest();
  15000. var stats = this.stats;
  15001. stats.tfirst = 0;
  15002. stats.loaded = 0;
  15003. var xhrSetup = this.xhrSetup;
  15004. try {
  15005. if (xhrSetup) {
  15006. try {
  15007. xhrSetup(xhr, context.url);
  15008. } catch (e) {
  15009. // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");}
  15010. // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN
  15011. xhr.open('GET', context.url, true);
  15012. xhrSetup(xhr, context.url);
  15013. }
  15014. }
  15015. if (!xhr.readyState) {
  15016. xhr.open('GET', context.url, true);
  15017. }
  15018. } catch (e) {
  15019. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  15020. this.callbacks.onError({ code: xhr.status, text: e.message }, context, xhr);
  15021. return;
  15022. }
  15023. if (context.rangeEnd) {
  15024. xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
  15025. }
  15026. xhr.onreadystatechange = this.readystatechange.bind(this);
  15027. xhr.onprogress = this.loadprogress.bind(this);
  15028. xhr.responseType = context.responseType;
  15029. // setup timeout before we perform request
  15030. this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout);
  15031. xhr.send();
  15032. }
  15033. }, {
  15034. key: 'readystatechange',
  15035. value: function readystatechange(event) {
  15036. var xhr = event.currentTarget,
  15037. readyState = xhr.readyState,
  15038. stats = this.stats,
  15039. context = this.context,
  15040. config = this.config;
  15041. // don't proceed if xhr has been aborted
  15042. if (stats.aborted) {
  15043. return;
  15044. }
  15045. // >= HEADERS_RECEIVED
  15046. if (readyState >= 2) {
  15047. // clear xhr timeout and rearm it if readyState less than 4
  15048. window.clearTimeout(this.requestTimeout);
  15049. if (stats.tfirst === 0) {
  15050. stats.tfirst = Math.max(performance.now(), stats.trequest);
  15051. }
  15052. if (readyState === 4) {
  15053. var status = xhr.status;
  15054. // http status between 200 to 299 are all successful
  15055. if (status >= 200 && status < 300) {
  15056. stats.tload = Math.max(stats.tfirst, performance.now());
  15057. var data = void 0,
  15058. len = void 0;
  15059. if (context.responseType === 'arraybuffer') {
  15060. data = xhr.response;
  15061. len = data.byteLength;
  15062. } else {
  15063. data = xhr.responseText;
  15064. len = data.length;
  15065. }
  15066. stats.loaded = stats.total = len;
  15067. var response = { url: xhr.responseURL, data: data };
  15068. this.callbacks.onSuccess(response, stats, context, xhr);
  15069. } else {
  15070. // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
  15071. if (stats.retry >= config.maxRetry || status >= 400 && status < 499) {
  15072. _logger.logger.error(status + ' while loading ' + context.url);
  15073. this.callbacks.onError({ code: status, text: xhr.statusText }, context, xhr);
  15074. } else {
  15075. // retry
  15076. _logger.logger.warn(status + ' while loading ' + context.url + ', retrying in ' + this.retryDelay + '...');
  15077. // aborts and resets internal state
  15078. this.destroy();
  15079. // schedule retry
  15080. this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  15081. // set exponential backoff
  15082. this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);
  15083. stats.retry++;
  15084. }
  15085. }
  15086. } else {
  15087. // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
  15088. this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout);
  15089. }
  15090. }
  15091. }
  15092. }, {
  15093. key: 'loadtimeout',
  15094. value: function loadtimeout() {
  15095. _logger.logger.warn('timeout while loading ' + this.context.url);
  15096. this.callbacks.onTimeout(this.stats, this.context, null);
  15097. }
  15098. }, {
  15099. key: 'loadprogress',
  15100. value: function loadprogress(event) {
  15101. var xhr = event.currentTarget,
  15102. stats = this.stats;
  15103. stats.loaded = event.loaded;
  15104. if (event.lengthComputable) {
  15105. stats.total = event.total;
  15106. }
  15107. var onProgress = this.callbacks.onProgress;
  15108. if (onProgress) {
  15109. // third arg is to provide on progress data
  15110. onProgress(stats, this.context, null, xhr);
  15111. }
  15112. }
  15113. }]);
  15114. return XhrLoader;
  15115. }();
  15116. exports.default = XhrLoader;
  15117. module.exports = exports['default'];
  15118. /***/ }),
  15119. /* 68 */
  15120. /***/ (function(module, exports, __webpack_require__) {
  15121. "use strict";
  15122. Object.defineProperty(exports, "__esModule", {
  15123. value: true
  15124. });
  15125. 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; }; }();
  15126. var _events = __webpack_require__(1);
  15127. var _events2 = _interopRequireDefault(_events);
  15128. var _taskLoop = __webpack_require__(28);
  15129. var _taskLoop2 = _interopRequireDefault(_taskLoop);
  15130. var _logger = __webpack_require__(0);
  15131. var _errors = __webpack_require__(2);
  15132. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  15133. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  15134. 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; }
  15135. 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; }
  15136. /**
  15137. * @class AudioTrackController
  15138. * @implements {EventHandler}
  15139. *
  15140. * Handles main manifest and audio-track metadata loaded,
  15141. * owns and exposes the selectable audio-tracks data-models.
  15142. *
  15143. * Exposes internal interface to select available audio-tracks.
  15144. *
  15145. * Handles errors on loading audio-track playlists. Manages fallback mechanism
  15146. * with redundants tracks (group-IDs).
  15147. *
  15148. * Handles level-loading and group-ID switches for video (fallback on video levels),
  15149. * and eventually adapts the audio-track group-ID to match.
  15150. *
  15151. * @fires AUDIO_TRACK_LOADING
  15152. * @fires AUDIO_TRACK_SWITCHING
  15153. * @fires AUDIO_TRACKS_UPDATED
  15154. * @fires ERROR
  15155. *
  15156. */
  15157. var AudioTrackController = function (_TaskLoop) {
  15158. _inherits(AudioTrackController, _TaskLoop);
  15159. function AudioTrackController(hls) {
  15160. _classCallCheck(this, AudioTrackController);
  15161. /**
  15162. * @private
  15163. * Currently selected index in `tracks`
  15164. * @member {number} trackId
  15165. */
  15166. var _this = _possibleConstructorReturn(this, (AudioTrackController.__proto__ || Object.getPrototypeOf(AudioTrackController)).call(this, hls, _events2.default.MANIFEST_LOADING, _events2.default.MANIFEST_PARSED, _events2.default.AUDIO_TRACK_LOADED, _events2.default.AUDIO_TRACK_SWITCHED, _events2.default.LEVEL_LOADED, _events2.default.ERROR));
  15167. _this._trackId = -1;
  15168. /**
  15169. * @private
  15170. * If should select tracks according to default track attribute
  15171. * @member {boolean} _selectDefaultTrack
  15172. */
  15173. _this._selectDefaultTrack = true;
  15174. /**
  15175. * @public
  15176. * All tracks available
  15177. * @member {AudioTrack[]}
  15178. */
  15179. _this.tracks = [];
  15180. /**
  15181. * @public
  15182. * List of blacklisted audio track IDs (that have caused failure)
  15183. * @member {number[]}
  15184. */
  15185. _this.trackIdBlacklist = Object.create(null);
  15186. /**
  15187. * @public
  15188. * The currently running group ID for audio
  15189. * (we grab this on manifest-parsed and new level-loaded)
  15190. * @member {string}
  15191. */
  15192. _this.audioGroupId = null;
  15193. return _this;
  15194. }
  15195. /**
  15196. * Reset audio tracks on new manifest loading.
  15197. */
  15198. _createClass(AudioTrackController, [{
  15199. key: 'onManifestLoading',
  15200. value: function onManifestLoading() {
  15201. this.tracks = [];
  15202. this._trackId = -1;
  15203. this._selectDefaultTrack = true;
  15204. }
  15205. /**
  15206. * Store tracks data from manifest parsed data.
  15207. *
  15208. * Trigger AUDIO_TRACKS_UPDATED event.
  15209. *
  15210. * @param {*} data
  15211. */
  15212. }, {
  15213. key: 'onManifestParsed',
  15214. value: function onManifestParsed(data) {
  15215. var tracks = this.tracks = data.audioTracks || [];
  15216. this.hls.trigger(_events2.default.AUDIO_TRACKS_UPDATED, { audioTracks: tracks });
  15217. }
  15218. /**
  15219. * Store track details of loaded track in our data-model.
  15220. *
  15221. * Set-up metadata update interval task for live-mode streams.
  15222. *
  15223. * @param {} data
  15224. */
  15225. }, {
  15226. key: 'onAudioTrackLoaded',
  15227. value: function onAudioTrackLoaded(data) {
  15228. if (data.id >= this.tracks.length) {
  15229. _logger.logger.warn('Invalid audio track id:', data.id);
  15230. return;
  15231. }
  15232. _logger.logger.log('audioTrack ' + data.id + ' loaded');
  15233. this.tracks[data.id].details = data.details;
  15234. // check if current playlist is a live playlist
  15235. // and if we have already our reload interval setup
  15236. if (data.details.live && !this.hasInterval()) {
  15237. // if live playlist we will have to reload it periodically
  15238. // set reload period to playlist target duration
  15239. var updatePeriodMs = data.details.targetduration * 1000;
  15240. this.setInterval(updatePeriodMs);
  15241. }
  15242. if (!data.details.live && this.hasInterval()) {
  15243. // playlist is not live and timer is scheduled: cancel it
  15244. this.clearInterval();
  15245. }
  15246. }
  15247. /**
  15248. * Update the internal group ID to any audio-track we may have set manually
  15249. * or because of a failure-handling fallback.
  15250. *
  15251. * Quality-levels should update to that group ID in this case.
  15252. *
  15253. * @param {*} data
  15254. */
  15255. }, {
  15256. key: 'onAudioTrackSwitched',
  15257. value: function onAudioTrackSwitched(data) {
  15258. var audioGroupId = this.tracks[data.id].groupId;
  15259. if (audioGroupId && this.audioGroupId !== audioGroupId) {
  15260. this.audioGroupId = audioGroupId;
  15261. }
  15262. }
  15263. /**
  15264. * When a level gets loaded, if it has redundant audioGroupIds (in the same ordinality as it's redundant URLs)
  15265. * we are setting our audio-group ID internally to the one set, if it is different from the group ID currently set.
  15266. *
  15267. * If group-ID got update, we re-select the appropriate audio-track with this group-ID matching the currently
  15268. * selected one (based on NAME property).
  15269. *
  15270. * @param {*} data
  15271. */
  15272. }, {
  15273. key: 'onLevelLoaded',
  15274. value: function onLevelLoaded(data) {
  15275. // FIXME: crashes because currentLevel is undefined
  15276. // const levelInfo = this.hls.levels[this.hls.currentLevel];
  15277. var levelInfo = this.hls.levels[data.level];
  15278. if (!levelInfo.audioGroupIds) {
  15279. return;
  15280. }
  15281. var audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];
  15282. if (this.audioGroupId !== audioGroupId) {
  15283. this.audioGroupId = audioGroupId;
  15284. this._selectInitialAudioTrack();
  15285. }
  15286. }
  15287. /**
  15288. * Handle network errors loading audio track manifests
  15289. * and also pausing on any netwok errors.
  15290. *
  15291. * @param {ErrorEventData} data
  15292. */
  15293. }, {
  15294. key: 'onError',
  15295. value: function onError(data) {
  15296. // Only handle network errors
  15297. if (data.type !== _errors.ErrorTypes.NETWORK_ERROR) {
  15298. return;
  15299. }
  15300. // If fatal network error, cancel update task
  15301. if (data.fatal) {
  15302. this.clearInterval();
  15303. }
  15304. // If not an audio-track loading error don't handle further
  15305. if (data.details !== _errors.ErrorDetails.AUDIO_TRACK_LOAD_ERROR) {
  15306. return;
  15307. }
  15308. _logger.logger.warn('Network failure on audio-track id:', data.context.id);
  15309. this._handleLoadError();
  15310. }
  15311. /**
  15312. * @type {AudioTrack[]} Audio-track list we own
  15313. */
  15314. }, {
  15315. key: '_setAudioTrack',
  15316. /**
  15317. * @private
  15318. * @param {number} newId
  15319. */
  15320. value: function _setAudioTrack(newId) {
  15321. // noop on same audio track id as already set
  15322. if (this._trackId === newId && this.tracks[this._trackId].details) {
  15323. _logger.logger.debug('Same id as current audio-track passed, and track details available -> no-op');
  15324. return;
  15325. }
  15326. // check if level idx is valid
  15327. if (newId < 0 || newId >= this.tracks.length) {
  15328. _logger.logger.warn('Invalid id passed to audio-track controller');
  15329. return;
  15330. }
  15331. var audioTrack = this.tracks[newId];
  15332. _logger.logger.log('Now switching to audio-track index ' + newId);
  15333. // stopping live reloading timer if any
  15334. this.clearInterval();
  15335. this._trackId = newId;
  15336. var url = audioTrack.url,
  15337. type = audioTrack.type,
  15338. id = audioTrack.id;
  15339. this.hls.trigger(_events2.default.AUDIO_TRACK_SWITCHING, { id: id, type: type, url: url });
  15340. this._loadTrackDetailsIfNeeded(audioTrack);
  15341. }
  15342. /**
  15343. * @override
  15344. */
  15345. }, {
  15346. key: 'doTick',
  15347. value: function doTick() {
  15348. this._updateTrack(this._trackId);
  15349. }
  15350. /**
  15351. * Select initial track
  15352. * @private
  15353. */
  15354. }, {
  15355. key: '_selectInitialAudioTrack',
  15356. value: function _selectInitialAudioTrack() {
  15357. var _this2 = this;
  15358. var tracks = this.tracks;
  15359. if (!tracks.length) {
  15360. return;
  15361. }
  15362. var currentAudioTrack = this.tracks[this._trackId];
  15363. var name = null;
  15364. if (currentAudioTrack) {
  15365. name = currentAudioTrack.name;
  15366. }
  15367. // Pre-select default tracks if there are any
  15368. if (this._selectDefaultTrack) {
  15369. var defaultTracks = tracks.filter(function (track) {
  15370. return track.default;
  15371. });
  15372. if (defaultTracks.length) {
  15373. tracks = defaultTracks;
  15374. } else {
  15375. _logger.logger.warn('No default audio tracks defined');
  15376. }
  15377. }
  15378. var trackFound = false;
  15379. var traverseTracks = function traverseTracks() {
  15380. // Select track with right group ID
  15381. tracks.forEach(function (track) {
  15382. if (trackFound) {
  15383. return;
  15384. }
  15385. // We need to match the (pre-)selected group ID
  15386. // and the NAME of the current track.
  15387. if ((!_this2.audioGroupId || track.groupId === _this2.audioGroupId) && (!name || name === track.name)) {
  15388. // If there was a previous track try to stay with the same `NAME`.
  15389. // It should be unique across tracks of same group, and consistent through redundant track groups.
  15390. _this2._setAudioTrack(track.id);
  15391. trackFound = true;
  15392. }
  15393. });
  15394. };
  15395. traverseTracks();
  15396. if (!trackFound) {
  15397. name = null;
  15398. traverseTracks();
  15399. }
  15400. if (!trackFound) {
  15401. _logger.logger.error('No track found for running audio group-ID: ' + this.audioGroupId);
  15402. this.hls.trigger(_events2.default.ERROR, {
  15403. type: _errors.ErrorTypes.MEDIA_ERROR,
  15404. details: _errors.ErrorDetails.AUDIO_TRACK_LOAD_ERROR,
  15405. fatal: true
  15406. });
  15407. }
  15408. }
  15409. /**
  15410. * @private
  15411. * @param {AudioTrack} audioTrack
  15412. * @returns {boolean}
  15413. */
  15414. }, {
  15415. key: '_needsTrackLoading',
  15416. value: function _needsTrackLoading(audioTrack) {
  15417. var details = audioTrack.details,
  15418. url = audioTrack.url;
  15419. if (!details || details.live) {
  15420. // check if we face an audio track embedded in main playlist (audio track without URI attribute)
  15421. return !!url;
  15422. }
  15423. return false;
  15424. }
  15425. /**
  15426. * @private
  15427. * @param {AudioTrack} audioTrack
  15428. */
  15429. }, {
  15430. key: '_loadTrackDetailsIfNeeded',
  15431. value: function _loadTrackDetailsIfNeeded(audioTrack) {
  15432. if (this._needsTrackLoading(audioTrack)) {
  15433. var url = audioTrack.url,
  15434. id = audioTrack.id;
  15435. // track not retrieved yet, or live playlist we need to (re)load it
  15436. _logger.logger.log('loading audio-track playlist for id: ' + id);
  15437. this.hls.trigger(_events2.default.AUDIO_TRACK_LOADING, { url: url, id: id });
  15438. }
  15439. }
  15440. /**
  15441. * @private
  15442. * @param {number} newId
  15443. */
  15444. }, {
  15445. key: '_updateTrack',
  15446. value: function _updateTrack(newId) {
  15447. // check if level idx is valid
  15448. if (newId < 0 || newId >= this.tracks.length) {
  15449. return;
  15450. }
  15451. // stopping live reloading timer if any
  15452. this.clearInterval();
  15453. this._trackId = newId;
  15454. _logger.logger.log('trying to update audio-track ' + newId);
  15455. var audioTrack = this.tracks[newId];
  15456. this._loadTrackDetailsIfNeeded(audioTrack);
  15457. }
  15458. /**
  15459. * @private
  15460. */
  15461. }, {
  15462. key: '_handleLoadError',
  15463. value: function _handleLoadError() {
  15464. // First, let's black list current track id
  15465. this.trackIdBlacklist[this._trackId] = true;
  15466. // Let's try to fall back on a functional audio-track with the same group ID
  15467. var previousId = this._trackId;
  15468. var _tracks$previousId = this.tracks[previousId],
  15469. name = _tracks$previousId.name,
  15470. language = _tracks$previousId.language,
  15471. groupId = _tracks$previousId.groupId;
  15472. _logger.logger.warn('Loading failed on audio track id: ' + previousId + ', group-id: ' + groupId + ', name/language: "' + name + '" / "' + language + '"');
  15473. // Find a non-blacklisted track ID with the same NAME
  15474. // At least a track that is not blacklisted, thus on another group-ID.
  15475. var newId = previousId;
  15476. for (var i = 0; i < this.tracks.length; i++) {
  15477. if (this.trackIdBlacklist[i]) {
  15478. continue;
  15479. }
  15480. var newTrack = this.tracks[i];
  15481. if (newTrack.name === name) {
  15482. newId = i;
  15483. break;
  15484. }
  15485. }
  15486. if (newId === previousId) {
  15487. _logger.logger.warn('No fallback audio-track found for name/language: "' + name + '" / "' + language + '"');
  15488. return;
  15489. }
  15490. _logger.logger.log('Attempting audio-track fallback id:', newId, 'group-id:', this.tracks[newId].groupId);
  15491. this._setAudioTrack(newId);
  15492. }
  15493. }, {
  15494. key: 'audioTracks',
  15495. get: function get() {
  15496. return this.tracks;
  15497. }
  15498. /**
  15499. * @type {number} Index into audio-tracks list of currently selected track.
  15500. */
  15501. }, {
  15502. key: 'audioTrack',
  15503. get: function get() {
  15504. return this._trackId;
  15505. }
  15506. /**
  15507. * Select current track by index
  15508. */
  15509. ,
  15510. set: function set(newId) {
  15511. this._setAudioTrack(newId);
  15512. // If audio track is selected from API then don't choose from the manifest default track
  15513. this._selectDefaultTrack = false;
  15514. }
  15515. }]);
  15516. return AudioTrackController;
  15517. }(_taskLoop2.default);
  15518. exports.default = AudioTrackController;
  15519. module.exports = exports['default'];
  15520. /***/ }),
  15521. /* 69 */
  15522. /***/ (function(module, exports, __webpack_require__) {
  15523. "use strict";
  15524. Object.defineProperty(exports, "__esModule", {
  15525. value: true
  15526. });
  15527. 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; }; }();
  15528. var _binarySearch = __webpack_require__(9);
  15529. var _binarySearch2 = _interopRequireDefault(_binarySearch);
  15530. var _bufferHelper = __webpack_require__(4);
  15531. var _demuxer = __webpack_require__(19);
  15532. var _demuxer2 = _interopRequireDefault(_demuxer);
  15533. var _events = __webpack_require__(1);
  15534. var _events2 = _interopRequireDefault(_events);
  15535. var _levelHelper = __webpack_require__(7);
  15536. var LevelHelper = _interopRequireWildcard(_levelHelper);
  15537. var _timeRanges = __webpack_require__(25);
  15538. var _timeRanges2 = _interopRequireDefault(_timeRanges);
  15539. var _errors = __webpack_require__(2);
  15540. var _logger = __webpack_require__(0);
  15541. var _discontinuities = __webpack_require__(26);
  15542. var _fragmentTracker = __webpack_require__(6);
  15543. var _fragment = __webpack_require__(11);
  15544. var _fragment2 = _interopRequireDefault(_fragment);
  15545. var _baseStreamController = __webpack_require__(14);
  15546. var _baseStreamController2 = _interopRequireDefault(_baseStreamController);
  15547. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  15548. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  15549. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  15550. 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; }
  15551. 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; } /*
  15552. * Audio Stream Controller
  15553. */
  15554. var _window = window,
  15555. performance = _window.performance;
  15556. var TICK_INTERVAL = 100; // how often to tick in ms
  15557. var AudioStreamController = function (_BaseStreamController) {
  15558. _inherits(AudioStreamController, _BaseStreamController);
  15559. function AudioStreamController(hls, fragmentTracker) {
  15560. _classCallCheck(this, AudioStreamController);
  15561. var _this = _possibleConstructorReturn(this, (AudioStreamController.__proto__ || Object.getPrototypeOf(AudioStreamController)).call(this, hls, _events2.default.MEDIA_ATTACHED, _events2.default.MEDIA_DETACHING, _events2.default.AUDIO_TRACKS_UPDATED, _events2.default.AUDIO_TRACK_SWITCHING, _events2.default.AUDIO_TRACK_LOADED, _events2.default.KEY_LOADED, _events2.default.FRAG_LOADED, _events2.default.FRAG_PARSING_INIT_SEGMENT, _events2.default.FRAG_PARSING_DATA, _events2.default.FRAG_PARSED, _events2.default.ERROR, _events2.default.BUFFER_RESET, _events2.default.BUFFER_CREATED, _events2.default.BUFFER_APPENDED, _events2.default.BUFFER_FLUSHED, _events2.default.INIT_PTS_FOUND));
  15562. _this.fragmentTracker = fragmentTracker;
  15563. _this.config = hls.config;
  15564. _this.audioCodecSwap = false;
  15565. _this._state = _baseStreamController.State.STOPPED;
  15566. _this.initPTS = [];
  15567. _this.waitingFragment = null;
  15568. _this.videoTrackCC = null;
  15569. return _this;
  15570. }
  15571. // Signal that video PTS was found
  15572. _createClass(AudioStreamController, [{
  15573. key: 'onInitPtsFound',
  15574. value: function onInitPtsFound(data) {
  15575. var demuxerId = data.id,
  15576. cc = data.frag.cc,
  15577. initPTS = data.initPTS;
  15578. if (demuxerId === 'main') {
  15579. // Always update the new INIT PTS
  15580. // Can change due level switch
  15581. this.initPTS[cc] = initPTS;
  15582. this.videoTrackCC = cc;
  15583. _logger.logger.log('InitPTS for cc: ' + cc + ' found from video track: ' + initPTS);
  15584. // If we are waiting we need to demux/remux the waiting frag
  15585. // With the new initPTS
  15586. if (this.state === _baseStreamController.State.WAITING_INIT_PTS) {
  15587. this.tick();
  15588. }
  15589. }
  15590. }
  15591. }, {
  15592. key: 'startLoad',
  15593. value: function startLoad(startPosition) {
  15594. if (this.tracks) {
  15595. var lastCurrentTime = this.lastCurrentTime;
  15596. this.stopLoad();
  15597. this.setInterval(TICK_INTERVAL);
  15598. this.fragLoadError = 0;
  15599. if (lastCurrentTime > 0 && startPosition === -1) {
  15600. _logger.logger.log('audio:override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3));
  15601. this.state = _baseStreamController.State.IDLE;
  15602. } else {
  15603. this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition;
  15604. this.state = _baseStreamController.State.STARTING;
  15605. }
  15606. this.nextLoadPosition = this.startPosition = this.lastCurrentTime;
  15607. this.tick();
  15608. } else {
  15609. this.startPosition = startPosition;
  15610. this.state = _baseStreamController.State.STOPPED;
  15611. }
  15612. }
  15613. }, {
  15614. key: 'doTick',
  15615. value: function doTick() {
  15616. var pos = void 0,
  15617. track = void 0,
  15618. trackDetails = void 0,
  15619. hls = this.hls,
  15620. config = hls.config;
  15621. // logger.log('audioStream:' + this.state);
  15622. switch (this.state) {
  15623. case _baseStreamController.State.ERROR:
  15624. // don't do anything in error state to avoid breaking further ...
  15625. case _baseStreamController.State.PAUSED:
  15626. // don't do anything in paused state either ...
  15627. case _baseStreamController.State.BUFFER_FLUSHING:
  15628. break;
  15629. case _baseStreamController.State.STARTING:
  15630. this.state = _baseStreamController.State.WAITING_TRACK;
  15631. this.loadedmetadata = false;
  15632. break;
  15633. case _baseStreamController.State.IDLE:
  15634. var tracks = this.tracks;
  15635. // audio tracks not received => exit loop
  15636. if (!tracks) {
  15637. break;
  15638. }
  15639. // if video not attached AND
  15640. // start fragment already requested OR start frag prefetch disable
  15641. // exit loop
  15642. // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
  15643. if (!this.media && (this.startFragRequested || !config.startFragPrefetch)) {
  15644. break;
  15645. }
  15646. // determine next candidate fragment to be loaded, based on current position and
  15647. // end of buffer position
  15648. // if we have not yet loaded any fragment, start loading from start position
  15649. if (this.loadedmetadata) {
  15650. pos = this.media.currentTime;
  15651. } else {
  15652. pos = this.nextLoadPosition;
  15653. if (pos === undefined) {
  15654. break;
  15655. }
  15656. }
  15657. var media = this.mediaBuffer ? this.mediaBuffer : this.media,
  15658. videoBuffer = this.videoBuffer ? this.videoBuffer : this.media,
  15659. bufferInfo = _bufferHelper.BufferHelper.bufferInfo(media, pos, config.maxBufferHole),
  15660. mainBufferInfo = _bufferHelper.BufferHelper.bufferInfo(videoBuffer, pos, config.maxBufferHole),
  15661. bufferLen = bufferInfo.len,
  15662. bufferEnd = bufferInfo.end,
  15663. fragPrevious = this.fragPrevious,
  15664. // ensure we buffer at least config.maxBufferLength (default 30s) or config.maxMaxBufferLength (default: 600s)
  15665. // whichever is smaller.
  15666. // once we reach that threshold, don't buffer more than video (mainBufferInfo.len)
  15667. maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength),
  15668. maxBufLen = Math.max(maxConfigBuffer, mainBufferInfo.len),
  15669. audioSwitch = this.audioSwitch,
  15670. trackId = this.trackId;
  15671. // if buffer length is less than maxBufLen try to load a new fragment
  15672. if ((bufferLen < maxBufLen || audioSwitch) && trackId < tracks.length) {
  15673. trackDetails = tracks[trackId].details;
  15674. // if track info not retrieved yet, switch state and wait for track retrieval
  15675. if (typeof trackDetails === 'undefined') {
  15676. this.state = _baseStreamController.State.WAITING_TRACK;
  15677. break;
  15678. }
  15679. if (!audioSwitch && this._streamEnded(bufferInfo, trackDetails)) {
  15680. this.hls.trigger(_events2.default.BUFFER_EOS, { type: 'audio' });
  15681. this.state = _baseStreamController.State.ENDED;
  15682. return;
  15683. }
  15684. // find fragment index, contiguous with end of buffer position
  15685. var fragments = trackDetails.fragments,
  15686. fragLen = fragments.length,
  15687. start = fragments[0].start,
  15688. end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
  15689. frag = void 0;
  15690. // When switching audio track, reload audio as close as possible to currentTime
  15691. if (audioSwitch) {
  15692. if (trackDetails.live && !trackDetails.PTSKnown) {
  15693. _logger.logger.log('switching audiotrack, live stream, unknown PTS,load first fragment');
  15694. bufferEnd = 0;
  15695. } else {
  15696. bufferEnd = pos;
  15697. // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime
  15698. if (trackDetails.PTSKnown && pos < start) {
  15699. // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start
  15700. if (bufferInfo.end > start || bufferInfo.nextStart) {
  15701. _logger.logger.log('alt audio track ahead of main track, seek to start of alt audio track');
  15702. this.media.currentTime = start + 0.05;
  15703. } else {
  15704. return;
  15705. }
  15706. }
  15707. }
  15708. }
  15709. if (trackDetails.initSegment && !trackDetails.initSegment.data) {
  15710. frag = trackDetails.initSegment;
  15711. } // eslint-disable-line brace-style
  15712. // if bufferEnd before start of playlist, load first fragment
  15713. else if (bufferEnd <= start) {
  15714. frag = fragments[0];
  15715. if (this.videoTrackCC !== null && frag.cc !== this.videoTrackCC) {
  15716. // Ensure we find a fragment which matches the continuity of the video track
  15717. frag = (0, _discontinuities.findFragWithCC)(fragments, this.videoTrackCC);
  15718. }
  15719. if (trackDetails.live && frag.loadIdx && frag.loadIdx === this.fragLoadIdx) {
  15720. // we just loaded this first fragment, and we are still lagging behind the start of the live playlist
  15721. // let's force seek to start
  15722. var nextBuffered = bufferInfo.nextStart ? bufferInfo.nextStart : start;
  15723. _logger.logger.log('no alt audio available @currentTime:' + this.media.currentTime + ', seeking @' + (nextBuffered + 0.05));
  15724. this.media.currentTime = nextBuffered + 0.05;
  15725. return;
  15726. }
  15727. } else {
  15728. var foundFrag = void 0;
  15729. var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
  15730. var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;
  15731. var fragmentWithinToleranceTest = function fragmentWithinToleranceTest(candidate) {
  15732. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  15733. // this is to cope with situations like
  15734. // bufferEnd = 9.991
  15735. // frag[Ø] : [0,10]
  15736. // frag[1] : [10,20]
  15737. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  15738. // frag start frag start+duration
  15739. // |-----------------------------|
  15740. // <---> <--->
  15741. // ...--------><-----------------------------><---------....
  15742. // previous frag matching fragment next frag
  15743. // return -1 return 0 return 1
  15744. // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  15745. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  15746. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration);
  15747. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  15748. return 1;
  15749. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  15750. // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  15751. return -1;
  15752. }
  15753. return 0;
  15754. };
  15755. if (bufferEnd < end) {
  15756. if (bufferEnd > end - maxFragLookUpTolerance) {
  15757. maxFragLookUpTolerance = 0;
  15758. }
  15759. // Prefer the next fragment if it's within tolerance
  15760. if (fragNext && !fragmentWithinToleranceTest(fragNext)) {
  15761. foundFrag = fragNext;
  15762. } else {
  15763. foundFrag = _binarySearch2.default.search(fragments, fragmentWithinToleranceTest);
  15764. }
  15765. } else {
  15766. // reach end of playlist
  15767. foundFrag = fragments[fragLen - 1];
  15768. }
  15769. if (foundFrag) {
  15770. frag = foundFrag;
  15771. start = foundFrag.start;
  15772. // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
  15773. if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) {
  15774. if (frag.sn < trackDetails.endSN) {
  15775. frag = fragments[frag.sn + 1 - trackDetails.startSN];
  15776. _logger.logger.log('SN just loaded, load next one: ' + frag.sn);
  15777. } else {
  15778. frag = null;
  15779. }
  15780. }
  15781. }
  15782. }
  15783. if (frag) {
  15784. // logger.log(' loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));
  15785. if (frag.encrypted) {
  15786. _logger.logger.log('Loading key for ' + frag.sn + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId);
  15787. this.state = _baseStreamController.State.KEY_LOADING;
  15788. hls.trigger(_events2.default.KEY_LOADING, { frag: frag });
  15789. } else {
  15790. _logger.logger.log('Loading ' + frag.sn + ', cc: ' + frag.cc + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId + ', currentTime:' + pos + ',bufferEnd:' + bufferEnd.toFixed(3));
  15791. // only load if fragment is not loaded or if in audio switch
  15792. // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch
  15793. this.fragCurrent = frag;
  15794. if (audioSwitch || this.fragmentTracker.getState(frag) === _fragmentTracker.FragmentState.NOT_LOADED) {
  15795. this.startFragRequested = true;
  15796. if (Number.isFinite(frag.sn)) {
  15797. this.nextLoadPosition = frag.start + frag.duration;
  15798. }
  15799. hls.trigger(_events2.default.FRAG_LOADING, { frag: frag });
  15800. this.state = _baseStreamController.State.FRAG_LOADING;
  15801. }
  15802. }
  15803. }
  15804. }
  15805. break;
  15806. case _baseStreamController.State.WAITING_TRACK:
  15807. track = this.tracks[this.trackId];
  15808. // check if playlist is already loaded
  15809. if (track && track.details) {
  15810. this.state = _baseStreamController.State.IDLE;
  15811. }
  15812. break;
  15813. case _baseStreamController.State.FRAG_LOADING_WAITING_RETRY:
  15814. var now = performance.now();
  15815. var retryDate = this.retryDate;
  15816. media = this.media;
  15817. var isSeeking = media && media.seeking;
  15818. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  15819. if (!retryDate || now >= retryDate || isSeeking) {
  15820. _logger.logger.log('audioStreamController: retryDate reached, switch back to IDLE state');
  15821. this.state = _baseStreamController.State.IDLE;
  15822. }
  15823. break;
  15824. case _baseStreamController.State.WAITING_INIT_PTS:
  15825. var videoTrackCC = this.videoTrackCC;
  15826. if (this.initPTS[videoTrackCC] === undefined) {
  15827. break;
  15828. }
  15829. // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS
  15830. var waitingFrag = this.waitingFragment;
  15831. if (waitingFrag) {
  15832. var waitingFragCC = waitingFrag.frag.cc;
  15833. if (videoTrackCC !== waitingFragCC) {
  15834. track = this.tracks[this.trackId];
  15835. if (track.details && track.details.live) {
  15836. _logger.logger.warn('Waiting fragment CC (' + waitingFragCC + ') does not match video track CC (' + videoTrackCC + ')');
  15837. this.waitingFragment = null;
  15838. this.state = _baseStreamController.State.IDLE;
  15839. }
  15840. } else {
  15841. this.state = _baseStreamController.State.FRAG_LOADING;
  15842. this.onFragLoaded(this.waitingFragment);
  15843. this.waitingFragment = null;
  15844. }
  15845. } else {
  15846. this.state = _baseStreamController.State.IDLE;
  15847. }
  15848. break;
  15849. case _baseStreamController.State.STOPPED:
  15850. case _baseStreamController.State.FRAG_LOADING:
  15851. case _baseStreamController.State.PARSING:
  15852. case _baseStreamController.State.PARSED:
  15853. case _baseStreamController.State.ENDED:
  15854. break;
  15855. default:
  15856. break;
  15857. }
  15858. }
  15859. }, {
  15860. key: 'onMediaAttached',
  15861. value: function onMediaAttached(data) {
  15862. var media = this.media = this.mediaBuffer = data.media;
  15863. this.onvseeking = this.onMediaSeeking.bind(this);
  15864. this.onvended = this.onMediaEnded.bind(this);
  15865. media.addEventListener('seeking', this.onvseeking);
  15866. media.addEventListener('ended', this.onvended);
  15867. var config = this.config;
  15868. if (this.tracks && config.autoStartLoad) {
  15869. this.startLoad(config.startPosition);
  15870. }
  15871. }
  15872. }, {
  15873. key: 'onMediaDetaching',
  15874. value: function onMediaDetaching() {
  15875. var media = this.media;
  15876. if (media && media.ended) {
  15877. _logger.logger.log('MSE detaching and video ended, reset startPosition');
  15878. this.startPosition = this.lastCurrentTime = 0;
  15879. }
  15880. // remove video listeners
  15881. if (media) {
  15882. media.removeEventListener('seeking', this.onvseeking);
  15883. media.removeEventListener('ended', this.onvended);
  15884. this.onvseeking = this.onvseeked = this.onvended = null;
  15885. }
  15886. this.media = this.mediaBuffer = this.videoBuffer = null;
  15887. this.loadedmetadata = false;
  15888. this.stopLoad();
  15889. }
  15890. }, {
  15891. key: 'onAudioTracksUpdated',
  15892. value: function onAudioTracksUpdated(data) {
  15893. _logger.logger.log('audio tracks updated');
  15894. this.tracks = data.audioTracks;
  15895. }
  15896. }, {
  15897. key: 'onAudioTrackSwitching',
  15898. value: function onAudioTrackSwitching(data) {
  15899. // if any URL found on new audio track, it is an alternate audio track
  15900. var altAudio = !!data.url;
  15901. this.trackId = data.id;
  15902. this.fragCurrent = null;
  15903. this.state = _baseStreamController.State.PAUSED;
  15904. this.waitingFragment = null;
  15905. // destroy useless demuxer when switching audio to main
  15906. if (!altAudio) {
  15907. if (this.demuxer) {
  15908. this.demuxer.destroy();
  15909. this.demuxer = null;
  15910. }
  15911. } else {
  15912. // switching to audio track, start timer if not already started
  15913. this.setInterval(TICK_INTERVAL);
  15914. }
  15915. // should we switch tracks ?
  15916. if (altAudio) {
  15917. this.audioSwitch = true;
  15918. // main audio track are handled by stream-controller, just do something if switching to alt audio track
  15919. this.state = _baseStreamController.State.IDLE;
  15920. }
  15921. this.tick();
  15922. }
  15923. }, {
  15924. key: 'onAudioTrackLoaded',
  15925. value: function onAudioTrackLoaded(data) {
  15926. var newDetails = data.details,
  15927. trackId = data.id,
  15928. track = this.tracks[trackId],
  15929. duration = newDetails.totalduration,
  15930. sliding = 0;
  15931. _logger.logger.log('track ' + trackId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration);
  15932. if (newDetails.live) {
  15933. var curDetails = track.details;
  15934. if (curDetails && newDetails.fragments.length > 0) {
  15935. // we already have details for that level, merge them
  15936. LevelHelper.mergeDetails(curDetails, newDetails);
  15937. sliding = newDetails.fragments[0].start;
  15938. // TODO
  15939. // this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
  15940. if (newDetails.PTSKnown) {
  15941. _logger.logger.log('live audio playlist sliding:' + sliding.toFixed(3));
  15942. } else {
  15943. _logger.logger.log('live audio playlist - outdated PTS, unknown sliding');
  15944. }
  15945. } else {
  15946. newDetails.PTSKnown = false;
  15947. _logger.logger.log('live audio playlist - first load, unknown sliding');
  15948. }
  15949. } else {
  15950. newDetails.PTSKnown = false;
  15951. }
  15952. track.details = newDetails;
  15953. // compute start position
  15954. if (!this.startFragRequested) {
  15955. // compute start position if set to -1. use it straight away if value is defined
  15956. if (this.startPosition === -1) {
  15957. // first, check if start time offset has been set in playlist, if yes, use this value
  15958. var startTimeOffset = newDetails.startTimeOffset;
  15959. if (Number.isFinite(startTimeOffset)) {
  15960. _logger.logger.log('start time offset found in playlist, adjust startPosition to ' + startTimeOffset);
  15961. this.startPosition = startTimeOffset;
  15962. } else {
  15963. this.startPosition = 0;
  15964. }
  15965. }
  15966. this.nextLoadPosition = this.startPosition;
  15967. }
  15968. // only switch batck to IDLE state if we were waiting for track to start downloading a new fragment
  15969. if (this.state === _baseStreamController.State.WAITING_TRACK) {
  15970. this.state = _baseStreamController.State.IDLE;
  15971. }
  15972. // trigger handler right now
  15973. this.tick();
  15974. }
  15975. }, {
  15976. key: 'onKeyLoaded',
  15977. value: function onKeyLoaded() {
  15978. if (this.state === _baseStreamController.State.KEY_LOADING) {
  15979. this.state = _baseStreamController.State.IDLE;
  15980. this.tick();
  15981. }
  15982. }
  15983. }, {
  15984. key: 'onFragLoaded',
  15985. value: function onFragLoaded(data) {
  15986. var fragCurrent = this.fragCurrent,
  15987. fragLoaded = data.frag;
  15988. if (this.state === _baseStreamController.State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'audio' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
  15989. var track = this.tracks[this.trackId],
  15990. details = track.details,
  15991. duration = details.totalduration,
  15992. trackId = fragCurrent.level,
  15993. sn = fragCurrent.sn,
  15994. cc = fragCurrent.cc,
  15995. audioCodec = this.config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2',
  15996. stats = this.stats = data.stats;
  15997. if (sn === 'initSegment') {
  15998. this.state = _baseStreamController.State.IDLE;
  15999. stats.tparsed = stats.tbuffered = performance.now();
  16000. details.initSegment.data = data.payload;
  16001. this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'audio' });
  16002. this.tick();
  16003. } else {
  16004. this.state = _baseStreamController.State.PARSING;
  16005. // transmux the MPEG-TS data to ISO-BMFF segments
  16006. this.appended = false;
  16007. if (!this.demuxer) {
  16008. this.demuxer = new _demuxer2.default(this.hls, 'audio');
  16009. }
  16010. // Check if we have video initPTS
  16011. // If not we need to wait for it
  16012. var initPTS = this.initPTS[cc];
  16013. var initSegmentData = details.initSegment ? details.initSegment.data : [];
  16014. if (details.initSegment || initPTS !== undefined) {
  16015. this.pendingBuffering = true;
  16016. _logger.logger.log('Demuxing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],track ' + trackId);
  16017. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  16018. var accurateTimeOffset = false; // details.PTSKnown || !details.live;
  16019. this.demuxer.push(data.payload, initSegmentData, audioCodec, null, fragCurrent, duration, accurateTimeOffset, initPTS);
  16020. } else {
  16021. _logger.logger.log('unknown video PTS for continuity counter ' + cc + ', waiting for video PTS before demuxing audio frag ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],track ' + trackId);
  16022. this.waitingFragment = data;
  16023. this.state = _baseStreamController.State.WAITING_INIT_PTS;
  16024. }
  16025. }
  16026. }
  16027. this.fragLoadError = 0;
  16028. }
  16029. }, {
  16030. key: 'onFragParsingInitSegment',
  16031. value: function onFragParsingInitSegment(data) {
  16032. var fragCurrent = this.fragCurrent;
  16033. var fragNew = data.frag;
  16034. if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === _baseStreamController.State.PARSING) {
  16035. var tracks = data.tracks,
  16036. track = void 0;
  16037. // delete any video track found on audio demuxer
  16038. if (tracks.video) {
  16039. delete tracks.video;
  16040. }
  16041. // include levelCodec in audio and video tracks
  16042. track = tracks.audio;
  16043. if (track) {
  16044. track.levelCodec = track.codec;
  16045. track.id = data.id;
  16046. this.hls.trigger(_events2.default.BUFFER_CODECS, tracks);
  16047. _logger.logger.log('audio track:audio,container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']');
  16048. var initSegment = track.initSegment;
  16049. if (initSegment) {
  16050. var appendObj = { type: 'audio', data: initSegment, parent: 'audio', content: 'initSegment' };
  16051. if (this.audioSwitch) {
  16052. this.pendingData = [appendObj];
  16053. } else {
  16054. this.appended = true;
  16055. // arm pending Buffering flag before appending a segment
  16056. this.pendingBuffering = true;
  16057. this.hls.trigger(_events2.default.BUFFER_APPENDING, appendObj);
  16058. }
  16059. }
  16060. // trigger handler right now
  16061. this.tick();
  16062. }
  16063. }
  16064. }
  16065. }, {
  16066. key: 'onFragParsingData',
  16067. value: function onFragParsingData(data) {
  16068. var _this2 = this;
  16069. var fragCurrent = this.fragCurrent;
  16070. var fragNew = data.frag;
  16071. if (fragCurrent && data.id === 'audio' && data.type === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === _baseStreamController.State.PARSING) {
  16072. var trackId = this.trackId,
  16073. track = this.tracks[trackId],
  16074. hls = this.hls;
  16075. if (!Number.isFinite(data.endPTS)) {
  16076. data.endPTS = data.startPTS + fragCurrent.duration;
  16077. data.endDTS = data.startDTS + fragCurrent.duration;
  16078. }
  16079. fragCurrent.addElementaryStream(_fragment2.default.ElementaryStreamTypes.AUDIO);
  16080. _logger.logger.log('parsed ' + data.type + ',PTS:[' + data.startPTS.toFixed(3) + ',' + data.endPTS.toFixed(3) + '],DTS:[' + data.startDTS.toFixed(3) + '/' + data.endDTS.toFixed(3) + '],nb:' + data.nb);
  16081. LevelHelper.updateFragPTSDTS(track.details, fragCurrent, data.startPTS, data.endPTS);
  16082. var audioSwitch = this.audioSwitch,
  16083. media = this.media,
  16084. appendOnBufferFlush = false;
  16085. // Only flush audio from old audio tracks when PTS is known on new audio track
  16086. if (audioSwitch && media) {
  16087. if (media.readyState) {
  16088. var currentTime = media.currentTime;
  16089. _logger.logger.log('switching audio track : currentTime:' + currentTime);
  16090. if (currentTime >= data.startPTS) {
  16091. _logger.logger.log('switching audio track : flushing all audio');
  16092. this.state = _baseStreamController.State.BUFFER_FLUSHING;
  16093. hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
  16094. appendOnBufferFlush = true;
  16095. // Lets announce that the initial audio track switch flush occur
  16096. this.audioSwitch = false;
  16097. hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: trackId });
  16098. }
  16099. } else {
  16100. // Lets announce that the initial audio track switch flush occur
  16101. this.audioSwitch = false;
  16102. hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: trackId });
  16103. }
  16104. }
  16105. var pendingData = this.pendingData;
  16106. if (!pendingData) {
  16107. _logger.logger.warn('Apparently attempt to enqueue media payload without codec initialization data upfront');
  16108. hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: null, fatal: true });
  16109. return;
  16110. }
  16111. if (!this.audioSwitch) {
  16112. [data.data1, data.data2].forEach(function (buffer) {
  16113. if (buffer && buffer.length) {
  16114. pendingData.push({ type: data.type, data: buffer, parent: 'audio', content: 'data' });
  16115. }
  16116. });
  16117. if (!appendOnBufferFlush && pendingData.length) {
  16118. pendingData.forEach(function (appendObj) {
  16119. // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
  16120. // in that case it is useless to append following segments
  16121. if (_this2.state === _baseStreamController.State.PARSING) {
  16122. // arm pending Buffering flag before appending a segment
  16123. _this2.pendingBuffering = true;
  16124. _this2.hls.trigger(_events2.default.BUFFER_APPENDING, appendObj);
  16125. }
  16126. });
  16127. this.pendingData = [];
  16128. this.appended = true;
  16129. }
  16130. }
  16131. // trigger handler right now
  16132. this.tick();
  16133. }
  16134. }
  16135. }, {
  16136. key: 'onFragParsed',
  16137. value: function onFragParsed(data) {
  16138. var fragCurrent = this.fragCurrent;
  16139. var fragNew = data.frag;
  16140. if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === _baseStreamController.State.PARSING) {
  16141. this.stats.tparsed = performance.now();
  16142. this.state = _baseStreamController.State.PARSED;
  16143. this._checkAppendedParsed();
  16144. }
  16145. }
  16146. }, {
  16147. key: 'onBufferReset',
  16148. value: function onBufferReset() {
  16149. // reset reference to sourcebuffers
  16150. this.mediaBuffer = this.videoBuffer = null;
  16151. this.loadedmetadata = false;
  16152. }
  16153. }, {
  16154. key: 'onBufferCreated',
  16155. value: function onBufferCreated(data) {
  16156. var audioTrack = data.tracks.audio;
  16157. if (audioTrack) {
  16158. this.mediaBuffer = audioTrack.buffer;
  16159. this.loadedmetadata = true;
  16160. }
  16161. if (data.tracks.video) {
  16162. this.videoBuffer = data.tracks.video.buffer;
  16163. }
  16164. }
  16165. }, {
  16166. key: 'onBufferAppended',
  16167. value: function onBufferAppended(data) {
  16168. if (data.parent === 'audio') {
  16169. var state = this.state;
  16170. if (state === _baseStreamController.State.PARSING || state === _baseStreamController.State.PARSED) {
  16171. // check if all buffers have been appended
  16172. this.pendingBuffering = data.pending > 0;
  16173. this._checkAppendedParsed();
  16174. }
  16175. }
  16176. }
  16177. }, {
  16178. key: '_checkAppendedParsed',
  16179. value: function _checkAppendedParsed() {
  16180. // trigger handler right now
  16181. if (this.state === _baseStreamController.State.PARSED && (!this.appended || !this.pendingBuffering)) {
  16182. var frag = this.fragCurrent,
  16183. stats = this.stats,
  16184. hls = this.hls;
  16185. if (frag) {
  16186. this.fragPrevious = frag;
  16187. stats.tbuffered = performance.now();
  16188. hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'audio' });
  16189. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  16190. _logger.logger.log('audio buffered : ' + _timeRanges2.default.toString(media.buffered));
  16191. if (this.audioSwitch && this.appended) {
  16192. this.audioSwitch = false;
  16193. hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: this.trackId });
  16194. }
  16195. this.state = _baseStreamController.State.IDLE;
  16196. }
  16197. this.tick();
  16198. }
  16199. }
  16200. }, {
  16201. key: 'onError',
  16202. value: function onError(data) {
  16203. var frag = data.frag;
  16204. // don't handle frag error not related to audio fragment
  16205. if (frag && frag.type !== 'audio') {
  16206. return;
  16207. }
  16208. switch (data.details) {
  16209. case _errors.ErrorDetails.FRAG_LOAD_ERROR:
  16210. case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
  16211. var _frag = data.frag;
  16212. // don't handle frag error not related to audio fragment
  16213. if (_frag && _frag.type !== 'audio') {
  16214. break;
  16215. }
  16216. if (!data.fatal) {
  16217. var loadError = this.fragLoadError;
  16218. if (loadError) {
  16219. loadError++;
  16220. } else {
  16221. loadError = 1;
  16222. }
  16223. var config = this.config;
  16224. if (loadError <= config.fragLoadingMaxRetry) {
  16225. this.fragLoadError = loadError;
  16226. // exponential backoff capped to config.fragLoadingMaxRetryTimeout
  16227. var delay = Math.min(Math.pow(2, loadError - 1) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);
  16228. _logger.logger.warn('AudioStreamController: frag loading failed, retry in ' + delay + ' ms');
  16229. this.retryDate = performance.now() + delay;
  16230. // retry loading state
  16231. this.state = _baseStreamController.State.FRAG_LOADING_WAITING_RETRY;
  16232. } else {
  16233. _logger.logger.error('AudioStreamController: ' + data.details + ' reaches max retry, redispatch as fatal ...');
  16234. // switch error to fatal
  16235. data.fatal = true;
  16236. this.state = _baseStreamController.State.ERROR;
  16237. }
  16238. }
  16239. break;
  16240. case _errors.ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  16241. case _errors.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  16242. case _errors.ErrorDetails.KEY_LOAD_ERROR:
  16243. case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
  16244. // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received
  16245. if (this.state !== _baseStreamController.State.ERROR) {
  16246. // if fatal error, stop processing, otherwise move to IDLE to retry loading
  16247. this.state = data.fatal ? _baseStreamController.State.ERROR : _baseStreamController.State.IDLE;
  16248. _logger.logger.warn('AudioStreamController: ' + data.details + ' while loading frag, now switching to ' + this.state + ' state ...');
  16249. }
  16250. break;
  16251. case _errors.ErrorDetails.BUFFER_FULL_ERROR:
  16252. // if in appending state
  16253. if (data.parent === 'audio' && (this.state === _baseStreamController.State.PARSING || this.state === _baseStreamController.State.PARSED)) {
  16254. var media = this.mediaBuffer,
  16255. currentTime = this.media.currentTime,
  16256. mediaBuffered = media && _bufferHelper.BufferHelper.isBuffered(media, currentTime) && _bufferHelper.BufferHelper.isBuffered(media, currentTime + 0.5);
  16257. // reduce max buf len if current position is buffered
  16258. if (mediaBuffered) {
  16259. var _config = this.config;
  16260. if (_config.maxMaxBufferLength >= _config.maxBufferLength) {
  16261. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  16262. _config.maxMaxBufferLength /= 2;
  16263. _logger.logger.warn('AudioStreamController: reduce max buffer length to ' + _config.maxMaxBufferLength + 's');
  16264. }
  16265. this.state = _baseStreamController.State.IDLE;
  16266. } else {
  16267. // current position is not buffered, but browser is still complaining about buffer full error
  16268. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  16269. // in that case flush the whole audio buffer to recover
  16270. _logger.logger.warn('AudioStreamController: buffer full error also media.currentTime is not buffered, flush audio buffer');
  16271. this.fragCurrent = null;
  16272. // flush everything
  16273. this.state = _baseStreamController.State.BUFFER_FLUSHING;
  16274. this.hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
  16275. }
  16276. }
  16277. break;
  16278. default:
  16279. break;
  16280. }
  16281. }
  16282. }, {
  16283. key: 'onBufferFlushed',
  16284. value: function onBufferFlushed() {
  16285. var _this3 = this;
  16286. var pendingData = this.pendingData;
  16287. if (pendingData && pendingData.length) {
  16288. _logger.logger.log('AudioStreamController: appending pending audio data after buffer flushed');
  16289. pendingData.forEach(function (appendObj) {
  16290. _this3.hls.trigger(_events2.default.BUFFER_APPENDING, appendObj);
  16291. });
  16292. this.appended = true;
  16293. this.pendingData = [];
  16294. this.state = _baseStreamController.State.PARSED;
  16295. } else {
  16296. // move to IDLE once flush complete. this should trigger new fragment loading
  16297. this.state = _baseStreamController.State.IDLE;
  16298. // reset reference to frag
  16299. this.fragPrevious = null;
  16300. this.tick();
  16301. }
  16302. }
  16303. }, {
  16304. key: 'state',
  16305. set: function set(nextState) {
  16306. if (this.state !== nextState) {
  16307. var previousState = this.state;
  16308. this._state = nextState;
  16309. _logger.logger.log('audio stream:' + previousState + '->' + nextState);
  16310. }
  16311. },
  16312. get: function get() {
  16313. return this._state;
  16314. }
  16315. }]);
  16316. return AudioStreamController;
  16317. }(_baseStreamController2.default);
  16318. exports.default = AudioStreamController;
  16319. module.exports = exports['default'];
  16320. /***/ }),
  16321. /* 70 */
  16322. /***/ (function(module, exports, __webpack_require__) {
  16323. "use strict";
  16324. Object.defineProperty(exports, "__esModule", {
  16325. value: true
  16326. });
  16327. exports.newCue = newCue;
  16328. var _vttparser = __webpack_require__(30);
  16329. function newCue(track, startTime, endTime, captionScreen) {
  16330. var row = void 0;
  16331. var cue = void 0;
  16332. var indenting = void 0;
  16333. var indent = void 0;
  16334. var text = void 0;
  16335. var VTTCue = window.VTTCue || window.TextTrackCue;
  16336. for (var r = 0; r < captionScreen.rows.length; r++) {
  16337. row = captionScreen.rows[r];
  16338. indenting = true;
  16339. indent = 0;
  16340. text = '';
  16341. if (!row.isEmpty()) {
  16342. for (var c = 0; c < row.chars.length; c++) {
  16343. if (row.chars[c].uchar.match(/\s/) && indenting) {
  16344. indent++;
  16345. } else {
  16346. text += row.chars[c].uchar;
  16347. indenting = false;
  16348. }
  16349. }
  16350. // To be used for cleaning-up orphaned roll-up captions
  16351. row.cueStartTime = startTime;
  16352. // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
  16353. if (startTime === endTime) {
  16354. endTime += 0.0001;
  16355. }
  16356. cue = new VTTCue(startTime, endTime, (0, _vttparser.fixLineBreaks)(text.trim()));
  16357. if (indent >= 16) {
  16358. indent--;
  16359. } else {
  16360. indent++;
  16361. }
  16362. // VTTCue.line get's flakey when using controls, so let's now include line 13&14
  16363. // also, drop line 1 since it's to close to the top
  16364. if (navigator.userAgent.match(/Firefox\//)) {
  16365. cue.line = r + 1;
  16366. } else {
  16367. cue.line = r > 7 ? r - 2 : r + 1;
  16368. }
  16369. cue.align = 'left';
  16370. // Clamp the position between 0 and 100 - if out of these bounds, Firefox throws an exception and captions break
  16371. cue.position = Math.max(0, Math.min(100, 100 * (indent / 32) + (navigator.userAgent.match(/Firefox\//) ? 50 : 0)));
  16372. track.addCue(cue);
  16373. }
  16374. }
  16375. }
  16376. /***/ }),
  16377. /* 71 */
  16378. /***/ (function(module, exports, __webpack_require__) {
  16379. "use strict";
  16380. Object.defineProperty(exports, "__esModule", {
  16381. value: true
  16382. });
  16383. /**
  16384. * Copyright 2013 vtt.js Contributors
  16385. *
  16386. * Licensed under the Apache License, Version 2.0 (the "License");
  16387. * you may not use this file except in compliance with the License.
  16388. * You may obtain a copy of the License at
  16389. *
  16390. * http://www.apache.org/licenses/LICENSE-2.0
  16391. *
  16392. * Unless required by applicable law or agreed to in writing, software
  16393. * distributed under the License is distributed on an "AS IS" BASIS,
  16394. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16395. * See the License for the specific language governing permissions and
  16396. * limitations under the License.
  16397. */
  16398. exports.default = function () {
  16399. if (typeof window !== 'undefined' && window.VTTCue) {
  16400. return window.VTTCue;
  16401. }
  16402. var autoKeyword = 'auto';
  16403. var directionSetting = {
  16404. '': true,
  16405. lr: true,
  16406. rl: true
  16407. };
  16408. var alignSetting = {
  16409. start: true,
  16410. middle: true,
  16411. end: true,
  16412. left: true,
  16413. right: true
  16414. };
  16415. function findDirectionSetting(value) {
  16416. if (typeof value !== 'string') {
  16417. return false;
  16418. }
  16419. var dir = directionSetting[value.toLowerCase()];
  16420. return dir ? value.toLowerCase() : false;
  16421. }
  16422. function findAlignSetting(value) {
  16423. if (typeof value !== 'string') {
  16424. return false;
  16425. }
  16426. var align = alignSetting[value.toLowerCase()];
  16427. return align ? value.toLowerCase() : false;
  16428. }
  16429. function extend(obj) {
  16430. var i = 1;
  16431. for (; i < arguments.length; i++) {
  16432. var cobj = arguments[i];
  16433. for (var p in cobj) {
  16434. obj[p] = cobj[p];
  16435. }
  16436. }
  16437. return obj;
  16438. }
  16439. function VTTCue(startTime, endTime, text) {
  16440. var cue = this;
  16441. var isIE8 = function () {
  16442. if (typeof navigator === 'undefined') {
  16443. return;
  16444. }
  16445. return (/MSIE\s8\.0/.test(navigator.userAgent)
  16446. );
  16447. }();
  16448. var baseObj = {};
  16449. if (isIE8) {
  16450. cue = document.createElement('custom');
  16451. } else {
  16452. baseObj.enumerable = true;
  16453. }
  16454. /**
  16455. * Shim implementation specific properties. These properties are not in
  16456. * the spec.
  16457. */
  16458. // Lets us know when the VTTCue's data has changed in such a way that we need
  16459. // to recompute its display state. This lets us compute its display state
  16460. // lazily.
  16461. cue.hasBeenReset = false;
  16462. /**
  16463. * VTTCue and TextTrackCue properties
  16464. * http://dev.w3.org/html5/webvtt/#vttcue-interface
  16465. */
  16466. var _id = '';
  16467. var _pauseOnExit = false;
  16468. var _startTime = startTime;
  16469. var _endTime = endTime;
  16470. var _text = text;
  16471. var _region = null;
  16472. var _vertical = '';
  16473. var _snapToLines = true;
  16474. var _line = 'auto';
  16475. var _lineAlign = 'start';
  16476. var _position = 50;
  16477. var _positionAlign = 'middle';
  16478. var _size = 50;
  16479. var _align = 'middle';
  16480. Object.defineProperty(cue, 'id', extend({}, baseObj, {
  16481. get: function get() {
  16482. return _id;
  16483. },
  16484. set: function set(value) {
  16485. _id = '' + value;
  16486. }
  16487. }));
  16488. Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {
  16489. get: function get() {
  16490. return _pauseOnExit;
  16491. },
  16492. set: function set(value) {
  16493. _pauseOnExit = !!value;
  16494. }
  16495. }));
  16496. Object.defineProperty(cue, 'startTime', extend({}, baseObj, {
  16497. get: function get() {
  16498. return _startTime;
  16499. },
  16500. set: function set(value) {
  16501. if (typeof value !== 'number') {
  16502. throw new TypeError('Start time must be set to a number.');
  16503. }
  16504. _startTime = value;
  16505. this.hasBeenReset = true;
  16506. }
  16507. }));
  16508. Object.defineProperty(cue, 'endTime', extend({}, baseObj, {
  16509. get: function get() {
  16510. return _endTime;
  16511. },
  16512. set: function set(value) {
  16513. if (typeof value !== 'number') {
  16514. throw new TypeError('End time must be set to a number.');
  16515. }
  16516. _endTime = value;
  16517. this.hasBeenReset = true;
  16518. }
  16519. }));
  16520. Object.defineProperty(cue, 'text', extend({}, baseObj, {
  16521. get: function get() {
  16522. return _text;
  16523. },
  16524. set: function set(value) {
  16525. _text = '' + value;
  16526. this.hasBeenReset = true;
  16527. }
  16528. }));
  16529. Object.defineProperty(cue, 'region', extend({}, baseObj, {
  16530. get: function get() {
  16531. return _region;
  16532. },
  16533. set: function set(value) {
  16534. _region = value;
  16535. this.hasBeenReset = true;
  16536. }
  16537. }));
  16538. Object.defineProperty(cue, 'vertical', extend({}, baseObj, {
  16539. get: function get() {
  16540. return _vertical;
  16541. },
  16542. set: function set(value) {
  16543. var setting = findDirectionSetting(value);
  16544. // Have to check for false because the setting an be an empty string.
  16545. if (setting === false) {
  16546. throw new SyntaxError('An invalid or illegal string was specified.');
  16547. }
  16548. _vertical = setting;
  16549. this.hasBeenReset = true;
  16550. }
  16551. }));
  16552. Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {
  16553. get: function get() {
  16554. return _snapToLines;
  16555. },
  16556. set: function set(value) {
  16557. _snapToLines = !!value;
  16558. this.hasBeenReset = true;
  16559. }
  16560. }));
  16561. Object.defineProperty(cue, 'line', extend({}, baseObj, {
  16562. get: function get() {
  16563. return _line;
  16564. },
  16565. set: function set(value) {
  16566. if (typeof value !== 'number' && value !== autoKeyword) {
  16567. throw new SyntaxError('An invalid number or illegal string was specified.');
  16568. }
  16569. _line = value;
  16570. this.hasBeenReset = true;
  16571. }
  16572. }));
  16573. Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {
  16574. get: function get() {
  16575. return _lineAlign;
  16576. },
  16577. set: function set(value) {
  16578. var setting = findAlignSetting(value);
  16579. if (!setting) {
  16580. throw new SyntaxError('An invalid or illegal string was specified.');
  16581. }
  16582. _lineAlign = setting;
  16583. this.hasBeenReset = true;
  16584. }
  16585. }));
  16586. Object.defineProperty(cue, 'position', extend({}, baseObj, {
  16587. get: function get() {
  16588. return _position;
  16589. },
  16590. set: function set(value) {
  16591. if (value < 0 || value > 100) {
  16592. throw new Error('Position must be between 0 and 100.');
  16593. }
  16594. _position = value;
  16595. this.hasBeenReset = true;
  16596. }
  16597. }));
  16598. Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {
  16599. get: function get() {
  16600. return _positionAlign;
  16601. },
  16602. set: function set(value) {
  16603. var setting = findAlignSetting(value);
  16604. if (!setting) {
  16605. throw new SyntaxError('An invalid or illegal string was specified.');
  16606. }
  16607. _positionAlign = setting;
  16608. this.hasBeenReset = true;
  16609. }
  16610. }));
  16611. Object.defineProperty(cue, 'size', extend({}, baseObj, {
  16612. get: function get() {
  16613. return _size;
  16614. },
  16615. set: function set(value) {
  16616. if (value < 0 || value > 100) {
  16617. throw new Error('Size must be between 0 and 100.');
  16618. }
  16619. _size = value;
  16620. this.hasBeenReset = true;
  16621. }
  16622. }));
  16623. Object.defineProperty(cue, 'align', extend({}, baseObj, {
  16624. get: function get() {
  16625. return _align;
  16626. },
  16627. set: function set(value) {
  16628. var setting = findAlignSetting(value);
  16629. if (!setting) {
  16630. throw new SyntaxError('An invalid or illegal string was specified.');
  16631. }
  16632. _align = setting;
  16633. this.hasBeenReset = true;
  16634. }
  16635. }));
  16636. /**
  16637. * Other <track> spec defined properties
  16638. */
  16639. // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
  16640. cue.displayState = undefined;
  16641. if (isIE8) {
  16642. return cue;
  16643. }
  16644. }
  16645. /**
  16646. * VTTCue methods
  16647. */
  16648. VTTCue.prototype.getCueAsHTML = function () {
  16649. // Assume WebVTT.convertCueToDOMTree is on the global.
  16650. var WebVTT = window.WebVTT;
  16651. return WebVTT.convertCueToDOMTree(window, this.text);
  16652. };
  16653. return VTTCue;
  16654. }();
  16655. module.exports = exports['default'];
  16656. /***/ }),
  16657. /* 72 */
  16658. /***/ (function(module, exports, __webpack_require__) {
  16659. "use strict";
  16660. Object.defineProperty(exports, "__esModule", {
  16661. value: true
  16662. });
  16663. 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; }; }();
  16664. var _events = __webpack_require__(1);
  16665. var _events2 = _interopRequireDefault(_events);
  16666. var _eventHandler = __webpack_require__(3);
  16667. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  16668. var _cea608Parser = __webpack_require__(73);
  16669. var _cea608Parser2 = _interopRequireDefault(_cea608Parser);
  16670. var _outputFilter = __webpack_require__(74);
  16671. var _outputFilter2 = _interopRequireDefault(_outputFilter);
  16672. var _webvttParser = __webpack_require__(75);
  16673. var _webvttParser2 = _interopRequireDefault(_webvttParser);
  16674. var _logger = __webpack_require__(0);
  16675. var _texttrackUtils = __webpack_require__(29);
  16676. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  16677. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  16678. 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; }
  16679. 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; } /*
  16680. * Timeline Controller
  16681. */
  16682. function canReuseVttTextTrack(inUseTrack, manifestTrack) {
  16683. return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);
  16684. }
  16685. function intersection(x1, x2, y1, y2) {
  16686. return Math.min(x2, y2) - Math.max(x1, y1);
  16687. }
  16688. var TimelineController = function (_EventHandler) {
  16689. _inherits(TimelineController, _EventHandler);
  16690. function TimelineController(hls) {
  16691. _classCallCheck(this, TimelineController);
  16692. var _this = _possibleConstructorReturn(this, (TimelineController.__proto__ || Object.getPrototypeOf(TimelineController)).call(this, hls, _events2.default.MEDIA_ATTACHING, _events2.default.MEDIA_DETACHING, _events2.default.FRAG_PARSING_USERDATA, _events2.default.FRAG_DECRYPTED, _events2.default.MANIFEST_LOADING, _events2.default.MANIFEST_LOADED, _events2.default.FRAG_LOADED, _events2.default.LEVEL_SWITCHING, _events2.default.INIT_PTS_FOUND));
  16693. _this.hls = hls;
  16694. _this.config = hls.config;
  16695. _this.enabled = true;
  16696. _this.Cues = hls.config.cueHandler;
  16697. _this.textTracks = [];
  16698. _this.tracks = [];
  16699. _this.unparsedVttFrags = [];
  16700. _this.initPTS = [];
  16701. _this.cueRanges = [];
  16702. _this.captionsTracks = {};
  16703. _this.captionsProperties = {
  16704. textTrack1: {
  16705. label: _this.config.captionsTextTrack1Label,
  16706. languageCode: _this.config.captionsTextTrack1LanguageCode
  16707. },
  16708. textTrack2: {
  16709. label: _this.config.captionsTextTrack2Label,
  16710. languageCode: _this.config.captionsTextTrack2LanguageCode
  16711. }
  16712. };
  16713. if (_this.config.enableCEA708Captions) {
  16714. var channel1 = new _outputFilter2.default(_this, 'textTrack1');
  16715. var channel2 = new _outputFilter2.default(_this, 'textTrack2');
  16716. _this.cea608Parser = new _cea608Parser2.default(0, channel1, channel2);
  16717. }
  16718. return _this;
  16719. }
  16720. _createClass(TimelineController, [{
  16721. key: 'addCues',
  16722. value: function addCues(trackName, startTime, endTime, screen) {
  16723. // skip cues which overlap more than 50% with previously parsed time ranges
  16724. var ranges = this.cueRanges;
  16725. var merged = false;
  16726. for (var i = ranges.length; i--;) {
  16727. var cueRange = ranges[i];
  16728. var overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
  16729. if (overlap >= 0) {
  16730. cueRange[0] = Math.min(cueRange[0], startTime);
  16731. cueRange[1] = Math.max(cueRange[1], endTime);
  16732. merged = true;
  16733. if (overlap / (endTime - startTime) > 0.5) {
  16734. return;
  16735. }
  16736. }
  16737. }
  16738. if (!merged) {
  16739. ranges.push([startTime, endTime]);
  16740. }
  16741. this.Cues.newCue(this.captionsTracks[trackName], startTime, endTime, screen);
  16742. }
  16743. // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
  16744. }, {
  16745. key: 'onInitPtsFound',
  16746. value: function onInitPtsFound(data) {
  16747. var _this2 = this;
  16748. if (data.id === 'main') {
  16749. this.initPTS[data.frag.cc] = data.initPTS;
  16750. }
  16751. // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.
  16752. // Parse any unparsed fragments upon receiving the initial PTS.
  16753. if (this.unparsedVttFrags.length) {
  16754. var unparsedVttFrags = this.unparsedVttFrags;
  16755. this.unparsedVttFrags = [];
  16756. unparsedVttFrags.forEach(function (frag) {
  16757. _this2.onFragLoaded(frag);
  16758. });
  16759. }
  16760. }
  16761. }, {
  16762. key: 'getExistingTrack',
  16763. value: function getExistingTrack(trackName) {
  16764. var media = this.media;
  16765. if (media) {
  16766. for (var i = 0; i < media.textTracks.length; i++) {
  16767. var textTrack = media.textTracks[i];
  16768. if (textTrack[trackName]) {
  16769. return textTrack;
  16770. }
  16771. }
  16772. }
  16773. return null;
  16774. }
  16775. }, {
  16776. key: 'createCaptionsTrack',
  16777. value: function createCaptionsTrack(trackName) {
  16778. var _captionsProperties$t = this.captionsProperties[trackName],
  16779. label = _captionsProperties$t.label,
  16780. languageCode = _captionsProperties$t.languageCode;
  16781. var captionsTracks = this.captionsTracks;
  16782. if (!captionsTracks[trackName]) {
  16783. // Enable reuse of existing text track.
  16784. var existingTrack = this.getExistingTrack(trackName);
  16785. if (!existingTrack) {
  16786. var textTrack = this.createTextTrack('captions', label, languageCode);
  16787. if (textTrack) {
  16788. // Set a special property on the track so we know it's managed by Hls.js
  16789. textTrack[trackName] = true;
  16790. captionsTracks[trackName] = textTrack;
  16791. }
  16792. } else {
  16793. captionsTracks[trackName] = existingTrack;
  16794. (0, _texttrackUtils.clearCurrentCues)(captionsTracks[trackName]);
  16795. (0, _texttrackUtils.sendAddTrackEvent)(captionsTracks[trackName], this.media);
  16796. }
  16797. }
  16798. }
  16799. }, {
  16800. key: 'createTextTrack',
  16801. value: function createTextTrack(kind, label, lang) {
  16802. var media = this.media;
  16803. if (media) {
  16804. return media.addTextTrack(kind, label, lang);
  16805. }
  16806. }
  16807. }, {
  16808. key: 'destroy',
  16809. value: function destroy() {
  16810. _eventHandler2.default.prototype.destroy.call(this);
  16811. }
  16812. }, {
  16813. key: 'onMediaAttaching',
  16814. value: function onMediaAttaching(data) {
  16815. this.media = data.media;
  16816. this._cleanTracks();
  16817. }
  16818. }, {
  16819. key: 'onMediaDetaching',
  16820. value: function onMediaDetaching() {
  16821. var captionsTracks = this.captionsTracks;
  16822. Object.keys(captionsTracks).forEach(function (trackName) {
  16823. (0, _texttrackUtils.clearCurrentCues)(captionsTracks[trackName]);
  16824. delete captionsTracks[trackName];
  16825. });
  16826. }
  16827. }, {
  16828. key: 'onManifestLoading',
  16829. value: function onManifestLoading() {
  16830. this.lastSn = -1; // Detect discontiguity in fragment parsing
  16831. this.prevCC = -1;
  16832. this.vttCCs = { // Detect discontinuity in subtitle manifests
  16833. ccOffset: 0,
  16834. presentationOffset: 0,
  16835. 0: {
  16836. start: 0, prevCC: -1, new: false
  16837. }
  16838. };
  16839. this._cleanTracks();
  16840. }
  16841. }, {
  16842. key: '_cleanTracks',
  16843. value: function _cleanTracks() {
  16844. // clear outdated subtitles
  16845. var media = this.media;
  16846. if (media) {
  16847. var textTracks = media.textTracks;
  16848. if (textTracks) {
  16849. for (var i = 0; i < textTracks.length; i++) {
  16850. (0, _texttrackUtils.clearCurrentCues)(textTracks[i]);
  16851. }
  16852. }
  16853. }
  16854. }
  16855. }, {
  16856. key: 'onManifestLoaded',
  16857. value: function onManifestLoaded(data) {
  16858. var _this3 = this;
  16859. this.textTracks = [];
  16860. this.unparsedVttFrags = this.unparsedVttFrags || [];
  16861. this.initPTS = [];
  16862. this.cueRanges = [];
  16863. if (this.config.enableWebVTT) {
  16864. this.tracks = data.subtitles || [];
  16865. var inUseTracks = this.media ? this.media.textTracks : [];
  16866. this.tracks.forEach(function (track, index) {
  16867. var textTrack = void 0;
  16868. if (index < inUseTracks.length) {
  16869. var inUseTrack = null;
  16870. for (var i = 0; i < inUseTracks.length; i++) {
  16871. if (canReuseVttTextTrack(inUseTracks[i], track)) {
  16872. inUseTrack = inUseTracks[i];
  16873. break;
  16874. }
  16875. }
  16876. // Reuse tracks with the same label, but do not reuse 608/708 tracks
  16877. if (inUseTrack) {
  16878. textTrack = inUseTrack;
  16879. }
  16880. }
  16881. if (!textTrack) {
  16882. textTrack = _this3.createTextTrack('subtitles', track.name, track.lang);
  16883. }
  16884. if (track.default) {
  16885. textTrack.mode = _this3.hls.subtitleDisplay ? 'showing' : 'hidden';
  16886. } else {
  16887. textTrack.mode = 'disabled';
  16888. }
  16889. _this3.textTracks.push(textTrack);
  16890. });
  16891. }
  16892. }
  16893. }, {
  16894. key: 'onLevelSwitching',
  16895. value: function onLevelSwitching() {
  16896. this.enabled = this.hls.currentLevel.closedCaptions !== 'NONE';
  16897. }
  16898. }, {
  16899. key: 'onFragLoaded',
  16900. value: function onFragLoaded(data) {
  16901. var frag = data.frag,
  16902. payload = data.payload;
  16903. if (frag.type === 'main') {
  16904. var sn = frag.sn;
  16905. // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
  16906. if (sn !== this.lastSn + 1) {
  16907. var cea608Parser = this.cea608Parser;
  16908. if (cea608Parser) {
  16909. cea608Parser.reset();
  16910. }
  16911. }
  16912. this.lastSn = sn;
  16913. } // eslint-disable-line brace-style
  16914. // If fragment is subtitle type, parse as WebVTT.
  16915. else if (frag.type === 'subtitle') {
  16916. if (payload.byteLength) {
  16917. // We need an initial synchronisation PTS. Store fragments as long as none has arrived.
  16918. if (!Number.isFinite(this.initPTS[frag.cc])) {
  16919. this.unparsedVttFrags.push(data);
  16920. if (this.initPTS.length) {
  16921. // finish unsuccessfully, otherwise the subtitle-stream-controller could be blocked from loading new frags.
  16922. this.hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  16923. }
  16924. return;
  16925. }
  16926. var decryptData = frag.decryptdata;
  16927. // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.
  16928. if (decryptData == null || decryptData.key == null || decryptData.method !== 'AES-128') {
  16929. this._parseVTTs(frag, payload);
  16930. }
  16931. } else {
  16932. // In case there is no payload, finish unsuccessfully.
  16933. this.hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  16934. }
  16935. }
  16936. }
  16937. }, {
  16938. key: '_parseVTTs',
  16939. value: function _parseVTTs(frag, payload) {
  16940. var vttCCs = this.vttCCs;
  16941. if (!vttCCs[frag.cc]) {
  16942. vttCCs[frag.cc] = { start: frag.start, prevCC: this.prevCC, new: true };
  16943. this.prevCC = frag.cc;
  16944. }
  16945. var textTracks = this.textTracks,
  16946. hls = this.hls;
  16947. // Parse the WebVTT file contents.
  16948. _webvttParser2.default.parse(payload, this.initPTS[frag.cc], vttCCs, frag.cc, function (cues) {
  16949. var currentTrack = textTracks[frag.level];
  16950. // WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled"
  16951. // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null
  16952. // and trying to access getCueById method of cues will throw an exception
  16953. if (currentTrack.mode === 'disabled') {
  16954. hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  16955. return;
  16956. }
  16957. // Add cues and trigger event with success true.
  16958. cues.forEach(function (cue) {
  16959. // Sometimes there are cue overlaps on segmented vtts so the same
  16960. // cue can appear more than once in different vtt files.
  16961. // This avoid showing duplicated cues with same timecode and text.
  16962. if (!currentTrack.cues.getCueById(cue.id)) {
  16963. try {
  16964. currentTrack.addCue(cue);
  16965. } catch (err) {
  16966. var textTrackCue = new window.TextTrackCue(cue.startTime, cue.endTime, cue.text);
  16967. textTrackCue.id = cue.id;
  16968. currentTrack.addCue(textTrackCue);
  16969. }
  16970. }
  16971. });
  16972. hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: true, frag: frag });
  16973. }, function (e) {
  16974. // Something went wrong while parsing. Trigger event with success false.
  16975. _logger.logger.log('Failed to parse VTT cue: ' + e);
  16976. hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  16977. });
  16978. }
  16979. }, {
  16980. key: 'onFragDecrypted',
  16981. value: function onFragDecrypted(data) {
  16982. var decryptedData = data.payload,
  16983. frag = data.frag;
  16984. if (frag.type === 'subtitle') {
  16985. if (!Number.isFinite(this.initPTS[frag.cc])) {
  16986. this.unparsedVttFrags.push(data);
  16987. return;
  16988. }
  16989. this._parseVTTs(frag, decryptedData);
  16990. }
  16991. }
  16992. }, {
  16993. key: 'onFragParsingUserdata',
  16994. value: function onFragParsingUserdata(data) {
  16995. // push all of the CEA-708 messages into the interpreter
  16996. // immediately. It will create the proper timestamps based on our PTS value
  16997. if (this.enabled && this.config.enableCEA708Captions) {
  16998. for (var i = 0; i < data.samples.length; i++) {
  16999. var ccdatas = this.extractCea608Data(data.samples[i].bytes);
  17000. this.cea608Parser.addData(data.samples[i].pts, ccdatas);
  17001. }
  17002. }
  17003. }
  17004. }, {
  17005. key: 'extractCea608Data',
  17006. value: function extractCea608Data(byteArray) {
  17007. var count = byteArray[0] & 31;
  17008. var position = 2;
  17009. var tmpByte = void 0,
  17010. ccbyte1 = void 0,
  17011. ccbyte2 = void 0,
  17012. ccValid = void 0,
  17013. ccType = void 0;
  17014. var actualCCBytes = [];
  17015. for (var j = 0; j < count; j++) {
  17016. tmpByte = byteArray[position++];
  17017. ccbyte1 = 0x7F & byteArray[position++];
  17018. ccbyte2 = 0x7F & byteArray[position++];
  17019. ccValid = (4 & tmpByte) !== 0;
  17020. ccType = 3 & tmpByte;
  17021. if (ccbyte1 === 0 && ccbyte2 === 0) {
  17022. continue;
  17023. }
  17024. if (ccValid) {
  17025. if (ccType === 0) {
  17026. // || ccType === 1
  17027. actualCCBytes.push(ccbyte1);
  17028. actualCCBytes.push(ccbyte2);
  17029. }
  17030. }
  17031. }
  17032. return actualCCBytes;
  17033. }
  17034. }]);
  17035. return TimelineController;
  17036. }(_eventHandler2.default);
  17037. exports.default = TimelineController;
  17038. module.exports = exports['default'];
  17039. /***/ }),
  17040. /* 73 */
  17041. /***/ (function(module, exports, __webpack_require__) {
  17042. "use strict";
  17043. Object.defineProperty(exports, "__esModule", {
  17044. value: true
  17045. });
  17046. 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; }; }();
  17047. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  17048. /**
  17049. *
  17050. * This code was ported from the dash.js project at:
  17051. * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
  17052. * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
  17053. *
  17054. * The original copyright appears below:
  17055. *
  17056. * The copyright in this software is being made available under the BSD License,
  17057. * included below. This software may be subject to other third party and contributor
  17058. * rights, including patent rights, and no such rights are granted under this license.
  17059. *
  17060. * Copyright (c) 2015-2016, DASH Industry Forum.
  17061. * All rights reserved.
  17062. *
  17063. * Redistribution and use in source and binary forms, with or without modification,
  17064. * are permitted provided that the following conditions are met:
  17065. * 1. Redistributions of source code must retain the above copyright notice, this
  17066. * list of conditions and the following disclaimer.
  17067. * * Redistributions in binary form must reproduce the above copyright notice,
  17068. * this list of conditions and the following disclaimer in the documentation and/or
  17069. * other materials provided with the distribution.
  17070. * 2. Neither the name of Dash Industry Forum nor the names of its
  17071. * contributors may be used to endorse or promote products derived from this software
  17072. * without specific prior written permission.
  17073. *
  17074. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
  17075. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  17076. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  17077. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  17078. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  17079. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  17080. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  17081. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  17082. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  17083. * POSSIBILITY OF SUCH DAMAGE.
  17084. */
  17085. /**
  17086. * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes
  17087. */
  17088. var specialCea608CharsCodes = {
  17089. 0x2a: 0xe1, // lowercase a, acute accent
  17090. 0x5c: 0xe9, // lowercase e, acute accent
  17091. 0x5e: 0xed, // lowercase i, acute accent
  17092. 0x5f: 0xf3, // lowercase o, acute accent
  17093. 0x60: 0xfa, // lowercase u, acute accent
  17094. 0x7b: 0xe7, // lowercase c with cedilla
  17095. 0x7c: 0xf7, // division symbol
  17096. 0x7d: 0xd1, // uppercase N tilde
  17097. 0x7e: 0xf1, // lowercase n tilde
  17098. 0x7f: 0x2588, // Full block
  17099. // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  17100. // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
  17101. // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
  17102. 0x80: 0xae, // Registered symbol (R)
  17103. 0x81: 0xb0, // degree sign
  17104. 0x82: 0xbd, // 1/2 symbol
  17105. 0x83: 0xbf, // Inverted (open) question mark
  17106. 0x84: 0x2122, // Trademark symbol (TM)
  17107. 0x85: 0xa2, // Cents symbol
  17108. 0x86: 0xa3, // Pounds sterling
  17109. 0x87: 0x266a, // Music 8'th note
  17110. 0x88: 0xe0, // lowercase a, grave accent
  17111. 0x89: 0x20, // transparent space (regular)
  17112. 0x8a: 0xe8, // lowercase e, grave accent
  17113. 0x8b: 0xe2, // lowercase a, circumflex accent
  17114. 0x8c: 0xea, // lowercase e, circumflex accent
  17115. 0x8d: 0xee, // lowercase i, circumflex accent
  17116. 0x8e: 0xf4, // lowercase o, circumflex accent
  17117. 0x8f: 0xfb, // lowercase u, circumflex accent
  17118. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  17119. // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
  17120. 0x90: 0xc1, // capital letter A with acute
  17121. 0x91: 0xc9, // capital letter E with acute
  17122. 0x92: 0xd3, // capital letter O with acute
  17123. 0x93: 0xda, // capital letter U with acute
  17124. 0x94: 0xdc, // capital letter U with diaresis
  17125. 0x95: 0xfc, // lowercase letter U with diaeresis
  17126. 0x96: 0x2018, // opening single quote
  17127. 0x97: 0xa1, // inverted exclamation mark
  17128. 0x98: 0x2a, // asterisk
  17129. 0x99: 0x2019, // closing single quote
  17130. 0x9a: 0x2501, // box drawings heavy horizontal
  17131. 0x9b: 0xa9, // copyright sign
  17132. 0x9c: 0x2120, // Service mark
  17133. 0x9d: 0x2022, // (round) bullet
  17134. 0x9e: 0x201c, // Left double quotation mark
  17135. 0x9f: 0x201d, // Right double quotation mark
  17136. 0xa0: 0xc0, // uppercase A, grave accent
  17137. 0xa1: 0xc2, // uppercase A, circumflex
  17138. 0xa2: 0xc7, // uppercase C with cedilla
  17139. 0xa3: 0xc8, // uppercase E, grave accent
  17140. 0xa4: 0xca, // uppercase E, circumflex
  17141. 0xa5: 0xcb, // capital letter E with diaresis
  17142. 0xa6: 0xeb, // lowercase letter e with diaresis
  17143. 0xa7: 0xce, // uppercase I, circumflex
  17144. 0xa8: 0xcf, // uppercase I, with diaresis
  17145. 0xa9: 0xef, // lowercase i, with diaresis
  17146. 0xaa: 0xd4, // uppercase O, circumflex
  17147. 0xab: 0xd9, // uppercase U, grave accent
  17148. 0xac: 0xf9, // lowercase u, grave accent
  17149. 0xad: 0xdb, // uppercase U, circumflex
  17150. 0xae: 0xab, // left-pointing double angle quotation mark
  17151. 0xaf: 0xbb, // right-pointing double angle quotation mark
  17152. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  17153. // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
  17154. 0xb0: 0xc3, // Uppercase A, tilde
  17155. 0xb1: 0xe3, // Lowercase a, tilde
  17156. 0xb2: 0xcd, // Uppercase I, acute accent
  17157. 0xb3: 0xcc, // Uppercase I, grave accent
  17158. 0xb4: 0xec, // Lowercase i, grave accent
  17159. 0xb5: 0xd2, // Uppercase O, grave accent
  17160. 0xb6: 0xf2, // Lowercase o, grave accent
  17161. 0xb7: 0xd5, // Uppercase O, tilde
  17162. 0xb8: 0xf5, // Lowercase o, tilde
  17163. 0xb9: 0x7b, // Open curly brace
  17164. 0xba: 0x7d, // Closing curly brace
  17165. 0xbb: 0x5c, // Backslash
  17166. 0xbc: 0x5e, // Caret
  17167. 0xbd: 0x5f, // Underscore
  17168. 0xbe: 0x7c, // Pipe (vertical line)
  17169. 0xbf: 0x223c, // Tilde operator
  17170. 0xc0: 0xc4, // Uppercase A, umlaut
  17171. 0xc1: 0xe4, // Lowercase A, umlaut
  17172. 0xc2: 0xd6, // Uppercase O, umlaut
  17173. 0xc3: 0xf6, // Lowercase o, umlaut
  17174. 0xc4: 0xdf, // Esszett (sharp S)
  17175. 0xc5: 0xa5, // Yen symbol
  17176. 0xc6: 0xa4, // Generic currency sign
  17177. 0xc7: 0x2503, // Box drawings heavy vertical
  17178. 0xc8: 0xc5, // Uppercase A, ring
  17179. 0xc9: 0xe5, // Lowercase A, ring
  17180. 0xca: 0xd8, // Uppercase O, stroke
  17181. 0xcb: 0xf8, // Lowercase o, strok
  17182. 0xcc: 0x250f, // Box drawings heavy down and right
  17183. 0xcd: 0x2513, // Box drawings heavy down and left
  17184. 0xce: 0x2517, // Box drawings heavy up and right
  17185. 0xcf: 0x251b // Box drawings heavy up and left
  17186. };
  17187. /**
  17188. * Utils
  17189. */
  17190. var getCharForByte = function getCharForByte(byte) {
  17191. var charCode = byte;
  17192. if (specialCea608CharsCodes.hasOwnProperty(byte)) {
  17193. charCode = specialCea608CharsCodes[byte];
  17194. }
  17195. return String.fromCharCode(charCode);
  17196. };
  17197. var NR_ROWS = 15,
  17198. NR_COLS = 100;
  17199. // Tables to look up row from PAC data
  17200. var rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 };
  17201. var rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 };
  17202. var rowsLowCh2 = { 0x19: 1, 0x1A: 3, 0x1D: 5, 0x1E: 7, 0x1F: 9, 0x18: 11, 0x1B: 12, 0x1C: 14 };
  17203. var rowsHighCh2 = { 0x19: 2, 0x1A: 4, 0x1D: 6, 0x1E: 8, 0x1F: 10, 0x1B: 13, 0x1C: 15 };
  17204. var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];
  17205. /**
  17206. * Simple logger class to be able to write with time-stamps and filter on level.
  17207. */
  17208. var logger = {
  17209. verboseFilter: { 'DATA': 3, 'DEBUG': 3, 'INFO': 2, 'WARNING': 2, 'TEXT': 1, 'ERROR': 0 },
  17210. time: null,
  17211. verboseLevel: 0, // Only write errors
  17212. setTime: function setTime(newTime) {
  17213. this.time = newTime;
  17214. },
  17215. log: function log(severity, msg) {
  17216. var minLevel = this.verboseFilter[severity];
  17217. if (this.verboseLevel >= minLevel) {
  17218. // console.log(this.time + ' [' + severity + '] ' + msg);
  17219. }
  17220. }
  17221. };
  17222. var numArrayToHexArray = function numArrayToHexArray(numArray) {
  17223. var hexArray = [];
  17224. for (var j = 0; j < numArray.length; j++) {
  17225. hexArray.push(numArray[j].toString(16));
  17226. }
  17227. return hexArray;
  17228. };
  17229. var PenState = function () {
  17230. function PenState(foreground, underline, italics, background, flash) {
  17231. _classCallCheck(this, PenState);
  17232. this.foreground = foreground || 'white';
  17233. this.underline = underline || false;
  17234. this.italics = italics || false;
  17235. this.background = background || 'black';
  17236. this.flash = flash || false;
  17237. }
  17238. _createClass(PenState, [{
  17239. key: 'reset',
  17240. value: function reset() {
  17241. this.foreground = 'white';
  17242. this.underline = false;
  17243. this.italics = false;
  17244. this.background = 'black';
  17245. this.flash = false;
  17246. }
  17247. }, {
  17248. key: 'setStyles',
  17249. value: function setStyles(styles) {
  17250. var attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];
  17251. for (var i = 0; i < attribs.length; i++) {
  17252. var style = attribs[i];
  17253. if (styles.hasOwnProperty(style)) {
  17254. this[style] = styles[style];
  17255. }
  17256. }
  17257. }
  17258. }, {
  17259. key: 'isDefault',
  17260. value: function isDefault() {
  17261. return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;
  17262. }
  17263. }, {
  17264. key: 'equals',
  17265. value: function equals(other) {
  17266. return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
  17267. }
  17268. }, {
  17269. key: 'copy',
  17270. value: function copy(newPenState) {
  17271. this.foreground = newPenState.foreground;
  17272. this.underline = newPenState.underline;
  17273. this.italics = newPenState.italics;
  17274. this.background = newPenState.background;
  17275. this.flash = newPenState.flash;
  17276. }
  17277. }, {
  17278. key: 'toString',
  17279. value: function toString() {
  17280. return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;
  17281. }
  17282. }]);
  17283. return PenState;
  17284. }();
  17285. /**
  17286. * Unicode character with styling and background.
  17287. * @constructor
  17288. */
  17289. var StyledUnicodeChar = function () {
  17290. function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) {
  17291. _classCallCheck(this, StyledUnicodeChar);
  17292. this.uchar = uchar || ' '; // unicode character
  17293. this.penState = new PenState(foreground, underline, italics, background, flash);
  17294. }
  17295. _createClass(StyledUnicodeChar, [{
  17296. key: 'reset',
  17297. value: function reset() {
  17298. this.uchar = ' ';
  17299. this.penState.reset();
  17300. }
  17301. }, {
  17302. key: 'setChar',
  17303. value: function setChar(uchar, newPenState) {
  17304. this.uchar = uchar;
  17305. this.penState.copy(newPenState);
  17306. }
  17307. }, {
  17308. key: 'setPenState',
  17309. value: function setPenState(newPenState) {
  17310. this.penState.copy(newPenState);
  17311. }
  17312. }, {
  17313. key: 'equals',
  17314. value: function equals(other) {
  17315. return this.uchar === other.uchar && this.penState.equals(other.penState);
  17316. }
  17317. }, {
  17318. key: 'copy',
  17319. value: function copy(newChar) {
  17320. this.uchar = newChar.uchar;
  17321. this.penState.copy(newChar.penState);
  17322. }
  17323. }, {
  17324. key: 'isEmpty',
  17325. value: function isEmpty() {
  17326. return this.uchar === ' ' && this.penState.isDefault();
  17327. }
  17328. }]);
  17329. return StyledUnicodeChar;
  17330. }();
  17331. /**
  17332. * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
  17333. * @constructor
  17334. */
  17335. var Row = function () {
  17336. function Row() {
  17337. _classCallCheck(this, Row);
  17338. this.chars = [];
  17339. for (var i = 0; i < NR_COLS; i++) {
  17340. this.chars.push(new StyledUnicodeChar());
  17341. }
  17342. this.pos = 0;
  17343. this.currPenState = new PenState();
  17344. }
  17345. _createClass(Row, [{
  17346. key: 'equals',
  17347. value: function equals(other) {
  17348. var equal = true;
  17349. for (var i = 0; i < NR_COLS; i++) {
  17350. if (!this.chars[i].equals(other.chars[i])) {
  17351. equal = false;
  17352. break;
  17353. }
  17354. }
  17355. return equal;
  17356. }
  17357. }, {
  17358. key: 'copy',
  17359. value: function copy(other) {
  17360. for (var i = 0; i < NR_COLS; i++) {
  17361. this.chars[i].copy(other.chars[i]);
  17362. }
  17363. }
  17364. }, {
  17365. key: 'isEmpty',
  17366. value: function isEmpty() {
  17367. var empty = true;
  17368. for (var i = 0; i < NR_COLS; i++) {
  17369. if (!this.chars[i].isEmpty()) {
  17370. empty = false;
  17371. break;
  17372. }
  17373. }
  17374. return empty;
  17375. }
  17376. /**
  17377. * Set the cursor to a valid column.
  17378. */
  17379. }, {
  17380. key: 'setCursor',
  17381. value: function setCursor(absPos) {
  17382. if (this.pos !== absPos) {
  17383. this.pos = absPos;
  17384. }
  17385. if (this.pos < 0) {
  17386. logger.log('ERROR', 'Negative cursor position ' + this.pos);
  17387. this.pos = 0;
  17388. } else if (this.pos > NR_COLS) {
  17389. logger.log('ERROR', 'Too large cursor position ' + this.pos);
  17390. this.pos = NR_COLS;
  17391. }
  17392. }
  17393. /**
  17394. * Move the cursor relative to current position.
  17395. */
  17396. }, {
  17397. key: 'moveCursor',
  17398. value: function moveCursor(relPos) {
  17399. var newPos = this.pos + relPos;
  17400. if (relPos > 1) {
  17401. for (var i = this.pos + 1; i < newPos + 1; i++) {
  17402. this.chars[i].setPenState(this.currPenState);
  17403. }
  17404. }
  17405. this.setCursor(newPos);
  17406. }
  17407. /**
  17408. * Backspace, move one step back and clear character.
  17409. */
  17410. }, {
  17411. key: 'backSpace',
  17412. value: function backSpace() {
  17413. this.moveCursor(-1);
  17414. this.chars[this.pos].setChar(' ', this.currPenState);
  17415. }
  17416. }, {
  17417. key: 'insertChar',
  17418. value: function insertChar(byte) {
  17419. if (byte >= 0x90) {
  17420. // Extended char
  17421. this.backSpace();
  17422. }
  17423. var char = getCharForByte(byte);
  17424. if (this.pos >= NR_COLS) {
  17425. logger.log('ERROR', 'Cannot insert ' + byte.toString(16) + ' (' + char + ') at position ' + this.pos + '. Skipping it!');
  17426. return;
  17427. }
  17428. this.chars[this.pos].setChar(char, this.currPenState);
  17429. this.moveCursor(1);
  17430. }
  17431. }, {
  17432. key: 'clearFromPos',
  17433. value: function clearFromPos(startPos) {
  17434. var i = void 0;
  17435. for (i = startPos; i < NR_COLS; i++) {
  17436. this.chars[i].reset();
  17437. }
  17438. }
  17439. }, {
  17440. key: 'clear',
  17441. value: function clear() {
  17442. this.clearFromPos(0);
  17443. this.pos = 0;
  17444. this.currPenState.reset();
  17445. }
  17446. }, {
  17447. key: 'clearToEndOfRow',
  17448. value: function clearToEndOfRow() {
  17449. this.clearFromPos(this.pos);
  17450. }
  17451. }, {
  17452. key: 'getTextString',
  17453. value: function getTextString() {
  17454. var chars = [];
  17455. var empty = true;
  17456. for (var i = 0; i < NR_COLS; i++) {
  17457. var char = this.chars[i].uchar;
  17458. if (char !== ' ') {
  17459. empty = false;
  17460. }
  17461. chars.push(char);
  17462. }
  17463. if (empty) {
  17464. return '';
  17465. } else {
  17466. return chars.join('');
  17467. }
  17468. }
  17469. }, {
  17470. key: 'setPenStyles',
  17471. value: function setPenStyles(styles) {
  17472. this.currPenState.setStyles(styles);
  17473. var currChar = this.chars[this.pos];
  17474. currChar.setPenState(this.currPenState);
  17475. }
  17476. }]);
  17477. return Row;
  17478. }();
  17479. /**
  17480. * Keep a CEA-608 screen of 32x15 styled characters
  17481. * @constructor
  17482. */
  17483. var CaptionScreen = function () {
  17484. function CaptionScreen() {
  17485. _classCallCheck(this, CaptionScreen);
  17486. this.rows = [];
  17487. for (var i = 0; i < NR_ROWS; i++) {
  17488. this.rows.push(new Row());
  17489. } // Note that we use zero-based numbering (0-14)
  17490. this.currRow = NR_ROWS - 1;
  17491. this.nrRollUpRows = null;
  17492. this.reset();
  17493. }
  17494. _createClass(CaptionScreen, [{
  17495. key: 'reset',
  17496. value: function reset() {
  17497. for (var i = 0; i < NR_ROWS; i++) {
  17498. this.rows[i].clear();
  17499. }
  17500. this.currRow = NR_ROWS - 1;
  17501. }
  17502. }, {
  17503. key: 'equals',
  17504. value: function equals(other) {
  17505. var equal = true;
  17506. for (var i = 0; i < NR_ROWS; i++) {
  17507. if (!this.rows[i].equals(other.rows[i])) {
  17508. equal = false;
  17509. break;
  17510. }
  17511. }
  17512. return equal;
  17513. }
  17514. }, {
  17515. key: 'copy',
  17516. value: function copy(other) {
  17517. for (var i = 0; i < NR_ROWS; i++) {
  17518. this.rows[i].copy(other.rows[i]);
  17519. }
  17520. }
  17521. }, {
  17522. key: 'isEmpty',
  17523. value: function isEmpty() {
  17524. var empty = true;
  17525. for (var i = 0; i < NR_ROWS; i++) {
  17526. if (!this.rows[i].isEmpty()) {
  17527. empty = false;
  17528. break;
  17529. }
  17530. }
  17531. return empty;
  17532. }
  17533. }, {
  17534. key: 'backSpace',
  17535. value: function backSpace() {
  17536. var row = this.rows[this.currRow];
  17537. row.backSpace();
  17538. }
  17539. }, {
  17540. key: 'clearToEndOfRow',
  17541. value: function clearToEndOfRow() {
  17542. var row = this.rows[this.currRow];
  17543. row.clearToEndOfRow();
  17544. }
  17545. /**
  17546. * Insert a character (without styling) in the current row.
  17547. */
  17548. }, {
  17549. key: 'insertChar',
  17550. value: function insertChar(char) {
  17551. var row = this.rows[this.currRow];
  17552. row.insertChar(char);
  17553. }
  17554. }, {
  17555. key: 'setPen',
  17556. value: function setPen(styles) {
  17557. var row = this.rows[this.currRow];
  17558. row.setPenStyles(styles);
  17559. }
  17560. }, {
  17561. key: 'moveCursor',
  17562. value: function moveCursor(relPos) {
  17563. var row = this.rows[this.currRow];
  17564. row.moveCursor(relPos);
  17565. }
  17566. }, {
  17567. key: 'setCursor',
  17568. value: function setCursor(absPos) {
  17569. logger.log('INFO', 'setCursor: ' + absPos);
  17570. var row = this.rows[this.currRow];
  17571. row.setCursor(absPos);
  17572. }
  17573. }, {
  17574. key: 'setPAC',
  17575. value: function setPAC(pacData) {
  17576. logger.log('INFO', 'pacData = ' + JSON.stringify(pacData));
  17577. var newRow = pacData.row - 1;
  17578. if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
  17579. newRow = this.nrRollUpRows - 1;
  17580. }
  17581. // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows
  17582. if (this.nrRollUpRows && this.currRow !== newRow) {
  17583. // clear all rows first
  17584. for (var i = 0; i < NR_ROWS; i++) {
  17585. this.rows[i].clear();
  17586. }
  17587. // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location
  17588. // topRowIndex - the start of rows to copy (inclusive index)
  17589. var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  17590. // We only copy if the last position was already shown.
  17591. // We use the cueStartTime value to check this.
  17592. var lastOutputScreen = this.lastOutputScreen;
  17593. if (lastOutputScreen) {
  17594. var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
  17595. if (prevLineTime && prevLineTime < logger.time) {
  17596. for (var _i = 0; _i < this.nrRollUpRows; _i++) {
  17597. this.rows[newRow - this.nrRollUpRows + _i + 1].copy(lastOutputScreen.rows[topRowIndex + _i]);
  17598. }
  17599. }
  17600. }
  17601. }
  17602. this.currRow = newRow;
  17603. var row = this.rows[this.currRow];
  17604. if (pacData.indent !== null) {
  17605. var indent = pacData.indent;
  17606. var prevPos = Math.max(indent - 1, 0);
  17607. row.setCursor(pacData.indent);
  17608. pacData.color = row.chars[prevPos].penState.foreground;
  17609. }
  17610. var styles = { foreground: pacData.color, underline: pacData.underline, italics: pacData.italics, background: 'black', flash: false };
  17611. this.setPen(styles);
  17612. }
  17613. /**
  17614. * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
  17615. */
  17616. }, {
  17617. key: 'setBkgData',
  17618. value: function setBkgData(bkgData) {
  17619. logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData));
  17620. this.backSpace();
  17621. this.setPen(bkgData);
  17622. this.insertChar(0x20); // Space
  17623. }
  17624. }, {
  17625. key: 'setRollUpRows',
  17626. value: function setRollUpRows(nrRows) {
  17627. this.nrRollUpRows = nrRows;
  17628. }
  17629. }, {
  17630. key: 'rollUp',
  17631. value: function rollUp() {
  17632. if (this.nrRollUpRows === null) {
  17633. logger.log('DEBUG', 'roll_up but nrRollUpRows not set yet');
  17634. return; // Not properly setup
  17635. }
  17636. logger.log('TEXT', this.getDisplayText());
  17637. var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  17638. var topRow = this.rows.splice(topRowIndex, 1)[0];
  17639. topRow.clear();
  17640. this.rows.splice(this.currRow, 0, topRow);
  17641. logger.log('INFO', 'Rolling up');
  17642. // logger.log('TEXT', this.get_display_text())
  17643. }
  17644. /**
  17645. * Get all non-empty rows with as unicode text.
  17646. */
  17647. }, {
  17648. key: 'getDisplayText',
  17649. value: function getDisplayText(asOneRow) {
  17650. asOneRow = asOneRow || false;
  17651. var displayText = [];
  17652. var text = '';
  17653. var rowNr = -1;
  17654. for (var i = 0; i < NR_ROWS; i++) {
  17655. var rowText = this.rows[i].getTextString();
  17656. if (rowText) {
  17657. rowNr = i + 1;
  17658. if (asOneRow) {
  17659. displayText.push('Row ' + rowNr + ': \'' + rowText + '\'');
  17660. } else {
  17661. displayText.push(rowText.trim());
  17662. }
  17663. }
  17664. }
  17665. if (displayText.length > 0) {
  17666. if (asOneRow) {
  17667. text = '[' + displayText.join(' | ') + ']';
  17668. } else {
  17669. text = displayText.join('\n');
  17670. }
  17671. }
  17672. return text;
  17673. }
  17674. }, {
  17675. key: 'getTextAndFormat',
  17676. value: function getTextAndFormat() {
  17677. return this.rows;
  17678. }
  17679. }]);
  17680. return CaptionScreen;
  17681. }();
  17682. // var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
  17683. var Cea608Channel = function () {
  17684. function Cea608Channel(channelNumber, outputFilter) {
  17685. _classCallCheck(this, Cea608Channel);
  17686. this.chNr = channelNumber;
  17687. this.outputFilter = outputFilter;
  17688. this.mode = null;
  17689. this.verbose = 0;
  17690. this.displayedMemory = new CaptionScreen();
  17691. this.nonDisplayedMemory = new CaptionScreen();
  17692. this.lastOutputScreen = new CaptionScreen();
  17693. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  17694. this.writeScreen = this.displayedMemory;
  17695. this.mode = null;
  17696. this.cueStartTime = null; // Keeps track of where a cue started.
  17697. }
  17698. _createClass(Cea608Channel, [{
  17699. key: 'reset',
  17700. value: function reset() {
  17701. this.mode = null;
  17702. this.displayedMemory.reset();
  17703. this.nonDisplayedMemory.reset();
  17704. this.lastOutputScreen.reset();
  17705. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  17706. this.writeScreen = this.displayedMemory;
  17707. this.mode = null;
  17708. this.cueStartTime = null;
  17709. this.lastCueEndTime = null;
  17710. }
  17711. }, {
  17712. key: 'getHandler',
  17713. value: function getHandler() {
  17714. return this.outputFilter;
  17715. }
  17716. }, {
  17717. key: 'setHandler',
  17718. value: function setHandler(newHandler) {
  17719. this.outputFilter = newHandler;
  17720. }
  17721. }, {
  17722. key: 'setPAC',
  17723. value: function setPAC(pacData) {
  17724. this.writeScreen.setPAC(pacData);
  17725. }
  17726. }, {
  17727. key: 'setBkgData',
  17728. value: function setBkgData(bkgData) {
  17729. this.writeScreen.setBkgData(bkgData);
  17730. }
  17731. }, {
  17732. key: 'setMode',
  17733. value: function setMode(newMode) {
  17734. if (newMode === this.mode) {
  17735. return;
  17736. }
  17737. this.mode = newMode;
  17738. logger.log('INFO', 'MODE=' + newMode);
  17739. if (this.mode === 'MODE_POP-ON') {
  17740. this.writeScreen = this.nonDisplayedMemory;
  17741. } else {
  17742. this.writeScreen = this.displayedMemory;
  17743. this.writeScreen.reset();
  17744. }
  17745. if (this.mode !== 'MODE_ROLL-UP') {
  17746. this.displayedMemory.nrRollUpRows = null;
  17747. this.nonDisplayedMemory.nrRollUpRows = null;
  17748. }
  17749. this.mode = newMode;
  17750. }
  17751. }, {
  17752. key: 'insertChars',
  17753. value: function insertChars(chars) {
  17754. for (var i = 0; i < chars.length; i++) {
  17755. this.writeScreen.insertChar(chars[i]);
  17756. }
  17757. var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';
  17758. logger.log('INFO', screen + ': ' + this.writeScreen.getDisplayText(true));
  17759. if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
  17760. logger.log('TEXT', 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));
  17761. this.outputDataUpdate();
  17762. }
  17763. }
  17764. }, {
  17765. key: 'ccRCL',
  17766. value: function ccRCL() {
  17767. // Resume Caption Loading (switch mode to Pop On)
  17768. logger.log('INFO', 'RCL - Resume Caption Loading');
  17769. this.setMode('MODE_POP-ON');
  17770. }
  17771. }, {
  17772. key: 'ccBS',
  17773. value: function ccBS() {
  17774. // BackSpace
  17775. logger.log('INFO', 'BS - BackSpace');
  17776. if (this.mode === 'MODE_TEXT') {
  17777. return;
  17778. }
  17779. this.writeScreen.backSpace();
  17780. if (this.writeScreen === this.displayedMemory) {
  17781. this.outputDataUpdate();
  17782. }
  17783. }
  17784. }, {
  17785. key: 'ccAOF',
  17786. value: function ccAOF() {// Reserved (formerly Alarm Off)
  17787. }
  17788. }, {
  17789. key: 'ccAON',
  17790. value: function ccAON() {// Reserved (formerly Alarm On)
  17791. }
  17792. }, {
  17793. key: 'ccDER',
  17794. value: function ccDER() {
  17795. // Delete to End of Row
  17796. logger.log('INFO', 'DER- Delete to End of Row');
  17797. this.writeScreen.clearToEndOfRow();
  17798. this.outputDataUpdate();
  17799. }
  17800. }, {
  17801. key: 'ccRU',
  17802. value: function ccRU(nrRows) {
  17803. // Roll-Up Captions-2,3,or 4 Rows
  17804. logger.log('INFO', 'RU(' + nrRows + ') - Roll Up');
  17805. this.writeScreen = this.displayedMemory;
  17806. this.setMode('MODE_ROLL-UP');
  17807. this.writeScreen.setRollUpRows(nrRows);
  17808. }
  17809. }, {
  17810. key: 'ccFON',
  17811. value: function ccFON() {
  17812. // Flash On
  17813. logger.log('INFO', 'FON - Flash On');
  17814. this.writeScreen.setPen({ flash: true });
  17815. }
  17816. }, {
  17817. key: 'ccRDC',
  17818. value: function ccRDC() {
  17819. // Resume Direct Captioning (switch mode to PaintOn)
  17820. logger.log('INFO', 'RDC - Resume Direct Captioning');
  17821. this.setMode('MODE_PAINT-ON');
  17822. }
  17823. }, {
  17824. key: 'ccTR',
  17825. value: function ccTR() {
  17826. // Text Restart in text mode (not supported, however)
  17827. logger.log('INFO', 'TR');
  17828. this.setMode('MODE_TEXT');
  17829. }
  17830. }, {
  17831. key: 'ccRTD',
  17832. value: function ccRTD() {
  17833. // Resume Text Display in Text mode (not supported, however)
  17834. logger.log('INFO', 'RTD');
  17835. this.setMode('MODE_TEXT');
  17836. }
  17837. }, {
  17838. key: 'ccEDM',
  17839. value: function ccEDM() {
  17840. // Erase Displayed Memory
  17841. logger.log('INFO', 'EDM - Erase Displayed Memory');
  17842. this.displayedMemory.reset();
  17843. this.outputDataUpdate(true);
  17844. }
  17845. }, {
  17846. key: 'ccCR',
  17847. value: function ccCR() {
  17848. // Carriage Return
  17849. logger.log('CR - Carriage Return');
  17850. this.writeScreen.rollUp();
  17851. this.outputDataUpdate(true);
  17852. }
  17853. }, {
  17854. key: 'ccENM',
  17855. value: function ccENM() {
  17856. // Erase Non-Displayed Memory
  17857. logger.log('INFO', 'ENM - Erase Non-displayed Memory');
  17858. this.nonDisplayedMemory.reset();
  17859. }
  17860. }, {
  17861. key: 'ccEOC',
  17862. value: function ccEOC() {
  17863. // End of Caption (Flip Memories)
  17864. logger.log('INFO', 'EOC - End Of Caption');
  17865. if (this.mode === 'MODE_POP-ON') {
  17866. var tmp = this.displayedMemory;
  17867. this.displayedMemory = this.nonDisplayedMemory;
  17868. this.nonDisplayedMemory = tmp;
  17869. this.writeScreen = this.nonDisplayedMemory;
  17870. logger.log('TEXT', 'DISP: ' + this.displayedMemory.getDisplayText());
  17871. }
  17872. this.outputDataUpdate(true);
  17873. }
  17874. }, {
  17875. key: 'ccTO',
  17876. value: function ccTO(nrCols) {
  17877. // Tab Offset 1,2, or 3 columns
  17878. logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset');
  17879. this.writeScreen.moveCursor(nrCols);
  17880. }
  17881. }, {
  17882. key: 'ccMIDROW',
  17883. value: function ccMIDROW(secondByte) {
  17884. // Parse MIDROW command
  17885. var styles = { flash: false };
  17886. styles.underline = secondByte % 2 === 1;
  17887. styles.italics = secondByte >= 0x2e;
  17888. if (!styles.italics) {
  17889. var colorIndex = Math.floor(secondByte / 2) - 0x10;
  17890. var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];
  17891. styles.foreground = colors[colorIndex];
  17892. } else {
  17893. styles.foreground = 'white';
  17894. }
  17895. logger.log('INFO', 'MIDROW: ' + JSON.stringify(styles));
  17896. this.writeScreen.setPen(styles);
  17897. }
  17898. }, {
  17899. key: 'outputDataUpdate',
  17900. value: function outputDataUpdate() {
  17901. var dispatch = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  17902. var t = logger.time;
  17903. if (t === null) {
  17904. return;
  17905. }
  17906. if (this.outputFilter) {
  17907. if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
  17908. // Start of a new cue
  17909. this.cueStartTime = t;
  17910. } else {
  17911. if (!this.displayedMemory.equals(this.lastOutputScreen)) {
  17912. if (this.outputFilter.newCue) {
  17913. this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen);
  17914. if (dispatch === true && this.outputFilter.dispatchCue) {
  17915. this.outputFilter.dispatchCue();
  17916. }
  17917. }
  17918. this.cueStartTime = this.displayedMemory.isEmpty() ? null : t;
  17919. }
  17920. }
  17921. this.lastOutputScreen.copy(this.displayedMemory);
  17922. }
  17923. }
  17924. }, {
  17925. key: 'cueSplitAtTime',
  17926. value: function cueSplitAtTime(t) {
  17927. if (this.outputFilter) {
  17928. if (!this.displayedMemory.isEmpty()) {
  17929. if (this.outputFilter.newCue) {
  17930. this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
  17931. }
  17932. this.cueStartTime = t;
  17933. }
  17934. }
  17935. }
  17936. }]);
  17937. return Cea608Channel;
  17938. }();
  17939. var Cea608Parser = function () {
  17940. function Cea608Parser(field, out1, out2) {
  17941. _classCallCheck(this, Cea608Parser);
  17942. this.field = field || 1;
  17943. this.outputs = [out1, out2];
  17944. this.channels = [new Cea608Channel(1, out1), new Cea608Channel(2, out2)];
  17945. this.currChNr = -1; // Will be 1 or 2
  17946. this.lastCmdA = null; // First byte of last command
  17947. this.lastCmdB = null; // Second byte of last command
  17948. this.bufferedData = [];
  17949. this.startTime = null;
  17950. this.lastTime = null;
  17951. this.dataCounters = { 'padding': 0, 'char': 0, 'cmd': 0, 'other': 0 };
  17952. }
  17953. _createClass(Cea608Parser, [{
  17954. key: 'getHandler',
  17955. value: function getHandler(index) {
  17956. return this.channels[index].getHandler();
  17957. }
  17958. }, {
  17959. key: 'setHandler',
  17960. value: function setHandler(index, newHandler) {
  17961. this.channels[index].setHandler(newHandler);
  17962. }
  17963. /**
  17964. * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
  17965. */
  17966. }, {
  17967. key: 'addData',
  17968. value: function addData(t, byteList) {
  17969. var cmdFound = void 0,
  17970. a = void 0,
  17971. b = void 0,
  17972. charsFound = false;
  17973. this.lastTime = t;
  17974. logger.setTime(t);
  17975. for (var i = 0; i < byteList.length; i += 2) {
  17976. a = byteList[i] & 0x7f;
  17977. b = byteList[i + 1] & 0x7f;
  17978. if (a === 0 && b === 0) {
  17979. this.dataCounters.padding += 2;
  17980. continue;
  17981. } else {
  17982. logger.log('DATA', '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');
  17983. }
  17984. cmdFound = this.parseCmd(a, b);
  17985. if (!cmdFound) {
  17986. cmdFound = this.parseMidrow(a, b);
  17987. }
  17988. if (!cmdFound) {
  17989. cmdFound = this.parsePAC(a, b);
  17990. }
  17991. if (!cmdFound) {
  17992. cmdFound = this.parseBackgroundAttributes(a, b);
  17993. }
  17994. if (!cmdFound) {
  17995. charsFound = this.parseChars(a, b);
  17996. if (charsFound) {
  17997. if (this.currChNr && this.currChNr >= 0) {
  17998. var channel = this.channels[this.currChNr - 1];
  17999. channel.insertChars(charsFound);
  18000. } else {
  18001. logger.log('WARNING', 'No channel found yet. TEXT-MODE?');
  18002. }
  18003. }
  18004. }
  18005. if (cmdFound) {
  18006. this.dataCounters.cmd += 2;
  18007. } else if (charsFound) {
  18008. this.dataCounters.char += 2;
  18009. } else {
  18010. this.dataCounters.other += 2;
  18011. logger.log('WARNING', 'Couldn\'t parse cleaned data ' + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));
  18012. }
  18013. }
  18014. }
  18015. /**
  18016. * Parse Command.
  18017. * @returns {Boolean} Tells if a command was found
  18018. */
  18019. }, {
  18020. key: 'parseCmd',
  18021. value: function parseCmd(a, b) {
  18022. var chNr = null;
  18023. var cond1 = (a === 0x14 || a === 0x1C) && b >= 0x20 && b <= 0x2F;
  18024. var cond2 = (a === 0x17 || a === 0x1F) && b >= 0x21 && b <= 0x23;
  18025. if (!(cond1 || cond2)) {
  18026. return false;
  18027. }
  18028. if (a === this.lastCmdA && b === this.lastCmdB) {
  18029. this.lastCmdA = null;
  18030. this.lastCmdB = null; // Repeated commands are dropped (once)
  18031. logger.log('DEBUG', 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');
  18032. return true;
  18033. }
  18034. if (a === 0x14 || a === 0x17) {
  18035. chNr = 1;
  18036. } else {
  18037. chNr = 2;
  18038. } // (a === 0x1C || a=== 0x1f)
  18039. var channel = this.channels[chNr - 1];
  18040. if (a === 0x14 || a === 0x1C) {
  18041. if (b === 0x20) {
  18042. channel.ccRCL();
  18043. } else if (b === 0x21) {
  18044. channel.ccBS();
  18045. } else if (b === 0x22) {
  18046. channel.ccAOF();
  18047. } else if (b === 0x23) {
  18048. channel.ccAON();
  18049. } else if (b === 0x24) {
  18050. channel.ccDER();
  18051. } else if (b === 0x25) {
  18052. channel.ccRU(2);
  18053. } else if (b === 0x26) {
  18054. channel.ccRU(3);
  18055. } else if (b === 0x27) {
  18056. channel.ccRU(4);
  18057. } else if (b === 0x28) {
  18058. channel.ccFON();
  18059. } else if (b === 0x29) {
  18060. channel.ccRDC();
  18061. } else if (b === 0x2A) {
  18062. channel.ccTR();
  18063. } else if (b === 0x2B) {
  18064. channel.ccRTD();
  18065. } else if (b === 0x2C) {
  18066. channel.ccEDM();
  18067. } else if (b === 0x2D) {
  18068. channel.ccCR();
  18069. } else if (b === 0x2E) {
  18070. channel.ccENM();
  18071. } else if (b === 0x2F) {
  18072. channel.ccEOC();
  18073. }
  18074. } else {
  18075. // a == 0x17 || a == 0x1F
  18076. channel.ccTO(b - 0x20);
  18077. }
  18078. this.lastCmdA = a;
  18079. this.lastCmdB = b;
  18080. this.currChNr = chNr;
  18081. return true;
  18082. }
  18083. /**
  18084. * Parse midrow styling command
  18085. * @returns {Boolean}
  18086. */
  18087. }, {
  18088. key: 'parseMidrow',
  18089. value: function parseMidrow(a, b) {
  18090. var chNr = null;
  18091. if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {
  18092. if (a === 0x11) {
  18093. chNr = 1;
  18094. } else {
  18095. chNr = 2;
  18096. }
  18097. if (chNr !== this.currChNr) {
  18098. logger.log('ERROR', 'Mismatch channel in midrow parsing');
  18099. return false;
  18100. }
  18101. var channel = this.channels[chNr - 1];
  18102. channel.ccMIDROW(b);
  18103. logger.log('DEBUG', 'MIDROW (' + numArrayToHexArray([a, b]) + ')');
  18104. return true;
  18105. }
  18106. return false;
  18107. }
  18108. /**
  18109. * Parse Preable Access Codes (Table 53).
  18110. * @returns {Boolean} Tells if PAC found
  18111. */
  18112. }, {
  18113. key: 'parsePAC',
  18114. value: function parsePAC(a, b) {
  18115. var chNr = null;
  18116. var row = null;
  18117. var case1 = (a >= 0x11 && a <= 0x17 || a >= 0x19 && a <= 0x1F) && b >= 0x40 && b <= 0x7F;
  18118. var case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5F;
  18119. if (!(case1 || case2)) {
  18120. return false;
  18121. }
  18122. if (a === this.lastCmdA && b === this.lastCmdB) {
  18123. this.lastCmdA = null;
  18124. this.lastCmdB = null;
  18125. return true; // Repeated commands are dropped (once)
  18126. }
  18127. chNr = a <= 0x17 ? 1 : 2;
  18128. if (b >= 0x40 && b <= 0x5F) {
  18129. row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
  18130. } else {
  18131. // 0x60 <= b <= 0x7F
  18132. row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
  18133. }
  18134. var pacData = this.interpretPAC(row, b);
  18135. var channel = this.channels[chNr - 1];
  18136. channel.setPAC(pacData);
  18137. this.lastCmdA = a;
  18138. this.lastCmdB = b;
  18139. this.currChNr = chNr;
  18140. return true;
  18141. }
  18142. /**
  18143. * Interpret the second byte of the pac, and return the information.
  18144. * @returns {Object} pacData with style parameters.
  18145. */
  18146. }, {
  18147. key: 'interpretPAC',
  18148. value: function interpretPAC(row, byte) {
  18149. var pacIndex = byte;
  18150. var pacData = { color: null, italics: false, indent: null, underline: false, row: row };
  18151. if (byte > 0x5F) {
  18152. pacIndex = byte - 0x60;
  18153. } else {
  18154. pacIndex = byte - 0x40;
  18155. }
  18156. pacData.underline = (pacIndex & 1) === 1;
  18157. if (pacIndex <= 0xd) {
  18158. pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];
  18159. } else if (pacIndex <= 0xf) {
  18160. pacData.italics = true;
  18161. pacData.color = 'white';
  18162. } else {
  18163. pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;
  18164. }
  18165. return pacData; // Note that row has zero offset. The spec uses 1.
  18166. }
  18167. /**
  18168. * Parse characters.
  18169. * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
  18170. */
  18171. }, {
  18172. key: 'parseChars',
  18173. value: function parseChars(a, b) {
  18174. var channelNr = null,
  18175. charCodes = null,
  18176. charCode1 = null;
  18177. if (a >= 0x19) {
  18178. channelNr = 2;
  18179. charCode1 = a - 8;
  18180. } else {
  18181. channelNr = 1;
  18182. charCode1 = a;
  18183. }
  18184. if (charCode1 >= 0x11 && charCode1 <= 0x13) {
  18185. // Special character
  18186. var oneCode = b;
  18187. if (charCode1 === 0x11) {
  18188. oneCode = b + 0x50;
  18189. } else if (charCode1 === 0x12) {
  18190. oneCode = b + 0x70;
  18191. } else {
  18192. oneCode = b + 0x90;
  18193. }
  18194. logger.log('INFO', 'Special char \'' + getCharForByte(oneCode) + '\' in channel ' + channelNr);
  18195. charCodes = [oneCode];
  18196. } else if (a >= 0x20 && a <= 0x7f) {
  18197. charCodes = b === 0 ? [a] : [a, b];
  18198. }
  18199. if (charCodes) {
  18200. var hexCodes = numArrayToHexArray(charCodes);
  18201. logger.log('DEBUG', 'Char codes = ' + hexCodes.join(','));
  18202. this.lastCmdA = null;
  18203. this.lastCmdB = null;
  18204. }
  18205. return charCodes;
  18206. }
  18207. /**
  18208. * Parse extended background attributes as well as new foreground color black.
  18209. * @returns{Boolean} Tells if background attributes are found
  18210. */
  18211. }, {
  18212. key: 'parseBackgroundAttributes',
  18213. value: function parseBackgroundAttributes(a, b) {
  18214. var bkgData = void 0,
  18215. index = void 0,
  18216. chNr = void 0,
  18217. channel = void 0;
  18218. var case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;
  18219. var case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;
  18220. if (!(case1 || case2)) {
  18221. return false;
  18222. }
  18223. bkgData = {};
  18224. if (a === 0x10 || a === 0x18) {
  18225. index = Math.floor((b - 0x20) / 2);
  18226. bkgData.background = backgroundColors[index];
  18227. if (b % 2 === 1) {
  18228. bkgData.background = bkgData.background + '_semi';
  18229. }
  18230. } else if (b === 0x2d) {
  18231. bkgData.background = 'transparent';
  18232. } else {
  18233. bkgData.foreground = 'black';
  18234. if (b === 0x2f) {
  18235. bkgData.underline = true;
  18236. }
  18237. }
  18238. chNr = a < 0x18 ? 1 : 2;
  18239. channel = this.channels[chNr - 1];
  18240. channel.setBkgData(bkgData);
  18241. this.lastCmdA = null;
  18242. this.lastCmdB = null;
  18243. return true;
  18244. }
  18245. /**
  18246. * Reset state of parser and its channels.
  18247. */
  18248. }, {
  18249. key: 'reset',
  18250. value: function reset() {
  18251. for (var i = 0; i < this.channels.length; i++) {
  18252. if (this.channels[i]) {
  18253. this.channels[i].reset();
  18254. }
  18255. }
  18256. this.lastCmdA = null;
  18257. this.lastCmdB = null;
  18258. }
  18259. /**
  18260. * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
  18261. */
  18262. }, {
  18263. key: 'cueSplitAtTime',
  18264. value: function cueSplitAtTime(t) {
  18265. for (var i = 0; i < this.channels.length; i++) {
  18266. if (this.channels[i]) {
  18267. this.channels[i].cueSplitAtTime(t);
  18268. }
  18269. }
  18270. }
  18271. }]);
  18272. return Cea608Parser;
  18273. }();
  18274. exports.default = Cea608Parser;
  18275. module.exports = exports['default'];
  18276. /***/ }),
  18277. /* 74 */
  18278. /***/ (function(module, exports, __webpack_require__) {
  18279. "use strict";
  18280. Object.defineProperty(exports, "__esModule", {
  18281. value: true
  18282. });
  18283. 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; }; }();
  18284. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  18285. var OutputFilter = function () {
  18286. function OutputFilter(timelineController, trackName) {
  18287. _classCallCheck(this, OutputFilter);
  18288. this.timelineController = timelineController;
  18289. this.trackName = trackName;
  18290. this.startTime = null;
  18291. this.endTime = null;
  18292. this.screen = null;
  18293. }
  18294. _createClass(OutputFilter, [{
  18295. key: "dispatchCue",
  18296. value: function dispatchCue() {
  18297. if (this.startTime === null) {
  18298. return;
  18299. }
  18300. this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen);
  18301. this.startTime = null;
  18302. }
  18303. }, {
  18304. key: "newCue",
  18305. value: function newCue(startTime, endTime, screen) {
  18306. if (this.startTime === null || this.startTime > startTime) {
  18307. this.startTime = startTime;
  18308. }
  18309. this.endTime = endTime;
  18310. this.screen = screen;
  18311. this.timelineController.createCaptionsTrack(this.trackName);
  18312. }
  18313. }]);
  18314. return OutputFilter;
  18315. }();
  18316. exports.default = OutputFilter;
  18317. module.exports = exports["default"];
  18318. /***/ }),
  18319. /* 75 */
  18320. /***/ (function(module, exports, __webpack_require__) {
  18321. "use strict";
  18322. Object.defineProperty(exports, "__esModule", {
  18323. value: true
  18324. });
  18325. var _vttparser = __webpack_require__(30);
  18326. var _vttparser2 = _interopRequireDefault(_vttparser);
  18327. var _id = __webpack_require__(10);
  18328. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  18329. // String.prototype.startsWith is not supported in IE11
  18330. var startsWith = function startsWith(inputString, searchString, position) {
  18331. return inputString.substr(position || 0, searchString.length) === searchString;
  18332. };
  18333. var cueString2millis = function cueString2millis(timeString) {
  18334. var ts = parseInt(timeString.substr(-3));
  18335. var secs = parseInt(timeString.substr(-6, 2));
  18336. var mins = parseInt(timeString.substr(-9, 2));
  18337. var hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;
  18338. if (!Number.isFinite(ts) || !Number.isFinite(secs) || !Number.isFinite(mins) || !Number.isFinite(hours)) {
  18339. return -1;
  18340. }
  18341. ts += 1000 * secs;
  18342. ts += 60 * 1000 * mins;
  18343. ts += 60 * 60 * 1000 * hours;
  18344. return ts;
  18345. };
  18346. // From https://github.com/darkskyapp/string-hash
  18347. var hash = function hash(text) {
  18348. var hash = 5381;
  18349. var i = text.length;
  18350. while (i) {
  18351. hash = hash * 33 ^ text.charCodeAt(--i);
  18352. }
  18353. return (hash >>> 0).toString();
  18354. };
  18355. var calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {
  18356. var currCC = vttCCs[cc];
  18357. var prevCC = vttCCs[currCC.prevCC];
  18358. // This is the first discontinuity or cues have been processed since the last discontinuity
  18359. // Offset = current discontinuity time
  18360. if (!prevCC || !prevCC.new && currCC.new) {
  18361. vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
  18362. currCC.new = false;
  18363. return;
  18364. }
  18365. // There have been discontinuities since cues were last parsed.
  18366. // Offset = time elapsed
  18367. while (prevCC && prevCC.new) {
  18368. vttCCs.ccOffset += currCC.start - prevCC.start;
  18369. currCC.new = false;
  18370. currCC = prevCC;
  18371. prevCC = vttCCs[currCC.prevCC];
  18372. }
  18373. vttCCs.presentationOffset = presentationTime;
  18374. };
  18375. var WebVTTParser = {
  18376. parse: function parse(vttByteArray, syncPTS, vttCCs, cc, callBack, errorCallBack) {
  18377. // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character.
  18378. var re = /\r\n|\n\r|\n|\r/g;
  18379. // Uint8Array.prototype.reduce is not implemented in IE11
  18380. var vttLines = (0, _id.utf8ArrayToStr)(new Uint8Array(vttByteArray)).trim().replace(re, '\n').split('\n');
  18381. var cueTime = '00:00.000';
  18382. var mpegTs = 0;
  18383. var localTime = 0;
  18384. var presentationTime = 0;
  18385. var cues = [];
  18386. var parsingError = void 0;
  18387. var inHeader = true;
  18388. // let VTTCue = VTTCue || window.TextTrackCue;
  18389. // Create parser object using VTTCue with TextTrackCue fallback on certain browsers.
  18390. var parser = new _vttparser2.default();
  18391. parser.oncue = function (cue) {
  18392. // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.
  18393. var currCC = vttCCs[cc];
  18394. var cueOffset = vttCCs.ccOffset;
  18395. // Update offsets for new discontinuities
  18396. if (currCC && currCC.new) {
  18397. if (localTime !== undefined) {
  18398. // When local time is provided, offset = discontinuity start time - local time
  18399. cueOffset = vttCCs.ccOffset = currCC.start;
  18400. } else {
  18401. calculateOffset(vttCCs, cc, presentationTime);
  18402. }
  18403. }
  18404. if (presentationTime) {
  18405. // If we have MPEGTS, offset = presentation time + discontinuity offset
  18406. cueOffset = presentationTime - vttCCs.presentationOffset;
  18407. }
  18408. cue.startTime += cueOffset - localTime;
  18409. cue.endTime += cueOffset - localTime;
  18410. // Create a unique hash id for a cue based on start/end times and text.
  18411. // This helps timeline-controller to avoid showing repeated captions.
  18412. cue.id = hash(cue.startTime.toString()) + hash(cue.endTime.toString()) + hash(cue.text);
  18413. // Fix encoding of special characters. TODO: Test with all sorts of weird characters.
  18414. cue.text = decodeURIComponent(encodeURIComponent(cue.text));
  18415. if (cue.endTime > 0) {
  18416. cues.push(cue);
  18417. }
  18418. };
  18419. parser.onparsingerror = function (e) {
  18420. parsingError = e;
  18421. };
  18422. parser.onflush = function () {
  18423. if (parsingError && errorCallBack) {
  18424. errorCallBack(parsingError);
  18425. return;
  18426. }
  18427. callBack(cues);
  18428. };
  18429. // Go through contents line by line.
  18430. vttLines.forEach(function (line) {
  18431. if (inHeader) {
  18432. // Look for X-TIMESTAMP-MAP in header.
  18433. if (startsWith(line, 'X-TIMESTAMP-MAP=')) {
  18434. // Once found, no more are allowed anyway, so stop searching.
  18435. inHeader = false;
  18436. // Extract LOCAL and MPEGTS.
  18437. line.substr(16).split(',').forEach(function (timestamp) {
  18438. if (startsWith(timestamp, 'LOCAL:')) {
  18439. cueTime = timestamp.substr(6);
  18440. } else if (startsWith(timestamp, 'MPEGTS:')) {
  18441. mpegTs = parseInt(timestamp.substr(7));
  18442. }
  18443. });
  18444. try {
  18445. // Calculate subtitle offset in milliseconds.
  18446. if (syncPTS + (vttCCs[cc].start * 90000 || 0) < 0) {
  18447. syncPTS += 8589934592;
  18448. }
  18449. // Adjust MPEGTS by sync PTS.
  18450. mpegTs -= syncPTS;
  18451. // Convert cue time to seconds
  18452. localTime = cueString2millis(cueTime) / 1000;
  18453. // Convert MPEGTS to seconds from 90kHz.
  18454. presentationTime = mpegTs / 90000;
  18455. if (localTime === -1) {
  18456. parsingError = new Error('Malformed X-TIMESTAMP-MAP: ' + line);
  18457. }
  18458. } catch (e) {
  18459. parsingError = new Error('Malformed X-TIMESTAMP-MAP: ' + line);
  18460. }
  18461. // Return without parsing X-TIMESTAMP-MAP line.
  18462. return;
  18463. } else if (line === '') {
  18464. inHeader = false;
  18465. }
  18466. }
  18467. // Parse line by default.
  18468. parser.parse(line + '\n');
  18469. });
  18470. parser.flush();
  18471. }
  18472. };
  18473. exports.default = WebVTTParser;
  18474. module.exports = exports['default'];
  18475. /***/ }),
  18476. /* 76 */
  18477. /***/ (function(module, exports, __webpack_require__) {
  18478. "use strict";
  18479. Object.defineProperty(exports, "__esModule", {
  18480. value: true
  18481. });
  18482. 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; }; }();
  18483. var _events = __webpack_require__(1);
  18484. var _events2 = _interopRequireDefault(_events);
  18485. var _eventHandler = __webpack_require__(3);
  18486. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  18487. var _logger = __webpack_require__(0);
  18488. var _levelHelper = __webpack_require__(7);
  18489. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  18490. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  18491. 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; }
  18492. 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; }
  18493. var SubtitleTrackController = function (_EventHandler) {
  18494. _inherits(SubtitleTrackController, _EventHandler);
  18495. function SubtitleTrackController(hls) {
  18496. _classCallCheck(this, SubtitleTrackController);
  18497. var _this = _possibleConstructorReturn(this, (SubtitleTrackController.__proto__ || Object.getPrototypeOf(SubtitleTrackController)).call(this, hls, _events2.default.MEDIA_ATTACHED, _events2.default.MEDIA_DETACHING, _events2.default.MANIFEST_LOADED, _events2.default.SUBTITLE_TRACK_LOADED));
  18498. _this.tracks = [];
  18499. _this.trackId = -1;
  18500. _this.media = null;
  18501. _this.stopped = true;
  18502. /**
  18503. * @member {boolean} subtitleDisplay Enable/disable subtitle display rendering
  18504. */
  18505. _this.subtitleDisplay = true;
  18506. return _this;
  18507. }
  18508. _createClass(SubtitleTrackController, [{
  18509. key: 'destroy',
  18510. value: function destroy() {
  18511. _eventHandler2.default.prototype.destroy.call(this);
  18512. }
  18513. // Listen for subtitle track change, then extract the current track ID.
  18514. }, {
  18515. key: 'onMediaAttached',
  18516. value: function onMediaAttached(data) {
  18517. var _this2 = this;
  18518. this.media = data.media;
  18519. if (!this.media) {
  18520. return;
  18521. }
  18522. if (this.queuedDefaultTrack) {
  18523. this.subtitleTrack = this.queuedDefaultTrack;
  18524. delete this.queuedDefaultTrack;
  18525. }
  18526. this.trackChangeListener = this._onTextTracksChanged.bind(this);
  18527. this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);
  18528. if (this.useTextTrackPolling) {
  18529. this.subtitlePollingInterval = setInterval(function () {
  18530. _this2.trackChangeListener();
  18531. }, 500);
  18532. } else {
  18533. this.media.textTracks.addEventListener('change', this.trackChangeListener);
  18534. }
  18535. }
  18536. }, {
  18537. key: 'onMediaDetaching',
  18538. value: function onMediaDetaching() {
  18539. if (!this.media) {
  18540. return;
  18541. }
  18542. if (this.useTextTrackPolling) {
  18543. clearInterval(this.subtitlePollingInterval);
  18544. } else {
  18545. this.media.textTracks.removeEventListener('change', this.trackChangeListener);
  18546. }
  18547. this.media = null;
  18548. }
  18549. // Fired whenever a new manifest is loaded.
  18550. }, {
  18551. key: 'onManifestLoaded',
  18552. value: function onManifestLoaded(data) {
  18553. var _this3 = this;
  18554. var tracks = data.subtitles || [];
  18555. this.tracks = tracks;
  18556. this.hls.trigger(_events2.default.SUBTITLE_TRACKS_UPDATED, { subtitleTracks: tracks });
  18557. // loop through available subtitle tracks and autoselect default if needed
  18558. // TODO: improve selection logic to handle forced, etc
  18559. tracks.forEach(function (track) {
  18560. if (track.default) {
  18561. // setting this.subtitleTrack will trigger internal logic
  18562. // if media has not been attached yet, it will fail
  18563. // we keep a reference to the default track id
  18564. // and we'll set subtitleTrack when onMediaAttached is triggered
  18565. if (_this3.media) {
  18566. _this3.subtitleTrack = track.id;
  18567. } else {
  18568. _this3.queuedDefaultTrack = track.id;
  18569. }
  18570. }
  18571. });
  18572. }
  18573. }, {
  18574. key: 'onSubtitleTrackLoaded',
  18575. value: function onSubtitleTrackLoaded(data) {
  18576. var _this4 = this;
  18577. var id = data.id,
  18578. details = data.details;
  18579. var trackId = this.trackId,
  18580. tracks = this.tracks;
  18581. var currentTrack = tracks[trackId];
  18582. if (id >= tracks.length || id !== trackId || !currentTrack || this.stopped) {
  18583. this._clearReloadTimer();
  18584. return;
  18585. }
  18586. _logger.logger.log('subtitle track ' + id + ' loaded');
  18587. if (details.live) {
  18588. var reloadInterval = (0, _levelHelper.computeReloadInterval)(currentTrack.details, details, data.stats.trequest);
  18589. _logger.logger.log('Reloading live subtitle playlist in ' + reloadInterval + 'ms');
  18590. this.timer = setTimeout(function () {
  18591. _this4._loadCurrentTrack();
  18592. }, reloadInterval);
  18593. } else {
  18594. this._clearReloadTimer();
  18595. }
  18596. }
  18597. }, {
  18598. key: 'startLoad',
  18599. value: function startLoad() {
  18600. this.stopped = false;
  18601. this._loadCurrentTrack();
  18602. }
  18603. }, {
  18604. key: 'stopLoad',
  18605. value: function stopLoad() {
  18606. this.stopped = true;
  18607. this._clearReloadTimer();
  18608. }
  18609. /** get alternate subtitle tracks list from playlist **/
  18610. }, {
  18611. key: '_clearReloadTimer',
  18612. value: function _clearReloadTimer() {
  18613. if (this.timer) {
  18614. clearTimeout(this.timer);
  18615. this.timer = null;
  18616. }
  18617. }
  18618. }, {
  18619. key: '_loadCurrentTrack',
  18620. value: function _loadCurrentTrack() {
  18621. var trackId = this.trackId,
  18622. tracks = this.tracks,
  18623. hls = this.hls;
  18624. var currentTrack = tracks[trackId];
  18625. if (trackId < 0 || !currentTrack || currentTrack.details && !currentTrack.details.live) {
  18626. return;
  18627. }
  18628. _logger.logger.log('Loading subtitle track ' + trackId);
  18629. hls.trigger(_events2.default.SUBTITLE_TRACK_LOADING, { url: currentTrack.url, id: trackId });
  18630. }
  18631. /**
  18632. * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
  18633. * This operates on the DOM textTracks.
  18634. * A value of -1 will disable all subtitle tracks.
  18635. * @param newId - The id of the next track to enable
  18636. * @private
  18637. */
  18638. }, {
  18639. key: '_toggleTrackModes',
  18640. value: function _toggleTrackModes(newId) {
  18641. var media = this.media,
  18642. subtitleDisplay = this.subtitleDisplay,
  18643. trackId = this.trackId;
  18644. if (!media) {
  18645. return;
  18646. }
  18647. var textTracks = filterSubtitleTracks(media.textTracks);
  18648. if (newId === -1) {
  18649. [].slice.call(textTracks).forEach(function (track) {
  18650. track.mode = 'disabled';
  18651. });
  18652. } else {
  18653. var oldTrack = textTracks[trackId];
  18654. if (oldTrack) {
  18655. oldTrack.mode = 'disabled';
  18656. }
  18657. }
  18658. var nextTrack = textTracks[newId];
  18659. if (nextTrack) {
  18660. nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden';
  18661. }
  18662. }
  18663. /**
  18664. * This method is responsible for validating the subtitle index and periodically reloading if live.
  18665. * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
  18666. * @param newId - The id of the subtitle track to activate.
  18667. */
  18668. }, {
  18669. key: '_setSubtitleTrackInternal',
  18670. value: function _setSubtitleTrackInternal(newId) {
  18671. var hls = this.hls,
  18672. tracks = this.tracks;
  18673. if (!Number.isFinite(newId) || newId < -1 || newId >= tracks.length) {
  18674. return;
  18675. }
  18676. this.trackId = newId;
  18677. _logger.logger.log('Switching to subtitle track ' + newId);
  18678. hls.trigger(_events2.default.SUBTITLE_TRACK_SWITCH, { id: newId });
  18679. this._loadCurrentTrack();
  18680. }
  18681. }, {
  18682. key: '_onTextTracksChanged',
  18683. value: function _onTextTracksChanged() {
  18684. // Media is undefined when switching streams via loadSource()
  18685. if (!this.media) {
  18686. return;
  18687. }
  18688. var trackId = -1;
  18689. var tracks = filterSubtitleTracks(this.media.textTracks);
  18690. for (var id = 0; id < tracks.length; id++) {
  18691. if (tracks[id].mode === 'hidden') {
  18692. // Do not break in case there is a following track with showing.
  18693. trackId = id;
  18694. } else if (tracks[id].mode === 'showing') {
  18695. trackId = id;
  18696. break;
  18697. }
  18698. }
  18699. // Setting current subtitleTrack will invoke code.
  18700. this.subtitleTrack = trackId;
  18701. }
  18702. }, {
  18703. key: 'subtitleTracks',
  18704. get: function get() {
  18705. return this.tracks;
  18706. }
  18707. /** get index of the selected subtitle track (index in subtitle track lists) **/
  18708. }, {
  18709. key: 'subtitleTrack',
  18710. get: function get() {
  18711. return this.trackId;
  18712. }
  18713. /** select a subtitle track, based on its index in subtitle track lists**/
  18714. ,
  18715. set: function set(subtitleTrackId) {
  18716. if (this.trackId !== subtitleTrackId) {
  18717. this._toggleTrackModes(subtitleTrackId);
  18718. this._setSubtitleTrackInternal(subtitleTrackId);
  18719. }
  18720. }
  18721. }]);
  18722. return SubtitleTrackController;
  18723. }(_eventHandler2.default);
  18724. function filterSubtitleTracks(textTrackList) {
  18725. var tracks = [];
  18726. for (var i = 0; i < textTrackList.length; i++) {
  18727. var track = textTrackList[i];
  18728. // Edge adds a track without a label; we don't want to use it
  18729. if (track.kind === 'subtitles' && track.label) {
  18730. tracks.push(textTrackList[i]);
  18731. }
  18732. }
  18733. return tracks;
  18734. }
  18735. exports.default = SubtitleTrackController;
  18736. module.exports = exports['default'];
  18737. /***/ }),
  18738. /* 77 */
  18739. /***/ (function(module, exports, __webpack_require__) {
  18740. "use strict";
  18741. Object.defineProperty(exports, "__esModule", {
  18742. value: true
  18743. });
  18744. exports.SubtitleStreamController = undefined;
  18745. 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; }; }();
  18746. 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); } };
  18747. var _events = __webpack_require__(1);
  18748. var _events2 = _interopRequireDefault(_events);
  18749. var _logger = __webpack_require__(0);
  18750. var _decrypter = __webpack_require__(12);
  18751. var _decrypter2 = _interopRequireDefault(_decrypter);
  18752. var _bufferHelper = __webpack_require__(4);
  18753. var _fragmentFinders = __webpack_require__(27);
  18754. var _fragmentTracker = __webpack_require__(6);
  18755. var _baseStreamController = __webpack_require__(14);
  18756. var _baseStreamController2 = _interopRequireDefault(_baseStreamController);
  18757. var _levelHelper = __webpack_require__(7);
  18758. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  18759. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  18760. 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; }
  18761. 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; } /**
  18762. * @class SubtitleStreamController
  18763. */
  18764. var _window = window,
  18765. performance = _window.performance;
  18766. var TICK_INTERVAL = 500; // how often to tick in ms
  18767. var SubtitleStreamController = exports.SubtitleStreamController = function (_BaseStreamController) {
  18768. _inherits(SubtitleStreamController, _BaseStreamController);
  18769. function SubtitleStreamController(hls, fragmentTracker) {
  18770. _classCallCheck(this, SubtitleStreamController);
  18771. var _this = _possibleConstructorReturn(this, (SubtitleStreamController.__proto__ || Object.getPrototypeOf(SubtitleStreamController)).call(this, hls, _events2.default.MEDIA_ATTACHED, _events2.default.MEDIA_DETACHING, _events2.default.ERROR, _events2.default.KEY_LOADED, _events2.default.FRAG_LOADED, _events2.default.SUBTITLE_TRACKS_UPDATED, _events2.default.SUBTITLE_TRACK_SWITCH, _events2.default.SUBTITLE_TRACK_LOADED, _events2.default.SUBTITLE_FRAG_PROCESSED, _events2.default.LEVEL_UPDATED));
  18772. _this.fragmentTracker = fragmentTracker;
  18773. _this.config = hls.config;
  18774. _this.state = _baseStreamController.State.STOPPED;
  18775. _this.tracks = [];
  18776. _this.tracksBuffered = [];
  18777. _this.currentTrackId = -1;
  18778. _this.decrypter = new _decrypter2.default(hls, hls.config);
  18779. // lastAVStart stores the time in seconds for the start time of a level load
  18780. _this.lastAVStart = 0;
  18781. _this._onMediaSeeking = _this.onMediaSeeking.bind(_this);
  18782. return _this;
  18783. }
  18784. _createClass(SubtitleStreamController, [{
  18785. key: 'onSubtitleFragProcessed',
  18786. value: function onSubtitleFragProcessed(data) {
  18787. var frag = data.frag,
  18788. success = data.success;
  18789. this.fragPrevious = frag;
  18790. this.state = _baseStreamController.State.IDLE;
  18791. if (!success) {
  18792. return;
  18793. }
  18794. var buffered = this.tracksBuffered[this.currentTrackId];
  18795. if (!buffered) {
  18796. return;
  18797. }
  18798. // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo
  18799. // so we can re-use the logic used to detect how much have been buffered
  18800. var timeRange = void 0;
  18801. var fragStart = frag.start;
  18802. for (var i = 0; i < buffered.length; i++) {
  18803. if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
  18804. timeRange = buffered[i];
  18805. break;
  18806. }
  18807. }
  18808. var fragEnd = frag.start + frag.duration;
  18809. if (timeRange) {
  18810. timeRange.end = fragEnd;
  18811. } else {
  18812. timeRange = {
  18813. start: fragStart,
  18814. end: fragEnd
  18815. };
  18816. buffered.push(timeRange);
  18817. }
  18818. }
  18819. }, {
  18820. key: 'onMediaAttached',
  18821. value: function onMediaAttached(_ref) {
  18822. var media = _ref.media;
  18823. this.media = media;
  18824. media.addEventListener('seeking', this._onMediaSeeking);
  18825. this.state = _baseStreamController.State.IDLE;
  18826. }
  18827. }, {
  18828. key: 'onMediaDetaching',
  18829. value: function onMediaDetaching() {
  18830. this.media.removeEventListener('seeking', this._onMediaSeeking);
  18831. this.media = null;
  18832. this.state = _baseStreamController.State.STOPPED;
  18833. }
  18834. // If something goes wrong, proceed to next frag, if we were processing one.
  18835. }, {
  18836. key: 'onError',
  18837. value: function onError(data) {
  18838. var frag = data.frag;
  18839. // don't handle error not related to subtitle fragment
  18840. if (!frag || frag.type !== 'subtitle') {
  18841. return;
  18842. }
  18843. this.state = _baseStreamController.State.IDLE;
  18844. }
  18845. // Got all new subtitle tracks.
  18846. }, {
  18847. key: 'onSubtitleTracksUpdated',
  18848. value: function onSubtitleTracksUpdated(data) {
  18849. var _this2 = this;
  18850. _logger.logger.log('subtitle tracks updated');
  18851. this.tracksBuffered = [];
  18852. this.tracks = data.subtitleTracks;
  18853. this.tracks.forEach(function (track) {
  18854. _this2.tracksBuffered[track.id] = [];
  18855. });
  18856. }
  18857. }, {
  18858. key: 'onSubtitleTrackSwitch',
  18859. value: function onSubtitleTrackSwitch(data) {
  18860. this.currentTrackId = data.id;
  18861. if (!this.tracks || this.currentTrackId === -1) {
  18862. this.clearInterval();
  18863. return;
  18864. }
  18865. // Check if track has the necessary details to load fragments
  18866. var currentTrack = this.tracks[this.currentTrackId];
  18867. if (currentTrack && currentTrack.details) {
  18868. this.setInterval(TICK_INTERVAL);
  18869. }
  18870. }
  18871. // Got a new set of subtitle fragments.
  18872. }, {
  18873. key: 'onSubtitleTrackLoaded',
  18874. value: function onSubtitleTrackLoaded(data) {
  18875. var id = data.id,
  18876. details = data.details;
  18877. var currentTrackId = this.currentTrackId,
  18878. tracks = this.tracks;
  18879. var currentTrack = tracks[currentTrackId];
  18880. if (id >= tracks.length || id !== currentTrackId || !currentTrack) {
  18881. return;
  18882. }
  18883. if (details.live) {
  18884. (0, _levelHelper.mergeSubtitlePlaylists)(currentTrack.details, details, this.lastAVStart);
  18885. }
  18886. currentTrack.details = details;
  18887. this.setInterval(TICK_INTERVAL);
  18888. }
  18889. }, {
  18890. key: 'onKeyLoaded',
  18891. value: function onKeyLoaded() {
  18892. if (this.state === _baseStreamController.State.KEY_LOADING) {
  18893. this.state = _baseStreamController.State.IDLE;
  18894. }
  18895. }
  18896. }, {
  18897. key: 'onFragLoaded',
  18898. value: function onFragLoaded(data) {
  18899. var fragCurrent = this.fragCurrent;
  18900. var decryptData = data.frag.decryptdata;
  18901. var fragLoaded = data.frag;
  18902. var hls = this.hls;
  18903. if (this.state === _baseStreamController.State.FRAG_LOADING && fragCurrent && data.frag.type === 'subtitle' && fragCurrent.sn === data.frag.sn) {
  18904. // check to see if the payload needs to be decrypted
  18905. if (data.payload.byteLength > 0 && decryptData && decryptData.key && decryptData.method === 'AES-128') {
  18906. var startTime = performance.now();
  18907. // decrypt the subtitles
  18908. this.decrypter.decrypt(data.payload, decryptData.key.buffer, decryptData.iv.buffer, function (decryptedData) {
  18909. var endTime = performance.now();
  18910. hls.trigger(_events2.default.FRAG_DECRYPTED, { frag: fragLoaded, payload: decryptedData, stats: { tstart: startTime, tdecrypt: endTime } });
  18911. });
  18912. }
  18913. }
  18914. }
  18915. }, {
  18916. key: 'onLevelUpdated',
  18917. value: function onLevelUpdated(_ref2) {
  18918. var details = _ref2.details;
  18919. var frags = details.fragments;
  18920. this.lastAVStart = frags.length ? frags[0].start : 0;
  18921. }
  18922. }, {
  18923. key: 'doTick',
  18924. value: function doTick() {
  18925. if (!this.media) {
  18926. this.state = _baseStreamController.State.IDLE;
  18927. return;
  18928. }
  18929. switch (this.state) {
  18930. case _baseStreamController.State.IDLE:
  18931. {
  18932. var config = this.config,
  18933. currentTrackId = this.currentTrackId,
  18934. fragmentTracker = this.fragmentTracker,
  18935. media = this.media,
  18936. tracks = this.tracks;
  18937. if (!tracks || !tracks[currentTrackId] || !tracks[currentTrackId].details) {
  18938. break;
  18939. }
  18940. var maxBufferHole = config.maxBufferHole,
  18941. maxFragLookUpTolerance = config.maxFragLookUpTolerance;
  18942. var maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);
  18943. var bufferedInfo = _bufferHelper.BufferHelper.bufferedInfo(this._getBuffered(), media.currentTime, maxBufferHole);
  18944. var bufferEnd = bufferedInfo.end,
  18945. bufferLen = bufferedInfo.len;
  18946. var trackDetails = tracks[currentTrackId].details;
  18947. var fragments = trackDetails.fragments;
  18948. var fragLen = fragments.length;
  18949. var end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration;
  18950. if (bufferLen > maxConfigBuffer) {
  18951. return;
  18952. }
  18953. var foundFrag = void 0;
  18954. var fragPrevious = this.fragPrevious;
  18955. if (bufferEnd < end) {
  18956. if (fragPrevious && trackDetails.hasProgramDateTime) {
  18957. foundFrag = (0, _fragmentFinders.findFragmentByPDT)(fragments, fragPrevious.endProgramDateTime, maxFragLookUpTolerance);
  18958. }
  18959. if (!foundFrag) {
  18960. foundFrag = (0, _fragmentFinders.findFragmentByPTS)(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance);
  18961. }
  18962. } else {
  18963. foundFrag = fragments[fragLen - 1];
  18964. }
  18965. if (foundFrag && foundFrag.encrypted) {
  18966. _logger.logger.log('Loading key for ' + foundFrag.sn);
  18967. this.state = _baseStreamController.State.KEY_LOADING;
  18968. this.hls.trigger(_events2.default.KEY_LOADING, { frag: foundFrag });
  18969. } else if (foundFrag && fragmentTracker.getState(foundFrag) === _fragmentTracker.FragmentState.NOT_LOADED) {
  18970. // only load if fragment is not loaded
  18971. this.fragCurrent = foundFrag;
  18972. this.state = _baseStreamController.State.FRAG_LOADING;
  18973. this.hls.trigger(_events2.default.FRAG_LOADING, { frag: foundFrag });
  18974. }
  18975. }
  18976. }
  18977. }
  18978. }, {
  18979. key: 'stopLoad',
  18980. value: function stopLoad() {
  18981. this.lastAVStart = 0;
  18982. _get(SubtitleStreamController.prototype.__proto__ || Object.getPrototypeOf(SubtitleStreamController.prototype), 'stopLoad', this).call(this);
  18983. }
  18984. }, {
  18985. key: '_getBuffered',
  18986. value: function _getBuffered() {
  18987. return this.tracksBuffered[this.currentTrackId] || [];
  18988. }
  18989. }, {
  18990. key: 'onMediaSeeking',
  18991. value: function onMediaSeeking() {
  18992. this.fragPrevious = null;
  18993. }
  18994. }]);
  18995. return SubtitleStreamController;
  18996. }(_baseStreamController2.default);
  18997. /***/ }),
  18998. /* 78 */
  18999. /***/ (function(module, exports, __webpack_require__) {
  19000. "use strict";
  19001. Object.defineProperty(exports, "__esModule", {
  19002. value: true
  19003. });
  19004. 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; }; }();
  19005. var _eventHandler = __webpack_require__(3);
  19006. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  19007. var _events = __webpack_require__(1);
  19008. var _events2 = _interopRequireDefault(_events);
  19009. var _errors = __webpack_require__(2);
  19010. var _logger = __webpack_require__(0);
  19011. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  19012. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  19013. 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; }
  19014. 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; } /**
  19015. * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>
  19016. *
  19017. * DRM support for Hls.js
  19018. */
  19019. var _window = window,
  19020. XMLHttpRequest = _window.XMLHttpRequest;
  19021. var MAX_LICENSE_REQUEST_FAILURES = 3;
  19022. /**
  19023. * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess
  19024. */
  19025. var KeySystems = {
  19026. WIDEVINE: 'com.widevine.alpha',
  19027. PLAYREADY: 'com.microsoft.playready'
  19028. };
  19029. /**
  19030. * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration
  19031. * @param {Array<string>} audioCodecs List of required audio codecs to support
  19032. * @param {Array<string>} videoCodecs List of required video codecs to support
  19033. * @param {object} drmSystemOptions Optional parameters/requirements for the key-system
  19034. * @returns {Array<MediaSystemConfiguration>} An array of supported configurations
  19035. */
  19036. var createWidevineMediaKeySystemConfigurations = function createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions) {
  19037. /* jshint ignore:line */
  19038. var baseConfig = {
  19039. // initDataTypes: ['keyids', 'mp4'],
  19040. // label: "",
  19041. // persistentState: "not-allowed", // or "required" ?
  19042. // distinctiveIdentifier: "not-allowed", // or "required" ?
  19043. // sessionTypes: ['temporary'],
  19044. videoCapabilities: [
  19045. // { contentType: 'video/mp4; codecs="avc1.42E01E"' }
  19046. ]
  19047. };
  19048. videoCodecs.forEach(function (codec) {
  19049. baseConfig.videoCapabilities.push({
  19050. contentType: 'video/mp4; codecs="' + codec + '"'
  19051. });
  19052. });
  19053. return [baseConfig];
  19054. };
  19055. /**
  19056. * The idea here is to handle key-system (and their respective platforms) specific configuration differences
  19057. * in order to work with the local requestMediaKeySystemAccess method.
  19058. *
  19059. * We can also rule-out platform-related key-system support at this point by throwing an error or returning null.
  19060. *
  19061. * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
  19062. * @param {Array<string>} audioCodecs List of required audio codecs to support
  19063. * @param {Array<string>} videoCodecs List of required video codecs to support
  19064. * @returns {Array<MediaSystemConfiguration> | null} A non-empty Array of MediaKeySystemConfiguration objects or `null`
  19065. */
  19066. var getSupportedMediaKeySystemConfigurations = function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs) {
  19067. switch (keySystem) {
  19068. case KeySystems.WIDEVINE:
  19069. return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs);
  19070. default:
  19071. throw Error('Unknown key-system: ' + keySystem);
  19072. }
  19073. };
  19074. /**
  19075. * Controller to deal with encrypted media extensions (EME)
  19076. * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API
  19077. *
  19078. * @class
  19079. * @constructor
  19080. */
  19081. var EMEController = function (_EventHandler) {
  19082. _inherits(EMEController, _EventHandler);
  19083. /**
  19084. * @constructs
  19085. * @param {Hls} hls Our Hls.js instance
  19086. */
  19087. function EMEController(hls) {
  19088. _classCallCheck(this, EMEController);
  19089. var _this = _possibleConstructorReturn(this, (EMEController.__proto__ || Object.getPrototypeOf(EMEController)).call(this, hls, _events2.default.MEDIA_ATTACHED, _events2.default.MANIFEST_PARSED));
  19090. _this._widevineLicenseUrl = hls.config.widevineLicenseUrl;
  19091. _this._licenseXhrSetup = hls.config.licenseXhrSetup;
  19092. _this._emeEnabled = hls.config.emeEnabled;
  19093. _this._requestMediaKeySystemAccess = hls.config.requestMediaKeySystemAccessFunc;
  19094. _this._mediaKeysList = [];
  19095. _this._media = null;
  19096. _this._hasSetMediaKeys = false;
  19097. _this._isMediaEncrypted = false;
  19098. _this._requestLicenseFailureCount = 0;
  19099. return _this;
  19100. }
  19101. /**
  19102. *
  19103. * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
  19104. * @returns {string} License server URL for key-system (if any configured, otherwise causes error)
  19105. */
  19106. _createClass(EMEController, [{
  19107. key: 'getLicenseServerUrl',
  19108. value: function getLicenseServerUrl(keySystem) {
  19109. var url = void 0;
  19110. switch (keySystem) {
  19111. case KeySystems.WIDEVINE:
  19112. url = this._widevineLicenseUrl;
  19113. break;
  19114. default:
  19115. url = null;
  19116. break;
  19117. }
  19118. if (!url) {
  19119. _logger.logger.error('No license server URL configured for key-system "' + keySystem + '"');
  19120. this.hls.trigger(_events2.default.ERROR, {
  19121. type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
  19122. details: _errors.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  19123. fatal: true
  19124. });
  19125. }
  19126. return url;
  19127. }
  19128. /**
  19129. * Requests access object and adds it to our list upon success
  19130. * @private
  19131. * @param {string} keySystem System ID (see `KeySystems`)
  19132. * @param {Array<string>} audioCodecs List of required audio codecs to support
  19133. * @param {Array<string>} videoCodecs List of required video codecs to support
  19134. */
  19135. }, {
  19136. key: '_attemptKeySystemAccess',
  19137. value: function _attemptKeySystemAccess(keySystem, audioCodecs, videoCodecs) {
  19138. var _this2 = this;
  19139. // TODO: add other DRM "options"
  19140. var mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs);
  19141. if (!mediaKeySystemConfigs) {
  19142. _logger.logger.warn('Can not create config for key-system (maybe because platform is not supported):', keySystem);
  19143. return;
  19144. }
  19145. _logger.logger.log('Requesting encrypted media key-system access');
  19146. // expecting interface like window.navigator.requestMediaKeySystemAccess
  19147. this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs).then(function (mediaKeySystemAccess) {
  19148. _this2._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);
  19149. }).catch(function (err) {
  19150. _logger.logger.error('Failed to obtain key-system "' + keySystem + '" access:', err);
  19151. });
  19152. }
  19153. }, {
  19154. key: '_onMediaKeySystemAccessObtained',
  19155. /**
  19156. * Handles obtaining access to a key-system
  19157. *
  19158. * @param {string} keySystem
  19159. * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess
  19160. */
  19161. value: function _onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess) {
  19162. var _this3 = this;
  19163. _logger.logger.log('Access for key-system "' + keySystem + '" obtained');
  19164. var mediaKeysListItem = {
  19165. mediaKeys: null,
  19166. mediaKeysSession: null,
  19167. mediaKeysSessionInitialized: false,
  19168. mediaKeySystemAccess: mediaKeySystemAccess,
  19169. mediaKeySystemDomain: keySystem
  19170. };
  19171. this._mediaKeysList.push(mediaKeysListItem);
  19172. mediaKeySystemAccess.createMediaKeys().then(function (mediaKeys) {
  19173. mediaKeysListItem.mediaKeys = mediaKeys;
  19174. _logger.logger.log('Media-keys created for key-system "' + keySystem + '"');
  19175. _this3._onMediaKeysCreated();
  19176. }).catch(function (err) {
  19177. _logger.logger.error('Failed to create media-keys:', err);
  19178. });
  19179. }
  19180. /**
  19181. * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this
  19182. * for all existing keys where no session exists yet.
  19183. */
  19184. }, {
  19185. key: '_onMediaKeysCreated',
  19186. value: function _onMediaKeysCreated() {
  19187. var _this4 = this;
  19188. // check for all key-list items if a session exists, otherwise, create one
  19189. this._mediaKeysList.forEach(function (mediaKeysListItem) {
  19190. if (!mediaKeysListItem.mediaKeysSession) {
  19191. mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession();
  19192. _this4._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);
  19193. }
  19194. });
  19195. }
  19196. /**
  19197. *
  19198. * @param {*} keySession
  19199. */
  19200. }, {
  19201. key: '_onNewMediaKeySession',
  19202. value: function _onNewMediaKeySession(keySession) {
  19203. var _this5 = this;
  19204. _logger.logger.log('New key-system session ' + keySession.sessionId);
  19205. keySession.addEventListener('message', function (event) {
  19206. _this5._onKeySessionMessage(keySession, event.message);
  19207. }, false);
  19208. }
  19209. }, {
  19210. key: '_onKeySessionMessage',
  19211. value: function _onKeySessionMessage(keySession, message) {
  19212. _logger.logger.log('Got EME message event, creating license request');
  19213. this._requestLicense(message, function (data) {
  19214. _logger.logger.log('Received license data, updating key-session');
  19215. keySession.update(data);
  19216. });
  19217. }
  19218. }, {
  19219. key: '_onMediaEncrypted',
  19220. value: function _onMediaEncrypted(initDataType, initData) {
  19221. _logger.logger.log('Media is encrypted using "' + initDataType + '" init data type');
  19222. this._isMediaEncrypted = true;
  19223. this._mediaEncryptionInitDataType = initDataType;
  19224. this._mediaEncryptionInitData = initData;
  19225. this._attemptSetMediaKeys();
  19226. this._generateRequestWithPreferredKeySession();
  19227. }
  19228. }, {
  19229. key: '_attemptSetMediaKeys',
  19230. value: function _attemptSetMediaKeys() {
  19231. if (!this._hasSetMediaKeys) {
  19232. // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
  19233. var keysListItem = this._mediaKeysList[0];
  19234. if (!keysListItem || !keysListItem.mediaKeys) {
  19235. _logger.logger.error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');
  19236. this.hls.trigger(_events2.default.ERROR, {
  19237. type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
  19238. details: _errors.ErrorDetails.KEY_SYSTEM_NO_KEYS,
  19239. fatal: true
  19240. });
  19241. return;
  19242. }
  19243. _logger.logger.log('Setting keys for encrypted media');
  19244. this._media.setMediaKeys(keysListItem.mediaKeys);
  19245. this._hasSetMediaKeys = true;
  19246. }
  19247. }
  19248. }, {
  19249. key: '_generateRequestWithPreferredKeySession',
  19250. value: function _generateRequestWithPreferredKeySession() {
  19251. var _this6 = this;
  19252. // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
  19253. var keysListItem = this._mediaKeysList[0];
  19254. if (!keysListItem) {
  19255. _logger.logger.error('Fatal: Media is encrypted but not any key-system access has been obtained yet');
  19256. this.hls.trigger(_events2.default.ERROR, {
  19257. type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
  19258. details: _errors.ErrorDetails.KEY_SYSTEM_NO_ACCESS,
  19259. fatal: true
  19260. });
  19261. return;
  19262. }
  19263. if (keysListItem.mediaKeysSessionInitialized) {
  19264. _logger.logger.warn('Key-Session already initialized but requested again');
  19265. return;
  19266. }
  19267. var keySession = keysListItem.mediaKeysSession;
  19268. if (!keySession) {
  19269. _logger.logger.error('Fatal: Media is encrypted but no key-session existing');
  19270. this.hls.trigger(_events2.default.ERROR, {
  19271. type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
  19272. details: _errors.ErrorDetails.KEY_SYSTEM_NO_SESSION,
  19273. fatal: true
  19274. });
  19275. }
  19276. var initDataType = this._mediaEncryptionInitDataType;
  19277. var initData = this._mediaEncryptionInitData;
  19278. _logger.logger.log('Generating key-session request for "' + initDataType + '" init data type');
  19279. keysListItem.mediaKeysSessionInitialized = true;
  19280. keySession.generateRequest(initDataType, initData).then(function () {
  19281. _logger.logger.debug('Key-session generation succeeded');
  19282. }).catch(function (err) {
  19283. _logger.logger.error('Error generating key-session request:', err);
  19284. _this6.hls.trigger(_events2.default.ERROR, {
  19285. type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
  19286. details: _errors.ErrorDetails.KEY_SYSTEM_NO_SESSION,
  19287. fatal: false
  19288. });
  19289. });
  19290. }
  19291. /**
  19292. * @param {string} url License server URL
  19293. * @param {ArrayBuffer} keyMessage Message data issued by key-system
  19294. * @param {function} callback Called when XHR has succeeded
  19295. * @returns {XMLHttpRequest} Unsent (but opened state) XHR object
  19296. */
  19297. }, {
  19298. key: '_createLicenseXhr',
  19299. value: function _createLicenseXhr(url, keyMessage, callback) {
  19300. var xhr = new XMLHttpRequest();
  19301. var licenseXhrSetup = this._licenseXhrSetup;
  19302. try {
  19303. if (licenseXhrSetup) {
  19304. try {
  19305. licenseXhrSetup(xhr, url);
  19306. } catch (e) {
  19307. // let's try to open before running setup
  19308. xhr.open('POST', url, true);
  19309. licenseXhrSetup(xhr, url);
  19310. }
  19311. }
  19312. // if licenseXhrSetup did not yet call open, let's do it now
  19313. if (!xhr.readyState) {
  19314. xhr.open('POST', url, true);
  19315. }
  19316. } catch (e) {
  19317. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  19318. _logger.logger.error('Error setting up key-system license XHR', e);
  19319. this.hls.trigger(_events2.default.ERROR, {
  19320. type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
  19321. details: _errors.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  19322. fatal: true
  19323. });
  19324. return;
  19325. }
  19326. xhr.responseType = 'arraybuffer';
  19327. xhr.onreadystatechange = this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);
  19328. return xhr;
  19329. }
  19330. /**
  19331. * @param {XMLHttpRequest} xhr
  19332. * @param {string} url License server URL
  19333. * @param {ArrayBuffer} keyMessage Message data issued by key-system
  19334. * @param {function} callback Called when XHR has succeeded
  19335. *
  19336. */
  19337. }, {
  19338. key: '_onLicenseRequestReadyStageChange',
  19339. value: function _onLicenseRequestReadyStageChange(xhr, url, keyMessage, callback) {
  19340. switch (xhr.readyState) {
  19341. case 4:
  19342. if (xhr.status === 200) {
  19343. this._requestLicenseFailureCount = 0;
  19344. _logger.logger.log('License request succeeded');
  19345. callback(xhr.response);
  19346. } else {
  19347. _logger.logger.error('License Request XHR failed (' + url + '). Status: ' + xhr.status + ' (' + xhr.statusText + ')');
  19348. this._requestLicenseFailureCount++;
  19349. if (this._requestLicenseFailureCount <= MAX_LICENSE_REQUEST_FAILURES) {
  19350. var attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;
  19351. _logger.logger.warn('Retrying license request, ' + attemptsLeft + ' attempts left');
  19352. this._requestLicense(keyMessage, callback);
  19353. return;
  19354. }
  19355. this.hls.trigger(_events2.default.ERROR, {
  19356. type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
  19357. details: _errors.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  19358. fatal: true
  19359. });
  19360. }
  19361. break;
  19362. }
  19363. }
  19364. /**
  19365. * @param {object} keysListItem
  19366. * @param {ArrayBuffer} keyMessage
  19367. * @returns {ArrayBuffer} Challenge data posted to license server
  19368. */
  19369. }, {
  19370. key: '_generateLicenseRequestChallenge',
  19371. value: function _generateLicenseRequestChallenge(keysListItem, keyMessage) {
  19372. var challenge = void 0;
  19373. if (keysListItem.mediaKeySystemDomain === KeySystems.PLAYREADY) {
  19374. _logger.logger.error('PlayReady is not supported (yet)');
  19375. // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js
  19376. /*
  19377. if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {
  19378. // For PlayReady CDMs, we need to dig the Challenge out of the XML.
  19379. var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');
  19380. if (keyMessageXml.getElementsByTagName('Challenge')[0]) {
  19381. challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);
  19382. } else {
  19383. throw 'Cannot find <Challenge> in key message';
  19384. }
  19385. var headerNames = keyMessageXml.getElementsByTagName('name');
  19386. var headerValues = keyMessageXml.getElementsByTagName('value');
  19387. if (headerNames.length !== headerValues.length) {
  19388. throw 'Mismatched header <name>/<value> pair in key message';
  19389. }
  19390. for (var i = 0; i < headerNames.length; i++) {
  19391. xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);
  19392. }
  19393. }
  19394. */
  19395. } else if (keysListItem.mediaKeySystemDomain === KeySystems.WIDEVINE) {
  19396. // For Widevine CDMs, the challenge is the keyMessage.
  19397. challenge = keyMessage;
  19398. } else {
  19399. _logger.logger.error('Unsupported key-system:', keysListItem.mediaKeySystemDomain);
  19400. }
  19401. return challenge;
  19402. }
  19403. }, {
  19404. key: '_requestLicense',
  19405. value: function _requestLicense(keyMessage, callback) {
  19406. _logger.logger.log('Requesting content license for key-system');
  19407. var keysListItem = this._mediaKeysList[0];
  19408. if (!keysListItem) {
  19409. _logger.logger.error('Fatal error: Media is encrypted but no key-system access has been obtained yet');
  19410. this.hls.trigger(_events2.default.ERROR, {
  19411. type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
  19412. details: _errors.ErrorDetails.KEY_SYSTEM_NO_ACCESS,
  19413. fatal: true
  19414. });
  19415. return;
  19416. }
  19417. var url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);
  19418. var xhr = this._createLicenseXhr(url, keyMessage, callback);
  19419. _logger.logger.log('Sending license request to URL: ' + url);
  19420. xhr.send(this._generateLicenseRequestChallenge(keysListItem, keyMessage));
  19421. }
  19422. }, {
  19423. key: 'onMediaAttached',
  19424. value: function onMediaAttached(data) {
  19425. var _this7 = this;
  19426. if (!this._emeEnabled) {
  19427. return;
  19428. }
  19429. var media = data.media;
  19430. // keep reference of media
  19431. this._media = media;
  19432. // FIXME: also handle detaching media !
  19433. media.addEventListener('encrypted', function (e) {
  19434. _this7._onMediaEncrypted(e.initDataType, e.initData);
  19435. });
  19436. }
  19437. }, {
  19438. key: 'onManifestParsed',
  19439. value: function onManifestParsed(data) {
  19440. if (!this._emeEnabled) {
  19441. return;
  19442. }
  19443. var audioCodecs = data.levels.map(function (level) {
  19444. return level.audioCodec;
  19445. });
  19446. var videoCodecs = data.levels.map(function (level) {
  19447. return level.videoCodec;
  19448. });
  19449. this._attemptKeySystemAccess(KeySystems.WIDEVINE, audioCodecs, videoCodecs);
  19450. }
  19451. }, {
  19452. key: 'requestMediaKeySystemAccess',
  19453. get: function get() {
  19454. if (!this._requestMediaKeySystemAccess) {
  19455. throw new Error('No requestMediaKeySystemAccess function configured');
  19456. }
  19457. return this._requestMediaKeySystemAccess;
  19458. }
  19459. }]);
  19460. return EMEController;
  19461. }(_eventHandler2.default);
  19462. exports.default = EMEController;
  19463. module.exports = exports['default'];
  19464. /***/ }),
  19465. /* 79 */
  19466. /***/ (function(module, exports, __webpack_require__) {
  19467. "use strict";
  19468. Object.defineProperty(exports, "__esModule", {
  19469. value: true
  19470. });
  19471. var requestMediaKeySystemAccess = function () {
  19472. if (typeof window !== 'undefined' && window.navigator && window.navigator.requestMediaKeySystemAccess) {
  19473. return window.navigator.requestMediaKeySystemAccess.bind(window.navigator);
  19474. } else {
  19475. return null;
  19476. }
  19477. }();
  19478. exports.requestMediaKeySystemAccess = requestMediaKeySystemAccess;
  19479. /***/ }),
  19480. /* 80 */
  19481. /***/ (function(module, exports, __webpack_require__) {
  19482. "use strict";
  19483. Object.defineProperty(exports, "__esModule", {
  19484. value: true
  19485. });
  19486. var util = {};
  19487. util.getBrowserVersion = function () {
  19488. var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  19489. if (userAgent.toLowerCase().indexOf("mobile") > -1) {
  19490. return "Unknown";
  19491. }
  19492. if (userAgent.indexOf("Firefox") > -1) {
  19493. var version = userAgent.match(/firefox\/[\d.]+/gi)[0].match(/[\d]+/)[0];
  19494. return "Firefox " + version;
  19495. } else if (userAgent.indexOf("Edge") > -1) {
  19496. var _version = userAgent.match(/edge\/[\d.]+/gi)[0].match(/[\d]+/)[0];
  19497. return "Edge " + _version;
  19498. } else if (userAgent.indexOf("rv:11") > -1) {
  19499. return "IE 11";
  19500. } else if (userAgent.indexOf("Opera") > -1 || userAgent.indexOf("OPR") > -1) {
  19501. if (userAgent.indexOf("Opera") > -1) {
  19502. var _version2 = userAgent.match(/opera\/[\d.]+/gi)[0].match(/[\d]+/)[0];
  19503. return "Opera " + _version2;
  19504. }
  19505. if (userAgent.indexOf("OPR") > -1) {
  19506. var _version3 = userAgent.match(/opr\/[\d.]+/gi)[0].match(/[\d]+/)[0];
  19507. return "Opera " + _version3;
  19508. }
  19509. } else if (userAgent.indexOf("Chrome") > -1) {
  19510. var _version4 = userAgent.match(/chrome\/[\d.]+/gi)[0].match(/[\d]+/)[0];
  19511. return "Chrome " + _version4;
  19512. } else if (userAgent.indexOf("Safari") > -1) {
  19513. var _version5 = userAgent.match(/safari\/[\d.]+/gi)[0].match(/[\d]+/)[0];
  19514. return "Safari " + _version5;
  19515. } else if (userAgent.indexOf("MSIE") > -1 || userAgent.indexOf("Trident") > -1) {
  19516. if (userAgent.indexOf("MSIE") > -1) {
  19517. var _version6 = userAgent.match(/msie [\d.]+/gi)[0].match(/[\d]+/)[0];
  19518. return "IE " + _version6;
  19519. }
  19520. if (userAgent.indexOf("Trident") > -1) {
  19521. var versionTrident = userAgent.match(/trident\/[\d.]+/gi)[0].match(/[\d]+/)[0];
  19522. var _version7 = parseInt(versionTrident) + 4;
  19523. return "IE " + _version7;
  19524. }
  19525. } else {
  19526. return "Unknown";
  19527. }
  19528. };
  19529. exports.default = util;
  19530. module.exports = exports["default"];
  19531. /***/ })
  19532. /******/ ]);
  19533. });
  19534. /***/ }),
  19535. /***/ "90e3":
  19536. /***/ (function(module, exports) {
  19537. var id = 0;
  19538. var postfix = Math.random();
  19539. module.exports = function (key) {
  19540. return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);
  19541. };
  19542. /***/ }),
  19543. /***/ "9112":
  19544. /***/ (function(module, exports, __webpack_require__) {
  19545. var DESCRIPTORS = __webpack_require__("83ab");
  19546. var definePropertyModule = __webpack_require__("9bf2");
  19547. var createPropertyDescriptor = __webpack_require__("5c6c");
  19548. module.exports = DESCRIPTORS ? function (object, key, value) {
  19549. return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
  19550. } : function (object, key, value) {
  19551. object[key] = value;
  19552. return object;
  19553. };
  19554. /***/ }),
  19555. /***/ "94ca":
  19556. /***/ (function(module, exports, __webpack_require__) {
  19557. var fails = __webpack_require__("d039");
  19558. var replacement = /#|\.prototype\./;
  19559. var isForced = function (feature, detection) {
  19560. var value = data[normalize(feature)];
  19561. return value == POLYFILL ? true
  19562. : value == NATIVE ? false
  19563. : typeof detection == 'function' ? fails(detection)
  19564. : !!detection;
  19565. };
  19566. var normalize = isForced.normalize = function (string) {
  19567. return String(string).replace(replacement, '.').toLowerCase();
  19568. };
  19569. var data = isForced.data = {};
  19570. var NATIVE = isForced.NATIVE = 'N';
  19571. var POLYFILL = isForced.POLYFILL = 'P';
  19572. module.exports = isForced;
  19573. /***/ }),
  19574. /***/ "9bf2":
  19575. /***/ (function(module, exports, __webpack_require__) {
  19576. var DESCRIPTORS = __webpack_require__("83ab");
  19577. var IE8_DOM_DEFINE = __webpack_require__("0cfb");
  19578. var anObject = __webpack_require__("825a");
  19579. var toPrimitive = __webpack_require__("c04e");
  19580. var nativeDefineProperty = Object.defineProperty;
  19581. // `Object.defineProperty` method
  19582. // https://tc39.github.io/ecma262/#sec-object.defineproperty
  19583. exports.f = DESCRIPTORS ? nativeDefineProperty : function defineProperty(O, P, Attributes) {
  19584. anObject(O);
  19585. P = toPrimitive(P, true);
  19586. anObject(Attributes);
  19587. if (IE8_DOM_DEFINE) try {
  19588. return nativeDefineProperty(O, P, Attributes);
  19589. } catch (error) { /* empty */ }
  19590. if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
  19591. if ('value' in Attributes) O[P] = Attributes.value;
  19592. return O;
  19593. };
  19594. /***/ }),
  19595. /***/ "a691":
  19596. /***/ (function(module, exports) {
  19597. var ceil = Math.ceil;
  19598. var floor = Math.floor;
  19599. // `ToInteger` abstract operation
  19600. // https://tc39.github.io/ecma262/#sec-tointeger
  19601. module.exports = function (argument) {
  19602. return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);
  19603. };
  19604. /***/ }),
  19605. /***/ "b402":
  19606. /***/ (function(module, exports, __webpack_require__) {
  19607. (function webpackUniversalModuleDefinition(root, factory) {
  19608. if(true)
  19609. module.exports = factory(__webpack_require__("5392"));
  19610. else {}
  19611. })(window, function(__WEBPACK_EXTERNAL_MODULE__20__) {
  19612. return /******/ (function(modules) { // webpackBootstrap
  19613. /******/ // The module cache
  19614. /******/ var installedModules = {};
  19615. /******/
  19616. /******/ // The require function
  19617. /******/ function __webpack_require__(moduleId) {
  19618. /******/
  19619. /******/ // Check if module is in cache
  19620. /******/ if(installedModules[moduleId]) {
  19621. /******/ return installedModules[moduleId].exports;
  19622. /******/ }
  19623. /******/ // Create a new module (and put it into the cache)
  19624. /******/ var module = installedModules[moduleId] = {
  19625. /******/ i: moduleId,
  19626. /******/ l: false,
  19627. /******/ exports: {}
  19628. /******/ };
  19629. /******/
  19630. /******/ // Execute the module function
  19631. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  19632. /******/
  19633. /******/ // Flag the module as loaded
  19634. /******/ module.l = true;
  19635. /******/
  19636. /******/ // Return the exports of the module
  19637. /******/ return module.exports;
  19638. /******/ }
  19639. /******/
  19640. /******/
  19641. /******/ // expose the modules object (__webpack_modules__)
  19642. /******/ __webpack_require__.m = modules;
  19643. /******/
  19644. /******/ // expose the module cache
  19645. /******/ __webpack_require__.c = installedModules;
  19646. /******/
  19647. /******/ // define getter function for harmony exports
  19648. /******/ __webpack_require__.d = function(exports, name, getter) {
  19649. /******/ if(!__webpack_require__.o(exports, name)) {
  19650. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  19651. /******/ }
  19652. /******/ };
  19653. /******/
  19654. /******/ // define __esModule on exports
  19655. /******/ __webpack_require__.r = function(exports) {
  19656. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  19657. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  19658. /******/ }
  19659. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  19660. /******/ };
  19661. /******/
  19662. /******/ // create a fake namespace object
  19663. /******/ // mode & 1: value is a module id, require it
  19664. /******/ // mode & 2: merge all properties of value into the ns
  19665. /******/ // mode & 4: return value when already ns object
  19666. /******/ // mode & 8|1: behave like require
  19667. /******/ __webpack_require__.t = function(value, mode) {
  19668. /******/ if(mode & 1) value = __webpack_require__(value);
  19669. /******/ if(mode & 8) return value;
  19670. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  19671. /******/ var ns = Object.create(null);
  19672. /******/ __webpack_require__.r(ns);
  19673. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  19674. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  19675. /******/ return ns;
  19676. /******/ };
  19677. /******/
  19678. /******/ // getDefaultExport function for compatibility with non-harmony modules
  19679. /******/ __webpack_require__.n = function(module) {
  19680. /******/ var getter = module && module.__esModule ?
  19681. /******/ function getDefault() { return module['default']; } :
  19682. /******/ function getModuleExports() { return module; };
  19683. /******/ __webpack_require__.d(getter, 'a', getter);
  19684. /******/ return getter;
  19685. /******/ };
  19686. /******/
  19687. /******/ // Object.prototype.hasOwnProperty.call
  19688. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  19689. /******/
  19690. /******/ // __webpack_public_path__
  19691. /******/ __webpack_require__.p = "";
  19692. /******/
  19693. /******/
  19694. /******/ // Load entry module and return exports
  19695. /******/ return __webpack_require__(__webpack_require__.s = 18);
  19696. /******/ })
  19697. /************************************************************************/
  19698. /******/ ([
  19699. /* 0 */
  19700. /***/ (function(module, exports, __webpack_require__) {
  19701. "use strict";
  19702. Object.defineProperty(exports, "__esModule", {
  19703. value: true
  19704. });
  19705. 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; }; }(); /*
  19706. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  19707. *
  19708. * @author zheng qian <xqq@xqq.im>
  19709. *
  19710. * Licensed under the Apache License, Version 2.0 (the "License");
  19711. * you may not use this file except in compliance with the License.
  19712. * You may obtain a copy of the License at
  19713. *
  19714. * http://www.apache.org/licenses/LICENSE-2.0
  19715. *
  19716. * Unless required by applicable law or agreed to in writing, software
  19717. * distributed under the License is distributed on an "AS IS" BASIS,
  19718. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19719. * See the License for the specific language governing permissions and
  19720. * limitations under the License.
  19721. */
  19722. var _events = __webpack_require__(2);
  19723. var _events2 = _interopRequireDefault(_events);
  19724. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  19725. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  19726. var Log = function () {
  19727. function Log() {
  19728. _classCallCheck(this, Log);
  19729. }
  19730. _createClass(Log, null, [{
  19731. key: 'e',
  19732. value: function e(tag, msg) {
  19733. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  19734. var str = '[' + tag + '] > ' + msg;
  19735. if (Log.ENABLE_CALLBACK) {
  19736. Log.emitter.emit('log', 'error', str);
  19737. }
  19738. if (!Log.ENABLE_ERROR) {
  19739. return;
  19740. }
  19741. }
  19742. }, {
  19743. key: 'i',
  19744. value: function i(tag, msg) {
  19745. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  19746. var str = '[' + tag + '] > ' + msg;
  19747. if (Log.ENABLE_CALLBACK) {
  19748. Log.emitter.emit('log', 'info', str);
  19749. }
  19750. if (!Log.ENABLE_INFO) {
  19751. return;
  19752. }
  19753. }
  19754. }, {
  19755. key: 'w',
  19756. value: function w(tag, msg) {
  19757. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  19758. var str = '[' + tag + '] > ' + msg;
  19759. if (Log.ENABLE_CALLBACK) {
  19760. Log.emitter.emit('log', 'warn', str);
  19761. }
  19762. if (!Log.ENABLE_WARN) {
  19763. return;
  19764. }
  19765. }
  19766. }, {
  19767. key: 'd',
  19768. value: function d(tag, msg) {
  19769. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  19770. var str = '[' + tag + '] > ' + msg;
  19771. if (Log.ENABLE_CALLBACK) {
  19772. Log.emitter.emit('log', 'debug', str);
  19773. }
  19774. if (!Log.ENABLE_DEBUG) {
  19775. return;
  19776. }
  19777. }
  19778. }, {
  19779. key: 'v',
  19780. value: function v(tag, msg) {
  19781. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  19782. var str = '[' + tag + '] > ' + msg;
  19783. if (Log.ENABLE_CALLBACK) {
  19784. Log.emitter.emit('log', 'verbose', str);
  19785. }
  19786. if (!Log.ENABLE_VERBOSE) {
  19787. return;
  19788. }
  19789. }
  19790. }]);
  19791. return Log;
  19792. }();
  19793. Log.GLOBAL_TAG = 'flv.js';
  19794. Log.FORCE_GLOBAL_TAG = false;
  19795. Log.ENABLE_ERROR = true;
  19796. Log.ENABLE_INFO = true;
  19797. Log.ENABLE_WARN = true;
  19798. Log.ENABLE_DEBUG = true;
  19799. Log.ENABLE_VERBOSE = true;
  19800. Log.ENABLE_CALLBACK = false;
  19801. Log.emitter = new _events2.default();
  19802. exports.default = Log;
  19803. module.exports = exports['default'];
  19804. /***/ }),
  19805. /* 1 */
  19806. /***/ (function(module, exports, __webpack_require__) {
  19807. "use strict";
  19808. Object.defineProperty(exports, "__esModule", {
  19809. value: true
  19810. });
  19811. 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; }; }();
  19812. 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; }
  19813. 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; }
  19814. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  19815. /*
  19816. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  19817. *
  19818. * @author zheng qian <xqq@xqq.im>
  19819. *
  19820. * Licensed under the Apache License, Version 2.0 (the "License");
  19821. * you may not use this file except in compliance with the License.
  19822. * You may obtain a copy of the License at
  19823. *
  19824. * http://www.apache.org/licenses/LICENSE-2.0
  19825. *
  19826. * Unless required by applicable law or agreed to in writing, software
  19827. * distributed under the License is distributed on an "AS IS" BASIS,
  19828. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19829. * See the License for the specific language governing permissions and
  19830. * limitations under the License.
  19831. */
  19832. var RuntimeException = exports.RuntimeException = function () {
  19833. function RuntimeException(message) {
  19834. _classCallCheck(this, RuntimeException);
  19835. this._message = message;
  19836. }
  19837. _createClass(RuntimeException, [{
  19838. key: 'toString',
  19839. value: function toString() {
  19840. return this.name + ': ' + this.message;
  19841. }
  19842. }, {
  19843. key: 'name',
  19844. get: function get() {
  19845. return 'RuntimeException';
  19846. }
  19847. }, {
  19848. key: 'message',
  19849. get: function get() {
  19850. return this._message;
  19851. }
  19852. }]);
  19853. return RuntimeException;
  19854. }();
  19855. var IllegalStateException = exports.IllegalStateException = function (_RuntimeException) {
  19856. _inherits(IllegalStateException, _RuntimeException);
  19857. function IllegalStateException(message) {
  19858. _classCallCheck(this, IllegalStateException);
  19859. return _possibleConstructorReturn(this, (IllegalStateException.__proto__ || Object.getPrototypeOf(IllegalStateException)).call(this, message));
  19860. }
  19861. _createClass(IllegalStateException, [{
  19862. key: 'name',
  19863. get: function get() {
  19864. return 'IllegalStateException';
  19865. }
  19866. }]);
  19867. return IllegalStateException;
  19868. }(RuntimeException);
  19869. var InvalidArgumentException = exports.InvalidArgumentException = function (_RuntimeException2) {
  19870. _inherits(InvalidArgumentException, _RuntimeException2);
  19871. function InvalidArgumentException(message) {
  19872. _classCallCheck(this, InvalidArgumentException);
  19873. return _possibleConstructorReturn(this, (InvalidArgumentException.__proto__ || Object.getPrototypeOf(InvalidArgumentException)).call(this, message));
  19874. }
  19875. _createClass(InvalidArgumentException, [{
  19876. key: 'name',
  19877. get: function get() {
  19878. return 'InvalidArgumentException';
  19879. }
  19880. }]);
  19881. return InvalidArgumentException;
  19882. }(RuntimeException);
  19883. var NotImplementedException = exports.NotImplementedException = function (_RuntimeException3) {
  19884. _inherits(NotImplementedException, _RuntimeException3);
  19885. function NotImplementedException(message) {
  19886. _classCallCheck(this, NotImplementedException);
  19887. return _possibleConstructorReturn(this, (NotImplementedException.__proto__ || Object.getPrototypeOf(NotImplementedException)).call(this, message));
  19888. }
  19889. _createClass(NotImplementedException, [{
  19890. key: 'name',
  19891. get: function get() {
  19892. return 'NotImplementedException';
  19893. }
  19894. }]);
  19895. return NotImplementedException;
  19896. }(RuntimeException);
  19897. /***/ }),
  19898. /* 2 */
  19899. /***/ (function(module, exports, __webpack_require__) {
  19900. "use strict";
  19901. // Copyright Joyent, Inc. and other Node contributors.
  19902. //
  19903. // Permission is hereby granted, free of charge, to any person obtaining a
  19904. // copy of this software and associated documentation files (the
  19905. // "Software"), to deal in the Software without restriction, including
  19906. // without limitation the rights to use, copy, modify, merge, publish,
  19907. // distribute, sublicense, and/or sell copies of the Software, and to permit
  19908. // persons to whom the Software is furnished to do so, subject to the
  19909. // following conditions:
  19910. //
  19911. // The above copyright notice and this permission notice shall be included
  19912. // in all copies or substantial portions of the Software.
  19913. //
  19914. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19915. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19916. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  19917. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19918. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19919. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  19920. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  19921. var R = typeof Reflect === 'object' ? Reflect : null
  19922. var ReflectApply = R && typeof R.apply === 'function'
  19923. ? R.apply
  19924. : function ReflectApply(target, receiver, args) {
  19925. return Function.prototype.apply.call(target, receiver, args);
  19926. }
  19927. var ReflectOwnKeys
  19928. if (R && typeof R.ownKeys === 'function') {
  19929. ReflectOwnKeys = R.ownKeys
  19930. } else if (Object.getOwnPropertySymbols) {
  19931. ReflectOwnKeys = function ReflectOwnKeys(target) {
  19932. return Object.getOwnPropertyNames(target)
  19933. .concat(Object.getOwnPropertySymbols(target));
  19934. };
  19935. } else {
  19936. ReflectOwnKeys = function ReflectOwnKeys(target) {
  19937. return Object.getOwnPropertyNames(target);
  19938. };
  19939. }
  19940. function ProcessEmitWarning(warning) {
  19941. if (console && console.warn) console.warn(warning);
  19942. }
  19943. var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
  19944. return value !== value;
  19945. }
  19946. function EventEmitter() {
  19947. EventEmitter.init.call(this);
  19948. }
  19949. module.exports = EventEmitter;
  19950. // Backwards-compat with node 0.10.x
  19951. EventEmitter.EventEmitter = EventEmitter;
  19952. EventEmitter.prototype._events = undefined;
  19953. EventEmitter.prototype._eventsCount = 0;
  19954. EventEmitter.prototype._maxListeners = undefined;
  19955. // By default EventEmitters will print a warning if more than 10 listeners are
  19956. // added to it. This is a useful default which helps finding memory leaks.
  19957. var defaultMaxListeners = 10;
  19958. function checkListener(listener) {
  19959. if (typeof listener !== 'function') {
  19960. throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
  19961. }
  19962. }
  19963. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  19964. enumerable: true,
  19965. get: function() {
  19966. return defaultMaxListeners;
  19967. },
  19968. set: function(arg) {
  19969. if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
  19970. throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
  19971. }
  19972. defaultMaxListeners = arg;
  19973. }
  19974. });
  19975. EventEmitter.init = function() {
  19976. if (this._events === undefined ||
  19977. this._events === Object.getPrototypeOf(this)._events) {
  19978. this._events = Object.create(null);
  19979. this._eventsCount = 0;
  19980. }
  19981. this._maxListeners = this._maxListeners || undefined;
  19982. };
  19983. // Obviously not all Emitters should be limited to 10. This function allows
  19984. // that to be increased. Set to zero for unlimited.
  19985. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  19986. if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
  19987. throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
  19988. }
  19989. this._maxListeners = n;
  19990. return this;
  19991. };
  19992. function _getMaxListeners(that) {
  19993. if (that._maxListeners === undefined)
  19994. return EventEmitter.defaultMaxListeners;
  19995. return that._maxListeners;
  19996. }
  19997. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  19998. return _getMaxListeners(this);
  19999. };
  20000. EventEmitter.prototype.emit = function emit(type) {
  20001. var args = [];
  20002. for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
  20003. var doError = (type === 'error');
  20004. var events = this._events;
  20005. if (events !== undefined)
  20006. doError = (doError && events.error === undefined);
  20007. else if (!doError)
  20008. return false;
  20009. // If there is no 'error' event listener then throw.
  20010. if (doError) {
  20011. var er;
  20012. if (args.length > 0)
  20013. er = args[0];
  20014. if (er instanceof Error) {
  20015. // Note: The comments on the `throw` lines are intentional, they show
  20016. // up in Node's output if this results in an unhandled exception.
  20017. throw er; // Unhandled 'error' event
  20018. }
  20019. // At least give some kind of context to the user
  20020. var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
  20021. err.context = er;
  20022. throw err; // Unhandled 'error' event
  20023. }
  20024. var handler = events[type];
  20025. if (handler === undefined)
  20026. return false;
  20027. if (typeof handler === 'function') {
  20028. ReflectApply(handler, this, args);
  20029. } else {
  20030. var len = handler.length;
  20031. var listeners = arrayClone(handler, len);
  20032. for (var i = 0; i < len; ++i)
  20033. ReflectApply(listeners[i], this, args);
  20034. }
  20035. return true;
  20036. };
  20037. function _addListener(target, type, listener, prepend) {
  20038. var m;
  20039. var events;
  20040. var existing;
  20041. checkListener(listener);
  20042. events = target._events;
  20043. if (events === undefined) {
  20044. events = target._events = Object.create(null);
  20045. target._eventsCount = 0;
  20046. } else {
  20047. // To avoid recursion in the case that type === "newListener"! Before
  20048. // adding it to the listeners, first emit "newListener".
  20049. if (events.newListener !== undefined) {
  20050. target.emit('newListener', type,
  20051. listener.listener ? listener.listener : listener);
  20052. // Re-assign `events` because a newListener handler could have caused the
  20053. // this._events to be assigned to a new object
  20054. events = target._events;
  20055. }
  20056. existing = events[type];
  20057. }
  20058. if (existing === undefined) {
  20059. // Optimize the case of one listener. Don't need the extra array object.
  20060. existing = events[type] = listener;
  20061. ++target._eventsCount;
  20062. } else {
  20063. if (typeof existing === 'function') {
  20064. // Adding the second element, need to change to array.
  20065. existing = events[type] =
  20066. prepend ? [listener, existing] : [existing, listener];
  20067. // If we've already got an array, just append.
  20068. } else if (prepend) {
  20069. existing.unshift(listener);
  20070. } else {
  20071. existing.push(listener);
  20072. }
  20073. // Check for listener leak
  20074. m = _getMaxListeners(target);
  20075. if (m > 0 && existing.length > m && !existing.warned) {
  20076. existing.warned = true;
  20077. // No error code for this since it is a Warning
  20078. // eslint-disable-next-line no-restricted-syntax
  20079. var w = new Error('Possible EventEmitter memory leak detected. ' +
  20080. existing.length + ' ' + String(type) + ' listeners ' +
  20081. 'added. Use emitter.setMaxListeners() to ' +
  20082. 'increase limit');
  20083. w.name = 'MaxListenersExceededWarning';
  20084. w.emitter = target;
  20085. w.type = type;
  20086. w.count = existing.length;
  20087. ProcessEmitWarning(w);
  20088. }
  20089. }
  20090. return target;
  20091. }
  20092. EventEmitter.prototype.addListener = function addListener(type, listener) {
  20093. return _addListener(this, type, listener, false);
  20094. };
  20095. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  20096. EventEmitter.prototype.prependListener =
  20097. function prependListener(type, listener) {
  20098. return _addListener(this, type, listener, true);
  20099. };
  20100. function onceWrapper() {
  20101. if (!this.fired) {
  20102. this.target.removeListener(this.type, this.wrapFn);
  20103. this.fired = true;
  20104. if (arguments.length === 0)
  20105. return this.listener.call(this.target);
  20106. return this.listener.apply(this.target, arguments);
  20107. }
  20108. }
  20109. function _onceWrap(target, type, listener) {
  20110. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  20111. var wrapped = onceWrapper.bind(state);
  20112. wrapped.listener = listener;
  20113. state.wrapFn = wrapped;
  20114. return wrapped;
  20115. }
  20116. EventEmitter.prototype.once = function once(type, listener) {
  20117. checkListener(listener);
  20118. this.on(type, _onceWrap(this, type, listener));
  20119. return this;
  20120. };
  20121. EventEmitter.prototype.prependOnceListener =
  20122. function prependOnceListener(type, listener) {
  20123. checkListener(listener);
  20124. this.prependListener(type, _onceWrap(this, type, listener));
  20125. return this;
  20126. };
  20127. // Emits a 'removeListener' event if and only if the listener was removed.
  20128. EventEmitter.prototype.removeListener =
  20129. function removeListener(type, listener) {
  20130. var list, events, position, i, originalListener;
  20131. checkListener(listener);
  20132. events = this._events;
  20133. if (events === undefined)
  20134. return this;
  20135. list = events[type];
  20136. if (list === undefined)
  20137. return this;
  20138. if (list === listener || list.listener === listener) {
  20139. if (--this._eventsCount === 0)
  20140. this._events = Object.create(null);
  20141. else {
  20142. delete events[type];
  20143. if (events.removeListener)
  20144. this.emit('removeListener', type, list.listener || listener);
  20145. }
  20146. } else if (typeof list !== 'function') {
  20147. position = -1;
  20148. for (i = list.length - 1; i >= 0; i--) {
  20149. if (list[i] === listener || list[i].listener === listener) {
  20150. originalListener = list[i].listener;
  20151. position = i;
  20152. break;
  20153. }
  20154. }
  20155. if (position < 0)
  20156. return this;
  20157. if (position === 0)
  20158. list.shift();
  20159. else {
  20160. spliceOne(list, position);
  20161. }
  20162. if (list.length === 1)
  20163. events[type] = list[0];
  20164. if (events.removeListener !== undefined)
  20165. this.emit('removeListener', type, originalListener || listener);
  20166. }
  20167. return this;
  20168. };
  20169. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  20170. EventEmitter.prototype.removeAllListeners =
  20171. function removeAllListeners(type) {
  20172. var listeners, events, i;
  20173. events = this._events;
  20174. if (events === undefined)
  20175. return this;
  20176. // not listening for removeListener, no need to emit
  20177. if (events.removeListener === undefined) {
  20178. if (arguments.length === 0) {
  20179. this._events = Object.create(null);
  20180. this._eventsCount = 0;
  20181. } else if (events[type] !== undefined) {
  20182. if (--this._eventsCount === 0)
  20183. this._events = Object.create(null);
  20184. else
  20185. delete events[type];
  20186. }
  20187. return this;
  20188. }
  20189. // emit removeListener for all listeners on all events
  20190. if (arguments.length === 0) {
  20191. var keys = Object.keys(events);
  20192. var key;
  20193. for (i = 0; i < keys.length; ++i) {
  20194. key = keys[i];
  20195. if (key === 'removeListener') continue;
  20196. this.removeAllListeners(key);
  20197. }
  20198. this.removeAllListeners('removeListener');
  20199. this._events = Object.create(null);
  20200. this._eventsCount = 0;
  20201. return this;
  20202. }
  20203. listeners = events[type];
  20204. if (typeof listeners === 'function') {
  20205. this.removeListener(type, listeners);
  20206. } else if (listeners !== undefined) {
  20207. // LIFO order
  20208. for (i = listeners.length - 1; i >= 0; i--) {
  20209. this.removeListener(type, listeners[i]);
  20210. }
  20211. }
  20212. return this;
  20213. };
  20214. function _listeners(target, type, unwrap) {
  20215. var events = target._events;
  20216. if (events === undefined)
  20217. return [];
  20218. var evlistener = events[type];
  20219. if (evlistener === undefined)
  20220. return [];
  20221. if (typeof evlistener === 'function')
  20222. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  20223. return unwrap ?
  20224. unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  20225. }
  20226. EventEmitter.prototype.listeners = function listeners(type) {
  20227. return _listeners(this, type, true);
  20228. };
  20229. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  20230. return _listeners(this, type, false);
  20231. };
  20232. EventEmitter.listenerCount = function(emitter, type) {
  20233. if (typeof emitter.listenerCount === 'function') {
  20234. return emitter.listenerCount(type);
  20235. } else {
  20236. return listenerCount.call(emitter, type);
  20237. }
  20238. };
  20239. EventEmitter.prototype.listenerCount = listenerCount;
  20240. function listenerCount(type) {
  20241. var events = this._events;
  20242. if (events !== undefined) {
  20243. var evlistener = events[type];
  20244. if (typeof evlistener === 'function') {
  20245. return 1;
  20246. } else if (evlistener !== undefined) {
  20247. return evlistener.length;
  20248. }
  20249. }
  20250. return 0;
  20251. }
  20252. EventEmitter.prototype.eventNames = function eventNames() {
  20253. return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
  20254. };
  20255. function arrayClone(arr, n) {
  20256. var copy = new Array(n);
  20257. for (var i = 0; i < n; ++i)
  20258. copy[i] = arr[i];
  20259. return copy;
  20260. }
  20261. function spliceOne(list, index) {
  20262. for (; index + 1 < list.length; index++)
  20263. list[index] = list[index + 1];
  20264. list.pop();
  20265. }
  20266. function unwrapListeners(arr) {
  20267. var ret = new Array(arr.length);
  20268. for (var i = 0; i < ret.length; ++i) {
  20269. ret[i] = arr[i].listener || arr[i];
  20270. }
  20271. return ret;
  20272. }
  20273. /***/ }),
  20274. /* 3 */
  20275. /***/ (function(module, exports, __webpack_require__) {
  20276. "use strict";
  20277. Object.defineProperty(exports, "__esModule", {
  20278. value: true
  20279. });
  20280. exports.BaseLoader = exports.LoaderErrors = exports.LoaderStatus = undefined;
  20281. 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; }; }(); /*
  20282. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20283. *
  20284. * @author zheng qian <xqq@xqq.im>
  20285. *
  20286. * Licensed under the Apache License, Version 2.0 (the "License");
  20287. * you may not use this file except in compliance with the License.
  20288. * You may obtain a copy of the License at
  20289. *
  20290. * http://www.apache.org/licenses/LICENSE-2.0
  20291. *
  20292. * Unless required by applicable law or agreed to in writing, software
  20293. * distributed under the License is distributed on an "AS IS" BASIS,
  20294. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20295. * See the License for the specific language governing permissions and
  20296. * limitations under the License.
  20297. */
  20298. var _exception = __webpack_require__(1);
  20299. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  20300. var LoaderStatus = exports.LoaderStatus = {
  20301. kIdle: 0,
  20302. kConnecting: 1,
  20303. kBuffering: 2,
  20304. kError: 3,
  20305. kComplete: 4
  20306. };
  20307. var LoaderErrors = exports.LoaderErrors = {
  20308. OK: 'OK',
  20309. EXCEPTION: 'Exception',
  20310. HTTP_STATUS_CODE_INVALID: 'HttpStatusCodeInvalid',
  20311. CONNECTING_TIMEOUT: 'ConnectingTimeout',
  20312. EARLY_EOF: 'EarlyEof',
  20313. UNRECOVERABLE_EARLY_EOF: 'UnrecoverableEarlyEof'
  20314. };
  20315. /* Loader has callbacks which have following prototypes:
  20316. * function onContentLengthKnown(contentLength: number): void
  20317. * function onURLRedirect(url: string): void
  20318. * function onDataArrival(chunk: ArrayBuffer, byteStart: number, receivedLength: number): void
  20319. * function onError(errorType: number, errorInfo: {code: number, msg: string}): void
  20320. * function onComplete(rangeFrom: number, rangeTo: number): void
  20321. */
  20322. var BaseLoader = exports.BaseLoader = function () {
  20323. function BaseLoader(typeName) {
  20324. _classCallCheck(this, BaseLoader);
  20325. this._type = typeName || 'undefined';
  20326. this._status = LoaderStatus.kIdle;
  20327. this._needStash = false;
  20328. // callbacks
  20329. this._onContentLengthKnown = null;
  20330. this._onURLRedirect = null;
  20331. this._onDataArrival = null;
  20332. this._onError = null;
  20333. this._onComplete = null;
  20334. }
  20335. _createClass(BaseLoader, [{
  20336. key: 'destroy',
  20337. value: function destroy() {
  20338. this._status = LoaderStatus.kIdle;
  20339. this._onContentLengthKnown = null;
  20340. this._onURLRedirect = null;
  20341. this._onDataArrival = null;
  20342. this._onError = null;
  20343. this._onComplete = null;
  20344. }
  20345. }, {
  20346. key: 'isWorking',
  20347. value: function isWorking() {
  20348. return this._status === LoaderStatus.kConnecting || this._status === LoaderStatus.kBuffering;
  20349. }
  20350. }, {
  20351. key: 'open',
  20352. // pure virtual
  20353. value: function open(dataSource, range) {
  20354. throw new _exception.NotImplementedException('Unimplemented abstract function!');
  20355. }
  20356. }, {
  20357. key: 'abort',
  20358. value: function abort() {
  20359. throw new _exception.NotImplementedException('Unimplemented abstract function!');
  20360. }
  20361. }, {
  20362. key: 'type',
  20363. get: function get() {
  20364. return this._type;
  20365. }
  20366. }, {
  20367. key: 'status',
  20368. get: function get() {
  20369. return this._status;
  20370. }
  20371. }, {
  20372. key: 'needStashBuffer',
  20373. get: function get() {
  20374. return this._needStash;
  20375. }
  20376. }, {
  20377. key: 'onContentLengthKnown',
  20378. get: function get() {
  20379. return this._onContentLengthKnown;
  20380. },
  20381. set: function set(callback) {
  20382. this._onContentLengthKnown = callback;
  20383. }
  20384. }, {
  20385. key: 'onURLRedirect',
  20386. get: function get() {
  20387. return this._onURLRedirect;
  20388. },
  20389. set: function set(callback) {
  20390. this._onURLRedirect = callback;
  20391. }
  20392. }, {
  20393. key: 'onDataArrival',
  20394. get: function get() {
  20395. return this._onDataArrival;
  20396. },
  20397. set: function set(callback) {
  20398. this._onDataArrival = callback;
  20399. }
  20400. }, {
  20401. key: 'onError',
  20402. get: function get() {
  20403. return this._onError;
  20404. },
  20405. set: function set(callback) {
  20406. this._onError = callback;
  20407. }
  20408. }, {
  20409. key: 'onComplete',
  20410. get: function get() {
  20411. return this._onComplete;
  20412. },
  20413. set: function set(callback) {
  20414. this._onComplete = callback;
  20415. }
  20416. }]);
  20417. return BaseLoader;
  20418. }();
  20419. /***/ }),
  20420. /* 4 */
  20421. /***/ (function(module, exports, __webpack_require__) {
  20422. "use strict";
  20423. Object.defineProperty(exports, "__esModule", {
  20424. value: true
  20425. });
  20426. /*
  20427. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20428. *
  20429. * @author zheng qian <xqq@xqq.im>
  20430. *
  20431. * Licensed under the Apache License, Version 2.0 (the "License");
  20432. * you may not use this file except in compliance with the License.
  20433. * You may obtain a copy of the License at
  20434. *
  20435. * http://www.apache.org/licenses/LICENSE-2.0
  20436. *
  20437. * Unless required by applicable law or agreed to in writing, software
  20438. * distributed under the License is distributed on an "AS IS" BASIS,
  20439. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20440. * See the License for the specific language governing permissions and
  20441. * limitations under the License.
  20442. */
  20443. var Browser = {};
  20444. function detect() {
  20445. // modified from jquery-browser-plugin
  20446. var ua = self.navigator.userAgent.toLowerCase();
  20447. 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) || [];
  20448. 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) || [];
  20449. var matched = {
  20450. browser: match[5] || match[3] || match[1] || '',
  20451. version: match[2] || match[4] || '0',
  20452. majorVersion: match[4] || match[2] || '0',
  20453. platform: platform_match[0] || ''
  20454. };
  20455. var browser = {};
  20456. if (matched.browser) {
  20457. browser[matched.browser] = true;
  20458. var versionArray = matched.majorVersion.split('.');
  20459. browser.version = {
  20460. major: parseInt(matched.majorVersion, 10),
  20461. string: matched.version
  20462. };
  20463. if (versionArray.length > 1) {
  20464. browser.version.minor = parseInt(versionArray[1], 10);
  20465. }
  20466. if (versionArray.length > 2) {
  20467. browser.version.build = parseInt(versionArray[2], 10);
  20468. }
  20469. }
  20470. if (matched.platform) {
  20471. browser[matched.platform] = true;
  20472. }
  20473. if (browser.chrome || browser.opr || browser.safari) {
  20474. browser.webkit = true;
  20475. }
  20476. // MSIE. IE11 has 'rv' identifer
  20477. if (browser.rv || browser.iemobile) {
  20478. if (browser.rv) {
  20479. delete browser.rv;
  20480. }
  20481. var msie = 'msie';
  20482. matched.browser = msie;
  20483. browser[msie] = true;
  20484. }
  20485. // Microsoft Edge
  20486. if (browser.edge) {
  20487. delete browser.edge;
  20488. var msedge = 'msedge';
  20489. matched.browser = msedge;
  20490. browser[msedge] = true;
  20491. }
  20492. // Opera 15+
  20493. if (browser.opr) {
  20494. var opera = 'opera';
  20495. matched.browser = opera;
  20496. browser[opera] = true;
  20497. }
  20498. // Stock android browsers are marked as Safari
  20499. if (browser.safari && browser.android) {
  20500. var android = 'android';
  20501. matched.browser = android;
  20502. browser[android] = true;
  20503. }
  20504. browser.name = matched.browser;
  20505. browser.platform = matched.platform;
  20506. for (var key in Browser) {
  20507. if (Browser.hasOwnProperty(key)) {
  20508. delete Browser[key];
  20509. }
  20510. }
  20511. Object.assign(Browser, browser);
  20512. }
  20513. detect();
  20514. exports.default = Browser;
  20515. module.exports = exports['default'];
  20516. /***/ }),
  20517. /* 5 */
  20518. /***/ (function(module, exports, __webpack_require__) {
  20519. "use strict";
  20520. Object.defineProperty(exports, "__esModule", {
  20521. value: true
  20522. });
  20523. /*
  20524. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20525. *
  20526. * @author zheng qian <xqq@xqq.im>
  20527. *
  20528. * Licensed under the Apache License, Version 2.0 (the "License");
  20529. * you may not use this file except in compliance with the License.
  20530. * You may obtain a copy of the License at
  20531. *
  20532. * http://www.apache.org/licenses/LICENSE-2.0
  20533. *
  20534. * Unless required by applicable law or agreed to in writing, software
  20535. * distributed under the License is distributed on an "AS IS" BASIS,
  20536. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20537. * See the License for the specific language governing permissions and
  20538. * limitations under the License.
  20539. */
  20540. var TransmuxingEvents = {
  20541. IO_ERROR: 'io_error',
  20542. DEMUX_ERROR: 'demux_error',
  20543. INIT_SEGMENT: 'init_segment',
  20544. MEDIA_SEGMENT: 'media_segment',
  20545. LOADING_COMPLETE: 'loading_complete',
  20546. RECOVERED_EARLY_EOF: 'recovered_early_eof',
  20547. MEDIA_INFO: 'media_info',
  20548. STATISTICS_INFO: 'statistics_info',
  20549. RECOMMEND_SEEKPOINT: 'recommend_seekpoint',
  20550. LOADED_SEI: 'loaded_sei'
  20551. };
  20552. exports.default = TransmuxingEvents;
  20553. module.exports = exports['default'];
  20554. /***/ }),
  20555. /* 6 */
  20556. /***/ (function(module, exports, __webpack_require__) {
  20557. "use strict";
  20558. Object.defineProperty(exports, "__esModule", {
  20559. value: true
  20560. });
  20561. exports.createDefaultConfig = createDefaultConfig;
  20562. /*
  20563. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20564. *
  20565. * @author zheng qian <xqq@xqq.im>
  20566. *
  20567. * Licensed under the Apache License, Version 2.0 (the "License");
  20568. * you may not use this file except in compliance with the License.
  20569. * You may obtain a copy of the License at
  20570. *
  20571. * http://www.apache.org/licenses/LICENSE-2.0
  20572. *
  20573. * Unless required by applicable law or agreed to in writing, software
  20574. * distributed under the License is distributed on an "AS IS" BASIS,
  20575. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20576. * See the License for the specific language governing permissions and
  20577. * limitations under the License.
  20578. */
  20579. var defaultConfig = exports.defaultConfig = {
  20580. enableWorker: false,
  20581. enableStashBuffer: true,
  20582. stashInitialSize: undefined,
  20583. isLive: false,
  20584. lazyLoad: true,
  20585. lazyLoadMaxDuration: 3 * 60,
  20586. lazyLoadRecoverDuration: 30,
  20587. deferLoadAfterSourceOpen: true,
  20588. // autoCleanupSourceBuffer: default as false, leave unspecified
  20589. autoCleanupMaxBackwardDuration: 3 * 60,
  20590. autoCleanupMinBackwardDuration: 2 * 60,
  20591. statisticsInfoReportInterval: 600,
  20592. fixAudioTimestampGap: true,
  20593. accurateSeek: false,
  20594. seekType: 'range', // [range, param, custom]
  20595. seekParamStart: 'bstart',
  20596. seekParamEnd: 'bend',
  20597. rangeLoadZeroStart: false,
  20598. customSeekHandler: undefined,
  20599. reuseRedirectedURL: false
  20600. // referrerPolicy: leave as unspecified
  20601. };
  20602. function createDefaultConfig() {
  20603. return Object.assign({}, defaultConfig);
  20604. }
  20605. /***/ }),
  20606. /* 7 */
  20607. /***/ (function(module, exports, __webpack_require__) {
  20608. "use strict";
  20609. Object.defineProperty(exports, "__esModule", {
  20610. value: true
  20611. });
  20612. /*
  20613. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20614. *
  20615. * @author zheng qian <xqq@xqq.im>
  20616. *
  20617. * Licensed under the Apache License, Version 2.0 (the "License");
  20618. * you may not use this file except in compliance with the License.
  20619. * You may obtain a copy of the License at
  20620. *
  20621. * http://www.apache.org/licenses/LICENSE-2.0
  20622. *
  20623. * Unless required by applicable law or agreed to in writing, software
  20624. * distributed under the License is distributed on an "AS IS" BASIS,
  20625. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20626. * See the License for the specific language governing permissions and
  20627. * limitations under the License.
  20628. */
  20629. var PlayerEvents = {
  20630. ERROR: 'error',
  20631. LOADING_COMPLETE: 'loading_complete',
  20632. RECOVERED_EARLY_EOF: 'recovered_early_eof',
  20633. MEDIA_INFO: 'media_info',
  20634. STATISTICS_INFO: 'statistics_info',
  20635. LOADED_SEI: 'loaded_sei'
  20636. };
  20637. exports.default = PlayerEvents;
  20638. module.exports = exports['default'];
  20639. /***/ }),
  20640. /* 8 */
  20641. /***/ (function(module, exports, __webpack_require__) {
  20642. "use strict";
  20643. Object.defineProperty(exports, "__esModule", {
  20644. value: true
  20645. });
  20646. 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; }; }(); /*
  20647. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20648. *
  20649. * @author zheng qian <xqq@xqq.im>
  20650. *
  20651. * Licensed under the Apache License, Version 2.0 (the "License");
  20652. * you may not use this file except in compliance with the License.
  20653. * You may obtain a copy of the License at
  20654. *
  20655. * http://www.apache.org/licenses/LICENSE-2.0
  20656. *
  20657. * Unless required by applicable law or agreed to in writing, software
  20658. * distributed under the License is distributed on an "AS IS" BASIS,
  20659. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20660. * See the License for the specific language governing permissions and
  20661. * limitations under the License.
  20662. */
  20663. var _events = __webpack_require__(2);
  20664. var _events2 = _interopRequireDefault(_events);
  20665. var _logger = __webpack_require__(0);
  20666. var _logger2 = _interopRequireDefault(_logger);
  20667. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  20668. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  20669. var LoggingControl = function () {
  20670. function LoggingControl() {
  20671. _classCallCheck(this, LoggingControl);
  20672. }
  20673. _createClass(LoggingControl, null, [{
  20674. key: 'getConfig',
  20675. value: function getConfig() {
  20676. return {
  20677. globalTag: _logger2.default.GLOBAL_TAG,
  20678. forceGlobalTag: _logger2.default.FORCE_GLOBAL_TAG,
  20679. enableVerbose: _logger2.default.ENABLE_VERBOSE,
  20680. enableDebug: _logger2.default.ENABLE_DEBUG,
  20681. enableInfo: _logger2.default.ENABLE_INFO,
  20682. enableWarn: _logger2.default.ENABLE_WARN,
  20683. enableError: _logger2.default.ENABLE_ERROR,
  20684. enableCallback: _logger2.default.ENABLE_CALLBACK
  20685. };
  20686. }
  20687. }, {
  20688. key: 'applyConfig',
  20689. value: function applyConfig(config) {
  20690. _logger2.default.GLOBAL_TAG = config.globalTag;
  20691. _logger2.default.FORCE_GLOBAL_TAG = config.forceGlobalTag;
  20692. _logger2.default.ENABLE_VERBOSE = config.enableVerbose;
  20693. _logger2.default.ENABLE_DEBUG = config.enableDebug;
  20694. _logger2.default.ENABLE_INFO = config.enableInfo;
  20695. _logger2.default.ENABLE_WARN = config.enableWarn;
  20696. _logger2.default.ENABLE_ERROR = config.enableError;
  20697. _logger2.default.ENABLE_CALLBACK = config.enableCallback;
  20698. }
  20699. }, {
  20700. key: '_notifyChange',
  20701. value: function _notifyChange() {
  20702. var emitter = LoggingControl.emitter;
  20703. if (emitter.listenerCount('change') > 0) {
  20704. var config = LoggingControl.getConfig();
  20705. emitter.emit('change', config);
  20706. }
  20707. }
  20708. }, {
  20709. key: 'registerListener',
  20710. value: function registerListener(listener) {
  20711. LoggingControl.emitter.addListener('change', listener);
  20712. }
  20713. }, {
  20714. key: 'removeListener',
  20715. value: function removeListener(listener) {
  20716. LoggingControl.emitter.removeListener('change', listener);
  20717. }
  20718. }, {
  20719. key: 'addLogListener',
  20720. value: function addLogListener(listener) {
  20721. _logger2.default.emitter.addListener('log', listener);
  20722. if (_logger2.default.emitter.listenerCount('log') > 0) {
  20723. _logger2.default.ENABLE_CALLBACK = true;
  20724. LoggingControl._notifyChange();
  20725. }
  20726. }
  20727. }, {
  20728. key: 'removeLogListener',
  20729. value: function removeLogListener(listener) {
  20730. _logger2.default.emitter.removeListener('log', listener);
  20731. if (_logger2.default.emitter.listenerCount('log') === 0) {
  20732. _logger2.default.ENABLE_CALLBACK = false;
  20733. LoggingControl._notifyChange();
  20734. }
  20735. }
  20736. }, {
  20737. key: 'forceGlobalTag',
  20738. get: function get() {
  20739. return _logger2.default.FORCE_GLOBAL_TAG;
  20740. },
  20741. set: function set(enable) {
  20742. _logger2.default.FORCE_GLOBAL_TAG = enable;
  20743. LoggingControl._notifyChange();
  20744. }
  20745. }, {
  20746. key: 'globalTag',
  20747. get: function get() {
  20748. return _logger2.default.GLOBAL_TAG;
  20749. },
  20750. set: function set(tag) {
  20751. _logger2.default.GLOBAL_TAG = tag;
  20752. LoggingControl._notifyChange();
  20753. }
  20754. }, {
  20755. key: 'enableAll',
  20756. get: function get() {
  20757. return _logger2.default.ENABLE_VERBOSE && _logger2.default.ENABLE_DEBUG && _logger2.default.ENABLE_INFO && _logger2.default.ENABLE_WARN && _logger2.default.ENABLE_ERROR;
  20758. },
  20759. set: function set(enable) {
  20760. _logger2.default.ENABLE_VERBOSE = enable;
  20761. _logger2.default.ENABLE_DEBUG = enable;
  20762. _logger2.default.ENABLE_INFO = enable;
  20763. _logger2.default.ENABLE_WARN = enable;
  20764. _logger2.default.ENABLE_ERROR = enable;
  20765. LoggingControl._notifyChange();
  20766. }
  20767. }, {
  20768. key: 'enableDebug',
  20769. get: function get() {
  20770. return _logger2.default.ENABLE_DEBUG;
  20771. },
  20772. set: function set(enable) {
  20773. _logger2.default.ENABLE_DEBUG = enable;
  20774. LoggingControl._notifyChange();
  20775. }
  20776. }, {
  20777. key: 'enableVerbose',
  20778. get: function get() {
  20779. return _logger2.default.ENABLE_VERBOSE;
  20780. },
  20781. set: function set(enable) {
  20782. _logger2.default.ENABLE_VERBOSE = enable;
  20783. LoggingControl._notifyChange();
  20784. }
  20785. }, {
  20786. key: 'enableInfo',
  20787. get: function get() {
  20788. return _logger2.default.ENABLE_INFO;
  20789. },
  20790. set: function set(enable) {
  20791. _logger2.default.ENABLE_INFO = enable;
  20792. LoggingControl._notifyChange();
  20793. }
  20794. }, {
  20795. key: 'enableWarn',
  20796. get: function get() {
  20797. return _logger2.default.ENABLE_WARN;
  20798. },
  20799. set: function set(enable) {
  20800. _logger2.default.ENABLE_WARN = enable;
  20801. LoggingControl._notifyChange();
  20802. }
  20803. }, {
  20804. key: 'enableError',
  20805. get: function get() {
  20806. return _logger2.default.ENABLE_ERROR;
  20807. },
  20808. set: function set(enable) {
  20809. _logger2.default.ENABLE_ERROR = enable;
  20810. LoggingControl._notifyChange();
  20811. }
  20812. }]);
  20813. return LoggingControl;
  20814. }();
  20815. LoggingControl.emitter = new _events2.default();
  20816. exports.default = LoggingControl;
  20817. module.exports = exports['default'];
  20818. /***/ }),
  20819. /* 9 */
  20820. /***/ (function(module, exports, __webpack_require__) {
  20821. "use strict";
  20822. Object.defineProperty(exports, "__esModule", {
  20823. value: true
  20824. });
  20825. 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; }; }();
  20826. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  20827. /*
  20828. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20829. *
  20830. * @author zheng qian <xqq@xqq.im>
  20831. *
  20832. * Licensed under the Apache License, Version 2.0 (the "License");
  20833. * you may not use this file except in compliance with the License.
  20834. * You may obtain a copy of the License at
  20835. *
  20836. * http://www.apache.org/licenses/LICENSE-2.0
  20837. *
  20838. * Unless required by applicable law or agreed to in writing, software
  20839. * distributed under the License is distributed on an "AS IS" BASIS,
  20840. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20841. * See the License for the specific language governing permissions and
  20842. * limitations under the License.
  20843. */
  20844. var MediaInfo = function () {
  20845. function MediaInfo() {
  20846. _classCallCheck(this, MediaInfo);
  20847. this.mimeType = null;
  20848. this.duration = null;
  20849. this.hasAudio = null;
  20850. this.hasVideo = null;
  20851. this.audioCodec = null;
  20852. this.videoCodec = null;
  20853. this.audioDataRate = null;
  20854. this.videoDataRate = null;
  20855. this.audioSampleRate = null;
  20856. this.audioChannelCount = null;
  20857. this.width = null;
  20858. this.height = null;
  20859. this.fps = null;
  20860. this.profile = null;
  20861. this.level = null;
  20862. this.refFrames = null;
  20863. this.chromaFormat = null;
  20864. this.sarNum = null;
  20865. this.sarDen = null;
  20866. this.metadata = null;
  20867. this.segments = null; // MediaInfo[]
  20868. this.segmentCount = null;
  20869. this.hasKeyframesIndex = null;
  20870. this.keyframesIndex = null;
  20871. }
  20872. _createClass(MediaInfo, [{
  20873. key: "isComplete",
  20874. value: function isComplete() {
  20875. var audioInfoComplete = this.hasAudio === false || this.hasAudio === true && this.audioCodec != null && this.audioSampleRate != null && this.audioChannelCount != null;
  20876. 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;
  20877. // keyframesIndex may not be present
  20878. return this.mimeType != null && this.duration != null && this.metadata != null && this.hasKeyframesIndex != null && audioInfoComplete && videoInfoComplete;
  20879. }
  20880. }, {
  20881. key: "isSeekable",
  20882. value: function isSeekable() {
  20883. return this.hasKeyframesIndex === true;
  20884. }
  20885. }, {
  20886. key: "getNearestKeyframe",
  20887. value: function getNearestKeyframe(milliseconds) {
  20888. if (this.keyframesIndex == null) {
  20889. return null;
  20890. }
  20891. var table = this.keyframesIndex;
  20892. var keyframeIdx = this._search(table.times, milliseconds);
  20893. return {
  20894. index: keyframeIdx,
  20895. milliseconds: table.times[keyframeIdx],
  20896. fileposition: table.filepositions[keyframeIdx]
  20897. };
  20898. }
  20899. }, {
  20900. key: "_search",
  20901. value: function _search(list, value) {
  20902. var idx = 0;
  20903. var last = list.length - 1;
  20904. var mid = 0;
  20905. var lbound = 0;
  20906. var ubound = last;
  20907. if (value < list[0]) {
  20908. idx = 0;
  20909. lbound = ubound + 1; // skip search
  20910. }
  20911. while (lbound <= ubound) {
  20912. mid = lbound + Math.floor((ubound - lbound) / 2);
  20913. if (mid === last || value >= list[mid] && value < list[mid + 1]) {
  20914. idx = mid;
  20915. break;
  20916. } else if (list[mid] < value) {
  20917. lbound = mid + 1;
  20918. } else {
  20919. ubound = mid - 1;
  20920. }
  20921. }
  20922. return idx;
  20923. }
  20924. }]);
  20925. return MediaInfo;
  20926. }();
  20927. exports.default = MediaInfo;
  20928. module.exports = exports["default"];
  20929. /***/ }),
  20930. /* 10 */
  20931. /***/ (function(module, exports, __webpack_require__) {
  20932. "use strict";
  20933. Object.defineProperty(exports, "__esModule", {
  20934. value: true
  20935. });
  20936. /*
  20937. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20938. *
  20939. * @author zheng qian <xqq@xqq.im>
  20940. *
  20941. * Licensed under the Apache License, Version 2.0 (the "License");
  20942. * you may not use this file except in compliance with the License.
  20943. * You may obtain a copy of the License at
  20944. *
  20945. * http://www.apache.org/licenses/LICENSE-2.0
  20946. *
  20947. * Unless required by applicable law or agreed to in writing, software
  20948. * distributed under the License is distributed on an "AS IS" BASIS,
  20949. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20950. * See the License for the specific language governing permissions and
  20951. * limitations under the License.
  20952. */
  20953. var DemuxErrors = {
  20954. OK: 'OK',
  20955. FORMAT_ERROR: 'FormatError',
  20956. FORMAT_UNSUPPORTED: 'FormatUnsupported',
  20957. CODEC_UNSUPPORTED: 'CodecUnsupported'
  20958. };
  20959. exports.default = DemuxErrors;
  20960. module.exports = exports['default'];
  20961. /***/ }),
  20962. /* 11 */
  20963. /***/ (function(module, exports, __webpack_require__) {
  20964. "use strict";
  20965. Object.defineProperty(exports, "__esModule", {
  20966. value: true
  20967. });
  20968. 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; }; }();
  20969. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  20970. /*
  20971. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20972. *
  20973. * @author zheng qian <xqq@xqq.im>
  20974. *
  20975. * Licensed under the Apache License, Version 2.0 (the "License");
  20976. * you may not use this file except in compliance with the License.
  20977. * You may obtain a copy of the License at
  20978. *
  20979. * http://www.apache.org/licenses/LICENSE-2.0
  20980. *
  20981. * Unless required by applicable law or agreed to in writing, software
  20982. * distributed under the License is distributed on an "AS IS" BASIS,
  20983. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20984. * See the License for the specific language governing permissions and
  20985. * limitations under the License.
  20986. */
  20987. var Polyfill = function () {
  20988. function Polyfill() {
  20989. _classCallCheck(this, Polyfill);
  20990. }
  20991. _createClass(Polyfill, null, [{
  20992. key: 'install',
  20993. value: function install() {
  20994. // ES6 Object.setPrototypeOf
  20995. Object.setPrototypeOf = Object.setPrototypeOf || function (obj, proto) {
  20996. obj.__proto__ = proto;
  20997. return obj;
  20998. };
  20999. // ES6 Object.assign
  21000. Object.assign = Object.assign || function (target) {
  21001. if (target === undefined || target === null) {
  21002. throw new TypeError('Cannot convert undefined or null to object');
  21003. }
  21004. var output = Object(target);
  21005. for (var i = 1; i < arguments.length; i++) {
  21006. var source = arguments[i];
  21007. if (source !== undefined && source !== null) {
  21008. for (var key in source) {
  21009. if (source.hasOwnProperty(key)) {
  21010. output[key] = source[key];
  21011. }
  21012. }
  21013. }
  21014. }
  21015. return output;
  21016. };
  21017. // ES6 Promise (missing support in IE11)
  21018. if (typeof self.Promise !== 'function') {
  21019. __webpack_require__(22).polyfill();
  21020. }
  21021. }
  21022. }]);
  21023. return Polyfill;
  21024. }();
  21025. Polyfill.install();
  21026. exports.default = Polyfill;
  21027. module.exports = exports['default'];
  21028. /***/ }),
  21029. /* 12 */
  21030. /***/ (function(module, exports, __webpack_require__) {
  21031. "use strict";
  21032. Object.defineProperty(exports, "__esModule", {
  21033. value: true
  21034. });
  21035. 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; }; }(); /*
  21036. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  21037. *
  21038. * @author zheng qian <xqq@xqq.im>
  21039. *
  21040. * Licensed under the Apache License, Version 2.0 (the "License");
  21041. * you may not use this file except in compliance with the License.
  21042. * You may obtain a copy of the License at
  21043. *
  21044. * http://www.apache.org/licenses/LICENSE-2.0
  21045. *
  21046. * Unless required by applicable law or agreed to in writing, software
  21047. * distributed under the License is distributed on an "AS IS" BASIS,
  21048. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21049. * See the License for the specific language governing permissions and
  21050. * limitations under the License.
  21051. */
  21052. var _logger = __webpack_require__(0);
  21053. var _logger2 = _interopRequireDefault(_logger);
  21054. var _speedSampler = __webpack_require__(13);
  21055. var _speedSampler2 = _interopRequireDefault(_speedSampler);
  21056. var _loader = __webpack_require__(3);
  21057. var _fetchStreamLoader = __webpack_require__(26);
  21058. var _fetchStreamLoader2 = _interopRequireDefault(_fetchStreamLoader);
  21059. var _xhrMozChunkedLoader = __webpack_require__(27);
  21060. var _xhrMozChunkedLoader2 = _interopRequireDefault(_xhrMozChunkedLoader);
  21061. var _xhrMsstreamLoader = __webpack_require__(28);
  21062. var _xhrMsstreamLoader2 = _interopRequireDefault(_xhrMsstreamLoader);
  21063. var _xhrRangeLoader = __webpack_require__(29);
  21064. var _xhrRangeLoader2 = _interopRequireDefault(_xhrRangeLoader);
  21065. var _websocketLoader = __webpack_require__(30);
  21066. var _websocketLoader2 = _interopRequireDefault(_websocketLoader);
  21067. var _rangeSeekHandler = __webpack_require__(31);
  21068. var _rangeSeekHandler2 = _interopRequireDefault(_rangeSeekHandler);
  21069. var _paramSeekHandler = __webpack_require__(32);
  21070. var _paramSeekHandler2 = _interopRequireDefault(_paramSeekHandler);
  21071. var _exception = __webpack_require__(1);
  21072. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  21073. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  21074. /**
  21075. * DataSource: {
  21076. * url: string,
  21077. * filesize: number,
  21078. * cors: boolean,
  21079. * withCredentials: boolean
  21080. * }
  21081. *
  21082. */
  21083. // Manage IO Loaders
  21084. var IOController = function () {
  21085. function IOController(dataSource, config, extraData) {
  21086. _classCallCheck(this, IOController);
  21087. this.TAG = 'IOController';
  21088. this._config = config;
  21089. this._extraData = extraData;
  21090. this._stashInitialSize = 1024 * 384; // default initial size: 384KB
  21091. if (config.stashInitialSize != undefined && config.stashInitialSize > 0) {
  21092. // apply from config
  21093. this._stashInitialSize = config.stashInitialSize;
  21094. }
  21095. this._stashUsed = 0;
  21096. this._stashSize = this._stashInitialSize;
  21097. this._bufferSize = 1024 * 1024 * 3; // initial size: 3MB
  21098. this._stashBuffer = new ArrayBuffer(this._bufferSize);
  21099. this._stashByteStart = 0;
  21100. this._enableStash = true;
  21101. if (config.enableStashBuffer === false) {
  21102. this._enableStash = false;
  21103. }
  21104. this._loader = null;
  21105. this._loaderClass = null;
  21106. this._seekHandler = null;
  21107. this._dataSource = dataSource;
  21108. this._isWebSocketURL = /wss?:\/\/(.+?)/.test(dataSource.url);
  21109. this._refTotalLength = dataSource.filesize ? dataSource.filesize : null;
  21110. this._totalLength = this._refTotalLength;
  21111. this._fullRequestFlag = false;
  21112. this._currentRange = null;
  21113. this._redirectedURL = null;
  21114. this._speedNormalized = 0;
  21115. this._speedSampler = new _speedSampler2.default();
  21116. this._speedNormalizeList = [64, 128, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096];
  21117. this._isEarlyEofReconnecting = false;
  21118. this._paused = false;
  21119. this._resumeFrom = 0;
  21120. this._onDataArrival = null;
  21121. this._onSeeked = null;
  21122. this._onError = null;
  21123. this._onComplete = null;
  21124. this._onRedirect = null;
  21125. this._onRecoveredEarlyEof = null;
  21126. this._selectSeekHandler();
  21127. this._selectLoader();
  21128. this._createLoader();
  21129. }
  21130. _createClass(IOController, [{
  21131. key: 'destroy',
  21132. value: function destroy() {
  21133. if (this._loader.isWorking()) {
  21134. this._loader.abort();
  21135. }
  21136. this._loader.destroy();
  21137. this._loader = null;
  21138. this._loaderClass = null;
  21139. this._dataSource = null;
  21140. this._stashBuffer = null;
  21141. this._stashUsed = this._stashSize = this._bufferSize = this._stashByteStart = 0;
  21142. this._currentRange = null;
  21143. this._speedSampler = null;
  21144. this._isEarlyEofReconnecting = false;
  21145. this._onDataArrival = null;
  21146. this._onSeeked = null;
  21147. this._onError = null;
  21148. this._onComplete = null;
  21149. this._onRedirect = null;
  21150. this._onRecoveredEarlyEof = null;
  21151. this._extraData = null;
  21152. }
  21153. }, {
  21154. key: 'isWorking',
  21155. value: function isWorking() {
  21156. return this._loader && this._loader.isWorking() && !this._paused;
  21157. }
  21158. }, {
  21159. key: 'isPaused',
  21160. value: function isPaused() {
  21161. return this._paused;
  21162. }
  21163. }, {
  21164. key: '_selectSeekHandler',
  21165. value: function _selectSeekHandler() {
  21166. var config = this._config;
  21167. if (config.seekType === 'range') {
  21168. this._seekHandler = new _rangeSeekHandler2.default(this._config.rangeLoadZeroStart);
  21169. } else if (config.seekType === 'param') {
  21170. var paramStart = config.seekParamStart || 'bstart';
  21171. var paramEnd = config.seekParamEnd || 'bend';
  21172. this._seekHandler = new _paramSeekHandler2.default(paramStart, paramEnd);
  21173. } else if (config.seekType === 'custom') {
  21174. if (typeof config.customSeekHandler !== 'function') {
  21175. throw new _exception.InvalidArgumentException('Custom seekType specified in config but invalid customSeekHandler!');
  21176. }
  21177. this._seekHandler = new config.customSeekHandler();
  21178. } else {
  21179. throw new _exception.InvalidArgumentException('Invalid seekType in config: ' + config.seekType);
  21180. }
  21181. }
  21182. }, {
  21183. key: '_selectLoader',
  21184. value: function _selectLoader() {
  21185. if (this._isWebSocketURL) {
  21186. this._loaderClass = _websocketLoader2.default;
  21187. } else if (_fetchStreamLoader2.default.isSupported()) {
  21188. this._loaderClass = _fetchStreamLoader2.default;
  21189. } else if (_xhrMozChunkedLoader2.default.isSupported()) {
  21190. this._loaderClass = _xhrMozChunkedLoader2.default;
  21191. } else if (_xhrRangeLoader2.default.isSupported()) {
  21192. this._loaderClass = _xhrRangeLoader2.default;
  21193. } else {
  21194. throw new _exception.RuntimeException('Your browser doesn\'t support xhr with arraybuffer responseType!');
  21195. }
  21196. }
  21197. }, {
  21198. key: '_createLoader',
  21199. value: function _createLoader() {
  21200. this._loader = new this._loaderClass(this._seekHandler, this._config);
  21201. if (this._loader.needStashBuffer === false) {
  21202. this._enableStash = false;
  21203. }
  21204. this._loader.onContentLengthKnown = this._onContentLengthKnown.bind(this);
  21205. this._loader.onURLRedirect = this._onURLRedirect.bind(this);
  21206. this._loader.onDataArrival = this._onLoaderChunkArrival.bind(this);
  21207. this._loader.onComplete = this._onLoaderComplete.bind(this);
  21208. this._loader.onError = this._onLoaderError.bind(this);
  21209. }
  21210. }, {
  21211. key: 'open',
  21212. value: function open(optionalFrom) {
  21213. this._currentRange = { from: 0, to: -1 };
  21214. if (optionalFrom) {
  21215. this._currentRange.from = optionalFrom;
  21216. }
  21217. this._speedSampler.reset();
  21218. if (!optionalFrom) {
  21219. this._fullRequestFlag = true;
  21220. }
  21221. this._loader.open(this._dataSource, Object.assign({}, this._currentRange));
  21222. }
  21223. }, {
  21224. key: 'abort',
  21225. value: function abort() {
  21226. this._loader.abort();
  21227. if (this._paused) {
  21228. this._paused = false;
  21229. this._resumeFrom = 0;
  21230. }
  21231. }
  21232. }, {
  21233. key: 'pause',
  21234. value: function pause() {
  21235. if (this.isWorking()) {
  21236. this._loader.abort();
  21237. if (this._stashUsed !== 0) {
  21238. this._resumeFrom = this._stashByteStart;
  21239. this._currentRange.to = this._stashByteStart - 1;
  21240. } else {
  21241. this._resumeFrom = this._currentRange.to + 1;
  21242. }
  21243. this._stashUsed = 0;
  21244. this._stashByteStart = 0;
  21245. this._paused = true;
  21246. }
  21247. }
  21248. }, {
  21249. key: 'resume',
  21250. value: function resume() {
  21251. if (this._paused) {
  21252. this._paused = false;
  21253. var bytes = this._resumeFrom;
  21254. this._resumeFrom = 0;
  21255. this._internalSeek(bytes, true);
  21256. }
  21257. }
  21258. }, {
  21259. key: 'seek',
  21260. value: function seek(bytes) {
  21261. this._paused = false;
  21262. this._stashUsed = 0;
  21263. this._stashByteStart = 0;
  21264. this._internalSeek(bytes, true);
  21265. }
  21266. /**
  21267. * When seeking request is from media seeking, unconsumed stash data should be dropped
  21268. * However, stash data shouldn't be dropped if seeking requested from http reconnection
  21269. *
  21270. * @dropUnconsumed: Ignore and discard all unconsumed data in stash buffer
  21271. */
  21272. }, {
  21273. key: '_internalSeek',
  21274. value: function _internalSeek(bytes, dropUnconsumed) {
  21275. if (this._loader.isWorking()) {
  21276. this._loader.abort();
  21277. }
  21278. // dispatch & flush stash buffer before seek
  21279. this._flushStashBuffer(dropUnconsumed);
  21280. this._loader.destroy();
  21281. this._loader = null;
  21282. var requestRange = { from: bytes, to: -1 };
  21283. this._currentRange = { from: requestRange.from, to: -1 };
  21284. this._speedSampler.reset();
  21285. this._stashSize = this._stashInitialSize;
  21286. this._createLoader();
  21287. this._loader.open(this._dataSource, requestRange);
  21288. if (this._onSeeked) {
  21289. this._onSeeked();
  21290. }
  21291. }
  21292. }, {
  21293. key: 'updateUrl',
  21294. value: function updateUrl(url) {
  21295. if (!url || typeof url !== 'string' || url.length === 0) {
  21296. throw new _exception.InvalidArgumentException('Url must be a non-empty string!');
  21297. }
  21298. this._dataSource.url = url;
  21299. // TODO: replace with new url
  21300. }
  21301. }, {
  21302. key: '_expandBuffer',
  21303. value: function _expandBuffer(expectedBytes) {
  21304. var bufferNewSize = this._stashSize;
  21305. while (bufferNewSize + 1024 * 1024 * 1 < expectedBytes) {
  21306. bufferNewSize *= 2;
  21307. }
  21308. bufferNewSize += 1024 * 1024 * 1; // bufferSize = stashSize + 1MB
  21309. if (bufferNewSize === this._bufferSize) {
  21310. return;
  21311. }
  21312. var newBuffer = new ArrayBuffer(bufferNewSize);
  21313. if (this._stashUsed > 0) {
  21314. // copy existing data into new buffer
  21315. var stashOldArray = new Uint8Array(this._stashBuffer, 0, this._stashUsed);
  21316. var stashNewArray = new Uint8Array(newBuffer, 0, bufferNewSize);
  21317. stashNewArray.set(stashOldArray, 0);
  21318. }
  21319. this._stashBuffer = newBuffer;
  21320. this._bufferSize = bufferNewSize;
  21321. }
  21322. }, {
  21323. key: '_normalizeSpeed',
  21324. value: function _normalizeSpeed(input) {
  21325. var list = this._speedNormalizeList;
  21326. var last = list.length - 1;
  21327. var mid = 0;
  21328. var lbound = 0;
  21329. var ubound = last;
  21330. if (input < list[0]) {
  21331. return list[0];
  21332. }
  21333. // binary search
  21334. while (lbound <= ubound) {
  21335. mid = lbound + Math.floor((ubound - lbound) / 2);
  21336. if (mid === last || input >= list[mid] && input < list[mid + 1]) {
  21337. return list[mid];
  21338. } else if (list[mid] < input) {
  21339. lbound = mid + 1;
  21340. } else {
  21341. ubound = mid - 1;
  21342. }
  21343. }
  21344. }
  21345. }, {
  21346. key: '_adjustStashSize',
  21347. value: function _adjustStashSize(normalized) {
  21348. var stashSizeKB = 0;
  21349. if (this._config.isLive) {
  21350. // live stream: always use single normalized speed for size of stashSizeKB
  21351. stashSizeKB = normalized;
  21352. } else {
  21353. if (normalized < 512) {
  21354. stashSizeKB = normalized;
  21355. } else if (normalized >= 512 && normalized <= 1024) {
  21356. stashSizeKB = Math.floor(normalized * 1.5);
  21357. } else {
  21358. stashSizeKB = normalized * 2;
  21359. }
  21360. }
  21361. if (stashSizeKB > 8192) {
  21362. stashSizeKB = 8192;
  21363. }
  21364. var bufferSize = stashSizeKB * 1024 + 1024 * 1024 * 1; // stashSize + 1MB
  21365. if (this._bufferSize < bufferSize) {
  21366. this._expandBuffer(bufferSize);
  21367. }
  21368. this._stashSize = stashSizeKB * 1024;
  21369. }
  21370. }, {
  21371. key: '_dispatchChunks',
  21372. value: function _dispatchChunks(chunks, byteStart) {
  21373. this._currentRange.to = byteStart + chunks.byteLength - 1;
  21374. return this._onDataArrival(chunks, byteStart);
  21375. }
  21376. }, {
  21377. key: '_onURLRedirect',
  21378. value: function _onURLRedirect(redirectedURL) {
  21379. this._redirectedURL = redirectedURL;
  21380. if (this._onRedirect) {
  21381. this._onRedirect(redirectedURL);
  21382. }
  21383. }
  21384. }, {
  21385. key: '_onContentLengthKnown',
  21386. value: function _onContentLengthKnown(contentLength) {
  21387. if (contentLength && this._fullRequestFlag) {
  21388. this._totalLength = contentLength;
  21389. this._fullRequestFlag = false;
  21390. }
  21391. }
  21392. }, {
  21393. key: '_onLoaderChunkArrival',
  21394. value: function _onLoaderChunkArrival(chunk, byteStart, receivedLength) {
  21395. if (!this._onDataArrival) {
  21396. throw new _exception.IllegalStateException('IOController: No existing consumer (onDataArrival) callback!');
  21397. }
  21398. if (this._paused) {
  21399. return;
  21400. }
  21401. if (this._isEarlyEofReconnecting) {
  21402. // Auto-reconnect for EarlyEof succeed, notify to upper-layer by callback
  21403. this._isEarlyEofReconnecting = false;
  21404. if (this._onRecoveredEarlyEof) {
  21405. this._onRecoveredEarlyEof();
  21406. }
  21407. }
  21408. this._speedSampler.addBytes(chunk.byteLength);
  21409. // adjust stash buffer size according to network speed dynamically
  21410. var KBps = this._speedSampler.lastSecondKBps;
  21411. if (KBps !== 0) {
  21412. var normalized = this._normalizeSpeed(KBps);
  21413. if (this._speedNormalized !== normalized) {
  21414. this._speedNormalized = normalized;
  21415. this._adjustStashSize(normalized);
  21416. }
  21417. }
  21418. if (!this._enableStash) {
  21419. // disable stash
  21420. if (this._stashUsed === 0) {
  21421. // dispatch chunk directly to consumer;
  21422. // check ret value (consumed bytes) and stash unconsumed to stashBuffer
  21423. var consumed = this._dispatchChunks(chunk, byteStart);
  21424. if (consumed < chunk.byteLength) {
  21425. // unconsumed data remain.
  21426. var remain = chunk.byteLength - consumed;
  21427. if (remain > this._bufferSize) {
  21428. this._expandBuffer(remain);
  21429. }
  21430. var stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  21431. stashArray.set(new Uint8Array(chunk, consumed), 0);
  21432. this._stashUsed += remain;
  21433. this._stashByteStart = byteStart + consumed;
  21434. }
  21435. } else {
  21436. // else: Merge chunk into stashBuffer, and dispatch stashBuffer to consumer.
  21437. if (this._stashUsed + chunk.byteLength > this._bufferSize) {
  21438. this._expandBuffer(this._stashUsed + chunk.byteLength);
  21439. }
  21440. var _stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  21441. _stashArray.set(new Uint8Array(chunk), this._stashUsed);
  21442. this._stashUsed += chunk.byteLength;
  21443. var _consumed = this._dispatchChunks(this._stashBuffer.slice(0, this._stashUsed), this._stashByteStart);
  21444. if (_consumed < this._stashUsed && _consumed > 0) {
  21445. // unconsumed data remain
  21446. var remainArray = new Uint8Array(this._stashBuffer, _consumed);
  21447. _stashArray.set(remainArray, 0);
  21448. }
  21449. this._stashUsed -= _consumed;
  21450. this._stashByteStart += _consumed;
  21451. }
  21452. } else {
  21453. // enable stash
  21454. if (this._stashUsed === 0 && this._stashByteStart === 0) {
  21455. // seeked? or init chunk?
  21456. // This is the first chunk after seek action
  21457. this._stashByteStart = byteStart;
  21458. }
  21459. if (this._stashUsed + chunk.byteLength <= this._stashSize) {
  21460. // just stash
  21461. var _stashArray2 = new Uint8Array(this._stashBuffer, 0, this._stashSize);
  21462. _stashArray2.set(new Uint8Array(chunk), this._stashUsed);
  21463. this._stashUsed += chunk.byteLength;
  21464. } else {
  21465. // stashUsed + chunkSize > stashSize, size limit exceeded
  21466. var _stashArray3 = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  21467. if (this._stashUsed > 0) {
  21468. // There're stash datas in buffer
  21469. // dispatch the whole stashBuffer, and stash remain data
  21470. // then append chunk to stashBuffer (stash)
  21471. var buffer = this._stashBuffer.slice(0, this._stashUsed);
  21472. var _consumed2 = this._dispatchChunks(buffer, this._stashByteStart);
  21473. if (_consumed2 < buffer.byteLength) {
  21474. if (_consumed2 > 0) {
  21475. var _remainArray = new Uint8Array(buffer, _consumed2);
  21476. _stashArray3.set(_remainArray, 0);
  21477. this._stashUsed = _remainArray.byteLength;
  21478. this._stashByteStart += _consumed2;
  21479. }
  21480. } else {
  21481. this._stashUsed = 0;
  21482. this._stashByteStart += _consumed2;
  21483. }
  21484. if (this._stashUsed + chunk.byteLength > this._bufferSize) {
  21485. this._expandBuffer(this._stashUsed + chunk.byteLength);
  21486. _stashArray3 = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  21487. }
  21488. _stashArray3.set(new Uint8Array(chunk), this._stashUsed);
  21489. this._stashUsed += chunk.byteLength;
  21490. } else {
  21491. // stash buffer empty, but chunkSize > stashSize (oh, holy shit)
  21492. // dispatch chunk directly and stash remain data
  21493. var _consumed3 = this._dispatchChunks(chunk, byteStart);
  21494. if (_consumed3 < chunk.byteLength) {
  21495. var _remain = chunk.byteLength - _consumed3;
  21496. if (_remain > this._bufferSize) {
  21497. this._expandBuffer(_remain);
  21498. _stashArray3 = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  21499. }
  21500. _stashArray3.set(new Uint8Array(chunk, _consumed3), 0);
  21501. this._stashUsed += _remain;
  21502. this._stashByteStart = byteStart + _consumed3;
  21503. }
  21504. }
  21505. }
  21506. }
  21507. }
  21508. }, {
  21509. key: '_flushStashBuffer',
  21510. value: function _flushStashBuffer(dropUnconsumed) {
  21511. if (this._stashUsed > 0) {
  21512. var buffer = this._stashBuffer.slice(0, this._stashUsed);
  21513. var consumed = this._dispatchChunks(buffer, this._stashByteStart);
  21514. var remain = buffer.byteLength - consumed;
  21515. if (consumed < buffer.byteLength) {
  21516. if (dropUnconsumed) {
  21517. _logger2.default.w(this.TAG, remain + ' bytes unconsumed data remain when flush buffer, dropped');
  21518. } else {
  21519. if (consumed > 0) {
  21520. var stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  21521. var remainArray = new Uint8Array(buffer, consumed);
  21522. stashArray.set(remainArray, 0);
  21523. this._stashUsed = remainArray.byteLength;
  21524. this._stashByteStart += consumed;
  21525. }
  21526. return 0;
  21527. }
  21528. }
  21529. this._stashUsed = 0;
  21530. this._stashByteStart = 0;
  21531. return remain;
  21532. }
  21533. return 0;
  21534. }
  21535. }, {
  21536. key: '_onLoaderComplete',
  21537. value: function _onLoaderComplete(from, to) {
  21538. // Force-flush stash buffer, and drop unconsumed data
  21539. this._flushStashBuffer(true);
  21540. if (this._onComplete) {
  21541. this._onComplete(this._extraData);
  21542. }
  21543. }
  21544. }, {
  21545. key: '_onLoaderError',
  21546. value: function _onLoaderError(type, data) {
  21547. _logger2.default.e(this.TAG, 'Loader error, code = ' + data.code + ', msg = ' + data.msg);
  21548. this._flushStashBuffer(false);
  21549. if (this._isEarlyEofReconnecting) {
  21550. // Auto-reconnect for EarlyEof failed, throw UnrecoverableEarlyEof error to upper-layer
  21551. this._isEarlyEofReconnecting = false;
  21552. type = _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF;
  21553. }
  21554. switch (type) {
  21555. case _loader.LoaderErrors.EARLY_EOF:
  21556. {
  21557. if (!this._config.isLive) {
  21558. // Do internal http reconnect if not live stream
  21559. if (this._totalLength) {
  21560. var nextFrom = this._currentRange.to + 1;
  21561. if (nextFrom < this._totalLength) {
  21562. _logger2.default.w(this.TAG, 'Connection lost, trying reconnect...');
  21563. this._isEarlyEofReconnecting = true;
  21564. this._internalSeek(nextFrom, false);
  21565. }
  21566. return;
  21567. }
  21568. // else: We don't know totalLength, throw UnrecoverableEarlyEof
  21569. }
  21570. // live stream: throw UnrecoverableEarlyEof error to upper-layer
  21571. type = _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF;
  21572. break;
  21573. }
  21574. case _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF:
  21575. case _loader.LoaderErrors.CONNECTING_TIMEOUT:
  21576. case _loader.LoaderErrors.HTTP_STATUS_CODE_INVALID:
  21577. case _loader.LoaderErrors.EXCEPTION:
  21578. break;
  21579. }
  21580. if (this._onError) {
  21581. this._onError(type, data);
  21582. } else {
  21583. throw new _exception.RuntimeException('IOException: ' + data.msg);
  21584. }
  21585. }
  21586. }, {
  21587. key: 'status',
  21588. get: function get() {
  21589. return this._loader.status;
  21590. }
  21591. }, {
  21592. key: 'extraData',
  21593. get: function get() {
  21594. return this._extraData;
  21595. },
  21596. set: function set(data) {
  21597. this._extraData = data;
  21598. }
  21599. // prototype: function onDataArrival(chunks: ArrayBuffer, byteStart: number): number
  21600. }, {
  21601. key: 'onDataArrival',
  21602. get: function get() {
  21603. return this._onDataArrival;
  21604. },
  21605. set: function set(callback) {
  21606. this._onDataArrival = callback;
  21607. }
  21608. }, {
  21609. key: 'onSeeked',
  21610. get: function get() {
  21611. return this._onSeeked;
  21612. },
  21613. set: function set(callback) {
  21614. this._onSeeked = callback;
  21615. }
  21616. // prototype: function onError(type: number, info: {code: number, msg: string}): void
  21617. }, {
  21618. key: 'onError',
  21619. get: function get() {
  21620. return this._onError;
  21621. },
  21622. set: function set(callback) {
  21623. this._onError = callback;
  21624. }
  21625. }, {
  21626. key: 'onComplete',
  21627. get: function get() {
  21628. return this._onComplete;
  21629. },
  21630. set: function set(callback) {
  21631. this._onComplete = callback;
  21632. }
  21633. }, {
  21634. key: 'onRedirect',
  21635. get: function get() {
  21636. return this._onRedirect;
  21637. },
  21638. set: function set(callback) {
  21639. this._onRedirect = callback;
  21640. }
  21641. }, {
  21642. key: 'onRecoveredEarlyEof',
  21643. get: function get() {
  21644. return this._onRecoveredEarlyEof;
  21645. },
  21646. set: function set(callback) {
  21647. this._onRecoveredEarlyEof = callback;
  21648. }
  21649. }, {
  21650. key: 'currentURL',
  21651. get: function get() {
  21652. return this._dataSource.url;
  21653. }
  21654. }, {
  21655. key: 'hasRedirect',
  21656. get: function get() {
  21657. return this._redirectedURL != null || this._dataSource.redirectedURL != undefined;
  21658. }
  21659. }, {
  21660. key: 'currentRedirectedURL',
  21661. get: function get() {
  21662. return this._redirectedURL || this._dataSource.redirectedURL;
  21663. }
  21664. // in KB/s
  21665. }, {
  21666. key: 'currentSpeed',
  21667. get: function get() {
  21668. if (this._loaderClass === _xhrRangeLoader2.default) {
  21669. // SpeedSampler is inaccuracy if loader is RangeLoader
  21670. return this._loader.currentSpeed;
  21671. }
  21672. return this._speedSampler.lastSecondKBps;
  21673. }
  21674. }, {
  21675. key: 'loaderType',
  21676. get: function get() {
  21677. return this._loader.type;
  21678. }
  21679. }]);
  21680. return IOController;
  21681. }();
  21682. exports.default = IOController;
  21683. module.exports = exports['default'];
  21684. /***/ }),
  21685. /* 13 */
  21686. /***/ (function(module, exports, __webpack_require__) {
  21687. "use strict";
  21688. Object.defineProperty(exports, "__esModule", {
  21689. value: true
  21690. });
  21691. 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; }; }();
  21692. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  21693. /*
  21694. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  21695. *
  21696. * @author zheng qian <xqq@xqq.im>
  21697. *
  21698. * Licensed under the Apache License, Version 2.0 (the "License");
  21699. * you may not use this file except in compliance with the License.
  21700. * You may obtain a copy of the License at
  21701. *
  21702. * http://www.apache.org/licenses/LICENSE-2.0
  21703. *
  21704. * Unless required by applicable law or agreed to in writing, software
  21705. * distributed under the License is distributed on an "AS IS" BASIS,
  21706. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21707. * See the License for the specific language governing permissions and
  21708. * limitations under the License.
  21709. */
  21710. // Utility class to calculate realtime network I/O speed
  21711. var SpeedSampler = function () {
  21712. function SpeedSampler() {
  21713. _classCallCheck(this, SpeedSampler);
  21714. // milliseconds
  21715. this._firstCheckpoint = 0;
  21716. this._lastCheckpoint = 0;
  21717. this._intervalBytes = 0;
  21718. this._totalBytes = 0;
  21719. this._lastSecondBytes = 0;
  21720. // compatibility detection
  21721. if (self.performance && self.performance.now) {
  21722. this._now = self.performance.now.bind(self.performance);
  21723. } else {
  21724. this._now = Date.now;
  21725. }
  21726. }
  21727. _createClass(SpeedSampler, [{
  21728. key: "reset",
  21729. value: function reset() {
  21730. this._firstCheckpoint = this._lastCheckpoint = 0;
  21731. this._totalBytes = this._intervalBytes = 0;
  21732. this._lastSecondBytes = 0;
  21733. }
  21734. }, {
  21735. key: "addBytes",
  21736. value: function addBytes(bytes) {
  21737. if (this._firstCheckpoint === 0) {
  21738. this._firstCheckpoint = this._now();
  21739. this._lastCheckpoint = this._firstCheckpoint;
  21740. this._intervalBytes += bytes;
  21741. this._totalBytes += bytes;
  21742. } else if (this._now() - this._lastCheckpoint < 1000) {
  21743. this._intervalBytes += bytes;
  21744. this._totalBytes += bytes;
  21745. } else {
  21746. // duration >= 1000
  21747. this._lastSecondBytes = this._intervalBytes;
  21748. this._intervalBytes = bytes;
  21749. this._totalBytes += bytes;
  21750. this._lastCheckpoint = this._now();
  21751. }
  21752. }
  21753. }, {
  21754. key: "currentKBps",
  21755. get: function get() {
  21756. this.addBytes(0);
  21757. var durationSeconds = (this._now() - this._lastCheckpoint) / 1000;
  21758. if (durationSeconds == 0) durationSeconds = 1;
  21759. return this._intervalBytes / durationSeconds / 1024;
  21760. }
  21761. }, {
  21762. key: "lastSecondKBps",
  21763. get: function get() {
  21764. this.addBytes(0);
  21765. if (this._lastSecondBytes !== 0) {
  21766. return this._lastSecondBytes / 1024;
  21767. } else {
  21768. // lastSecondBytes === 0
  21769. if (this._now() - this._lastCheckpoint >= 500) {
  21770. // if time interval since last checkpoint has exceeded 500ms
  21771. // the speed is nearly accurate
  21772. return this.currentKBps;
  21773. } else {
  21774. // We don't know
  21775. return 0;
  21776. }
  21777. }
  21778. }
  21779. }, {
  21780. key: "averageKBps",
  21781. get: function get() {
  21782. var durationSeconds = (this._now() - this._firstCheckpoint) / 1000;
  21783. return this._totalBytes / durationSeconds / 1024;
  21784. }
  21785. }]);
  21786. return SpeedSampler;
  21787. }();
  21788. exports.default = SpeedSampler;
  21789. module.exports = exports["default"];
  21790. /***/ }),
  21791. /* 14 */
  21792. /***/ (function(module, exports, __webpack_require__) {
  21793. "use strict";
  21794. Object.defineProperty(exports, "__esModule", {
  21795. value: true
  21796. });
  21797. 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; }; }(); /*
  21798. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  21799. *
  21800. * @author zheng qian <xqq@xqq.im>
  21801. *
  21802. * Licensed under the Apache License, Version 2.0 (the "License");
  21803. * you may not use this file except in compliance with the License.
  21804. * You may obtain a copy of the License at
  21805. *
  21806. * http://www.apache.org/licenses/LICENSE-2.0
  21807. *
  21808. * Unless required by applicable law or agreed to in writing, software
  21809. * distributed under the License is distributed on an "AS IS" BASIS,
  21810. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21811. * See the License for the specific language governing permissions and
  21812. * limitations under the License.
  21813. */
  21814. var _events = __webpack_require__(2);
  21815. var _events2 = _interopRequireDefault(_events);
  21816. var _logger = __webpack_require__(0);
  21817. var _logger2 = _interopRequireDefault(_logger);
  21818. var _browser = __webpack_require__(4);
  21819. var _browser2 = _interopRequireDefault(_browser);
  21820. var _mediaInfo = __webpack_require__(9);
  21821. var _mediaInfo2 = _interopRequireDefault(_mediaInfo);
  21822. var _flvDemuxer = __webpack_require__(35);
  21823. var _flvDemuxer2 = _interopRequireDefault(_flvDemuxer);
  21824. var _mp4Remuxer = __webpack_require__(40);
  21825. var _mp4Remuxer2 = _interopRequireDefault(_mp4Remuxer);
  21826. var _demuxErrors = __webpack_require__(10);
  21827. var _demuxErrors2 = _interopRequireDefault(_demuxErrors);
  21828. var _ioController = __webpack_require__(12);
  21829. var _ioController2 = _interopRequireDefault(_ioController);
  21830. var _transmuxingEvents = __webpack_require__(5);
  21831. var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
  21832. var _loader = __webpack_require__(3);
  21833. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  21834. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  21835. // Transmuxing (IO, Demuxing, Remuxing) controller, with multipart support
  21836. var TransmuxingController = function () {
  21837. function TransmuxingController(mediaDataSource, config) {
  21838. _classCallCheck(this, TransmuxingController);
  21839. this.TAG = 'TransmuxingController';
  21840. this._emitter = new _events2.default();
  21841. this._config = config;
  21842. // treat single part media as multipart media, which has only one segment
  21843. if (!mediaDataSource.segments) {
  21844. mediaDataSource.segments = [{
  21845. duration: mediaDataSource.duration,
  21846. filesize: mediaDataSource.filesize,
  21847. url: mediaDataSource.url
  21848. }];
  21849. }
  21850. // fill in default IO params if not exists
  21851. if (typeof mediaDataSource.cors !== 'boolean') {
  21852. mediaDataSource.cors = true;
  21853. }
  21854. if (typeof mediaDataSource.withCredentials !== 'boolean') {
  21855. mediaDataSource.withCredentials = false;
  21856. }
  21857. this._mediaDataSource = mediaDataSource;
  21858. this._currentSegmentIndex = 0;
  21859. var totalDuration = 0;
  21860. this._mediaDataSource.segments.forEach(function (segment) {
  21861. // timestampBase for each segment, and calculate total duration
  21862. segment.timestampBase = totalDuration;
  21863. totalDuration += segment.duration;
  21864. // params needed by IOController
  21865. segment.cors = mediaDataSource.cors;
  21866. segment.withCredentials = mediaDataSource.withCredentials;
  21867. // referrer policy control, if exist
  21868. if (config.referrerPolicy) {
  21869. segment.referrerPolicy = config.referrerPolicy;
  21870. }
  21871. });
  21872. if (!isNaN(totalDuration) && this._mediaDataSource.duration !== totalDuration) {
  21873. this._mediaDataSource.duration = totalDuration;
  21874. }
  21875. this._mediaInfo = null;
  21876. this._demuxer = null;
  21877. this._remuxer = null;
  21878. this._ioctl = null;
  21879. this._pendingSeekTime = null;
  21880. this._pendingResolveSeekPoint = null;
  21881. this._statisticsReporter = null;
  21882. }
  21883. _createClass(TransmuxingController, [{
  21884. key: 'destroy',
  21885. value: function destroy() {
  21886. this._mediaInfo = null;
  21887. this._mediaDataSource = null;
  21888. if (this._statisticsReporter) {
  21889. this._disableStatisticsReporter();
  21890. }
  21891. if (this._ioctl) {
  21892. this._ioctl.destroy();
  21893. this._ioctl = null;
  21894. }
  21895. if (this._demuxer) {
  21896. this._demuxer.destroy();
  21897. this._demuxer = null;
  21898. }
  21899. if (this._remuxer) {
  21900. this._remuxer.destroy();
  21901. this._remuxer = null;
  21902. }
  21903. this._emitter.removeAllListeners();
  21904. this._emitter = null;
  21905. }
  21906. }, {
  21907. key: 'on',
  21908. value: function on(event, listener) {
  21909. this._emitter.addListener(event, listener);
  21910. }
  21911. }, {
  21912. key: 'off',
  21913. value: function off(event, listener) {
  21914. this._emitter.removeListener(event, listener);
  21915. }
  21916. }, {
  21917. key: 'start',
  21918. value: function start() {
  21919. this._loadSegment(0);
  21920. this._enableStatisticsReporter();
  21921. }
  21922. }, {
  21923. key: '_loadSegment',
  21924. value: function _loadSegment(segmentIndex, optionalFrom) {
  21925. this._currentSegmentIndex = segmentIndex;
  21926. var dataSource = this._mediaDataSource.segments[segmentIndex];
  21927. var ioctl = this._ioctl = new _ioController2.default(dataSource, this._config, segmentIndex);
  21928. ioctl.onError = this._onIOException.bind(this);
  21929. ioctl.onSeeked = this._onIOSeeked.bind(this);
  21930. ioctl.onComplete = this._onIOComplete.bind(this);
  21931. ioctl.onRedirect = this._onIORedirect.bind(this);
  21932. ioctl.onRecoveredEarlyEof = this._onIORecoveredEarlyEof.bind(this);
  21933. if (optionalFrom) {
  21934. this._demuxer.bindDataSource(this._ioctl);
  21935. } else {
  21936. ioctl.onDataArrival = this._onInitChunkArrival.bind(this);
  21937. }
  21938. ioctl.open(optionalFrom);
  21939. }
  21940. }, {
  21941. key: 'stop',
  21942. value: function stop() {
  21943. this._internalAbort();
  21944. this._disableStatisticsReporter();
  21945. }
  21946. }, {
  21947. key: '_internalAbort',
  21948. value: function _internalAbort() {
  21949. if (this._ioctl) {
  21950. this._ioctl.destroy();
  21951. this._ioctl = null;
  21952. }
  21953. }
  21954. }, {
  21955. key: 'pause',
  21956. value: function pause() {
  21957. // take a rest
  21958. if (this._ioctl && this._ioctl.isWorking()) {
  21959. this._ioctl.pause();
  21960. this._disableStatisticsReporter();
  21961. }
  21962. }
  21963. }, {
  21964. key: 'resume',
  21965. value: function resume() {
  21966. if (this._ioctl && this._ioctl.isPaused()) {
  21967. this._ioctl.resume();
  21968. this._enableStatisticsReporter();
  21969. }
  21970. }
  21971. }, {
  21972. key: 'seek',
  21973. value: function seek(milliseconds) {
  21974. if (this._mediaInfo == null || !this._mediaInfo.isSeekable()) {
  21975. return;
  21976. }
  21977. var targetSegmentIndex = this._searchSegmentIndexContains(milliseconds);
  21978. if (targetSegmentIndex === this._currentSegmentIndex) {
  21979. // intra-segment seeking
  21980. var segmentInfo = this._mediaInfo.segments[targetSegmentIndex];
  21981. if (segmentInfo == undefined) {
  21982. // current segment loading started, but mediainfo hasn't received yet
  21983. // wait for the metadata loaded, then seek to expected position
  21984. this._pendingSeekTime = milliseconds;
  21985. } else {
  21986. var keyframe = segmentInfo.getNearestKeyframe(milliseconds);
  21987. this._remuxer.seek(keyframe.milliseconds);
  21988. this._ioctl.seek(keyframe.fileposition);
  21989. // Will be resolved in _onRemuxerMediaSegmentArrival()
  21990. this._pendingResolveSeekPoint = keyframe.milliseconds;
  21991. }
  21992. } else {
  21993. // cross-segment seeking
  21994. var targetSegmentInfo = this._mediaInfo.segments[targetSegmentIndex];
  21995. if (targetSegmentInfo == undefined) {
  21996. // target segment hasn't been loaded. We need metadata then seek to expected time
  21997. this._pendingSeekTime = milliseconds;
  21998. this._internalAbort();
  21999. this._remuxer.seek();
  22000. this._remuxer.insertDiscontinuity();
  22001. this._loadSegment(targetSegmentIndex);
  22002. // Here we wait for the metadata loaded, then seek to expected position
  22003. } else {
  22004. // We have target segment's metadata, direct seek to target position
  22005. var _keyframe = targetSegmentInfo.getNearestKeyframe(milliseconds);
  22006. this._internalAbort();
  22007. this._remuxer.seek(milliseconds);
  22008. this._remuxer.insertDiscontinuity();
  22009. this._demuxer.resetMediaInfo();
  22010. this._demuxer.timestampBase = this._mediaDataSource.segments[targetSegmentIndex].timestampBase;
  22011. this._loadSegment(targetSegmentIndex, _keyframe.fileposition);
  22012. this._pendingResolveSeekPoint = _keyframe.milliseconds;
  22013. this._reportSegmentMediaInfo(targetSegmentIndex);
  22014. }
  22015. }
  22016. this._enableStatisticsReporter();
  22017. }
  22018. }, {
  22019. key: '_searchSegmentIndexContains',
  22020. value: function _searchSegmentIndexContains(milliseconds) {
  22021. var segments = this._mediaDataSource.segments;
  22022. var idx = segments.length - 1;
  22023. for (var i = 0; i < segments.length; i++) {
  22024. if (milliseconds < segments[i].timestampBase) {
  22025. idx = i - 1;
  22026. break;
  22027. }
  22028. }
  22029. return idx;
  22030. }
  22031. }, {
  22032. key: '_onInitChunkArrival',
  22033. value: function _onInitChunkArrival(data, byteStart) {
  22034. var _this = this;
  22035. var probeData = null;
  22036. var consumed = 0;
  22037. if (byteStart > 0) {
  22038. // IOController seeked immediately after opened, byteStart > 0 callback may received
  22039. this._demuxer.bindDataSource(this._ioctl);
  22040. this._demuxer.timestampBase = this._mediaDataSource.segments[this._currentSegmentIndex].timestampBase;
  22041. consumed = this._demuxer.parseChunks(data, byteStart);
  22042. } else if ((probeData = _flvDemuxer2.default.probe(data)).match) {
  22043. // Always create new FLVDemuxer
  22044. this._demuxer = new _flvDemuxer2.default(probeData, this._config);
  22045. if (!this._remuxer) {
  22046. this._remuxer = new _mp4Remuxer2.default(this._config);
  22047. }
  22048. var mds = this._mediaDataSource;
  22049. if (mds.duration != undefined && !isNaN(mds.duration)) {
  22050. this._demuxer.overridedDuration = mds.duration;
  22051. }
  22052. if (typeof mds.hasAudio === 'boolean') {
  22053. this._demuxer.overridedHasAudio = mds.hasAudio;
  22054. }
  22055. if (typeof mds.hasVideo === 'boolean') {
  22056. this._demuxer.overridedHasVideo = mds.hasVideo;
  22057. }
  22058. this._demuxer.timestampBase = mds.segments[this._currentSegmentIndex].timestampBase;
  22059. this._demuxer.onError = this._onDemuxException.bind(this);
  22060. this._demuxer.onMediaInfo = this._onMediaInfo.bind(this);
  22061. this._demuxer.onLoadedSei = this._onLoadedSei.bind(this);
  22062. this._remuxer.bindDataSource(this._demuxer.bindDataSource(this._ioctl));
  22063. this._remuxer.onInitSegment = this._onRemuxerInitSegmentArrival.bind(this);
  22064. this._remuxer.onMediaSegment = this._onRemuxerMediaSegmentArrival.bind(this);
  22065. consumed = this._demuxer.parseChunks(data, byteStart);
  22066. } else {
  22067. probeData = null;
  22068. _logger2.default.e(this.TAG, 'Non-FLV, Unsupported media type!');
  22069. Promise.resolve().then(function () {
  22070. _this._internalAbort();
  22071. });
  22072. this._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR, _demuxErrors2.default.FORMAT_UNSUPPORTED, 'Non-FLV, Unsupported media type');
  22073. consumed = 0;
  22074. }
  22075. return consumed;
  22076. }
  22077. }, {
  22078. key: '_onMediaInfo',
  22079. value: function _onMediaInfo(mediaInfo) {
  22080. var _this2 = this;
  22081. if (this._mediaInfo == null) {
  22082. // Store first segment's mediainfo as global mediaInfo
  22083. this._mediaInfo = Object.assign({}, mediaInfo);
  22084. this._mediaInfo.keyframesIndex = null;
  22085. this._mediaInfo.segments = [];
  22086. this._mediaInfo.segmentCount = this._mediaDataSource.segments.length;
  22087. Object.setPrototypeOf(this._mediaInfo, _mediaInfo2.default.prototype);
  22088. }
  22089. var segmentInfo = Object.assign({}, mediaInfo);
  22090. Object.setPrototypeOf(segmentInfo, _mediaInfo2.default.prototype);
  22091. this._mediaInfo.segments[this._currentSegmentIndex] = segmentInfo;
  22092. // notify mediaInfo update
  22093. this._reportSegmentMediaInfo(this._currentSegmentIndex);
  22094. if (this._pendingSeekTime != null) {
  22095. Promise.resolve().then(function () {
  22096. var target = _this2._pendingSeekTime;
  22097. _this2._pendingSeekTime = null;
  22098. _this2.seek(target);
  22099. });
  22100. }
  22101. }
  22102. }, {
  22103. key: '_onLoadedSei',
  22104. value: function _onLoadedSei(timestamp, data) {
  22105. this._emitter.emit(_transmuxingEvents2.default.LOADED_SEI, timestamp, data);
  22106. }
  22107. }, {
  22108. key: '_onIOSeeked',
  22109. value: function _onIOSeeked() {
  22110. this._remuxer.insertDiscontinuity();
  22111. }
  22112. }, {
  22113. key: '_onIOComplete',
  22114. value: function _onIOComplete(extraData) {
  22115. var segmentIndex = extraData;
  22116. var nextSegmentIndex = segmentIndex + 1;
  22117. if (nextSegmentIndex < this._mediaDataSource.segments.length) {
  22118. this._internalAbort();
  22119. this._remuxer.flushStashedSamples();
  22120. this._loadSegment(nextSegmentIndex);
  22121. } else {
  22122. this._remuxer.flushStashedSamples();
  22123. this._emitter.emit(_transmuxingEvents2.default.LOADING_COMPLETE);
  22124. this._disableStatisticsReporter();
  22125. }
  22126. }
  22127. }, {
  22128. key: '_onIORedirect',
  22129. value: function _onIORedirect(redirectedURL) {
  22130. var segmentIndex = this._ioctl.extraData;
  22131. this._mediaDataSource.segments[segmentIndex].redirectedURL = redirectedURL;
  22132. }
  22133. }, {
  22134. key: '_onIORecoveredEarlyEof',
  22135. value: function _onIORecoveredEarlyEof() {
  22136. this._emitter.emit(_transmuxingEvents2.default.RECOVERED_EARLY_EOF);
  22137. }
  22138. }, {
  22139. key: '_onIOException',
  22140. value: function _onIOException(type, info) {
  22141. _logger2.default.e(this.TAG, 'IOException: type = ' + type + ', code = ' + info.code + ', msg = ' + info.msg);
  22142. this._emitter.emit(_transmuxingEvents2.default.IO_ERROR, type, info);
  22143. this._disableStatisticsReporter();
  22144. }
  22145. }, {
  22146. key: '_onDemuxException',
  22147. value: function _onDemuxException(type, info) {
  22148. _logger2.default.e(this.TAG, 'DemuxException: type = ' + type + ', info = ' + info);
  22149. this._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR, type, info);
  22150. }
  22151. }, {
  22152. key: '_onRemuxerInitSegmentArrival',
  22153. value: function _onRemuxerInitSegmentArrival(type, initSegment) {
  22154. this._emitter.emit(_transmuxingEvents2.default.INIT_SEGMENT, type, initSegment);
  22155. }
  22156. }, {
  22157. key: '_onRemuxerMediaSegmentArrival',
  22158. value: function _onRemuxerMediaSegmentArrival(type, mediaSegment) {
  22159. if (this._pendingSeekTime != null) {
  22160. // Media segments after new-segment cross-seeking should be dropped.
  22161. return;
  22162. }
  22163. this._emitter.emit(_transmuxingEvents2.default.MEDIA_SEGMENT, type, mediaSegment);
  22164. // Resolve pending seekPoint
  22165. if (this._pendingResolveSeekPoint != null && type === 'video') {
  22166. var syncPoints = mediaSegment.info.syncPoints;
  22167. var seekpoint = this._pendingResolveSeekPoint;
  22168. this._pendingResolveSeekPoint = null;
  22169. // Safari: Pass PTS for recommend_seekpoint
  22170. if (_browser2.default.safari && syncPoints.length > 0 && syncPoints[0].originalDts === seekpoint) {
  22171. seekpoint = syncPoints[0].pts;
  22172. }
  22173. // else: use original DTS (keyframe.milliseconds)
  22174. this._emitter.emit(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, seekpoint);
  22175. }
  22176. }
  22177. }, {
  22178. key: '_enableStatisticsReporter',
  22179. value: function _enableStatisticsReporter() {
  22180. if (this._statisticsReporter == null) {
  22181. this._statisticsReporter = self.setInterval(this._reportStatisticsInfo.bind(this), this._config.statisticsInfoReportInterval);
  22182. }
  22183. }
  22184. }, {
  22185. key: '_disableStatisticsReporter',
  22186. value: function _disableStatisticsReporter() {
  22187. if (this._statisticsReporter) {
  22188. self.clearInterval(this._statisticsReporter);
  22189. this._statisticsReporter = null;
  22190. }
  22191. }
  22192. }, {
  22193. key: '_reportSegmentMediaInfo',
  22194. value: function _reportSegmentMediaInfo(segmentIndex) {
  22195. var segmentInfo = this._mediaInfo.segments[segmentIndex];
  22196. var exportInfo = Object.assign({}, segmentInfo);
  22197. exportInfo.duration = this._mediaInfo.duration;
  22198. exportInfo.segmentCount = this._mediaInfo.segmentCount;
  22199. delete exportInfo.segments;
  22200. delete exportInfo.keyframesIndex;
  22201. this._emitter.emit(_transmuxingEvents2.default.MEDIA_INFO, exportInfo);
  22202. }
  22203. }, {
  22204. key: '_reportStatisticsInfo',
  22205. value: function _reportStatisticsInfo() {
  22206. var info = {};
  22207. info.url = this._ioctl.currentURL;
  22208. info.hasRedirect = this._ioctl.hasRedirect;
  22209. if (info.hasRedirect) {
  22210. info.redirectedURL = this._ioctl.currentRedirectedURL;
  22211. }
  22212. info.speed = this._ioctl.currentSpeed;
  22213. info.loaderType = this._ioctl.loaderType;
  22214. info.currentSegmentIndex = this._currentSegmentIndex;
  22215. info.totalSegmentCount = this._mediaDataSource.segments.length;
  22216. this._emitter.emit(_transmuxingEvents2.default.STATISTICS_INFO, info);
  22217. }
  22218. }]);
  22219. return TransmuxingController;
  22220. }();
  22221. exports.default = TransmuxingController;
  22222. module.exports = exports['default'];
  22223. /***/ }),
  22224. /* 15 */
  22225. /***/ (function(module, exports, __webpack_require__) {
  22226. "use strict";
  22227. Object.defineProperty(exports, "__esModule", {
  22228. value: true
  22229. });
  22230. 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; }; }();
  22231. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  22232. /*
  22233. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  22234. *
  22235. * @author zheng qian <xqq@xqq.im>
  22236. *
  22237. * Licensed under the Apache License, Version 2.0 (the "License");
  22238. * you may not use this file except in compliance with the License.
  22239. * You may obtain a copy of the License at
  22240. *
  22241. * http://www.apache.org/licenses/LICENSE-2.0
  22242. *
  22243. * Unless required by applicable law or agreed to in writing, software
  22244. * distributed under the License is distributed on an "AS IS" BASIS,
  22245. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22246. * See the License for the specific language governing permissions and
  22247. * limitations under the License.
  22248. */
  22249. // Represents an media sample (audio / video)
  22250. var SampleInfo = exports.SampleInfo = function SampleInfo(dts, pts, duration, originalDts, isSync) {
  22251. _classCallCheck(this, SampleInfo);
  22252. this.dts = dts;
  22253. this.pts = pts;
  22254. this.duration = duration;
  22255. this.originalDts = originalDts;
  22256. this.isSyncPoint = isSync;
  22257. this.fileposition = null;
  22258. };
  22259. // Media Segment concept is defined in Media Source Extensions spec.
  22260. // Particularly in ISO BMFF format, an Media Segment contains a moof box followed by a mdat box.
  22261. var MediaSegmentInfo = exports.MediaSegmentInfo = function () {
  22262. function MediaSegmentInfo() {
  22263. _classCallCheck(this, MediaSegmentInfo);
  22264. this.beginDts = 0;
  22265. this.endDts = 0;
  22266. this.beginPts = 0;
  22267. this.endPts = 0;
  22268. this.originalBeginDts = 0;
  22269. this.originalEndDts = 0;
  22270. this.syncPoints = []; // SampleInfo[n], for video IDR frames only
  22271. this.firstSample = null; // SampleInfo
  22272. this.lastSample = null; // SampleInfo
  22273. }
  22274. _createClass(MediaSegmentInfo, [{
  22275. key: "appendSyncPoint",
  22276. value: function appendSyncPoint(sampleInfo) {
  22277. // also called Random Access Point
  22278. sampleInfo.isSyncPoint = true;
  22279. this.syncPoints.push(sampleInfo);
  22280. }
  22281. }]);
  22282. return MediaSegmentInfo;
  22283. }();
  22284. // Ordered list for recording video IDR frames, sorted by originalDts
  22285. var IDRSampleList = exports.IDRSampleList = function () {
  22286. function IDRSampleList() {
  22287. _classCallCheck(this, IDRSampleList);
  22288. this._list = [];
  22289. }
  22290. _createClass(IDRSampleList, [{
  22291. key: "clear",
  22292. value: function clear() {
  22293. this._list = [];
  22294. }
  22295. }, {
  22296. key: "appendArray",
  22297. value: function appendArray(syncPoints) {
  22298. var list = this._list;
  22299. if (syncPoints.length === 0) {
  22300. return;
  22301. }
  22302. if (list.length > 0 && syncPoints[0].originalDts < list[list.length - 1].originalDts) {
  22303. this.clear();
  22304. }
  22305. Array.prototype.push.apply(list, syncPoints);
  22306. }
  22307. }, {
  22308. key: "getLastSyncPointBeforeDts",
  22309. value: function getLastSyncPointBeforeDts(dts) {
  22310. if (this._list.length == 0) {
  22311. return null;
  22312. }
  22313. var list = this._list;
  22314. var idx = 0;
  22315. var last = list.length - 1;
  22316. var mid = 0;
  22317. var lbound = 0;
  22318. var ubound = last;
  22319. if (dts < list[0].dts) {
  22320. idx = 0;
  22321. lbound = ubound + 1;
  22322. }
  22323. while (lbound <= ubound) {
  22324. mid = lbound + Math.floor((ubound - lbound) / 2);
  22325. if (mid === last || dts >= list[mid].dts && dts < list[mid + 1].dts) {
  22326. idx = mid;
  22327. break;
  22328. } else if (list[mid].dts < dts) {
  22329. lbound = mid + 1;
  22330. } else {
  22331. ubound = mid - 1;
  22332. }
  22333. }
  22334. return this._list[idx];
  22335. }
  22336. }]);
  22337. return IDRSampleList;
  22338. }();
  22339. // Data structure for recording information of media segments in single track.
  22340. var MediaSegmentInfoList = exports.MediaSegmentInfoList = function () {
  22341. function MediaSegmentInfoList(type) {
  22342. _classCallCheck(this, MediaSegmentInfoList);
  22343. this._type = type;
  22344. this._list = [];
  22345. this._lastAppendLocation = -1; // cached last insert location
  22346. }
  22347. _createClass(MediaSegmentInfoList, [{
  22348. key: "isEmpty",
  22349. value: function isEmpty() {
  22350. return this._list.length === 0;
  22351. }
  22352. }, {
  22353. key: "clear",
  22354. value: function clear() {
  22355. this._list = [];
  22356. this._lastAppendLocation = -1;
  22357. }
  22358. }, {
  22359. key: "_searchNearestSegmentBefore",
  22360. value: function _searchNearestSegmentBefore(originalBeginDts) {
  22361. var list = this._list;
  22362. if (list.length === 0) {
  22363. return -2;
  22364. }
  22365. var last = list.length - 1;
  22366. var mid = 0;
  22367. var lbound = 0;
  22368. var ubound = last;
  22369. var idx = 0;
  22370. if (originalBeginDts < list[0].originalBeginDts) {
  22371. idx = -1;
  22372. return idx;
  22373. }
  22374. while (lbound <= ubound) {
  22375. mid = lbound + Math.floor((ubound - lbound) / 2);
  22376. if (mid === last || originalBeginDts > list[mid].lastSample.originalDts && originalBeginDts < list[mid + 1].originalBeginDts) {
  22377. idx = mid;
  22378. break;
  22379. } else if (list[mid].originalBeginDts < originalBeginDts) {
  22380. lbound = mid + 1;
  22381. } else {
  22382. ubound = mid - 1;
  22383. }
  22384. }
  22385. return idx;
  22386. }
  22387. }, {
  22388. key: "_searchNearestSegmentAfter",
  22389. value: function _searchNearestSegmentAfter(originalBeginDts) {
  22390. return this._searchNearestSegmentBefore(originalBeginDts) + 1;
  22391. }
  22392. }, {
  22393. key: "append",
  22394. value: function append(mediaSegmentInfo) {
  22395. var list = this._list;
  22396. var msi = mediaSegmentInfo;
  22397. var lastAppendIdx = this._lastAppendLocation;
  22398. var insertIdx = 0;
  22399. 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)) {
  22400. insertIdx = lastAppendIdx + 1; // use cached location idx
  22401. } else {
  22402. if (list.length > 0) {
  22403. insertIdx = this._searchNearestSegmentBefore(msi.originalBeginDts) + 1;
  22404. }
  22405. }
  22406. this._lastAppendLocation = insertIdx;
  22407. this._list.splice(insertIdx, 0, msi);
  22408. }
  22409. }, {
  22410. key: "getLastSegmentBefore",
  22411. value: function getLastSegmentBefore(originalBeginDts) {
  22412. var idx = this._searchNearestSegmentBefore(originalBeginDts);
  22413. if (idx >= 0) {
  22414. return this._list[idx];
  22415. } else {
  22416. // -1
  22417. return null;
  22418. }
  22419. }
  22420. }, {
  22421. key: "getLastSampleBefore",
  22422. value: function getLastSampleBefore(originalBeginDts) {
  22423. var segment = this.getLastSegmentBefore(originalBeginDts);
  22424. if (segment != null) {
  22425. return segment.lastSample;
  22426. } else {
  22427. return null;
  22428. }
  22429. }
  22430. }, {
  22431. key: "getLastSyncPointBefore",
  22432. value: function getLastSyncPointBefore(originalBeginDts) {
  22433. var segmentIdx = this._searchNearestSegmentBefore(originalBeginDts);
  22434. var syncPoints = this._list[segmentIdx].syncPoints;
  22435. while (syncPoints.length === 0 && segmentIdx > 0) {
  22436. segmentIdx--;
  22437. syncPoints = this._list[segmentIdx].syncPoints;
  22438. }
  22439. if (syncPoints.length > 0) {
  22440. return syncPoints[syncPoints.length - 1];
  22441. } else {
  22442. return null;
  22443. }
  22444. }
  22445. }, {
  22446. key: "type",
  22447. get: function get() {
  22448. return this._type;
  22449. }
  22450. }, {
  22451. key: "length",
  22452. get: function get() {
  22453. return this._list.length;
  22454. }
  22455. }]);
  22456. return MediaSegmentInfoList;
  22457. }();
  22458. /***/ }),
  22459. /* 16 */
  22460. /***/ (function(module, exports, __webpack_require__) {
  22461. "use strict";
  22462. Object.defineProperty(exports, "__esModule", {
  22463. value: true
  22464. });
  22465. /*
  22466. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  22467. *
  22468. * @author zheng qian <xqq@xqq.im>
  22469. *
  22470. * Licensed under the Apache License, Version 2.0 (the "License");
  22471. * you may not use this file except in compliance with the License.
  22472. * You may obtain a copy of the License at
  22473. *
  22474. * http://www.apache.org/licenses/LICENSE-2.0
  22475. *
  22476. * Unless required by applicable law or agreed to in writing, software
  22477. * distributed under the License is distributed on an "AS IS" BASIS,
  22478. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22479. * See the License for the specific language governing permissions and
  22480. * limitations under the License.
  22481. */
  22482. var MSEEvents = {
  22483. ERROR: 'error',
  22484. SOURCE_OPEN: 'source_open',
  22485. UPDATE_END: 'update_end',
  22486. BUFFER_FULL: 'buffer_full'
  22487. };
  22488. exports.default = MSEEvents;
  22489. module.exports = exports['default'];
  22490. /***/ }),
  22491. /* 17 */
  22492. /***/ (function(module, exports, __webpack_require__) {
  22493. "use strict";
  22494. Object.defineProperty(exports, "__esModule", {
  22495. value: true
  22496. });
  22497. exports.ErrorDetails = exports.ErrorTypes = undefined;
  22498. var _loader = __webpack_require__(3);
  22499. var _demuxErrors = __webpack_require__(10);
  22500. var _demuxErrors2 = _interopRequireDefault(_demuxErrors);
  22501. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  22502. /*
  22503. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  22504. *
  22505. * @author zheng qian <xqq@xqq.im>
  22506. *
  22507. * Licensed under the Apache License, Version 2.0 (the "License");
  22508. * you may not use this file except in compliance with the License.
  22509. * You may obtain a copy of the License at
  22510. *
  22511. * http://www.apache.org/licenses/LICENSE-2.0
  22512. *
  22513. * Unless required by applicable law or agreed to in writing, software
  22514. * distributed under the License is distributed on an "AS IS" BASIS,
  22515. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22516. * See the License for the specific language governing permissions and
  22517. * limitations under the License.
  22518. */
  22519. var ErrorTypes = exports.ErrorTypes = {
  22520. NETWORK_ERROR: 'NetworkError',
  22521. MEDIA_ERROR: 'MediaError',
  22522. OTHER_ERROR: 'OtherError'
  22523. };
  22524. var ErrorDetails = exports.ErrorDetails = {
  22525. NETWORK_EXCEPTION: _loader.LoaderErrors.EXCEPTION,
  22526. NETWORK_STATUS_CODE_INVALID: _loader.LoaderErrors.HTTP_STATUS_CODE_INVALID,
  22527. NETWORK_TIMEOUT: _loader.LoaderErrors.CONNECTING_TIMEOUT,
  22528. NETWORK_UNRECOVERABLE_EARLY_EOF: _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF,
  22529. MEDIA_MSE_ERROR: 'MediaMSEError',
  22530. MEDIA_FORMAT_ERROR: _demuxErrors2.default.FORMAT_ERROR,
  22531. MEDIA_FORMAT_UNSUPPORTED: _demuxErrors2.default.FORMAT_UNSUPPORTED,
  22532. MEDIA_CODEC_UNSUPPORTED: _demuxErrors2.default.CODEC_UNSUPPORTED
  22533. };
  22534. /***/ }),
  22535. /* 18 */
  22536. /***/ (function(module, exports, __webpack_require__) {
  22537. module.exports = __webpack_require__(19);
  22538. /***/ }),
  22539. /* 19 */
  22540. /***/ (function(module, exports, __webpack_require__) {
  22541. "use strict";
  22542. Object.defineProperty(exports, "__esModule", {
  22543. value: true
  22544. });
  22545. 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; }; }();
  22546. var _xgplayer = __webpack_require__(20);
  22547. var _xgplayer2 = _interopRequireDefault(_xgplayer);
  22548. var _flv = __webpack_require__(21);
  22549. var _flv2 = _interopRequireDefault(_flv);
  22550. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  22551. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  22552. 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; }
  22553. 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; }
  22554. var FlvJsPlayer = function (_Player) {
  22555. _inherits(FlvJsPlayer, _Player);
  22556. function FlvJsPlayer(options) {
  22557. _classCallCheck(this, FlvJsPlayer);
  22558. var _this = _possibleConstructorReturn(this, (FlvJsPlayer.__proto__ || Object.getPrototypeOf(FlvJsPlayer)).call(this, options));
  22559. _this.flvOpts = { type: 'flv' };
  22560. _this.optionalConfig = {};
  22561. _xgplayer2.default.util.deepCopy(_this.flvOpts, options);
  22562. _xgplayer2.default.util.deepCopy(_this.optionalConfig, options.flvOptionalConfig);
  22563. var player = _this;
  22564. Object.defineProperty(player, 'src', {
  22565. get: function get() {
  22566. return player.currentSrc;
  22567. },
  22568. set: function set(url) {
  22569. player.flv_load(url);
  22570. var oldVol = player.volume;
  22571. player.video.muted = true;
  22572. _xgplayer2.default.util.addClass(player.root, 'xgplayer-is-enter');
  22573. player.once('playing', function () {
  22574. _xgplayer2.default.util.removeClass(player.root, 'xgplayer-is-enter');
  22575. player.video.muted = false;
  22576. });
  22577. player.once('canplay', function () {
  22578. player.play();
  22579. });
  22580. },
  22581. configurable: true
  22582. });
  22583. player.once('complete', function () {
  22584. player.__flv__ = _flv2.default.createPlayer(_this.flvOpts, _this.optionalConfig);
  22585. player.createInstance(player.__flv__);
  22586. if (player.config.isLive) {
  22587. _xgplayer2.default.util.addClass(player.root, 'xgplayer-is-live');
  22588. var live = _xgplayer2.default.util.createDom('xg-live', '正在直播', {}, 'xgplayer-live');
  22589. player.controls.appendChild(live);
  22590. }
  22591. });
  22592. return _this;
  22593. }
  22594. _createClass(FlvJsPlayer, [{
  22595. key: 'createInstance',
  22596. value: function createInstance(flv) {
  22597. var player = this;
  22598. player.video.addEventListener('contextmenu', function (e) {
  22599. e.preventDefault();
  22600. });
  22601. flv.attachMediaElement(player.video);
  22602. flv.load();
  22603. flv.play();
  22604. flv.on(_flv2.default.Events.ERROR, function (e) {
  22605. player.emit('error', new _xgplayer2.default.Errors('other', player.config.url));
  22606. });
  22607. flv.on(_flv2.default.Events.LOADED_SEI, function (timestamp, data) {
  22608. player.emit('loaded_sei', timestamp, data);
  22609. });
  22610. flv.on(_flv2.default.Events.STATISTICS_INFO, function (data) {
  22611. player.emit("statistics_info", data);
  22612. });
  22613. flv.on(_flv2.default.Events.MEDIA_INFO, function (data) {
  22614. player.mediainfo = data;
  22615. player.emit("MEDIA_INFO", data);
  22616. });
  22617. player.once('destroy', function () {
  22618. flv.destroy();
  22619. player.__flv__ = null;
  22620. });
  22621. }
  22622. }, {
  22623. key: 'flv_load',
  22624. value: function flv_load(newUrl) {
  22625. var mediaDataSource = this.flvOpts;
  22626. mediaDataSource.segments = [{
  22627. cors: true,
  22628. duration: undefined,
  22629. filesize: undefined,
  22630. timestampBase: 0,
  22631. url: newUrl,
  22632. withCredentials: false
  22633. }];
  22634. // mediaDataSource.cors = true
  22635. // mediaDataSource.hasAudio = true
  22636. // mediaDataSource.hasVideo = true
  22637. // mediaDataSource.isLive = true
  22638. mediaDataSource.url = newUrl;
  22639. // mediaDataSource.withCredentials = false
  22640. this.flv_load_mds(mediaDataSource);
  22641. }
  22642. }, {
  22643. key: 'flv_load_mds',
  22644. value: function flv_load_mds(mediaDataSource) {
  22645. var player = this;
  22646. if (typeof player.__flv__ !== 'undefined') {
  22647. if (player.__flv__ != null) {
  22648. player.__flv__.unload();
  22649. player.__flv__.detachMediaElement();
  22650. player.__flv__.destroy();
  22651. player.__flv__ = null;
  22652. }
  22653. }
  22654. player.__flv__ = _flv2.default.createPlayer(mediaDataSource, this.optionalConfig);
  22655. player.__flv__.attachMediaElement(player.video);
  22656. player.__flv__.load();
  22657. }
  22658. }, {
  22659. key: 'switchURL',
  22660. value: function switchURL(url) {
  22661. var player = this;
  22662. var curTime = 0;
  22663. if (!player.config.isLive) {
  22664. curTime = player.currentTime;
  22665. }
  22666. player.flv_load(url);
  22667. var oldVol = player.volume;
  22668. player.video.muted = true;
  22669. _xgplayer2.default.util.addClass(player.root, 'xgplayer-is-enter');
  22670. player.once('playing', function () {
  22671. _xgplayer2.default.util.removeClass(player.root, 'xgplayer-is-enter');
  22672. player.video.muted = false;
  22673. });
  22674. player.once('canplay', function () {
  22675. if (!player.config.isLive) {
  22676. player.currentTime = curTime;
  22677. }
  22678. player.play();
  22679. });
  22680. }
  22681. }]);
  22682. return FlvJsPlayer;
  22683. }(_xgplayer2.default);
  22684. FlvJsPlayer.isSupported = _flv2.default.isSupported;
  22685. exports.default = FlvJsPlayer;
  22686. module.exports = exports['default'];
  22687. /***/ }),
  22688. /* 20 */
  22689. /***/ (function(module, exports) {
  22690. module.exports = __WEBPACK_EXTERNAL_MODULE__20__;
  22691. /***/ }),
  22692. /* 21 */
  22693. /***/ (function(module, exports, __webpack_require__) {
  22694. "use strict";
  22695. Object.defineProperty(exports, "__esModule", {
  22696. value: true
  22697. });
  22698. 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; }; /*
  22699. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  22700. *
  22701. * @author zheng qian <xqq@xqq.im>
  22702. *
  22703. * Licensed under the Apache License, Version 2.0 (the "License");
  22704. * you may not use this file except in compliance with the License.
  22705. * You may obtain a copy of the License at
  22706. *
  22707. * http://www.apache.org/licenses/LICENSE-2.0
  22708. *
  22709. * Unless required by applicable law or agreed to in writing, software
  22710. * distributed under the License is distributed on an "AS IS" BASIS,
  22711. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22712. * See the License for the specific language governing permissions and
  22713. * limitations under the License.
  22714. */
  22715. var _polyfill = __webpack_require__(11);
  22716. var _polyfill2 = _interopRequireDefault(_polyfill);
  22717. var _features = __webpack_require__(25);
  22718. var _features2 = _interopRequireDefault(_features);
  22719. var _flvPlayer = __webpack_require__(33);
  22720. var _flvPlayer2 = _interopRequireDefault(_flvPlayer);
  22721. var _nativePlayer = __webpack_require__(46);
  22722. var _nativePlayer2 = _interopRequireDefault(_nativePlayer);
  22723. var _playerEvents = __webpack_require__(7);
  22724. var _playerEvents2 = _interopRequireDefault(_playerEvents);
  22725. var _playerErrors = __webpack_require__(17);
  22726. var _loggingControl = __webpack_require__(8);
  22727. var _loggingControl2 = _interopRequireDefault(_loggingControl);
  22728. var _exception = __webpack_require__(1);
  22729. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  22730. // here are all the interfaces
  22731. // install polyfills
  22732. _polyfill2.default.install();
  22733. // factory method
  22734. function createPlayer(mediaDataSource, optionalConfig) {
  22735. var mds = mediaDataSource;
  22736. if (mds == null || (typeof mds === 'undefined' ? 'undefined' : _typeof(mds)) !== 'object') {
  22737. throw new _exception.InvalidArgumentException('MediaDataSource must be an javascript object!');
  22738. }
  22739. if (!mds.hasOwnProperty('type')) {
  22740. throw new _exception.InvalidArgumentException('MediaDataSource must has type field to indicate video file type!');
  22741. }
  22742. switch (mds.type) {
  22743. case 'flv':
  22744. return new _flvPlayer2.default(mds, optionalConfig);
  22745. default:
  22746. return new _nativePlayer2.default(mds, optionalConfig);
  22747. }
  22748. }
  22749. // feature detection
  22750. function isSupported() {
  22751. return _features2.default.supportMSEH264Playback();
  22752. }
  22753. function getFeatureList() {
  22754. return _features2.default.getFeatureList();
  22755. }
  22756. // interfaces
  22757. var flvjs = {};
  22758. flvjs.createPlayer = createPlayer;
  22759. flvjs.isSupported = isSupported;
  22760. flvjs.getFeatureList = getFeatureList;
  22761. flvjs.Events = _playerEvents2.default;
  22762. flvjs.ErrorTypes = _playerErrors.ErrorTypes;
  22763. flvjs.ErrorDetails = _playerErrors.ErrorDetails;
  22764. flvjs.FlvPlayer = _flvPlayer2.default;
  22765. flvjs.NativePlayer = _nativePlayer2.default;
  22766. flvjs.LoggingControl = _loggingControl2.default;
  22767. Object.defineProperty(flvjs, 'version', {
  22768. enumerable: true,
  22769. get: function get() {
  22770. // replaced by browserify-versionify transform
  22771. return '__VERSION__';
  22772. }
  22773. });
  22774. exports.default = flvjs;
  22775. module.exports = exports['default'];
  22776. /***/ }),
  22777. /* 22 */
  22778. /***/ (function(module, exports, __webpack_require__) {
  22779. /* WEBPACK VAR INJECTION */(function(process, global) {/*!
  22780. * @overview es6-promise - a tiny implementation of Promises/A+.
  22781. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  22782. * @license Licensed under MIT license
  22783. * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
  22784. * @version v4.2.8+1e68dce6
  22785. */
  22786. (function (global, factory) {
  22787. true ? module.exports = factory() :
  22788. undefined;
  22789. }(this, (function () { 'use strict';
  22790. function objectOrFunction(x) {
  22791. var type = typeof x;
  22792. return x !== null && (type === 'object' || type === 'function');
  22793. }
  22794. function isFunction(x) {
  22795. return typeof x === 'function';
  22796. }
  22797. var _isArray = void 0;
  22798. if (Array.isArray) {
  22799. _isArray = Array.isArray;
  22800. } else {
  22801. _isArray = function (x) {
  22802. return Object.prototype.toString.call(x) === '[object Array]';
  22803. };
  22804. }
  22805. var isArray = _isArray;
  22806. var len = 0;
  22807. var vertxNext = void 0;
  22808. var customSchedulerFn = void 0;
  22809. var asap = function asap(callback, arg) {
  22810. queue[len] = callback;
  22811. queue[len + 1] = arg;
  22812. len += 2;
  22813. if (len === 2) {
  22814. // If len is 2, that means that we need to schedule an async flush.
  22815. // If additional callbacks are queued before the queue is flushed, they
  22816. // will be processed by this flush that we are scheduling.
  22817. if (customSchedulerFn) {
  22818. customSchedulerFn(flush);
  22819. } else {
  22820. scheduleFlush();
  22821. }
  22822. }
  22823. };
  22824. function setScheduler(scheduleFn) {
  22825. customSchedulerFn = scheduleFn;
  22826. }
  22827. function setAsap(asapFn) {
  22828. asap = asapFn;
  22829. }
  22830. var browserWindow = typeof window !== 'undefined' ? window : undefined;
  22831. var browserGlobal = browserWindow || {};
  22832. var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
  22833. var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  22834. // test for web worker but not in IE10
  22835. var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
  22836. // node
  22837. function useNextTick() {
  22838. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  22839. // see https://github.com/cujojs/when/issues/410 for details
  22840. return function () {
  22841. return process.nextTick(flush);
  22842. };
  22843. }
  22844. // vertx
  22845. function useVertxTimer() {
  22846. if (typeof vertxNext !== 'undefined') {
  22847. return function () {
  22848. vertxNext(flush);
  22849. };
  22850. }
  22851. return useSetTimeout();
  22852. }
  22853. function useMutationObserver() {
  22854. var iterations = 0;
  22855. var observer = new BrowserMutationObserver(flush);
  22856. var node = document.createTextNode('');
  22857. observer.observe(node, { characterData: true });
  22858. return function () {
  22859. node.data = iterations = ++iterations % 2;
  22860. };
  22861. }
  22862. // web worker
  22863. function useMessageChannel() {
  22864. var channel = new MessageChannel();
  22865. channel.port1.onmessage = flush;
  22866. return function () {
  22867. return channel.port2.postMessage(0);
  22868. };
  22869. }
  22870. function useSetTimeout() {
  22871. // Store setTimeout reference so es6-promise will be unaffected by
  22872. // other code modifying setTimeout (like sinon.useFakeTimers())
  22873. var globalSetTimeout = setTimeout;
  22874. return function () {
  22875. return globalSetTimeout(flush, 1);
  22876. };
  22877. }
  22878. var queue = new Array(1000);
  22879. function flush() {
  22880. for (var i = 0; i < len; i += 2) {
  22881. var callback = queue[i];
  22882. var arg = queue[i + 1];
  22883. callback(arg);
  22884. queue[i] = undefined;
  22885. queue[i + 1] = undefined;
  22886. }
  22887. len = 0;
  22888. }
  22889. function attemptVertx() {
  22890. try {
  22891. var vertx = Function('return this')().require('vertx');
  22892. vertxNext = vertx.runOnLoop || vertx.runOnContext;
  22893. return useVertxTimer();
  22894. } catch (e) {
  22895. return useSetTimeout();
  22896. }
  22897. }
  22898. var scheduleFlush = void 0;
  22899. // Decide what async method to use to triggering processing of queued callbacks:
  22900. if (isNode) {
  22901. scheduleFlush = useNextTick();
  22902. } else if (BrowserMutationObserver) {
  22903. scheduleFlush = useMutationObserver();
  22904. } else if (isWorker) {
  22905. scheduleFlush = useMessageChannel();
  22906. } else if (browserWindow === undefined && "function" === 'function') {
  22907. scheduleFlush = attemptVertx();
  22908. } else {
  22909. scheduleFlush = useSetTimeout();
  22910. }
  22911. function then(onFulfillment, onRejection) {
  22912. var parent = this;
  22913. var child = new this.constructor(noop);
  22914. if (child[PROMISE_ID] === undefined) {
  22915. makePromise(child);
  22916. }
  22917. var _state = parent._state;
  22918. if (_state) {
  22919. var callback = arguments[_state - 1];
  22920. asap(function () {
  22921. return invokeCallback(_state, child, callback, parent._result);
  22922. });
  22923. } else {
  22924. subscribe(parent, child, onFulfillment, onRejection);
  22925. }
  22926. return child;
  22927. }
  22928. /**
  22929. `Promise.resolve` returns a promise that will become resolved with the
  22930. passed `value`. It is shorthand for the following:
  22931. ```javascript
  22932. let promise = new Promise(function(resolve, reject){
  22933. resolve(1);
  22934. });
  22935. promise.then(function(value){
  22936. // value === 1
  22937. });
  22938. ```
  22939. Instead of writing the above, your code now simply becomes the following:
  22940. ```javascript
  22941. let promise = Promise.resolve(1);
  22942. promise.then(function(value){
  22943. // value === 1
  22944. });
  22945. ```
  22946. @method resolve
  22947. @static
  22948. @param {Any} value value that the returned promise will be resolved with
  22949. Useful for tooling.
  22950. @return {Promise} a promise that will become fulfilled with the given
  22951. `value`
  22952. */
  22953. function resolve$1(object) {
  22954. /*jshint validthis:true */
  22955. var Constructor = this;
  22956. if (object && typeof object === 'object' && object.constructor === Constructor) {
  22957. return object;
  22958. }
  22959. var promise = new Constructor(noop);
  22960. resolve(promise, object);
  22961. return promise;
  22962. }
  22963. var PROMISE_ID = Math.random().toString(36).substring(2);
  22964. function noop() {}
  22965. var PENDING = void 0;
  22966. var FULFILLED = 1;
  22967. var REJECTED = 2;
  22968. function selfFulfillment() {
  22969. return new TypeError("You cannot resolve a promise with itself");
  22970. }
  22971. function cannotReturnOwn() {
  22972. return new TypeError('A promises callback cannot return that same promise.');
  22973. }
  22974. function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
  22975. try {
  22976. then$$1.call(value, fulfillmentHandler, rejectionHandler);
  22977. } catch (e) {
  22978. return e;
  22979. }
  22980. }
  22981. function handleForeignThenable(promise, thenable, then$$1) {
  22982. asap(function (promise) {
  22983. var sealed = false;
  22984. var error = tryThen(then$$1, thenable, function (value) {
  22985. if (sealed) {
  22986. return;
  22987. }
  22988. sealed = true;
  22989. if (thenable !== value) {
  22990. resolve(promise, value);
  22991. } else {
  22992. fulfill(promise, value);
  22993. }
  22994. }, function (reason) {
  22995. if (sealed) {
  22996. return;
  22997. }
  22998. sealed = true;
  22999. reject(promise, reason);
  23000. }, 'Settle: ' + (promise._label || ' unknown promise'));
  23001. if (!sealed && error) {
  23002. sealed = true;
  23003. reject(promise, error);
  23004. }
  23005. }, promise);
  23006. }
  23007. function handleOwnThenable(promise, thenable) {
  23008. if (thenable._state === FULFILLED) {
  23009. fulfill(promise, thenable._result);
  23010. } else if (thenable._state === REJECTED) {
  23011. reject(promise, thenable._result);
  23012. } else {
  23013. subscribe(thenable, undefined, function (value) {
  23014. return resolve(promise, value);
  23015. }, function (reason) {
  23016. return reject(promise, reason);
  23017. });
  23018. }
  23019. }
  23020. function handleMaybeThenable(promise, maybeThenable, then$$1) {
  23021. if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
  23022. handleOwnThenable(promise, maybeThenable);
  23023. } else {
  23024. if (then$$1 === undefined) {
  23025. fulfill(promise, maybeThenable);
  23026. } else if (isFunction(then$$1)) {
  23027. handleForeignThenable(promise, maybeThenable, then$$1);
  23028. } else {
  23029. fulfill(promise, maybeThenable);
  23030. }
  23031. }
  23032. }
  23033. function resolve(promise, value) {
  23034. if (promise === value) {
  23035. reject(promise, selfFulfillment());
  23036. } else if (objectOrFunction(value)) {
  23037. var then$$1 = void 0;
  23038. try {
  23039. then$$1 = value.then;
  23040. } catch (error) {
  23041. reject(promise, error);
  23042. return;
  23043. }
  23044. handleMaybeThenable(promise, value, then$$1);
  23045. } else {
  23046. fulfill(promise, value);
  23047. }
  23048. }
  23049. function publishRejection(promise) {
  23050. if (promise._onerror) {
  23051. promise._onerror(promise._result);
  23052. }
  23053. publish(promise);
  23054. }
  23055. function fulfill(promise, value) {
  23056. if (promise._state !== PENDING) {
  23057. return;
  23058. }
  23059. promise._result = value;
  23060. promise._state = FULFILLED;
  23061. if (promise._subscribers.length !== 0) {
  23062. asap(publish, promise);
  23063. }
  23064. }
  23065. function reject(promise, reason) {
  23066. if (promise._state !== PENDING) {
  23067. return;
  23068. }
  23069. promise._state = REJECTED;
  23070. promise._result = reason;
  23071. asap(publishRejection, promise);
  23072. }
  23073. function subscribe(parent, child, onFulfillment, onRejection) {
  23074. var _subscribers = parent._subscribers;
  23075. var length = _subscribers.length;
  23076. parent._onerror = null;
  23077. _subscribers[length] = child;
  23078. _subscribers[length + FULFILLED] = onFulfillment;
  23079. _subscribers[length + REJECTED] = onRejection;
  23080. if (length === 0 && parent._state) {
  23081. asap(publish, parent);
  23082. }
  23083. }
  23084. function publish(promise) {
  23085. var subscribers = promise._subscribers;
  23086. var settled = promise._state;
  23087. if (subscribers.length === 0) {
  23088. return;
  23089. }
  23090. var child = void 0,
  23091. callback = void 0,
  23092. detail = promise._result;
  23093. for (var i = 0; i < subscribers.length; i += 3) {
  23094. child = subscribers[i];
  23095. callback = subscribers[i + settled];
  23096. if (child) {
  23097. invokeCallback(settled, child, callback, detail);
  23098. } else {
  23099. callback(detail);
  23100. }
  23101. }
  23102. promise._subscribers.length = 0;
  23103. }
  23104. function invokeCallback(settled, promise, callback, detail) {
  23105. var hasCallback = isFunction(callback),
  23106. value = void 0,
  23107. error = void 0,
  23108. succeeded = true;
  23109. if (hasCallback) {
  23110. try {
  23111. value = callback(detail);
  23112. } catch (e) {
  23113. succeeded = false;
  23114. error = e;
  23115. }
  23116. if (promise === value) {
  23117. reject(promise, cannotReturnOwn());
  23118. return;
  23119. }
  23120. } else {
  23121. value = detail;
  23122. }
  23123. if (promise._state !== PENDING) {
  23124. // noop
  23125. } else if (hasCallback && succeeded) {
  23126. resolve(promise, value);
  23127. } else if (succeeded === false) {
  23128. reject(promise, error);
  23129. } else if (settled === FULFILLED) {
  23130. fulfill(promise, value);
  23131. } else if (settled === REJECTED) {
  23132. reject(promise, value);
  23133. }
  23134. }
  23135. function initializePromise(promise, resolver) {
  23136. try {
  23137. resolver(function resolvePromise(value) {
  23138. resolve(promise, value);
  23139. }, function rejectPromise(reason) {
  23140. reject(promise, reason);
  23141. });
  23142. } catch (e) {
  23143. reject(promise, e);
  23144. }
  23145. }
  23146. var id = 0;
  23147. function nextId() {
  23148. return id++;
  23149. }
  23150. function makePromise(promise) {
  23151. promise[PROMISE_ID] = id++;
  23152. promise._state = undefined;
  23153. promise._result = undefined;
  23154. promise._subscribers = [];
  23155. }
  23156. function validationError() {
  23157. return new Error('Array Methods must be provided an Array');
  23158. }
  23159. var Enumerator = function () {
  23160. function Enumerator(Constructor, input) {
  23161. this._instanceConstructor = Constructor;
  23162. this.promise = new Constructor(noop);
  23163. if (!this.promise[PROMISE_ID]) {
  23164. makePromise(this.promise);
  23165. }
  23166. if (isArray(input)) {
  23167. this.length = input.length;
  23168. this._remaining = input.length;
  23169. this._result = new Array(this.length);
  23170. if (this.length === 0) {
  23171. fulfill(this.promise, this._result);
  23172. } else {
  23173. this.length = this.length || 0;
  23174. this._enumerate(input);
  23175. if (this._remaining === 0) {
  23176. fulfill(this.promise, this._result);
  23177. }
  23178. }
  23179. } else {
  23180. reject(this.promise, validationError());
  23181. }
  23182. }
  23183. Enumerator.prototype._enumerate = function _enumerate(input) {
  23184. for (var i = 0; this._state === PENDING && i < input.length; i++) {
  23185. this._eachEntry(input[i], i);
  23186. }
  23187. };
  23188. Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
  23189. var c = this._instanceConstructor;
  23190. var resolve$$1 = c.resolve;
  23191. if (resolve$$1 === resolve$1) {
  23192. var _then = void 0;
  23193. var error = void 0;
  23194. var didError = false;
  23195. try {
  23196. _then = entry.then;
  23197. } catch (e) {
  23198. didError = true;
  23199. error = e;
  23200. }
  23201. if (_then === then && entry._state !== PENDING) {
  23202. this._settledAt(entry._state, i, entry._result);
  23203. } else if (typeof _then !== 'function') {
  23204. this._remaining--;
  23205. this._result[i] = entry;
  23206. } else if (c === Promise$1) {
  23207. var promise = new c(noop);
  23208. if (didError) {
  23209. reject(promise, error);
  23210. } else {
  23211. handleMaybeThenable(promise, entry, _then);
  23212. }
  23213. this._willSettleAt(promise, i);
  23214. } else {
  23215. this._willSettleAt(new c(function (resolve$$1) {
  23216. return resolve$$1(entry);
  23217. }), i);
  23218. }
  23219. } else {
  23220. this._willSettleAt(resolve$$1(entry), i);
  23221. }
  23222. };
  23223. Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
  23224. var promise = this.promise;
  23225. if (promise._state === PENDING) {
  23226. this._remaining--;
  23227. if (state === REJECTED) {
  23228. reject(promise, value);
  23229. } else {
  23230. this._result[i] = value;
  23231. }
  23232. }
  23233. if (this._remaining === 0) {
  23234. fulfill(promise, this._result);
  23235. }
  23236. };
  23237. Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
  23238. var enumerator = this;
  23239. subscribe(promise, undefined, function (value) {
  23240. return enumerator._settledAt(FULFILLED, i, value);
  23241. }, function (reason) {
  23242. return enumerator._settledAt(REJECTED, i, reason);
  23243. });
  23244. };
  23245. return Enumerator;
  23246. }();
  23247. /**
  23248. `Promise.all` accepts an array of promises, and returns a new promise which
  23249. is fulfilled with an array of fulfillment values for the passed promises, or
  23250. rejected with the reason of the first passed promise to be rejected. It casts all
  23251. elements of the passed iterable to promises as it runs this algorithm.
  23252. Example:
  23253. ```javascript
  23254. let promise1 = resolve(1);
  23255. let promise2 = resolve(2);
  23256. let promise3 = resolve(3);
  23257. let promises = [ promise1, promise2, promise3 ];
  23258. Promise.all(promises).then(function(array){
  23259. // The array here would be [ 1, 2, 3 ];
  23260. });
  23261. ```
  23262. If any of the `promises` given to `all` are rejected, the first promise
  23263. that is rejected will be given as an argument to the returned promises's
  23264. rejection handler. For example:
  23265. Example:
  23266. ```javascript
  23267. let promise1 = resolve(1);
  23268. let promise2 = reject(new Error("2"));
  23269. let promise3 = reject(new Error("3"));
  23270. let promises = [ promise1, promise2, promise3 ];
  23271. Promise.all(promises).then(function(array){
  23272. // Code here never runs because there are rejected promises!
  23273. }, function(error) {
  23274. // error.message === "2"
  23275. });
  23276. ```
  23277. @method all
  23278. @static
  23279. @param {Array} entries array of promises
  23280. @param {String} label optional string for labeling the promise.
  23281. Useful for tooling.
  23282. @return {Promise} promise that is fulfilled when all `promises` have been
  23283. fulfilled, or rejected if any of them become rejected.
  23284. @static
  23285. */
  23286. function all(entries) {
  23287. return new Enumerator(this, entries).promise;
  23288. }
  23289. /**
  23290. `Promise.race` returns a new promise which is settled in the same way as the
  23291. first passed promise to settle.
  23292. Example:
  23293. ```javascript
  23294. let promise1 = new Promise(function(resolve, reject){
  23295. setTimeout(function(){
  23296. resolve('promise 1');
  23297. }, 200);
  23298. });
  23299. let promise2 = new Promise(function(resolve, reject){
  23300. setTimeout(function(){
  23301. resolve('promise 2');
  23302. }, 100);
  23303. });
  23304. Promise.race([promise1, promise2]).then(function(result){
  23305. // result === 'promise 2' because it was resolved before promise1
  23306. // was resolved.
  23307. });
  23308. ```
  23309. `Promise.race` is deterministic in that only the state of the first
  23310. settled promise matters. For example, even if other promises given to the
  23311. `promises` array argument are resolved, but the first settled promise has
  23312. become rejected before the other promises became fulfilled, the returned
  23313. promise will become rejected:
  23314. ```javascript
  23315. let promise1 = new Promise(function(resolve, reject){
  23316. setTimeout(function(){
  23317. resolve('promise 1');
  23318. }, 200);
  23319. });
  23320. let promise2 = new Promise(function(resolve, reject){
  23321. setTimeout(function(){
  23322. reject(new Error('promise 2'));
  23323. }, 100);
  23324. });
  23325. Promise.race([promise1, promise2]).then(function(result){
  23326. // Code here never runs
  23327. }, function(reason){
  23328. // reason.message === 'promise 2' because promise 2 became rejected before
  23329. // promise 1 became fulfilled
  23330. });
  23331. ```
  23332. An example real-world use case is implementing timeouts:
  23333. ```javascript
  23334. Promise.race([ajax('foo.json'), timeout(5000)])
  23335. ```
  23336. @method race
  23337. @static
  23338. @param {Array} promises array of promises to observe
  23339. Useful for tooling.
  23340. @return {Promise} a promise which settles in the same way as the first passed
  23341. promise to settle.
  23342. */
  23343. function race(entries) {
  23344. /*jshint validthis:true */
  23345. var Constructor = this;
  23346. if (!isArray(entries)) {
  23347. return new Constructor(function (_, reject) {
  23348. return reject(new TypeError('You must pass an array to race.'));
  23349. });
  23350. } else {
  23351. return new Constructor(function (resolve, reject) {
  23352. var length = entries.length;
  23353. for (var i = 0; i < length; i++) {
  23354. Constructor.resolve(entries[i]).then(resolve, reject);
  23355. }
  23356. });
  23357. }
  23358. }
  23359. /**
  23360. `Promise.reject` returns a promise rejected with the passed `reason`.
  23361. It is shorthand for the following:
  23362. ```javascript
  23363. let promise = new Promise(function(resolve, reject){
  23364. reject(new Error('WHOOPS'));
  23365. });
  23366. promise.then(function(value){
  23367. // Code here doesn't run because the promise is rejected!
  23368. }, function(reason){
  23369. // reason.message === 'WHOOPS'
  23370. });
  23371. ```
  23372. Instead of writing the above, your code now simply becomes the following:
  23373. ```javascript
  23374. let promise = Promise.reject(new Error('WHOOPS'));
  23375. promise.then(function(value){
  23376. // Code here doesn't run because the promise is rejected!
  23377. }, function(reason){
  23378. // reason.message === 'WHOOPS'
  23379. });
  23380. ```
  23381. @method reject
  23382. @static
  23383. @param {Any} reason value that the returned promise will be rejected with.
  23384. Useful for tooling.
  23385. @return {Promise} a promise rejected with the given `reason`.
  23386. */
  23387. function reject$1(reason) {
  23388. /*jshint validthis:true */
  23389. var Constructor = this;
  23390. var promise = new Constructor(noop);
  23391. reject(promise, reason);
  23392. return promise;
  23393. }
  23394. function needsResolver() {
  23395. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  23396. }
  23397. function needsNew() {
  23398. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  23399. }
  23400. /**
  23401. Promise objects represent the eventual result of an asynchronous operation. The
  23402. primary way of interacting with a promise is through its `then` method, which
  23403. registers callbacks to receive either a promise's eventual value or the reason
  23404. why the promise cannot be fulfilled.
  23405. Terminology
  23406. -----------
  23407. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  23408. - `thenable` is an object or function that defines a `then` method.
  23409. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  23410. - `exception` is a value that is thrown using the throw statement.
  23411. - `reason` is a value that indicates why a promise was rejected.
  23412. - `settled` the final resting state of a promise, fulfilled or rejected.
  23413. A promise can be in one of three states: pending, fulfilled, or rejected.
  23414. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  23415. state. Promises that are rejected have a rejection reason and are in the
  23416. rejected state. A fulfillment value is never a thenable.
  23417. Promises can also be said to *resolve* a value. If this value is also a
  23418. promise, then the original promise's settled state will match the value's
  23419. settled state. So a promise that *resolves* a promise that rejects will
  23420. itself reject, and a promise that *resolves* a promise that fulfills will
  23421. itself fulfill.
  23422. Basic Usage:
  23423. ------------
  23424. ```js
  23425. let promise = new Promise(function(resolve, reject) {
  23426. // on success
  23427. resolve(value);
  23428. // on failure
  23429. reject(reason);
  23430. });
  23431. promise.then(function(value) {
  23432. // on fulfillment
  23433. }, function(reason) {
  23434. // on rejection
  23435. });
  23436. ```
  23437. Advanced Usage:
  23438. ---------------
  23439. Promises shine when abstracting away asynchronous interactions such as
  23440. `XMLHttpRequest`s.
  23441. ```js
  23442. function getJSON(url) {
  23443. return new Promise(function(resolve, reject){
  23444. let xhr = new XMLHttpRequest();
  23445. xhr.open('GET', url);
  23446. xhr.onreadystatechange = handler;
  23447. xhr.responseType = 'json';
  23448. xhr.setRequestHeader('Accept', 'application/json');
  23449. xhr.send();
  23450. function handler() {
  23451. if (this.readyState === this.DONE) {
  23452. if (this.status === 200) {
  23453. resolve(this.response);
  23454. } else {
  23455. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  23456. }
  23457. }
  23458. };
  23459. });
  23460. }
  23461. getJSON('/posts.json').then(function(json) {
  23462. // on fulfillment
  23463. }, function(reason) {
  23464. // on rejection
  23465. });
  23466. ```
  23467. Unlike callbacks, promises are great composable primitives.
  23468. ```js
  23469. Promise.all([
  23470. getJSON('/posts'),
  23471. getJSON('/comments')
  23472. ]).then(function(values){
  23473. values[0] // => postsJSON
  23474. values[1] // => commentsJSON
  23475. return values;
  23476. });
  23477. ```
  23478. @class Promise
  23479. @param {Function} resolver
  23480. Useful for tooling.
  23481. @constructor
  23482. */
  23483. var Promise$1 = function () {
  23484. function Promise(resolver) {
  23485. this[PROMISE_ID] = nextId();
  23486. this._result = this._state = undefined;
  23487. this._subscribers = [];
  23488. if (noop !== resolver) {
  23489. typeof resolver !== 'function' && needsResolver();
  23490. this instanceof Promise ? initializePromise(this, resolver) : needsNew();
  23491. }
  23492. }
  23493. /**
  23494. The primary way of interacting with a promise is through its `then` method,
  23495. which registers callbacks to receive either a promise's eventual value or the
  23496. reason why the promise cannot be fulfilled.
  23497. ```js
  23498. findUser().then(function(user){
  23499. // user is available
  23500. }, function(reason){
  23501. // user is unavailable, and you are given the reason why
  23502. });
  23503. ```
  23504. Chaining
  23505. --------
  23506. The return value of `then` is itself a promise. This second, 'downstream'
  23507. promise is resolved with the return value of the first promise's fulfillment
  23508. or rejection handler, or rejected if the handler throws an exception.
  23509. ```js
  23510. findUser().then(function (user) {
  23511. return user.name;
  23512. }, function (reason) {
  23513. return 'default name';
  23514. }).then(function (userName) {
  23515. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  23516. // will be `'default name'`
  23517. });
  23518. findUser().then(function (user) {
  23519. throw new Error('Found user, but still unhappy');
  23520. }, function (reason) {
  23521. throw new Error('`findUser` rejected and we're unhappy');
  23522. }).then(function (value) {
  23523. // never reached
  23524. }, function (reason) {
  23525. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  23526. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  23527. });
  23528. ```
  23529. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  23530. ```js
  23531. findUser().then(function (user) {
  23532. throw new PedagogicalException('Upstream error');
  23533. }).then(function (value) {
  23534. // never reached
  23535. }).then(function (value) {
  23536. // never reached
  23537. }, function (reason) {
  23538. // The `PedgagocialException` is propagated all the way down to here
  23539. });
  23540. ```
  23541. Assimilation
  23542. ------------
  23543. Sometimes the value you want to propagate to a downstream promise can only be
  23544. retrieved asynchronously. This can be achieved by returning a promise in the
  23545. fulfillment or rejection handler. The downstream promise will then be pending
  23546. until the returned promise is settled. This is called *assimilation*.
  23547. ```js
  23548. findUser().then(function (user) {
  23549. return findCommentsByAuthor(user);
  23550. }).then(function (comments) {
  23551. // The user's comments are now available
  23552. });
  23553. ```
  23554. If the assimliated promise rejects, then the downstream promise will also reject.
  23555. ```js
  23556. findUser().then(function (user) {
  23557. return findCommentsByAuthor(user);
  23558. }).then(function (comments) {
  23559. // If `findCommentsByAuthor` fulfills, we'll have the value here
  23560. }, function (reason) {
  23561. // If `findCommentsByAuthor` rejects, we'll have the reason here
  23562. });
  23563. ```
  23564. Simple Example
  23565. --------------
  23566. Synchronous Example
  23567. ```javascript
  23568. let result;
  23569. try {
  23570. result = findResult();
  23571. // success
  23572. } catch(reason) {
  23573. // failure
  23574. }
  23575. ```
  23576. Errback Example
  23577. ```js
  23578. findResult(function(result, err){
  23579. if (err) {
  23580. // failure
  23581. } else {
  23582. // success
  23583. }
  23584. });
  23585. ```
  23586. Promise Example;
  23587. ```javascript
  23588. findResult().then(function(result){
  23589. // success
  23590. }, function(reason){
  23591. // failure
  23592. });
  23593. ```
  23594. Advanced Example
  23595. --------------
  23596. Synchronous Example
  23597. ```javascript
  23598. let author, books;
  23599. try {
  23600. author = findAuthor();
  23601. books = findBooksByAuthor(author);
  23602. // success
  23603. } catch(reason) {
  23604. // failure
  23605. }
  23606. ```
  23607. Errback Example
  23608. ```js
  23609. function foundBooks(books) {
  23610. }
  23611. function failure(reason) {
  23612. }
  23613. findAuthor(function(author, err){
  23614. if (err) {
  23615. failure(err);
  23616. // failure
  23617. } else {
  23618. try {
  23619. findBoooksByAuthor(author, function(books, err) {
  23620. if (err) {
  23621. failure(err);
  23622. } else {
  23623. try {
  23624. foundBooks(books);
  23625. } catch(reason) {
  23626. failure(reason);
  23627. }
  23628. }
  23629. });
  23630. } catch(error) {
  23631. failure(err);
  23632. }
  23633. // success
  23634. }
  23635. });
  23636. ```
  23637. Promise Example;
  23638. ```javascript
  23639. findAuthor().
  23640. then(findBooksByAuthor).
  23641. then(function(books){
  23642. // found books
  23643. }).catch(function(reason){
  23644. // something went wrong
  23645. });
  23646. ```
  23647. @method then
  23648. @param {Function} onFulfilled
  23649. @param {Function} onRejected
  23650. Useful for tooling.
  23651. @return {Promise}
  23652. */
  23653. /**
  23654. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  23655. as the catch block of a try/catch statement.
  23656. ```js
  23657. function findAuthor(){
  23658. throw new Error('couldn't find that author');
  23659. }
  23660. // synchronous
  23661. try {
  23662. findAuthor();
  23663. } catch(reason) {
  23664. // something went wrong
  23665. }
  23666. // async with promises
  23667. findAuthor().catch(function(reason){
  23668. // something went wrong
  23669. });
  23670. ```
  23671. @method catch
  23672. @param {Function} onRejection
  23673. Useful for tooling.
  23674. @return {Promise}
  23675. */
  23676. Promise.prototype.catch = function _catch(onRejection) {
  23677. return this.then(null, onRejection);
  23678. };
  23679. /**
  23680. `finally` will be invoked regardless of the promise's fate just as native
  23681. try/catch/finally behaves
  23682. Synchronous example:
  23683. ```js
  23684. findAuthor() {
  23685. if (Math.random() > 0.5) {
  23686. throw new Error();
  23687. }
  23688. return new Author();
  23689. }
  23690. try {
  23691. return findAuthor(); // succeed or fail
  23692. } catch(error) {
  23693. return findOtherAuther();
  23694. } finally {
  23695. // always runs
  23696. // doesn't affect the return value
  23697. }
  23698. ```
  23699. Asynchronous example:
  23700. ```js
  23701. findAuthor().catch(function(reason){
  23702. return findOtherAuther();
  23703. }).finally(function(){
  23704. // author was either found, or not
  23705. });
  23706. ```
  23707. @method finally
  23708. @param {Function} callback
  23709. @return {Promise}
  23710. */
  23711. Promise.prototype.finally = function _finally(callback) {
  23712. var promise = this;
  23713. var constructor = promise.constructor;
  23714. if (isFunction(callback)) {
  23715. return promise.then(function (value) {
  23716. return constructor.resolve(callback()).then(function () {
  23717. return value;
  23718. });
  23719. }, function (reason) {
  23720. return constructor.resolve(callback()).then(function () {
  23721. throw reason;
  23722. });
  23723. });
  23724. }
  23725. return promise.then(callback, callback);
  23726. };
  23727. return Promise;
  23728. }();
  23729. Promise$1.prototype.then = then;
  23730. Promise$1.all = all;
  23731. Promise$1.race = race;
  23732. Promise$1.resolve = resolve$1;
  23733. Promise$1.reject = reject$1;
  23734. Promise$1._setScheduler = setScheduler;
  23735. Promise$1._setAsap = setAsap;
  23736. Promise$1._asap = asap;
  23737. /*global self*/
  23738. function polyfill() {
  23739. var local = void 0;
  23740. if (typeof global !== 'undefined') {
  23741. local = global;
  23742. } else if (typeof self !== 'undefined') {
  23743. local = self;
  23744. } else {
  23745. try {
  23746. local = Function('return this')();
  23747. } catch (e) {
  23748. throw new Error('polyfill failed because global object is unavailable in this environment');
  23749. }
  23750. }
  23751. var P = local.Promise;
  23752. if (P) {
  23753. var promiseToString = null;
  23754. try {
  23755. promiseToString = Object.prototype.toString.call(P.resolve());
  23756. } catch (e) {
  23757. // silently ignored
  23758. }
  23759. if (promiseToString === '[object Promise]' && !P.cast) {
  23760. return;
  23761. }
  23762. }
  23763. local.Promise = Promise$1;
  23764. }
  23765. // Strange compat..
  23766. Promise$1.polyfill = polyfill;
  23767. Promise$1.Promise = Promise$1;
  23768. return Promise$1;
  23769. })));
  23770. //# sourceMappingURL=es6-promise.map
  23771. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(23), __webpack_require__(24)))
  23772. /***/ }),
  23773. /* 23 */
  23774. /***/ (function(module, exports) {
  23775. // shim for using process in browser
  23776. var process = module.exports = {};
  23777. // cached from whatever global is present so that test runners that stub it
  23778. // don't break things. But we need to wrap it in a try catch in case it is
  23779. // wrapped in strict mode code which doesn't define any globals. It's inside a
  23780. // function because try/catches deoptimize in certain engines.
  23781. var cachedSetTimeout;
  23782. var cachedClearTimeout;
  23783. function defaultSetTimout() {
  23784. throw new Error('setTimeout has not been defined');
  23785. }
  23786. function defaultClearTimeout () {
  23787. throw new Error('clearTimeout has not been defined');
  23788. }
  23789. (function () {
  23790. try {
  23791. if (typeof setTimeout === 'function') {
  23792. cachedSetTimeout = setTimeout;
  23793. } else {
  23794. cachedSetTimeout = defaultSetTimout;
  23795. }
  23796. } catch (e) {
  23797. cachedSetTimeout = defaultSetTimout;
  23798. }
  23799. try {
  23800. if (typeof clearTimeout === 'function') {
  23801. cachedClearTimeout = clearTimeout;
  23802. } else {
  23803. cachedClearTimeout = defaultClearTimeout;
  23804. }
  23805. } catch (e) {
  23806. cachedClearTimeout = defaultClearTimeout;
  23807. }
  23808. } ())
  23809. function runTimeout(fun) {
  23810. if (cachedSetTimeout === setTimeout) {
  23811. //normal enviroments in sane situations
  23812. return setTimeout(fun, 0);
  23813. }
  23814. // if setTimeout wasn't available but was latter defined
  23815. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  23816. cachedSetTimeout = setTimeout;
  23817. return setTimeout(fun, 0);
  23818. }
  23819. try {
  23820. // when when somebody has screwed with setTimeout but no I.E. maddness
  23821. return cachedSetTimeout(fun, 0);
  23822. } catch(e){
  23823. try {
  23824. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  23825. return cachedSetTimeout.call(null, fun, 0);
  23826. } catch(e){
  23827. // 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
  23828. return cachedSetTimeout.call(this, fun, 0);
  23829. }
  23830. }
  23831. }
  23832. function runClearTimeout(marker) {
  23833. if (cachedClearTimeout === clearTimeout) {
  23834. //normal enviroments in sane situations
  23835. return clearTimeout(marker);
  23836. }
  23837. // if clearTimeout wasn't available but was latter defined
  23838. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  23839. cachedClearTimeout = clearTimeout;
  23840. return clearTimeout(marker);
  23841. }
  23842. try {
  23843. // when when somebody has screwed with setTimeout but no I.E. maddness
  23844. return cachedClearTimeout(marker);
  23845. } catch (e){
  23846. try {
  23847. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  23848. return cachedClearTimeout.call(null, marker);
  23849. } catch (e){
  23850. // 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.
  23851. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  23852. return cachedClearTimeout.call(this, marker);
  23853. }
  23854. }
  23855. }
  23856. var queue = [];
  23857. var draining = false;
  23858. var currentQueue;
  23859. var queueIndex = -1;
  23860. function cleanUpNextTick() {
  23861. if (!draining || !currentQueue) {
  23862. return;
  23863. }
  23864. draining = false;
  23865. if (currentQueue.length) {
  23866. queue = currentQueue.concat(queue);
  23867. } else {
  23868. queueIndex = -1;
  23869. }
  23870. if (queue.length) {
  23871. drainQueue();
  23872. }
  23873. }
  23874. function drainQueue() {
  23875. if (draining) {
  23876. return;
  23877. }
  23878. var timeout = runTimeout(cleanUpNextTick);
  23879. draining = true;
  23880. var len = queue.length;
  23881. while(len) {
  23882. currentQueue = queue;
  23883. queue = [];
  23884. while (++queueIndex < len) {
  23885. if (currentQueue) {
  23886. currentQueue[queueIndex].run();
  23887. }
  23888. }
  23889. queueIndex = -1;
  23890. len = queue.length;
  23891. }
  23892. currentQueue = null;
  23893. draining = false;
  23894. runClearTimeout(timeout);
  23895. }
  23896. process.nextTick = function (fun) {
  23897. var args = new Array(arguments.length - 1);
  23898. if (arguments.length > 1) {
  23899. for (var i = 1; i < arguments.length; i++) {
  23900. args[i - 1] = arguments[i];
  23901. }
  23902. }
  23903. queue.push(new Item(fun, args));
  23904. if (queue.length === 1 && !draining) {
  23905. runTimeout(drainQueue);
  23906. }
  23907. };
  23908. // v8 likes predictible objects
  23909. function Item(fun, array) {
  23910. this.fun = fun;
  23911. this.array = array;
  23912. }
  23913. Item.prototype.run = function () {
  23914. this.fun.apply(null, this.array);
  23915. };
  23916. process.title = 'browser';
  23917. process.browser = true;
  23918. process.env = {};
  23919. process.argv = [];
  23920. process.version = ''; // empty string to avoid regexp issues
  23921. process.versions = {};
  23922. function noop() {}
  23923. process.on = noop;
  23924. process.addListener = noop;
  23925. process.once = noop;
  23926. process.off = noop;
  23927. process.removeListener = noop;
  23928. process.removeAllListeners = noop;
  23929. process.emit = noop;
  23930. process.prependListener = noop;
  23931. process.prependOnceListener = noop;
  23932. process.listeners = function (name) { return [] }
  23933. process.binding = function (name) {
  23934. throw new Error('process.binding is not supported');
  23935. };
  23936. process.cwd = function () { return '/' };
  23937. process.chdir = function (dir) {
  23938. throw new Error('process.chdir is not supported');
  23939. };
  23940. process.umask = function() { return 0; };
  23941. /***/ }),
  23942. /* 24 */
  23943. /***/ (function(module, exports) {
  23944. var g;
  23945. // This works in non-strict mode
  23946. g = (function() {
  23947. return this;
  23948. })();
  23949. try {
  23950. // This works if eval is allowed (see CSP)
  23951. g = g || new Function("return this")();
  23952. } catch (e) {
  23953. // This works if the window reference is available
  23954. if (typeof window === "object") g = window;
  23955. }
  23956. // g can still be undefined, but nothing to do about it...
  23957. // We return undefined, instead of nothing here, so it's
  23958. // easier to handle this case. if(!global) { ...}
  23959. module.exports = g;
  23960. /***/ }),
  23961. /* 25 */
  23962. /***/ (function(module, exports, __webpack_require__) {
  23963. "use strict";
  23964. Object.defineProperty(exports, "__esModule", {
  23965. value: true
  23966. });
  23967. 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; }; }(); /*
  23968. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  23969. *
  23970. * @author zheng qian <xqq@xqq.im>
  23971. *
  23972. * Licensed under the Apache License, Version 2.0 (the "License");
  23973. * you may not use this file except in compliance with the License.
  23974. * You may obtain a copy of the License at
  23975. *
  23976. * http://www.apache.org/licenses/LICENSE-2.0
  23977. *
  23978. * Unless required by applicable law or agreed to in writing, software
  23979. * distributed under the License is distributed on an "AS IS" BASIS,
  23980. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23981. * See the License for the specific language governing permissions and
  23982. * limitations under the License.
  23983. */
  23984. var _ioController = __webpack_require__(12);
  23985. var _ioController2 = _interopRequireDefault(_ioController);
  23986. var _config = __webpack_require__(6);
  23987. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  23988. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  23989. var Features = function () {
  23990. function Features() {
  23991. _classCallCheck(this, Features);
  23992. }
  23993. _createClass(Features, null, [{
  23994. key: 'supportMSEH264Playback',
  23995. value: function supportMSEH264Playback() {
  23996. return window.MediaSource && window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
  23997. }
  23998. }, {
  23999. key: 'supportNetworkStreamIO',
  24000. value: function supportNetworkStreamIO() {
  24001. var ioctl = new _ioController2.default({}, (0, _config.createDefaultConfig)());
  24002. var loaderType = ioctl.loaderType;
  24003. ioctl.destroy();
  24004. return loaderType == 'fetch-stream-loader' || loaderType == 'xhr-moz-chunked-loader';
  24005. }
  24006. }, {
  24007. key: 'getNetworkLoaderTypeName',
  24008. value: function getNetworkLoaderTypeName() {
  24009. var ioctl = new _ioController2.default({}, (0, _config.createDefaultConfig)());
  24010. var loaderType = ioctl.loaderType;
  24011. ioctl.destroy();
  24012. return loaderType;
  24013. }
  24014. }, {
  24015. key: 'supportNativeMediaPlayback',
  24016. value: function supportNativeMediaPlayback(mimeType) {
  24017. if (Features.videoElement == undefined) {
  24018. Features.videoElement = window.document.createElement('video');
  24019. }
  24020. var canPlay = Features.videoElement.canPlayType(mimeType);
  24021. return canPlay === 'probably' || canPlay == 'maybe';
  24022. }
  24023. }, {
  24024. key: 'getFeatureList',
  24025. value: function getFeatureList() {
  24026. var features = {
  24027. mseFlvPlayback: false,
  24028. mseLiveFlvPlayback: false,
  24029. networkStreamIO: false,
  24030. networkLoaderName: '',
  24031. nativeMP4H264Playback: false,
  24032. nativeWebmVP8Playback: false,
  24033. nativeWebmVP9Playback: false
  24034. };
  24035. features.mseFlvPlayback = Features.supportMSEH264Playback();
  24036. features.networkStreamIO = Features.supportNetworkStreamIO();
  24037. features.networkLoaderName = Features.getNetworkLoaderTypeName();
  24038. features.mseLiveFlvPlayback = features.mseFlvPlayback && features.networkStreamIO;
  24039. features.nativeMP4H264Playback = Features.supportNativeMediaPlayback('video/mp4; codecs="avc1.42001E, mp4a.40.2"');
  24040. features.nativeWebmVP8Playback = Features.supportNativeMediaPlayback('video/webm; codecs="vp8.0, vorbis"');
  24041. features.nativeWebmVP9Playback = Features.supportNativeMediaPlayback('video/webm; codecs="vp9"');
  24042. return features;
  24043. }
  24044. }]);
  24045. return Features;
  24046. }();
  24047. exports.default = Features;
  24048. module.exports = exports['default'];
  24049. /***/ }),
  24050. /* 26 */
  24051. /***/ (function(module, exports, __webpack_require__) {
  24052. "use strict";
  24053. Object.defineProperty(exports, "__esModule", {
  24054. value: true
  24055. });
  24056. 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; };
  24057. 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); } };
  24058. 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; }; }();
  24059. var _logger = __webpack_require__(0);
  24060. var _logger2 = _interopRequireDefault(_logger);
  24061. var _browser = __webpack_require__(4);
  24062. var _browser2 = _interopRequireDefault(_browser);
  24063. var _loader = __webpack_require__(3);
  24064. var _exception = __webpack_require__(1);
  24065. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24066. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  24067. 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; }
  24068. 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; } /*
  24069. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  24070. *
  24071. * @author zheng qian <xqq@xqq.im>
  24072. *
  24073. * Licensed under the Apache License, Version 2.0 (the "License");
  24074. * you may not use this file except in compliance with the License.
  24075. * You may obtain a copy of the License at
  24076. *
  24077. * http://www.apache.org/licenses/LICENSE-2.0
  24078. *
  24079. * Unless required by applicable law or agreed to in writing, software
  24080. * distributed under the License is distributed on an "AS IS" BASIS,
  24081. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24082. * See the License for the specific language governing permissions and
  24083. * limitations under the License.
  24084. */
  24085. /* fetch + stream IO loader. Currently working on chrome 43+.
  24086. * fetch provides a better alternative http API to XMLHttpRequest
  24087. *
  24088. * fetch spec https://fetch.spec.whatwg.org/
  24089. * stream spec https://streams.spec.whatwg.org/
  24090. */
  24091. var FetchStreamLoader = function (_BaseLoader) {
  24092. _inherits(FetchStreamLoader, _BaseLoader);
  24093. _createClass(FetchStreamLoader, null, [{
  24094. key: 'isSupported',
  24095. value: function isSupported() {
  24096. try {
  24097. // fetch + stream is broken on Microsoft Edge. Disable before build 15048.
  24098. // see https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8196907/
  24099. // Fixed in Jan 10, 2017. Build 15048+ removed from blacklist.
  24100. var isWorkWellEdge = _browser2.default.msedge && _browser2.default.version.minor >= 15048;
  24101. var browserNotBlacklisted = _browser2.default.msedge ? isWorkWellEdge : true;
  24102. return self.fetch && self.ReadableStream && browserNotBlacklisted;
  24103. } catch (e) {
  24104. return false;
  24105. }
  24106. }
  24107. }]);
  24108. function FetchStreamLoader(seekHandler, config) {
  24109. _classCallCheck(this, FetchStreamLoader);
  24110. var _this = _possibleConstructorReturn(this, (FetchStreamLoader.__proto__ || Object.getPrototypeOf(FetchStreamLoader)).call(this, 'fetch-stream-loader'));
  24111. _this.TAG = 'FetchStreamLoader';
  24112. _this._seekHandler = seekHandler;
  24113. _this._config = config;
  24114. _this._needStash = true;
  24115. _this._requestAbort = false;
  24116. _this._contentLength = null;
  24117. _this._receivedLength = 0;
  24118. return _this;
  24119. }
  24120. _createClass(FetchStreamLoader, [{
  24121. key: 'destroy',
  24122. value: function destroy() {
  24123. if (this.isWorking()) {
  24124. this.abort();
  24125. }
  24126. _get(FetchStreamLoader.prototype.__proto__ || Object.getPrototypeOf(FetchStreamLoader.prototype), 'destroy', this).call(this);
  24127. }
  24128. }, {
  24129. key: 'open',
  24130. value: function open(dataSource, range) {
  24131. var _this2 = this;
  24132. this._dataSource = dataSource;
  24133. this._range = range;
  24134. var sourceURL = dataSource.url;
  24135. if (this._config.reuseRedirectedURL && dataSource.redirectedURL != undefined) {
  24136. sourceURL = dataSource.redirectedURL;
  24137. }
  24138. var seekConfig = this._seekHandler.getConfig(sourceURL, range);
  24139. var headers = new self.Headers();
  24140. if (_typeof(seekConfig.headers) === 'object') {
  24141. var configHeaders = seekConfig.headers;
  24142. for (var key in configHeaders) {
  24143. if (configHeaders.hasOwnProperty(key)) {
  24144. headers.append(key, configHeaders[key]);
  24145. }
  24146. }
  24147. }
  24148. var params = {
  24149. method: 'GET',
  24150. headers: headers,
  24151. mode: 'cors',
  24152. cache: 'default',
  24153. // The default policy of Fetch API in the whatwg standard
  24154. // Safari incorrectly indicates 'no-referrer' as default policy, fuck it
  24155. referrerPolicy: 'no-referrer-when-downgrade'
  24156. };
  24157. // cors is enabled by default
  24158. if (dataSource.cors === false) {
  24159. // no-cors means 'disregard cors policy', which can only be used in ServiceWorker
  24160. params.mode = 'same-origin';
  24161. }
  24162. // withCredentials is disabled by default
  24163. if (dataSource.withCredentials) {
  24164. params.credentials = 'include';
  24165. }
  24166. // referrerPolicy from config
  24167. if (dataSource.referrerPolicy) {
  24168. params.referrerPolicy = dataSource.referrerPolicy;
  24169. }
  24170. this._status = _loader.LoaderStatus.kConnecting;
  24171. self.fetch(seekConfig.url, params).then(function (res) {
  24172. if (_this2._requestAbort) {
  24173. _this2._requestAbort = false;
  24174. _this2._status = _loader.LoaderStatus.kIdle;
  24175. return;
  24176. }
  24177. if (res.ok && res.status >= 200 && res.status <= 299) {
  24178. if (res.url !== seekConfig.url) {
  24179. if (_this2._onURLRedirect) {
  24180. var redirectedURL = _this2._seekHandler.removeURLParameters(res.url);
  24181. _this2._onURLRedirect(redirectedURL);
  24182. }
  24183. }
  24184. var lengthHeader = res.headers.get('Content-Length');
  24185. if (lengthHeader != null) {
  24186. _this2._contentLength = parseInt(lengthHeader);
  24187. if (_this2._contentLength !== 0) {
  24188. if (_this2._onContentLengthKnown) {
  24189. _this2._onContentLengthKnown(_this2._contentLength);
  24190. }
  24191. }
  24192. }
  24193. return _this2._pump.call(_this2, res.body.getReader());
  24194. } else {
  24195. _this2._status = _loader.LoaderStatus.kError;
  24196. if (_this2._onError) {
  24197. _this2._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: res.status, msg: res.statusText });
  24198. } else {
  24199. throw new _exception.RuntimeException('FetchStreamLoader: Http code invalid, ' + res.status + ' ' + res.statusText);
  24200. }
  24201. }
  24202. }).catch(function (e) {
  24203. _this2._status = _loader.LoaderStatus.kError;
  24204. if (_this2._onError) {
  24205. _this2._onError(_loader.LoaderErrors.EXCEPTION, { code: -1, msg: e.message });
  24206. } else {
  24207. throw e;
  24208. }
  24209. });
  24210. }
  24211. }, {
  24212. key: 'abort',
  24213. value: function abort() {
  24214. this._requestAbort = true;
  24215. }
  24216. }, {
  24217. key: '_pump',
  24218. value: function _pump(reader) {
  24219. var _this3 = this;
  24220. // ReadableStreamReader
  24221. return reader.read().then(function (result) {
  24222. if (result.done) {
  24223. // First check received length
  24224. if (_this3._contentLength !== null && _this3._receivedLength < _this3._contentLength) {
  24225. // Report Early-EOF
  24226. _this3._status = _loader.LoaderStatus.kError;
  24227. var type = _loader.LoaderErrors.EARLY_EOF;
  24228. var info = { code: -1, msg: 'Fetch stream meet Early-EOF' };
  24229. if (_this3._onError) {
  24230. _this3._onError(type, info);
  24231. } else {
  24232. throw new _exception.RuntimeException(info.msg);
  24233. }
  24234. } else {
  24235. // OK. Download complete
  24236. _this3._status = _loader.LoaderStatus.kComplete;
  24237. if (_this3._onComplete) {
  24238. _this3._onComplete(_this3._range.from, _this3._range.from + _this3._receivedLength - 1);
  24239. }
  24240. }
  24241. } else {
  24242. if (_this3._requestAbort === true) {
  24243. _this3._requestAbort = false;
  24244. _this3._status = _loader.LoaderStatus.kComplete;
  24245. return reader.cancel();
  24246. }
  24247. _this3._status = _loader.LoaderStatus.kBuffering;
  24248. var chunk = result.value.buffer;
  24249. var byteStart = _this3._range.from + _this3._receivedLength;
  24250. _this3._receivedLength += chunk.byteLength;
  24251. if (_this3._onDataArrival) {
  24252. _this3._onDataArrival(chunk, byteStart, _this3._receivedLength);
  24253. }
  24254. _this3._pump(reader);
  24255. }
  24256. }).catch(function (e) {
  24257. if (e.code === 11 && _browser2.default.msedge) {
  24258. // InvalidStateError on Microsoft Edge
  24259. // Workaround: Edge may throw InvalidStateError after ReadableStreamReader.cancel() call
  24260. // Ignore the unknown exception.
  24261. // Related issue: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/11265202/
  24262. return;
  24263. }
  24264. _this3._status = _loader.LoaderStatus.kError;
  24265. var type = 0;
  24266. var info = null;
  24267. if ((e.code === 19 || e.message === 'network error') && ( // NETWORK_ERR
  24268. _this3._contentLength === null || _this3._contentLength !== null && _this3._receivedLength < _this3._contentLength)) {
  24269. type = _loader.LoaderErrors.EARLY_EOF;
  24270. info = { code: e.code, msg: 'Fetch stream meet Early-EOF' };
  24271. } else {
  24272. type = _loader.LoaderErrors.EXCEPTION;
  24273. info = { code: e.code, msg: e.message };
  24274. }
  24275. if (_this3._onError) {
  24276. _this3._onError(type, info);
  24277. } else {
  24278. throw new _exception.RuntimeException(info.msg);
  24279. }
  24280. });
  24281. }
  24282. }]);
  24283. return FetchStreamLoader;
  24284. }(_loader.BaseLoader);
  24285. exports.default = FetchStreamLoader;
  24286. module.exports = exports['default'];
  24287. /***/ }),
  24288. /* 27 */
  24289. /***/ (function(module, exports, __webpack_require__) {
  24290. "use strict";
  24291. Object.defineProperty(exports, "__esModule", {
  24292. value: true
  24293. });
  24294. 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; };
  24295. 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); } };
  24296. 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; }; }();
  24297. var _logger = __webpack_require__(0);
  24298. var _logger2 = _interopRequireDefault(_logger);
  24299. var _loader = __webpack_require__(3);
  24300. var _exception = __webpack_require__(1);
  24301. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24302. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  24303. 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; }
  24304. 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; } /*
  24305. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  24306. *
  24307. * @author zheng qian <xqq@xqq.im>
  24308. *
  24309. * Licensed under the Apache License, Version 2.0 (the "License");
  24310. * you may not use this file except in compliance with the License.
  24311. * You may obtain a copy of the License at
  24312. *
  24313. * http://www.apache.org/licenses/LICENSE-2.0
  24314. *
  24315. * Unless required by applicable law or agreed to in writing, software
  24316. * distributed under the License is distributed on an "AS IS" BASIS,
  24317. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24318. * See the License for the specific language governing permissions and
  24319. * limitations under the License.
  24320. */
  24321. // For FireFox browser which supports `xhr.responseType = 'moz-chunked-arraybuffer'`
  24322. var MozChunkedLoader = function (_BaseLoader) {
  24323. _inherits(MozChunkedLoader, _BaseLoader);
  24324. _createClass(MozChunkedLoader, null, [{
  24325. key: 'isSupported',
  24326. value: function isSupported() {
  24327. try {
  24328. var xhr = new XMLHttpRequest();
  24329. // Firefox 37- requires .open() to be called before setting responseType
  24330. xhr.open('GET', 'https://example.com', true);
  24331. xhr.responseType = 'moz-chunked-arraybuffer';
  24332. return xhr.responseType === 'moz-chunked-arraybuffer';
  24333. } catch (e) {
  24334. _logger2.default.w('MozChunkedLoader', e.message);
  24335. return false;
  24336. }
  24337. }
  24338. }]);
  24339. function MozChunkedLoader(seekHandler, config) {
  24340. _classCallCheck(this, MozChunkedLoader);
  24341. var _this = _possibleConstructorReturn(this, (MozChunkedLoader.__proto__ || Object.getPrototypeOf(MozChunkedLoader)).call(this, 'xhr-moz-chunked-loader'));
  24342. _this.TAG = 'MozChunkedLoader';
  24343. _this._seekHandler = seekHandler;
  24344. _this._config = config;
  24345. _this._needStash = true;
  24346. _this._xhr = null;
  24347. _this._requestAbort = false;
  24348. _this._contentLength = null;
  24349. _this._receivedLength = 0;
  24350. return _this;
  24351. }
  24352. _createClass(MozChunkedLoader, [{
  24353. key: 'destroy',
  24354. value: function destroy() {
  24355. if (this.isWorking()) {
  24356. this.abort();
  24357. }
  24358. if (this._xhr) {
  24359. this._xhr.onreadystatechange = null;
  24360. this._xhr.onprogress = null;
  24361. this._xhr.onloadend = null;
  24362. this._xhr.onerror = null;
  24363. this._xhr = null;
  24364. }
  24365. _get(MozChunkedLoader.prototype.__proto__ || Object.getPrototypeOf(MozChunkedLoader.prototype), 'destroy', this).call(this);
  24366. }
  24367. }, {
  24368. key: 'open',
  24369. value: function open(dataSource, range) {
  24370. this._dataSource = dataSource;
  24371. this._range = range;
  24372. var sourceURL = dataSource.url;
  24373. if (this._config.reuseRedirectedURL && dataSource.redirectedURL != undefined) {
  24374. sourceURL = dataSource.redirectedURL;
  24375. }
  24376. var seekConfig = this._seekHandler.getConfig(sourceURL, range);
  24377. this._requestURL = seekConfig.url;
  24378. var xhr = this._xhr = new XMLHttpRequest();
  24379. xhr.open('GET', seekConfig.url, true);
  24380. xhr.responseType = 'moz-chunked-arraybuffer';
  24381. xhr.onreadystatechange = this._onReadyStateChange.bind(this);
  24382. xhr.onprogress = this._onProgress.bind(this);
  24383. xhr.onloadend = this._onLoadEnd.bind(this);
  24384. xhr.onerror = this._onXhrError.bind(this);
  24385. // cors is auto detected and enabled by xhr
  24386. // withCredentials is disabled by default
  24387. if (dataSource.withCredentials) {
  24388. xhr.withCredentials = true;
  24389. }
  24390. if (_typeof(seekConfig.headers) === 'object') {
  24391. var headers = seekConfig.headers;
  24392. for (var key in headers) {
  24393. if (headers.hasOwnProperty(key)) {
  24394. xhr.setRequestHeader(key, headers[key]);
  24395. }
  24396. }
  24397. }
  24398. this._status = _loader.LoaderStatus.kConnecting;
  24399. xhr.send();
  24400. }
  24401. }, {
  24402. key: 'abort',
  24403. value: function abort() {
  24404. this._requestAbort = true;
  24405. if (this._xhr) {
  24406. this._xhr.abort();
  24407. }
  24408. this._status = _loader.LoaderStatus.kComplete;
  24409. }
  24410. }, {
  24411. key: '_onReadyStateChange',
  24412. value: function _onReadyStateChange(e) {
  24413. var xhr = e.target;
  24414. if (xhr.readyState === 2) {
  24415. // HEADERS_RECEIVED
  24416. if (xhr.responseURL != undefined && xhr.responseURL !== this._requestURL) {
  24417. if (this._onURLRedirect) {
  24418. var redirectedURL = this._seekHandler.removeURLParameters(xhr.responseURL);
  24419. this._onURLRedirect(redirectedURL);
  24420. }
  24421. }
  24422. if (xhr.status !== 0 && (xhr.status < 200 || xhr.status > 299)) {
  24423. this._status = _loader.LoaderStatus.kError;
  24424. if (this._onError) {
  24425. this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: xhr.status, msg: xhr.statusText });
  24426. } else {
  24427. throw new _exception.RuntimeException('MozChunkedLoader: Http code invalid, ' + xhr.status + ' ' + xhr.statusText);
  24428. }
  24429. } else {
  24430. this._status = _loader.LoaderStatus.kBuffering;
  24431. }
  24432. }
  24433. }
  24434. }, {
  24435. key: '_onProgress',
  24436. value: function _onProgress(e) {
  24437. if (this._status === _loader.LoaderStatus.kError) {
  24438. // Ignore error response
  24439. return;
  24440. }
  24441. if (this._contentLength === null) {
  24442. if (e.total !== null && e.total !== 0) {
  24443. this._contentLength = e.total;
  24444. if (this._onContentLengthKnown) {
  24445. this._onContentLengthKnown(this._contentLength);
  24446. }
  24447. }
  24448. }
  24449. var chunk = e.target.response;
  24450. var byteStart = this._range.from + this._receivedLength;
  24451. this._receivedLength += chunk.byteLength;
  24452. if (this._onDataArrival) {
  24453. this._onDataArrival(chunk, byteStart, this._receivedLength);
  24454. }
  24455. }
  24456. }, {
  24457. key: '_onLoadEnd',
  24458. value: function _onLoadEnd(e) {
  24459. if (this._requestAbort === true) {
  24460. this._requestAbort = false;
  24461. return;
  24462. } else if (this._status === _loader.LoaderStatus.kError) {
  24463. return;
  24464. }
  24465. this._status = _loader.LoaderStatus.kComplete;
  24466. if (this._onComplete) {
  24467. this._onComplete(this._range.from, this._range.from + this._receivedLength - 1);
  24468. }
  24469. }
  24470. }, {
  24471. key: '_onXhrError',
  24472. value: function _onXhrError(e) {
  24473. this._status = _loader.LoaderStatus.kError;
  24474. var type = 0;
  24475. var info = null;
  24476. if (this._contentLength && e.loaded < this._contentLength) {
  24477. type = _loader.LoaderErrors.EARLY_EOF;
  24478. info = { code: -1, msg: 'Moz-Chunked stream meet Early-Eof' };
  24479. } else {
  24480. type = _loader.LoaderErrors.EXCEPTION;
  24481. info = { code: -1, msg: e.constructor.name + ' ' + e.type };
  24482. }
  24483. if (this._onError) {
  24484. this._onError(type, info);
  24485. } else {
  24486. throw new _exception.RuntimeException(info.msg);
  24487. }
  24488. }
  24489. }]);
  24490. return MozChunkedLoader;
  24491. }(_loader.BaseLoader);
  24492. exports.default = MozChunkedLoader;
  24493. module.exports = exports['default'];
  24494. /***/ }),
  24495. /* 28 */
  24496. /***/ (function(module, exports, __webpack_require__) {
  24497. "use strict";
  24498. Object.defineProperty(exports, "__esModule", {
  24499. value: true
  24500. });
  24501. 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; };
  24502. 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); } };
  24503. 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; }; }();
  24504. var _logger = __webpack_require__(0);
  24505. var _logger2 = _interopRequireDefault(_logger);
  24506. var _loader = __webpack_require__(3);
  24507. var _exception = __webpack_require__(1);
  24508. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24509. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  24510. 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; }
  24511. 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; } /*
  24512. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  24513. *
  24514. * @author zheng qian <xqq@xqq.im>
  24515. *
  24516. * Licensed under the Apache License, Version 2.0 (the "License");
  24517. * you may not use this file except in compliance with the License.
  24518. * You may obtain a copy of the License at
  24519. *
  24520. * http://www.apache.org/licenses/LICENSE-2.0
  24521. *
  24522. * Unless required by applicable law or agreed to in writing, software
  24523. * distributed under the License is distributed on an "AS IS" BASIS,
  24524. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24525. * See the License for the specific language governing permissions and
  24526. * limitations under the License.
  24527. */
  24528. /* Notice: ms-stream may cause IE/Edge browser crash if seek too frequently!!!
  24529. * The browser may crash in wininet.dll. Disable for now.
  24530. *
  24531. * For IE11/Edge browser by microsoft which supports `xhr.responseType = 'ms-stream'`
  24532. * Notice that ms-stream API sucks. The buffer is always expanding along with downloading.
  24533. *
  24534. * We need to abort the xhr if buffer size exceeded limit size (e.g. 16 MiB), then do reconnect.
  24535. * in order to release previous ArrayBuffer to avoid memory leak
  24536. *
  24537. * Otherwise, the ArrayBuffer will increase to a terrible size that equals final file size.
  24538. */
  24539. var MSStreamLoader = function (_BaseLoader) {
  24540. _inherits(MSStreamLoader, _BaseLoader);
  24541. _createClass(MSStreamLoader, null, [{
  24542. key: 'isSupported',
  24543. value: function isSupported() {
  24544. try {
  24545. if (typeof self.MSStream === 'undefined' || typeof self.MSStreamReader === 'undefined') {
  24546. return false;
  24547. }
  24548. var xhr = new XMLHttpRequest();
  24549. xhr.open('GET', 'https://example.com', true);
  24550. xhr.responseType = 'ms-stream';
  24551. return xhr.responseType === 'ms-stream';
  24552. } catch (e) {
  24553. _logger2.default.w('MSStreamLoader', e.message);
  24554. return false;
  24555. }
  24556. }
  24557. }]);
  24558. function MSStreamLoader(seekHandler, config) {
  24559. _classCallCheck(this, MSStreamLoader);
  24560. var _this = _possibleConstructorReturn(this, (MSStreamLoader.__proto__ || Object.getPrototypeOf(MSStreamLoader)).call(this, 'xhr-msstream-loader'));
  24561. _this.TAG = 'MSStreamLoader';
  24562. _this._seekHandler = seekHandler;
  24563. _this._config = config;
  24564. _this._needStash = true;
  24565. _this._xhr = null;
  24566. _this._reader = null; // MSStreamReader
  24567. _this._totalRange = null;
  24568. _this._currentRange = null;
  24569. _this._currentRequestURL = null;
  24570. _this._currentRedirectedURL = null;
  24571. _this._contentLength = null;
  24572. _this._receivedLength = 0;
  24573. _this._bufferLimit = 16 * 1024 * 1024; // 16MB
  24574. _this._lastTimeBufferSize = 0;
  24575. _this._isReconnecting = false;
  24576. return _this;
  24577. }
  24578. _createClass(MSStreamLoader, [{
  24579. key: 'destroy',
  24580. value: function destroy() {
  24581. if (this.isWorking()) {
  24582. this.abort();
  24583. }
  24584. if (this._reader) {
  24585. this._reader.onprogress = null;
  24586. this._reader.onload = null;
  24587. this._reader.onerror = null;
  24588. this._reader = null;
  24589. }
  24590. if (this._xhr) {
  24591. this._xhr.onreadystatechange = null;
  24592. this._xhr = null;
  24593. }
  24594. _get(MSStreamLoader.prototype.__proto__ || Object.getPrototypeOf(MSStreamLoader.prototype), 'destroy', this).call(this);
  24595. }
  24596. }, {
  24597. key: 'open',
  24598. value: function open(dataSource, range) {
  24599. this._internalOpen(dataSource, range, false);
  24600. }
  24601. }, {
  24602. key: '_internalOpen',
  24603. value: function _internalOpen(dataSource, range, isSubrange) {
  24604. this._dataSource = dataSource;
  24605. if (!isSubrange) {
  24606. this._totalRange = range;
  24607. } else {
  24608. this._currentRange = range;
  24609. }
  24610. var sourceURL = dataSource.url;
  24611. if (this._config.reuseRedirectedURL) {
  24612. if (this._currentRedirectedURL != undefined) {
  24613. sourceURL = this._currentRedirectedURL;
  24614. } else if (dataSource.redirectedURL != undefined) {
  24615. sourceURL = dataSource.redirectedURL;
  24616. }
  24617. }
  24618. var seekConfig = this._seekHandler.getConfig(sourceURL, range);
  24619. this._currentRequestURL = seekConfig.url;
  24620. var reader = this._reader = new self.MSStreamReader();
  24621. reader.onprogress = this._msrOnProgress.bind(this);
  24622. reader.onload = this._msrOnLoad.bind(this);
  24623. reader.onerror = this._msrOnError.bind(this);
  24624. var xhr = this._xhr = new XMLHttpRequest();
  24625. xhr.open('GET', seekConfig.url, true);
  24626. xhr.responseType = 'ms-stream';
  24627. xhr.onreadystatechange = this._xhrOnReadyStateChange.bind(this);
  24628. xhr.onerror = this._xhrOnError.bind(this);
  24629. if (dataSource.withCredentials) {
  24630. xhr.withCredentials = true;
  24631. }
  24632. if (_typeof(seekConfig.headers) === 'object') {
  24633. var headers = seekConfig.headers;
  24634. for (var key in headers) {
  24635. if (headers.hasOwnProperty(key)) {
  24636. xhr.setRequestHeader(key, headers[key]);
  24637. }
  24638. }
  24639. }
  24640. if (this._isReconnecting) {
  24641. this._isReconnecting = false;
  24642. } else {
  24643. this._status = _loader.LoaderStatus.kConnecting;
  24644. }
  24645. xhr.send();
  24646. }
  24647. }, {
  24648. key: 'abort',
  24649. value: function abort() {
  24650. this._internalAbort();
  24651. this._status = _loader.LoaderStatus.kComplete;
  24652. }
  24653. }, {
  24654. key: '_internalAbort',
  24655. value: function _internalAbort() {
  24656. if (this._reader) {
  24657. if (this._reader.readyState === 1) {
  24658. // LOADING
  24659. this._reader.abort();
  24660. }
  24661. this._reader.onprogress = null;
  24662. this._reader.onload = null;
  24663. this._reader.onerror = null;
  24664. this._reader = null;
  24665. }
  24666. if (this._xhr) {
  24667. this._xhr.abort();
  24668. this._xhr.onreadystatechange = null;
  24669. this._xhr = null;
  24670. }
  24671. }
  24672. }, {
  24673. key: '_xhrOnReadyStateChange',
  24674. value: function _xhrOnReadyStateChange(e) {
  24675. var xhr = e.target;
  24676. if (xhr.readyState === 2) {
  24677. // HEADERS_RECEIVED
  24678. if (xhr.status >= 200 && xhr.status <= 299) {
  24679. this._status = _loader.LoaderStatus.kBuffering;
  24680. if (xhr.responseURL != undefined) {
  24681. var redirectedURL = this._seekHandler.removeURLParameters(xhr.responseURL);
  24682. if (xhr.responseURL !== this._currentRequestURL && redirectedURL !== this._currentRedirectedURL) {
  24683. this._currentRedirectedURL = redirectedURL;
  24684. if (this._onURLRedirect) {
  24685. this._onURLRedirect(redirectedURL);
  24686. }
  24687. }
  24688. }
  24689. var lengthHeader = xhr.getResponseHeader('Content-Length');
  24690. if (lengthHeader != null && this._contentLength == null) {
  24691. var length = parseInt(lengthHeader);
  24692. if (length > 0) {
  24693. this._contentLength = length;
  24694. if (this._onContentLengthKnown) {
  24695. this._onContentLengthKnown(this._contentLength);
  24696. }
  24697. }
  24698. }
  24699. } else {
  24700. this._status = _loader.LoaderStatus.kError;
  24701. if (this._onError) {
  24702. this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: xhr.status, msg: xhr.statusText });
  24703. } else {
  24704. throw new _exception.RuntimeException('MSStreamLoader: Http code invalid, ' + xhr.status + ' ' + xhr.statusText);
  24705. }
  24706. }
  24707. } else if (xhr.readyState === 3) {
  24708. // LOADING
  24709. if (xhr.status >= 200 && xhr.status <= 299) {
  24710. this._status = _loader.LoaderStatus.kBuffering;
  24711. var msstream = xhr.response;
  24712. this._reader.readAsArrayBuffer(msstream);
  24713. }
  24714. }
  24715. }
  24716. }, {
  24717. key: '_xhrOnError',
  24718. value: function _xhrOnError(e) {
  24719. this._status = _loader.LoaderStatus.kError;
  24720. var type = _loader.LoaderErrors.EXCEPTION;
  24721. var info = { code: -1, msg: e.constructor.name + ' ' + e.type };
  24722. if (this._onError) {
  24723. this._onError(type, info);
  24724. } else {
  24725. throw new _exception.RuntimeException(info.msg);
  24726. }
  24727. }
  24728. }, {
  24729. key: '_msrOnProgress',
  24730. value: function _msrOnProgress(e) {
  24731. var reader = e.target;
  24732. var bigbuffer = reader.result;
  24733. if (bigbuffer == null) {
  24734. // result may be null, workaround for buggy M$
  24735. this._doReconnectIfNeeded();
  24736. return;
  24737. }
  24738. var slice = bigbuffer.slice(this._lastTimeBufferSize);
  24739. this._lastTimeBufferSize = bigbuffer.byteLength;
  24740. var byteStart = this._totalRange.from + this._receivedLength;
  24741. this._receivedLength += slice.byteLength;
  24742. if (this._onDataArrival) {
  24743. this._onDataArrival(slice, byteStart, this._receivedLength);
  24744. }
  24745. if (bigbuffer.byteLength >= this._bufferLimit) {
  24746. _logger2.default.v(this.TAG, 'MSStream buffer exceeded max size near ' + (byteStart + slice.byteLength) + ', reconnecting...');
  24747. this._doReconnectIfNeeded();
  24748. }
  24749. }
  24750. }, {
  24751. key: '_doReconnectIfNeeded',
  24752. value: function _doReconnectIfNeeded() {
  24753. if (this._contentLength == null || this._receivedLength < this._contentLength) {
  24754. this._isReconnecting = true;
  24755. this._lastTimeBufferSize = 0;
  24756. this._internalAbort();
  24757. var range = {
  24758. from: this._totalRange.from + this._receivedLength,
  24759. to: -1
  24760. };
  24761. this._internalOpen(this._dataSource, range, true);
  24762. }
  24763. }
  24764. }, {
  24765. key: '_msrOnLoad',
  24766. value: function _msrOnLoad(e) {
  24767. // actually it is onComplete event
  24768. this._status = _loader.LoaderStatus.kComplete;
  24769. if (this._onComplete) {
  24770. this._onComplete(this._totalRange.from, this._totalRange.from + this._receivedLength - 1);
  24771. }
  24772. }
  24773. }, {
  24774. key: '_msrOnError',
  24775. value: function _msrOnError(e) {
  24776. this._status = _loader.LoaderStatus.kError;
  24777. var type = 0;
  24778. var info = null;
  24779. if (this._contentLength && this._receivedLength < this._contentLength) {
  24780. type = _loader.LoaderErrors.EARLY_EOF;
  24781. info = { code: -1, msg: 'MSStream meet Early-Eof' };
  24782. } else {
  24783. type = _loader.LoaderErrors.EARLY_EOF;
  24784. info = { code: -1, msg: e.constructor.name + ' ' + e.type };
  24785. }
  24786. if (this._onError) {
  24787. this._onError(type, info);
  24788. } else {
  24789. throw new _exception.RuntimeException(info.msg);
  24790. }
  24791. }
  24792. }]);
  24793. return MSStreamLoader;
  24794. }(_loader.BaseLoader);
  24795. exports.default = MSStreamLoader;
  24796. module.exports = exports['default'];
  24797. /***/ }),
  24798. /* 29 */
  24799. /***/ (function(module, exports, __webpack_require__) {
  24800. "use strict";
  24801. Object.defineProperty(exports, "__esModule", {
  24802. value: true
  24803. });
  24804. 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; };
  24805. 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); } };
  24806. 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; }; }();
  24807. var _logger = __webpack_require__(0);
  24808. var _logger2 = _interopRequireDefault(_logger);
  24809. var _speedSampler = __webpack_require__(13);
  24810. var _speedSampler2 = _interopRequireDefault(_speedSampler);
  24811. var _loader = __webpack_require__(3);
  24812. var _exception = __webpack_require__(1);
  24813. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24814. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  24815. 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; }
  24816. 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; } /*
  24817. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  24818. *
  24819. * @author zheng qian <xqq@xqq.im>
  24820. *
  24821. * Licensed under the Apache License, Version 2.0 (the "License");
  24822. * you may not use this file except in compliance with the License.
  24823. * You may obtain a copy of the License at
  24824. *
  24825. * http://www.apache.org/licenses/LICENSE-2.0
  24826. *
  24827. * Unless required by applicable law or agreed to in writing, software
  24828. * distributed under the License is distributed on an "AS IS" BASIS,
  24829. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24830. * See the License for the specific language governing permissions and
  24831. * limitations under the License.
  24832. */
  24833. // Universal IO Loader, implemented by adding Range header in xhr's request header
  24834. var RangeLoader = function (_BaseLoader) {
  24835. _inherits(RangeLoader, _BaseLoader);
  24836. _createClass(RangeLoader, null, [{
  24837. key: 'isSupported',
  24838. value: function isSupported() {
  24839. try {
  24840. var xhr = new XMLHttpRequest();
  24841. xhr.open('GET', 'https://example.com', true);
  24842. xhr.responseType = 'arraybuffer';
  24843. return xhr.responseType === 'arraybuffer';
  24844. } catch (e) {
  24845. _logger2.default.w('RangeLoader', e.message);
  24846. return false;
  24847. }
  24848. }
  24849. }]);
  24850. function RangeLoader(seekHandler, config) {
  24851. _classCallCheck(this, RangeLoader);
  24852. var _this = _possibleConstructorReturn(this, (RangeLoader.__proto__ || Object.getPrototypeOf(RangeLoader)).call(this, 'xhr-range-loader'));
  24853. _this.TAG = 'RangeLoader';
  24854. _this._seekHandler = seekHandler;
  24855. _this._config = config;
  24856. _this._needStash = false;
  24857. _this._chunkSizeKBList = [128, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 5120, 6144, 7168, 8192];
  24858. _this._currentChunkSizeKB = 384;
  24859. _this._currentSpeedNormalized = 0;
  24860. _this._zeroSpeedChunkCount = 0;
  24861. _this._xhr = null;
  24862. _this._speedSampler = new _speedSampler2.default();
  24863. _this._requestAbort = false;
  24864. _this._waitForTotalLength = false;
  24865. _this._totalLengthReceived = false;
  24866. _this._currentRequestURL = null;
  24867. _this._currentRedirectedURL = null;
  24868. _this._currentRequestRange = null;
  24869. _this._totalLength = null; // size of the entire file
  24870. _this._contentLength = null; // Content-Length of entire request range
  24871. _this._receivedLength = 0; // total received bytes
  24872. _this._lastTimeLoaded = 0; // received bytes of current request sub-range
  24873. return _this;
  24874. }
  24875. _createClass(RangeLoader, [{
  24876. key: 'destroy',
  24877. value: function destroy() {
  24878. if (this.isWorking()) {
  24879. this.abort();
  24880. }
  24881. if (this._xhr) {
  24882. this._xhr.onreadystatechange = null;
  24883. this._xhr.onprogress = null;
  24884. this._xhr.onload = null;
  24885. this._xhr.onerror = null;
  24886. this._xhr = null;
  24887. }
  24888. _get(RangeLoader.prototype.__proto__ || Object.getPrototypeOf(RangeLoader.prototype), 'destroy', this).call(this);
  24889. }
  24890. }, {
  24891. key: 'open',
  24892. value: function open(dataSource, range) {
  24893. this._dataSource = dataSource;
  24894. this._range = range;
  24895. this._status = _loader.LoaderStatus.kConnecting;
  24896. var useRefTotalLength = false;
  24897. if (this._dataSource.filesize != undefined && this._dataSource.filesize !== 0) {
  24898. useRefTotalLength = true;
  24899. this._totalLength = this._dataSource.filesize;
  24900. }
  24901. if (!this._totalLengthReceived && !useRefTotalLength) {
  24902. // We need total filesize
  24903. this._waitForTotalLength = true;
  24904. this._internalOpen(this._dataSource, { from: 0, to: -1 });
  24905. } else {
  24906. // We have filesize, start loading
  24907. this._openSubRange();
  24908. }
  24909. }
  24910. }, {
  24911. key: '_openSubRange',
  24912. value: function _openSubRange() {
  24913. var chunkSize = this._currentChunkSizeKB * 1024;
  24914. var from = this._range.from + this._receivedLength;
  24915. var to = from + chunkSize;
  24916. if (this._contentLength != null) {
  24917. if (to - this._range.from >= this._contentLength) {
  24918. to = this._range.from + this._contentLength - 1;
  24919. }
  24920. }
  24921. this._currentRequestRange = { from: from, to: to };
  24922. this._internalOpen(this._dataSource, this._currentRequestRange);
  24923. }
  24924. }, {
  24925. key: '_internalOpen',
  24926. value: function _internalOpen(dataSource, range) {
  24927. this._lastTimeLoaded = 0;
  24928. var sourceURL = dataSource.url;
  24929. if (this._config.reuseRedirectedURL) {
  24930. if (this._currentRedirectedURL != undefined) {
  24931. sourceURL = this._currentRedirectedURL;
  24932. } else if (dataSource.redirectedURL != undefined) {
  24933. sourceURL = dataSource.redirectedURL;
  24934. }
  24935. }
  24936. var seekConfig = this._seekHandler.getConfig(sourceURL, range);
  24937. this._currentRequestURL = seekConfig.url;
  24938. var xhr = this._xhr = new XMLHttpRequest();
  24939. xhr.open('GET', seekConfig.url, true);
  24940. xhr.responseType = 'arraybuffer';
  24941. xhr.onreadystatechange = this._onReadyStateChange.bind(this);
  24942. xhr.onprogress = this._onProgress.bind(this);
  24943. xhr.onload = this._onLoad.bind(this);
  24944. xhr.onerror = this._onXhrError.bind(this);
  24945. if (dataSource.withCredentials) {
  24946. xhr.withCredentials = true;
  24947. }
  24948. if (_typeof(seekConfig.headers) === 'object') {
  24949. var headers = seekConfig.headers;
  24950. for (var key in headers) {
  24951. if (headers.hasOwnProperty(key)) {
  24952. xhr.setRequestHeader(key, headers[key]);
  24953. }
  24954. }
  24955. }
  24956. xhr.send();
  24957. }
  24958. }, {
  24959. key: 'abort',
  24960. value: function abort() {
  24961. this._requestAbort = true;
  24962. this._internalAbort();
  24963. this._status = _loader.LoaderStatus.kComplete;
  24964. }
  24965. }, {
  24966. key: '_internalAbort',
  24967. value: function _internalAbort() {
  24968. if (this._xhr) {
  24969. this._xhr.onreadystatechange = null;
  24970. this._xhr.onprogress = null;
  24971. this._xhr.onload = null;
  24972. this._xhr.onerror = null;
  24973. this._xhr.abort();
  24974. this._xhr = null;
  24975. }
  24976. }
  24977. }, {
  24978. key: '_onReadyStateChange',
  24979. value: function _onReadyStateChange(e) {
  24980. var xhr = e.target;
  24981. if (xhr.readyState === 2) {
  24982. // HEADERS_RECEIVED
  24983. if (xhr.responseURL != undefined) {
  24984. // if the browser support this property
  24985. var redirectedURL = this._seekHandler.removeURLParameters(xhr.responseURL);
  24986. if (xhr.responseURL !== this._currentRequestURL && redirectedURL !== this._currentRedirectedURL) {
  24987. this._currentRedirectedURL = redirectedURL;
  24988. if (this._onURLRedirect) {
  24989. this._onURLRedirect(redirectedURL);
  24990. }
  24991. }
  24992. }
  24993. if (xhr.status >= 200 && xhr.status <= 299) {
  24994. if (this._waitForTotalLength) {
  24995. return;
  24996. }
  24997. this._status = _loader.LoaderStatus.kBuffering;
  24998. } else {
  24999. this._status = _loader.LoaderStatus.kError;
  25000. if (this._onError) {
  25001. this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: xhr.status, msg: xhr.statusText });
  25002. } else {
  25003. throw new _exception.RuntimeException('RangeLoader: Http code invalid, ' + xhr.status + ' ' + xhr.statusText);
  25004. }
  25005. }
  25006. }
  25007. }
  25008. }, {
  25009. key: '_onProgress',
  25010. value: function _onProgress(e) {
  25011. if (this._status === _loader.LoaderStatus.kError) {
  25012. // Ignore error response
  25013. return;
  25014. }
  25015. if (this._contentLength === null) {
  25016. var openNextRange = false;
  25017. if (this._waitForTotalLength) {
  25018. this._waitForTotalLength = false;
  25019. this._totalLengthReceived = true;
  25020. openNextRange = true;
  25021. var total = e.total;
  25022. this._internalAbort();
  25023. if (total != null & total !== 0) {
  25024. this._totalLength = total;
  25025. }
  25026. }
  25027. // calculate currrent request range's contentLength
  25028. if (this._range.to === -1) {
  25029. this._contentLength = this._totalLength - this._range.from;
  25030. } else {
  25031. // to !== -1
  25032. this._contentLength = this._range.to - this._range.from + 1;
  25033. }
  25034. if (openNextRange) {
  25035. this._openSubRange();
  25036. return;
  25037. }
  25038. if (this._onContentLengthKnown) {
  25039. this._onContentLengthKnown(this._contentLength);
  25040. }
  25041. }
  25042. var delta = e.loaded - this._lastTimeLoaded;
  25043. this._lastTimeLoaded = e.loaded;
  25044. this._speedSampler.addBytes(delta);
  25045. }
  25046. }, {
  25047. key: '_normalizeSpeed',
  25048. value: function _normalizeSpeed(input) {
  25049. var list = this._chunkSizeKBList;
  25050. var last = list.length - 1;
  25051. var mid = 0;
  25052. var lbound = 0;
  25053. var ubound = last;
  25054. if (input < list[0]) {
  25055. return list[0];
  25056. }
  25057. while (lbound <= ubound) {
  25058. mid = lbound + Math.floor((ubound - lbound) / 2);
  25059. if (mid === last || input >= list[mid] && input < list[mid + 1]) {
  25060. return list[mid];
  25061. } else if (list[mid] < input) {
  25062. lbound = mid + 1;
  25063. } else {
  25064. ubound = mid - 1;
  25065. }
  25066. }
  25067. }
  25068. }, {
  25069. key: '_onLoad',
  25070. value: function _onLoad(e) {
  25071. if (this._status === _loader.LoaderStatus.kError) {
  25072. // Ignore error response
  25073. return;
  25074. }
  25075. if (this._waitForTotalLength) {
  25076. this._waitForTotalLength = false;
  25077. return;
  25078. }
  25079. this._lastTimeLoaded = 0;
  25080. var KBps = this._speedSampler.lastSecondKBps;
  25081. if (KBps === 0) {
  25082. this._zeroSpeedChunkCount++;
  25083. if (this._zeroSpeedChunkCount >= 3) {
  25084. // Try get currentKBps after 3 chunks
  25085. KBps = this._speedSampler.currentKBps;
  25086. }
  25087. }
  25088. if (KBps !== 0) {
  25089. var normalized = this._normalizeSpeed(KBps);
  25090. if (this._currentSpeedNormalized !== normalized) {
  25091. this._currentSpeedNormalized = normalized;
  25092. this._currentChunkSizeKB = normalized;
  25093. }
  25094. }
  25095. var chunk = e.target.response;
  25096. var byteStart = this._range.from + this._receivedLength;
  25097. this._receivedLength += chunk.byteLength;
  25098. var reportComplete = false;
  25099. if (this._contentLength != null && this._receivedLength < this._contentLength) {
  25100. // continue load next chunk
  25101. this._openSubRange();
  25102. } else {
  25103. reportComplete = true;
  25104. }
  25105. // dispatch received chunk
  25106. if (this._onDataArrival) {
  25107. this._onDataArrival(chunk, byteStart, this._receivedLength);
  25108. }
  25109. if (reportComplete) {
  25110. this._status = _loader.LoaderStatus.kComplete;
  25111. if (this._onComplete) {
  25112. this._onComplete(this._range.from, this._range.from + this._receivedLength - 1);
  25113. }
  25114. }
  25115. }
  25116. }, {
  25117. key: '_onXhrError',
  25118. value: function _onXhrError(e) {
  25119. this._status = _loader.LoaderStatus.kError;
  25120. var type = 0;
  25121. var info = null;
  25122. if (this._contentLength && this._receivedLength > 0 && this._receivedLength < this._contentLength) {
  25123. type = _loader.LoaderErrors.EARLY_EOF;
  25124. info = { code: -1, msg: 'RangeLoader meet Early-Eof' };
  25125. } else {
  25126. type = _loader.LoaderErrors.EXCEPTION;
  25127. info = { code: -1, msg: e.constructor.name + ' ' + e.type };
  25128. }
  25129. if (this._onError) {
  25130. this._onError(type, info);
  25131. } else {
  25132. throw new _exception.RuntimeException(info.msg);
  25133. }
  25134. }
  25135. }, {
  25136. key: 'currentSpeed',
  25137. get: function get() {
  25138. return this._speedSampler.lastSecondKBps;
  25139. }
  25140. }]);
  25141. return RangeLoader;
  25142. }(_loader.BaseLoader);
  25143. exports.default = RangeLoader;
  25144. module.exports = exports['default'];
  25145. /***/ }),
  25146. /* 30 */
  25147. /***/ (function(module, exports, __webpack_require__) {
  25148. "use strict";
  25149. Object.defineProperty(exports, "__esModule", {
  25150. value: true
  25151. });
  25152. 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); } };
  25153. 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; }; }();
  25154. var _logger = __webpack_require__(0);
  25155. var _logger2 = _interopRequireDefault(_logger);
  25156. var _loader = __webpack_require__(3);
  25157. var _exception = __webpack_require__(1);
  25158. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25159. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  25160. 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; }
  25161. 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; } /*
  25162. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  25163. *
  25164. * @author zheng qian <xqq@xqq.im>
  25165. *
  25166. * Licensed under the Apache License, Version 2.0 (the "License");
  25167. * you may not use this file except in compliance with the License.
  25168. * You may obtain a copy of the License at
  25169. *
  25170. * http://www.apache.org/licenses/LICENSE-2.0
  25171. *
  25172. * Unless required by applicable law or agreed to in writing, software
  25173. * distributed under the License is distributed on an "AS IS" BASIS,
  25174. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25175. * See the License for the specific language governing permissions and
  25176. * limitations under the License.
  25177. */
  25178. // For FLV over WebSocket live stream
  25179. var WebSocketLoader = function (_BaseLoader) {
  25180. _inherits(WebSocketLoader, _BaseLoader);
  25181. _createClass(WebSocketLoader, null, [{
  25182. key: 'isSupported',
  25183. value: function isSupported() {
  25184. try {
  25185. return typeof self.WebSocket !== 'undefined';
  25186. } catch (e) {
  25187. return false;
  25188. }
  25189. }
  25190. }]);
  25191. function WebSocketLoader() {
  25192. _classCallCheck(this, WebSocketLoader);
  25193. var _this = _possibleConstructorReturn(this, (WebSocketLoader.__proto__ || Object.getPrototypeOf(WebSocketLoader)).call(this, 'websocket-loader'));
  25194. _this.TAG = 'WebSocketLoader';
  25195. _this._needStash = true;
  25196. _this._ws = null;
  25197. _this._requestAbort = false;
  25198. _this._receivedLength = 0;
  25199. return _this;
  25200. }
  25201. _createClass(WebSocketLoader, [{
  25202. key: 'destroy',
  25203. value: function destroy() {
  25204. if (this._ws) {
  25205. this.abort();
  25206. }
  25207. _get(WebSocketLoader.prototype.__proto__ || Object.getPrototypeOf(WebSocketLoader.prototype), 'destroy', this).call(this);
  25208. }
  25209. }, {
  25210. key: 'open',
  25211. value: function open(dataSource) {
  25212. try {
  25213. var ws = this._ws = new self.WebSocket(dataSource.url);
  25214. ws.binaryType = 'arraybuffer';
  25215. ws.onopen = this._onWebSocketOpen.bind(this);
  25216. ws.onclose = this._onWebSocketClose.bind(this);
  25217. ws.onmessage = this._onWebSocketMessage.bind(this);
  25218. ws.onerror = this._onWebSocketError.bind(this);
  25219. this._status = _loader.LoaderStatus.kConnecting;
  25220. } catch (e) {
  25221. this._status = _loader.LoaderStatus.kError;
  25222. var info = { code: e.code, msg: e.message };
  25223. if (this._onError) {
  25224. this._onError(_loader.LoaderErrors.EXCEPTION, info);
  25225. } else {
  25226. throw new _exception.RuntimeException(info.msg);
  25227. }
  25228. }
  25229. }
  25230. }, {
  25231. key: 'abort',
  25232. value: function abort() {
  25233. var ws = this._ws;
  25234. if (ws && (ws.readyState === 0 || ws.readyState === 1)) {
  25235. // CONNECTING || OPEN
  25236. this._requestAbort = true;
  25237. ws.close();
  25238. }
  25239. this._ws = null;
  25240. this._status = _loader.LoaderStatus.kComplete;
  25241. }
  25242. }, {
  25243. key: '_onWebSocketOpen',
  25244. value: function _onWebSocketOpen(e) {
  25245. this._status = _loader.LoaderStatus.kBuffering;
  25246. }
  25247. }, {
  25248. key: '_onWebSocketClose',
  25249. value: function _onWebSocketClose(e) {
  25250. if (this._requestAbort === true) {
  25251. this._requestAbort = false;
  25252. return;
  25253. }
  25254. this._status = _loader.LoaderStatus.kComplete;
  25255. if (this._onComplete) {
  25256. this._onComplete(0, this._receivedLength - 1);
  25257. }
  25258. }
  25259. }, {
  25260. key: '_onWebSocketMessage',
  25261. value: function _onWebSocketMessage(e) {
  25262. var _this2 = this;
  25263. if (e.data instanceof ArrayBuffer) {
  25264. this._dispatchArrayBuffer(e.data);
  25265. } else if (e.data instanceof Blob) {
  25266. var reader = new FileReader();
  25267. reader.onload = function () {
  25268. _this2._dispatchArrayBuffer(reader.result);
  25269. };
  25270. reader.readAsArrayBuffer(e.data);
  25271. } else {
  25272. this._status = _loader.LoaderStatus.kError;
  25273. var info = { code: -1, msg: 'Unsupported WebSocket message type: ' + e.data.constructor.name };
  25274. if (this._onError) {
  25275. this._onError(_loader.LoaderErrors.EXCEPTION, info);
  25276. } else {
  25277. throw new _exception.RuntimeException(info.msg);
  25278. }
  25279. }
  25280. }
  25281. }, {
  25282. key: '_dispatchArrayBuffer',
  25283. value: function _dispatchArrayBuffer(arraybuffer) {
  25284. var chunk = arraybuffer;
  25285. var byteStart = this._receivedLength;
  25286. this._receivedLength += chunk.byteLength;
  25287. if (this._onDataArrival) {
  25288. this._onDataArrival(chunk, byteStart, this._receivedLength);
  25289. }
  25290. }
  25291. }, {
  25292. key: '_onWebSocketError',
  25293. value: function _onWebSocketError(e) {
  25294. this._status = _loader.LoaderStatus.kError;
  25295. var info = {
  25296. code: e.code,
  25297. msg: e.message
  25298. };
  25299. if (this._onError) {
  25300. this._onError(_loader.LoaderErrors.EXCEPTION, info);
  25301. } else {
  25302. throw new _exception.RuntimeException(info.msg);
  25303. }
  25304. }
  25305. }]);
  25306. return WebSocketLoader;
  25307. }(_loader.BaseLoader);
  25308. exports.default = WebSocketLoader;
  25309. module.exports = exports['default'];
  25310. /***/ }),
  25311. /* 31 */
  25312. /***/ (function(module, exports, __webpack_require__) {
  25313. "use strict";
  25314. Object.defineProperty(exports, "__esModule", {
  25315. value: true
  25316. });
  25317. 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; }; }();
  25318. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  25319. /*
  25320. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  25321. *
  25322. * @author zheng qian <xqq@xqq.im>
  25323. *
  25324. * Licensed under the Apache License, Version 2.0 (the "License");
  25325. * you may not use this file except in compliance with the License.
  25326. * You may obtain a copy of the License at
  25327. *
  25328. * http://www.apache.org/licenses/LICENSE-2.0
  25329. *
  25330. * Unless required by applicable law or agreed to in writing, software
  25331. * distributed under the License is distributed on an "AS IS" BASIS,
  25332. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25333. * See the License for the specific language governing permissions and
  25334. * limitations under the License.
  25335. */
  25336. var RangeSeekHandler = function () {
  25337. function RangeSeekHandler(zeroStart) {
  25338. _classCallCheck(this, RangeSeekHandler);
  25339. this._zeroStart = zeroStart || false;
  25340. }
  25341. _createClass(RangeSeekHandler, [{
  25342. key: 'getConfig',
  25343. value: function getConfig(url, range) {
  25344. var headers = {};
  25345. if (range.from !== 0 || range.to !== -1) {
  25346. var param = void 0;
  25347. if (range.to !== -1) {
  25348. param = 'bytes=' + range.from.toString() + '-' + range.to.toString();
  25349. } else {
  25350. param = 'bytes=' + range.from.toString() + '-';
  25351. }
  25352. headers['Range'] = param;
  25353. } else if (this._zeroStart) {
  25354. headers['Range'] = 'bytes=0-';
  25355. }
  25356. return {
  25357. url: url,
  25358. headers: headers
  25359. };
  25360. }
  25361. }, {
  25362. key: 'removeURLParameters',
  25363. value: function removeURLParameters(seekedURL) {
  25364. return seekedURL;
  25365. }
  25366. }]);
  25367. return RangeSeekHandler;
  25368. }();
  25369. exports.default = RangeSeekHandler;
  25370. module.exports = exports['default'];
  25371. /***/ }),
  25372. /* 32 */
  25373. /***/ (function(module, exports, __webpack_require__) {
  25374. "use strict";
  25375. Object.defineProperty(exports, "__esModule", {
  25376. value: true
  25377. });
  25378. 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; }; }();
  25379. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  25380. /*
  25381. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  25382. *
  25383. * @author zheng qian <xqq@xqq.im>
  25384. *
  25385. * Licensed under the Apache License, Version 2.0 (the "License");
  25386. * you may not use this file except in compliance with the License.
  25387. * You may obtain a copy of the License at
  25388. *
  25389. * http://www.apache.org/licenses/LICENSE-2.0
  25390. *
  25391. * Unless required by applicable law or agreed to in writing, software
  25392. * distributed under the License is distributed on an "AS IS" BASIS,
  25393. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25394. * See the License for the specific language governing permissions and
  25395. * limitations under the License.
  25396. */
  25397. var ParamSeekHandler = function () {
  25398. function ParamSeekHandler(paramStart, paramEnd) {
  25399. _classCallCheck(this, ParamSeekHandler);
  25400. this._startName = paramStart;
  25401. this._endName = paramEnd;
  25402. }
  25403. _createClass(ParamSeekHandler, [{
  25404. key: 'getConfig',
  25405. value: function getConfig(baseUrl, range) {
  25406. var url = baseUrl;
  25407. if (range.from !== 0 || range.to !== -1) {
  25408. var needAnd = true;
  25409. if (url.indexOf('?') === -1) {
  25410. url += '?';
  25411. needAnd = false;
  25412. }
  25413. if (needAnd) {
  25414. url += '&';
  25415. }
  25416. url += this._startName + '=' + range.from.toString();
  25417. if (range.to !== -1) {
  25418. url += '&' + this._endName + '=' + range.to.toString();
  25419. }
  25420. }
  25421. return {
  25422. url: url,
  25423. headers: {}
  25424. };
  25425. }
  25426. }, {
  25427. key: 'removeURLParameters',
  25428. value: function removeURLParameters(seekedURL) {
  25429. var baseURL = seekedURL.split('?')[0];
  25430. var params = undefined;
  25431. var queryIndex = seekedURL.indexOf('?');
  25432. if (queryIndex !== -1) {
  25433. params = seekedURL.substring(queryIndex + 1);
  25434. }
  25435. var resultParams = '';
  25436. if (params != undefined && params.length > 0) {
  25437. var pairs = params.split('&');
  25438. for (var i = 0; i < pairs.length; i++) {
  25439. var pair = pairs[i].split('=');
  25440. var requireAnd = i > 0;
  25441. if (pair[0] !== this._startName && pair[0] !== this._endName) {
  25442. if (requireAnd) {
  25443. resultParams += '&';
  25444. }
  25445. resultParams += pairs[i];
  25446. }
  25447. }
  25448. }
  25449. return resultParams.length === 0 ? baseURL : baseURL + '?' + resultParams;
  25450. }
  25451. }]);
  25452. return ParamSeekHandler;
  25453. }();
  25454. exports.default = ParamSeekHandler;
  25455. module.exports = exports['default'];
  25456. /***/ }),
  25457. /* 33 */
  25458. /***/ (function(module, exports, __webpack_require__) {
  25459. "use strict";
  25460. Object.defineProperty(exports, "__esModule", {
  25461. value: true
  25462. });
  25463. 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; };
  25464. 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; }; }(); /*
  25465. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  25466. *
  25467. * @author zheng qian <xqq@xqq.im>
  25468. *
  25469. * Licensed under the Apache License, Version 2.0 (the "License");
  25470. * you may not use this file except in compliance with the License.
  25471. * You may obtain a copy of the License at
  25472. *
  25473. * http://www.apache.org/licenses/LICENSE-2.0
  25474. *
  25475. * Unless required by applicable law or agreed to in writing, software
  25476. * distributed under the License is distributed on an "AS IS" BASIS,
  25477. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25478. * See the License for the specific language governing permissions and
  25479. * limitations under the License.
  25480. */
  25481. var _events = __webpack_require__(2);
  25482. var _events2 = _interopRequireDefault(_events);
  25483. var _logger = __webpack_require__(0);
  25484. var _logger2 = _interopRequireDefault(_logger);
  25485. var _browser = __webpack_require__(4);
  25486. var _browser2 = _interopRequireDefault(_browser);
  25487. var _playerEvents = __webpack_require__(7);
  25488. var _playerEvents2 = _interopRequireDefault(_playerEvents);
  25489. var _transmuxer = __webpack_require__(34);
  25490. var _transmuxer2 = _interopRequireDefault(_transmuxer);
  25491. var _transmuxingEvents = __webpack_require__(5);
  25492. var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
  25493. var _mseController = __webpack_require__(45);
  25494. var _mseController2 = _interopRequireDefault(_mseController);
  25495. var _mseEvents = __webpack_require__(16);
  25496. var _mseEvents2 = _interopRequireDefault(_mseEvents);
  25497. var _playerErrors = __webpack_require__(17);
  25498. var _config = __webpack_require__(6);
  25499. var _exception = __webpack_require__(1);
  25500. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25501. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  25502. var FlvPlayer = function () {
  25503. function FlvPlayer(mediaDataSource, config) {
  25504. _classCallCheck(this, FlvPlayer);
  25505. this.TAG = 'FlvPlayer';
  25506. this._type = 'FlvPlayer';
  25507. this._emitter = new _events2.default();
  25508. this._config = (0, _config.createDefaultConfig)();
  25509. if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object') {
  25510. Object.assign(this._config, config);
  25511. }
  25512. if (mediaDataSource.type.toLowerCase() !== 'flv') {
  25513. throw new _exception.InvalidArgumentException('FlvPlayer requires an flv MediaDataSource input!');
  25514. }
  25515. if (mediaDataSource.isLive === true) {
  25516. this._config.isLive = true;
  25517. }
  25518. this.e = {
  25519. onvLoadedMetadata: this._onvLoadedMetadata.bind(this),
  25520. onvSeeking: this._onvSeeking.bind(this),
  25521. onvCanPlay: this._onvCanPlay.bind(this),
  25522. onvStalled: this._onvStalled.bind(this),
  25523. onvProgress: this._onvProgress.bind(this)
  25524. };
  25525. if (self.performance && self.performance.now) {
  25526. this._now = self.performance.now.bind(self.performance);
  25527. } else {
  25528. this._now = Date.now;
  25529. }
  25530. this._pendingSeekTime = null; // in seconds
  25531. this._requestSetTime = false;
  25532. this._seekpointRecord = null;
  25533. this._progressChecker = null;
  25534. this._mediaDataSource = mediaDataSource;
  25535. this._mediaElement = null;
  25536. this._msectl = null;
  25537. this._transmuxer = null;
  25538. this._mseSourceOpened = false;
  25539. this._hasPendingLoad = false;
  25540. this._receivedCanPlay = false;
  25541. this._mediaInfo = null;
  25542. this._statisticsInfo = null;
  25543. var chromeNeedIDRFix = _browser2.default.chrome && (_browser2.default.version.major < 50 || _browser2.default.version.major === 50 && _browser2.default.version.build < 2661);
  25544. this._alwaysSeekKeyframe = chromeNeedIDRFix || _browser2.default.msedge || _browser2.default.msie ? true : false;
  25545. if (this._alwaysSeekKeyframe) {
  25546. this._config.accurateSeek = false;
  25547. }
  25548. }
  25549. _createClass(FlvPlayer, [{
  25550. key: 'destroy',
  25551. value: function destroy() {
  25552. if (this._progressChecker != null) {
  25553. window.clearInterval(this._progressChecker);
  25554. this._progressChecker = null;
  25555. }
  25556. if (this._transmuxer) {
  25557. this.unload();
  25558. }
  25559. if (this._mediaElement) {
  25560. this.detachMediaElement();
  25561. }
  25562. this.e = null;
  25563. this._mediaDataSource = null;
  25564. this._emitter.removeAllListeners();
  25565. this._emitter = null;
  25566. }
  25567. }, {
  25568. key: 'on',
  25569. value: function on(event, listener) {
  25570. var _this = this;
  25571. if (event === _playerEvents2.default.MEDIA_INFO) {
  25572. if (this._mediaInfo != null) {
  25573. Promise.resolve().then(function () {
  25574. _this._emitter.emit(_playerEvents2.default.MEDIA_INFO, _this.mediaInfo);
  25575. });
  25576. }
  25577. } else if (event === _playerEvents2.default.STATISTICS_INFO) {
  25578. if (this._statisticsInfo != null) {
  25579. Promise.resolve().then(function () {
  25580. _this._emitter.emit(_playerEvents2.default.STATISTICS_INFO, _this.statisticsInfo);
  25581. });
  25582. }
  25583. }
  25584. this._emitter.addListener(event, listener);
  25585. }
  25586. }, {
  25587. key: 'off',
  25588. value: function off(event, listener) {
  25589. this._emitter.removeListener(event, listener);
  25590. }
  25591. }, {
  25592. key: 'attachMediaElement',
  25593. value: function attachMediaElement(mediaElement) {
  25594. var _this2 = this;
  25595. this._mediaElement = mediaElement;
  25596. mediaElement.addEventListener('loadedmetadata', this.e.onvLoadedMetadata);
  25597. mediaElement.addEventListener('seeking', this.e.onvSeeking);
  25598. mediaElement.addEventListener('canplay', this.e.onvCanPlay);
  25599. mediaElement.addEventListener('stalled', this.e.onvStalled);
  25600. mediaElement.addEventListener('progress', this.e.onvProgress);
  25601. this._msectl = new _mseController2.default(this._config);
  25602. this._msectl.on(_mseEvents2.default.UPDATE_END, this._onmseUpdateEnd.bind(this));
  25603. this._msectl.on(_mseEvents2.default.BUFFER_FULL, this._onmseBufferFull.bind(this));
  25604. this._msectl.on(_mseEvents2.default.SOURCE_OPEN, function () {
  25605. _this2._mseSourceOpened = true;
  25606. if (_this2._hasPendingLoad) {
  25607. _this2._hasPendingLoad = false;
  25608. _this2.load();
  25609. }
  25610. });
  25611. this._msectl.on(_mseEvents2.default.ERROR, function (info) {
  25612. _this2._emitter.emit(_playerEvents2.default.ERROR, _playerErrors.ErrorTypes.MEDIA_ERROR, _playerErrors.ErrorDetails.MEDIA_MSE_ERROR, info);
  25613. });
  25614. this._msectl.attachMediaElement(mediaElement);
  25615. if (this._pendingSeekTime != null) {
  25616. try {
  25617. mediaElement.currentTime = this._pendingSeekTime;
  25618. this._pendingSeekTime = null;
  25619. } catch (e) {
  25620. // IE11 may throw InvalidStateError if readyState === 0
  25621. // We can defer set currentTime operation after loadedmetadata
  25622. }
  25623. }
  25624. }
  25625. }, {
  25626. key: 'detachMediaElement',
  25627. value: function detachMediaElement() {
  25628. if (this._mediaElement) {
  25629. this._msectl.detachMediaElement();
  25630. this._mediaElement.removeEventListener('loadedmetadata', this.e.onvLoadedMetadata);
  25631. this._mediaElement.removeEventListener('seeking', this.e.onvSeeking);
  25632. this._mediaElement.removeEventListener('canplay', this.e.onvCanPlay);
  25633. this._mediaElement.removeEventListener('stalled', this.e.onvStalled);
  25634. this._mediaElement.removeEventListener('progress', this.e.onvProgress);
  25635. this._mediaElement = null;
  25636. }
  25637. if (this._msectl) {
  25638. this._msectl.destroy();
  25639. this._msectl = null;
  25640. }
  25641. }
  25642. }, {
  25643. key: 'load',
  25644. value: function load() {
  25645. var _this3 = this;
  25646. if (!this._mediaElement) {
  25647. throw new _exception.IllegalStateException('HTMLMediaElement must be attached before load()!');
  25648. }
  25649. if (this._transmuxer) {
  25650. throw new _exception.IllegalStateException('FlvPlayer.load() has been called, please call unload() first!');
  25651. }
  25652. if (this._hasPendingLoad) {
  25653. return;
  25654. }
  25655. if (this._config.deferLoadAfterSourceOpen && this._mseSourceOpened === false) {
  25656. this._hasPendingLoad = true;
  25657. return;
  25658. }
  25659. if (this._mediaElement.readyState > 0) {
  25660. this._requestSetTime = true;
  25661. // IE11 may throw InvalidStateError if readyState === 0
  25662. this._mediaElement.currentTime = 0;
  25663. }
  25664. this._transmuxer = new _transmuxer2.default(this._mediaDataSource, this._config);
  25665. this._transmuxer.on(_transmuxingEvents2.default.INIT_SEGMENT, function (type, is) {
  25666. _this3._msectl.appendInitSegment(is);
  25667. });
  25668. this._transmuxer.on(_transmuxingEvents2.default.MEDIA_SEGMENT, function (type, ms) {
  25669. _this3._msectl.appendMediaSegment(ms);
  25670. // lazyLoad check
  25671. if (_this3._config.lazyLoad && !_this3._config.isLive) {
  25672. var currentTime = _this3._mediaElement.currentTime;
  25673. if (ms.info.endDts >= (currentTime + _this3._config.lazyLoadMaxDuration) * 1000) {
  25674. if (_this3._progressChecker == null) {
  25675. _logger2.default.v(_this3.TAG, 'Maximum buffering duration exceeded, suspend transmuxing task');
  25676. _this3._suspendTransmuxer();
  25677. }
  25678. }
  25679. }
  25680. });
  25681. this._transmuxer.on(_transmuxingEvents2.default.LOADING_COMPLETE, function () {
  25682. _this3._msectl.endOfStream();
  25683. _this3._emitter.emit(_playerEvents2.default.LOADING_COMPLETE);
  25684. });
  25685. this._transmuxer.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF, function () {
  25686. _this3._emitter.emit(_playerEvents2.default.RECOVERED_EARLY_EOF);
  25687. });
  25688. this._transmuxer.on(_transmuxingEvents2.default.IO_ERROR, function (detail, info) {
  25689. _this3._emitter.emit(_playerEvents2.default.ERROR, _playerErrors.ErrorTypes.NETWORK_ERROR, detail, info);
  25690. });
  25691. this._transmuxer.on(_transmuxingEvents2.default.DEMUX_ERROR, function (detail, info) {
  25692. _this3._emitter.emit(_playerEvents2.default.ERROR, _playerErrors.ErrorTypes.MEDIA_ERROR, detail, { code: -1, msg: info });
  25693. });
  25694. this._transmuxer.on(_transmuxingEvents2.default.MEDIA_INFO, function (mediaInfo) {
  25695. _this3._mediaInfo = mediaInfo;
  25696. _this3._emitter.emit(_playerEvents2.default.MEDIA_INFO, Object.assign({}, mediaInfo));
  25697. });
  25698. this._transmuxer.on(_transmuxingEvents2.default.STATISTICS_INFO, function (statInfo) {
  25699. _this3._statisticsInfo = _this3._fillStatisticsInfo(statInfo);
  25700. _this3._emitter.emit(_playerEvents2.default.STATISTICS_INFO, Object.assign({}, _this3._statisticsInfo));
  25701. });
  25702. this._transmuxer.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, function (milliseconds) {
  25703. if (_this3._mediaElement && !_this3._config.accurateSeek) {
  25704. _this3._requestSetTime = true;
  25705. _this3._mediaElement.currentTime = milliseconds / 1000;
  25706. }
  25707. });
  25708. this._transmuxer.on(_transmuxingEvents2.default.LOADED_SEI, function (timestamp, data) {
  25709. _this3._emitter.emit(_playerEvents2.default.LOADED_SEI, timestamp, data);
  25710. });
  25711. this._transmuxer.open();
  25712. }
  25713. }, {
  25714. key: 'unload',
  25715. value: function unload() {
  25716. if (this._mediaElement) {
  25717. this._mediaElement.pause();
  25718. }
  25719. if (this._msectl) {
  25720. this._msectl.seek(0);
  25721. }
  25722. if (this._transmuxer) {
  25723. this._transmuxer.close();
  25724. this._transmuxer.destroy();
  25725. this._transmuxer = null;
  25726. }
  25727. }
  25728. }, {
  25729. key: 'play',
  25730. value: function play() {
  25731. var playPromise = this._mediaElement.play();
  25732. if (playPromise !== undefined && playPromise) {
  25733. return playPromise.catch(function () {});
  25734. } else return undefined;
  25735. }
  25736. }, {
  25737. key: 'pause',
  25738. value: function pause() {
  25739. this._mediaElement.pause();
  25740. }
  25741. }, {
  25742. key: '_fillStatisticsInfo',
  25743. value: function _fillStatisticsInfo(statInfo) {
  25744. statInfo.playerType = this._type;
  25745. if (!(this._mediaElement instanceof HTMLVideoElement)) {
  25746. return statInfo;
  25747. }
  25748. var hasQualityInfo = true;
  25749. var decoded = 0;
  25750. var dropped = 0;
  25751. if (this._mediaElement.getVideoPlaybackQuality) {
  25752. var quality = this._mediaElement.getVideoPlaybackQuality();
  25753. decoded = quality.totalVideoFrames;
  25754. dropped = quality.droppedVideoFrames;
  25755. } else if (this._mediaElement.webkitDecodedFrameCount != undefined) {
  25756. decoded = this._mediaElement.webkitDecodedFrameCount;
  25757. dropped = this._mediaElement.webkitDroppedFrameCount;
  25758. } else {
  25759. hasQualityInfo = false;
  25760. }
  25761. if (hasQualityInfo) {
  25762. statInfo.decodedFrames = decoded;
  25763. statInfo.droppedFrames = dropped;
  25764. }
  25765. return statInfo;
  25766. }
  25767. }, {
  25768. key: '_onmseUpdateEnd',
  25769. value: function _onmseUpdateEnd() {
  25770. if (!this._config.lazyLoad || this._config.isLive) {
  25771. return;
  25772. }
  25773. var buffered = this._mediaElement.buffered;
  25774. var currentTime = this._mediaElement.currentTime;
  25775. var currentRangeStart = 0;
  25776. var currentRangeEnd = 0;
  25777. for (var i = 0; i < buffered.length; i++) {
  25778. var start = buffered.start(i);
  25779. var end = buffered.end(i);
  25780. if (start <= currentTime && currentTime < end) {
  25781. currentRangeStart = start;
  25782. currentRangeEnd = end;
  25783. break;
  25784. }
  25785. }
  25786. if (currentRangeEnd >= currentTime + this._config.lazyLoadMaxDuration && this._progressChecker == null) {
  25787. _logger2.default.v(this.TAG, 'Maximum buffering duration exceeded, suspend transmuxing task');
  25788. this._suspendTransmuxer();
  25789. }
  25790. }
  25791. }, {
  25792. key: '_onmseBufferFull',
  25793. value: function _onmseBufferFull() {
  25794. _logger2.default.v(this.TAG, 'MSE SourceBuffer is full, suspend transmuxing task');
  25795. if (this._progressChecker == null) {
  25796. this._suspendTransmuxer();
  25797. }
  25798. }
  25799. }, {
  25800. key: '_suspendTransmuxer',
  25801. value: function _suspendTransmuxer() {
  25802. if (this._transmuxer) {
  25803. this._transmuxer.pause();
  25804. if (this._progressChecker == null) {
  25805. this._progressChecker = window.setInterval(this._checkProgressAndResume.bind(this), 1000);
  25806. }
  25807. }
  25808. }
  25809. }, {
  25810. key: '_checkProgressAndResume',
  25811. value: function _checkProgressAndResume() {
  25812. var currentTime = this._mediaElement.currentTime;
  25813. var buffered = this._mediaElement.buffered;
  25814. var needResume = false;
  25815. for (var i = 0; i < buffered.length; i++) {
  25816. var from = buffered.start(i);
  25817. var to = buffered.end(i);
  25818. if (currentTime >= from && currentTime < to) {
  25819. if (currentTime >= to - this._config.lazyLoadRecoverDuration) {
  25820. needResume = true;
  25821. }
  25822. break;
  25823. }
  25824. }
  25825. if (needResume) {
  25826. window.clearInterval(this._progressChecker);
  25827. this._progressChecker = null;
  25828. if (needResume) {
  25829. _logger2.default.v(this.TAG, 'Continue loading from paused position');
  25830. this._transmuxer.resume();
  25831. }
  25832. }
  25833. }
  25834. }, {
  25835. key: '_isTimepointBuffered',
  25836. value: function _isTimepointBuffered(seconds) {
  25837. var buffered = this._mediaElement.buffered;
  25838. for (var i = 0; i < buffered.length; i++) {
  25839. var from = buffered.start(i);
  25840. var to = buffered.end(i);
  25841. if (seconds >= from && seconds < to) {
  25842. return true;
  25843. }
  25844. }
  25845. return false;
  25846. }
  25847. }, {
  25848. key: '_internalSeek',
  25849. value: function _internalSeek(seconds) {
  25850. var directSeek = this._isTimepointBuffered(seconds);
  25851. var directSeekBegin = false;
  25852. var directSeekBeginTime = 0;
  25853. if (seconds < 1.0 && this._mediaElement.buffered.length > 0) {
  25854. var videoBeginTime = this._mediaElement.buffered.start(0);
  25855. if (videoBeginTime < 1.0 && seconds < videoBeginTime || _browser2.default.safari) {
  25856. directSeekBegin = true;
  25857. // also workaround for Safari: Seek to 0 may cause video stuck, use 0.1 to avoid
  25858. directSeekBeginTime = _browser2.default.safari ? 0.1 : videoBeginTime;
  25859. }
  25860. }
  25861. if (directSeekBegin) {
  25862. // seek to video begin, set currentTime directly if beginPTS buffered
  25863. this._requestSetTime = true;
  25864. this._mediaElement.currentTime = directSeekBeginTime;
  25865. } else if (directSeek) {
  25866. // buffered position
  25867. if (!this._alwaysSeekKeyframe) {
  25868. this._requestSetTime = true;
  25869. this._mediaElement.currentTime = seconds;
  25870. } else {
  25871. var idr = this._msectl.getNearestKeyframe(Math.floor(seconds * 1000));
  25872. this._requestSetTime = true;
  25873. if (idr != null) {
  25874. this._mediaElement.currentTime = idr.dts / 1000;
  25875. } else {
  25876. this._mediaElement.currentTime = seconds;
  25877. }
  25878. }
  25879. if (this._progressChecker != null) {
  25880. this._checkProgressAndResume();
  25881. }
  25882. } else {
  25883. if (this._progressChecker != null) {
  25884. window.clearInterval(this._progressChecker);
  25885. this._progressChecker = null;
  25886. }
  25887. this._msectl.seek(seconds);
  25888. this._transmuxer.seek(Math.floor(seconds * 1000)); // in milliseconds
  25889. // no need to set mediaElement.currentTime if non-accurateSeek,
  25890. // just wait for the recommend_seekpoint callback
  25891. if (this._config.accurateSeek) {
  25892. this._requestSetTime = true;
  25893. this._mediaElement.currentTime = seconds;
  25894. }
  25895. }
  25896. }
  25897. }, {
  25898. key: '_checkAndApplyUnbufferedSeekpoint',
  25899. value: function _checkAndApplyUnbufferedSeekpoint() {
  25900. if (this._seekpointRecord) {
  25901. if (this._seekpointRecord.recordTime <= this._now() - 100) {
  25902. var target = this._mediaElement.currentTime;
  25903. this._seekpointRecord = null;
  25904. if (!this._isTimepointBuffered(target)) {
  25905. if (this._progressChecker != null) {
  25906. window.clearTimeout(this._progressChecker);
  25907. this._progressChecker = null;
  25908. }
  25909. // .currentTime is consists with .buffered timestamp
  25910. // Chrome/Edge use DTS, while FireFox/Safari use PTS
  25911. this._msectl.seek(target);
  25912. this._transmuxer.seek(Math.floor(target * 1000));
  25913. // set currentTime if accurateSeek, or wait for recommend_seekpoint callback
  25914. if (this._config.accurateSeek) {
  25915. this._requestSetTime = true;
  25916. this._mediaElement.currentTime = target;
  25917. }
  25918. }
  25919. } else {
  25920. window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this), 50);
  25921. }
  25922. }
  25923. }
  25924. }, {
  25925. key: '_checkAndResumeStuckPlayback',
  25926. value: function _checkAndResumeStuckPlayback(stalled) {
  25927. var media = this._mediaElement;
  25928. if (stalled || !this._receivedCanPlay || media.readyState < 2) {
  25929. // HAVE_CURRENT_DATA
  25930. var buffered = media.buffered;
  25931. if (buffered.length > 0 && media.currentTime < buffered.start(0)) {
  25932. _logger2.default.w(this.TAG, 'Playback seems stuck at ' + media.currentTime + ', seek to ' + buffered.start(0));
  25933. this._requestSetTime = true;
  25934. this._mediaElement.currentTime = buffered.start(0);
  25935. this._mediaElement.removeEventListener('progress', this.e.onvProgress);
  25936. }
  25937. } else {
  25938. // Playback didn't stuck, remove progress event listener
  25939. this._mediaElement.removeEventListener('progress', this.e.onvProgress);
  25940. }
  25941. }
  25942. }, {
  25943. key: '_onvLoadedMetadata',
  25944. value: function _onvLoadedMetadata(e) {
  25945. if (this._pendingSeekTime != null) {
  25946. this._mediaElement.currentTime = this._pendingSeekTime;
  25947. this._pendingSeekTime = null;
  25948. }
  25949. }
  25950. }, {
  25951. key: '_onvSeeking',
  25952. value: function _onvSeeking(e) {
  25953. // handle seeking request from browser's progress bar
  25954. var target = this._mediaElement.currentTime;
  25955. var buffered = this._mediaElement.buffered;
  25956. if (this._requestSetTime) {
  25957. this._requestSetTime = false;
  25958. return;
  25959. }
  25960. if (target < 1.0 && buffered.length > 0) {
  25961. // seek to video begin, set currentTime directly if beginPTS buffered
  25962. var videoBeginTime = buffered.start(0);
  25963. if (videoBeginTime < 1.0 && target < videoBeginTime || _browser2.default.safari) {
  25964. this._requestSetTime = true;
  25965. // also workaround for Safari: Seek to 0 may cause video stuck, use 0.1 to avoid
  25966. this._mediaElement.currentTime = _browser2.default.safari ? 0.1 : videoBeginTime;
  25967. return;
  25968. }
  25969. }
  25970. if (this._isTimepointBuffered(target)) {
  25971. if (this._alwaysSeekKeyframe) {
  25972. var idr = this._msectl.getNearestKeyframe(Math.floor(target * 1000));
  25973. if (idr != null) {
  25974. this._requestSetTime = true;
  25975. this._mediaElement.currentTime = idr.dts / 1000;
  25976. }
  25977. }
  25978. if (this._progressChecker != null) {
  25979. this._checkProgressAndResume();
  25980. }
  25981. return;
  25982. }
  25983. this._seekpointRecord = {
  25984. seekPoint: target,
  25985. recordTime: this._now()
  25986. };
  25987. window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this), 50);
  25988. }
  25989. }, {
  25990. key: '_onvCanPlay',
  25991. value: function _onvCanPlay(e) {
  25992. this._receivedCanPlay = true;
  25993. this._mediaElement.removeEventListener('canplay', this.e.onvCanPlay);
  25994. }
  25995. }, {
  25996. key: '_onvStalled',
  25997. value: function _onvStalled(e) {
  25998. this._checkAndResumeStuckPlayback(true);
  25999. }
  26000. }, {
  26001. key: '_onvProgress',
  26002. value: function _onvProgress(e) {
  26003. this._checkAndResumeStuckPlayback();
  26004. }
  26005. }, {
  26006. key: 'type',
  26007. get: function get() {
  26008. return this._type;
  26009. }
  26010. }, {
  26011. key: 'buffered',
  26012. get: function get() {
  26013. return this._mediaElement.buffered;
  26014. }
  26015. }, {
  26016. key: 'duration',
  26017. get: function get() {
  26018. return this._mediaElement.duration;
  26019. }
  26020. }, {
  26021. key: 'volume',
  26022. get: function get() {
  26023. return this._mediaElement.volume;
  26024. },
  26025. set: function set(value) {
  26026. this._mediaElement.volume = value;
  26027. }
  26028. }, {
  26029. key: 'muted',
  26030. get: function get() {
  26031. return this._mediaElement.muted;
  26032. },
  26033. set: function set(muted) {
  26034. this._mediaElement.muted = muted;
  26035. }
  26036. }, {
  26037. key: 'currentTime',
  26038. get: function get() {
  26039. if (this._mediaElement) {
  26040. return this._mediaElement.currentTime;
  26041. }
  26042. return 0;
  26043. },
  26044. set: function set(seconds) {
  26045. if (this._mediaElement) {
  26046. this._internalSeek(seconds);
  26047. } else {
  26048. this._pendingSeekTime = seconds;
  26049. }
  26050. }
  26051. }, {
  26052. key: 'mediaInfo',
  26053. get: function get() {
  26054. return Object.assign({}, this._mediaInfo);
  26055. }
  26056. }, {
  26057. key: 'statisticsInfo',
  26058. get: function get() {
  26059. if (this._statisticsInfo == null) {
  26060. this._statisticsInfo = {};
  26061. }
  26062. this._statisticsInfo = this._fillStatisticsInfo(this._statisticsInfo);
  26063. return Object.assign({}, this._statisticsInfo);
  26064. }
  26065. }]);
  26066. return FlvPlayer;
  26067. }();
  26068. exports.default = FlvPlayer;
  26069. module.exports = exports['default'];
  26070. /***/ }),
  26071. /* 34 */
  26072. /***/ (function(module, exports, __webpack_require__) {
  26073. "use strict";
  26074. Object.defineProperty(exports, "__esModule", {
  26075. value: true
  26076. });
  26077. 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; }; }(); /*
  26078. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  26079. *
  26080. * @author zheng qian <xqq@xqq.im>
  26081. *
  26082. * Licensed under the Apache License, Version 2.0 (the "License");
  26083. * you may not use this file except in compliance with the License.
  26084. * You may obtain a copy of the License at
  26085. *
  26086. * http://www.apache.org/licenses/LICENSE-2.0
  26087. *
  26088. * Unless required by applicable law or agreed to in writing, software
  26089. * distributed under the License is distributed on an "AS IS" BASIS,
  26090. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26091. * See the License for the specific language governing permissions and
  26092. * limitations under the License.
  26093. */
  26094. var _events = __webpack_require__(2);
  26095. var _events2 = _interopRequireDefault(_events);
  26096. var _logger = __webpack_require__(0);
  26097. var _logger2 = _interopRequireDefault(_logger);
  26098. var _loggingControl = __webpack_require__(8);
  26099. var _loggingControl2 = _interopRequireDefault(_loggingControl);
  26100. var _transmuxingController = __webpack_require__(14);
  26101. var _transmuxingController2 = _interopRequireDefault(_transmuxingController);
  26102. var _transmuxingEvents = __webpack_require__(5);
  26103. var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
  26104. var _transmuxingWorker = __webpack_require__(43);
  26105. var _transmuxingWorker2 = _interopRequireDefault(_transmuxingWorker);
  26106. var _mediaInfo = __webpack_require__(9);
  26107. var _mediaInfo2 = _interopRequireDefault(_mediaInfo);
  26108. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26109. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  26110. var Transmuxer = function () {
  26111. function Transmuxer(mediaDataSource, config) {
  26112. _classCallCheck(this, Transmuxer);
  26113. this.TAG = 'Transmuxer';
  26114. this._emitter = new _events2.default();
  26115. if (config.enableWorker && typeof Worker !== 'undefined') {
  26116. try {
  26117. var work = __webpack_require__(44);
  26118. this._worker = work(_transmuxingWorker2.default);
  26119. this._workerDestroying = false;
  26120. this._worker.addEventListener('message', this._onWorkerMessage.bind(this));
  26121. this._worker.postMessage({ cmd: 'init', param: [mediaDataSource, config] });
  26122. this.e = {
  26123. onLoggingConfigChanged: this._onLoggingConfigChanged.bind(this)
  26124. };
  26125. _loggingControl2.default.registerListener(this.e.onLoggingConfigChanged);
  26126. this._worker.postMessage({ cmd: 'logging_config', param: _loggingControl2.default.getConfig() });
  26127. } catch (error) {
  26128. _logger2.default.e(this.TAG, 'Error while initialize transmuxing worker, fallback to inline transmuxing');
  26129. this._worker = null;
  26130. this._controller = new _transmuxingController2.default(mediaDataSource, config);
  26131. }
  26132. } else {
  26133. this._controller = new _transmuxingController2.default(mediaDataSource, config);
  26134. }
  26135. if (this._controller) {
  26136. var ctl = this._controller;
  26137. ctl.on(_transmuxingEvents2.default.IO_ERROR, this._onIOError.bind(this));
  26138. ctl.on(_transmuxingEvents2.default.DEMUX_ERROR, this._onDemuxError.bind(this));
  26139. ctl.on(_transmuxingEvents2.default.INIT_SEGMENT, this._onInitSegment.bind(this));
  26140. ctl.on(_transmuxingEvents2.default.MEDIA_SEGMENT, this._onMediaSegment.bind(this));
  26141. ctl.on(_transmuxingEvents2.default.LOADING_COMPLETE, this._onLoadingComplete.bind(this));
  26142. ctl.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF, this._onRecoveredEarlyEof.bind(this));
  26143. ctl.on(_transmuxingEvents2.default.MEDIA_INFO, this._onMediaInfo.bind(this));
  26144. ctl.on(_transmuxingEvents2.default.STATISTICS_INFO, this._onStatisticsInfo.bind(this));
  26145. ctl.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, this._onRecommendSeekpoint.bind(this));
  26146. ctl.on(_transmuxingEvents2.default.LOADED_SEI, this._onLoadedSei.bind(this));
  26147. }
  26148. }
  26149. _createClass(Transmuxer, [{
  26150. key: 'destroy',
  26151. value: function destroy() {
  26152. if (this._worker) {
  26153. if (!this._workerDestroying) {
  26154. this._workerDestroying = true;
  26155. this._worker.postMessage({ cmd: 'destroy' });
  26156. _loggingControl2.default.removeListener(this.e.onLoggingConfigChanged);
  26157. this.e = null;
  26158. }
  26159. } else {
  26160. this._controller.destroy();
  26161. this._controller = null;
  26162. }
  26163. this._emitter.removeAllListeners();
  26164. this._emitter = null;
  26165. }
  26166. }, {
  26167. key: 'on',
  26168. value: function on(event, listener) {
  26169. this._emitter.addListener(event, listener);
  26170. }
  26171. }, {
  26172. key: 'off',
  26173. value: function off(event, listener) {
  26174. this._emitter.removeListener(event, listener);
  26175. }
  26176. }, {
  26177. key: 'hasWorker',
  26178. value: function hasWorker() {
  26179. return this._worker != null;
  26180. }
  26181. }, {
  26182. key: 'open',
  26183. value: function open() {
  26184. if (this._worker) {
  26185. this._worker.postMessage({ cmd: 'start' });
  26186. } else {
  26187. this._controller.start();
  26188. }
  26189. }
  26190. }, {
  26191. key: 'close',
  26192. value: function close() {
  26193. if (this._worker) {
  26194. this._worker.postMessage({ cmd: 'stop' });
  26195. } else {
  26196. this._controller.stop();
  26197. }
  26198. }
  26199. }, {
  26200. key: 'seek',
  26201. value: function seek(milliseconds) {
  26202. if (this._worker) {
  26203. this._worker.postMessage({ cmd: 'seek', param: milliseconds });
  26204. } else {
  26205. this._controller.seek(milliseconds);
  26206. }
  26207. }
  26208. }, {
  26209. key: 'pause',
  26210. value: function pause() {
  26211. if (this._worker) {
  26212. this._worker.postMessage({ cmd: 'pause' });
  26213. } else {
  26214. this._controller.pause();
  26215. }
  26216. }
  26217. }, {
  26218. key: 'resume',
  26219. value: function resume() {
  26220. if (this._worker) {
  26221. this._worker.postMessage({ cmd: 'resume' });
  26222. } else {
  26223. this._controller.resume();
  26224. }
  26225. }
  26226. }, {
  26227. key: '_onInitSegment',
  26228. value: function _onInitSegment(type, initSegment) {
  26229. var _this = this;
  26230. // do async invoke
  26231. Promise.resolve().then(function () {
  26232. _this._emitter.emit(_transmuxingEvents2.default.INIT_SEGMENT, type, initSegment);
  26233. });
  26234. }
  26235. }, {
  26236. key: '_onMediaSegment',
  26237. value: function _onMediaSegment(type, mediaSegment) {
  26238. var _this2 = this;
  26239. Promise.resolve().then(function () {
  26240. _this2._emitter.emit(_transmuxingEvents2.default.MEDIA_SEGMENT, type, mediaSegment);
  26241. });
  26242. }
  26243. }, {
  26244. key: '_onLoadingComplete',
  26245. value: function _onLoadingComplete() {
  26246. var _this3 = this;
  26247. Promise.resolve().then(function () {
  26248. _this3._emitter.emit(_transmuxingEvents2.default.LOADING_COMPLETE);
  26249. });
  26250. }
  26251. }, {
  26252. key: '_onRecoveredEarlyEof',
  26253. value: function _onRecoveredEarlyEof() {
  26254. var _this4 = this;
  26255. Promise.resolve().then(function () {
  26256. _this4._emitter.emit(_transmuxingEvents2.default.RECOVERED_EARLY_EOF);
  26257. });
  26258. }
  26259. }, {
  26260. key: '_onMediaInfo',
  26261. value: function _onMediaInfo(mediaInfo) {
  26262. var _this5 = this;
  26263. Promise.resolve().then(function () {
  26264. _this5._emitter.emit(_transmuxingEvents2.default.MEDIA_INFO, mediaInfo);
  26265. });
  26266. }
  26267. }, {
  26268. key: '_onStatisticsInfo',
  26269. value: function _onStatisticsInfo(statisticsInfo) {
  26270. var _this6 = this;
  26271. Promise.resolve().then(function () {
  26272. _this6._emitter.emit(_transmuxingEvents2.default.STATISTICS_INFO, statisticsInfo);
  26273. });
  26274. }
  26275. }, {
  26276. key: '_onIOError',
  26277. value: function _onIOError(type, info) {
  26278. var _this7 = this;
  26279. Promise.resolve().then(function () {
  26280. _this7._emitter.emit(_transmuxingEvents2.default.IO_ERROR, type, info);
  26281. });
  26282. }
  26283. }, {
  26284. key: '_onDemuxError',
  26285. value: function _onDemuxError(type, info) {
  26286. var _this8 = this;
  26287. Promise.resolve().then(function () {
  26288. _this8._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR, type, info);
  26289. });
  26290. }
  26291. }, {
  26292. key: '_onRecommendSeekpoint',
  26293. value: function _onRecommendSeekpoint(milliseconds) {
  26294. var _this9 = this;
  26295. Promise.resolve().then(function () {
  26296. _this9._emitter.emit(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, milliseconds);
  26297. });
  26298. }
  26299. }, {
  26300. key: '_onLoadedSei',
  26301. value: function _onLoadedSei(timestamp, data) {
  26302. var _this10 = this;
  26303. Promise.resolve().then(function () {
  26304. _this10._emitter.emit(_transmuxingEvents2.default.LOADED_SEI, timestamp, data);
  26305. });
  26306. }
  26307. }, {
  26308. key: '_onLoggingConfigChanged',
  26309. value: function _onLoggingConfigChanged(config) {
  26310. if (this._worker) {
  26311. this._worker.postMessage({ cmd: 'logging_config', param: config });
  26312. }
  26313. }
  26314. }, {
  26315. key: '_onWorkerMessage',
  26316. value: function _onWorkerMessage(e) {
  26317. var message = e.data;
  26318. var data = message.data;
  26319. if (message.msg === 'destroyed' || this._workerDestroying) {
  26320. this._workerDestroying = false;
  26321. this._worker.terminate();
  26322. this._worker = null;
  26323. return;
  26324. }
  26325. switch (message.msg) {
  26326. case _transmuxingEvents2.default.INIT_SEGMENT:
  26327. case _transmuxingEvents2.default.MEDIA_SEGMENT:
  26328. this._emitter.emit(message.msg, data.type, data.data);
  26329. break;
  26330. case _transmuxingEvents2.default.LOADING_COMPLETE:
  26331. case _transmuxingEvents2.default.RECOVERED_EARLY_EOF:
  26332. this._emitter.emit(message.msg);
  26333. break;
  26334. case _transmuxingEvents2.default.MEDIA_INFO:
  26335. Object.setPrototypeOf(data, _mediaInfo2.default.prototype);
  26336. this._emitter.emit(message.msg, data);
  26337. break;
  26338. case _transmuxingEvents2.default.STATISTICS_INFO:
  26339. this._emitter.emit(message.msg, data);
  26340. break;
  26341. case _transmuxingEvents2.default.IO_ERROR:
  26342. case _transmuxingEvents2.default.DEMUX_ERROR:
  26343. this._emitter.emit(message.msg, data.type, data.info);
  26344. break;
  26345. case _transmuxingEvents2.default.RECOMMEND_SEEKPOINT:
  26346. this._emitter.emit(message.msg, data);
  26347. break;
  26348. case 'logcat_callback':
  26349. _logger2.default.emitter.emit('log', data.type, data.logcat);
  26350. break;
  26351. default:
  26352. break;
  26353. }
  26354. }
  26355. }]);
  26356. return Transmuxer;
  26357. }();
  26358. exports.default = Transmuxer;
  26359. module.exports = exports['default'];
  26360. /***/ }),
  26361. /* 35 */
  26362. /***/ (function(module, exports, __webpack_require__) {
  26363. "use strict";
  26364. Object.defineProperty(exports, "__esModule", {
  26365. value: true
  26366. });
  26367. 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; };
  26368. 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; }; }(); /*
  26369. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  26370. *
  26371. * @author zheng qian <xqq@xqq.im>
  26372. *
  26373. * Licensed under the Apache License, Version 2.0 (the "License");
  26374. * you may not use this file except in compliance with the License.
  26375. * You may obtain a copy of the License at
  26376. *
  26377. * http://www.apache.org/licenses/LICENSE-2.0
  26378. *
  26379. * Unless required by applicable law or agreed to in writing, software
  26380. * distributed under the License is distributed on an "AS IS" BASIS,
  26381. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26382. * See the License for the specific language governing permissions and
  26383. * limitations under the License.
  26384. */
  26385. var _logger = __webpack_require__(0);
  26386. var _logger2 = _interopRequireDefault(_logger);
  26387. var _amfParser = __webpack_require__(36);
  26388. var _amfParser2 = _interopRequireDefault(_amfParser);
  26389. var _spsParser = __webpack_require__(38);
  26390. var _spsParser2 = _interopRequireDefault(_spsParser);
  26391. var _demuxErrors = __webpack_require__(10);
  26392. var _demuxErrors2 = _interopRequireDefault(_demuxErrors);
  26393. var _mediaInfo = __webpack_require__(9);
  26394. var _mediaInfo2 = _interopRequireDefault(_mediaInfo);
  26395. var _exception = __webpack_require__(1);
  26396. var _events = __webpack_require__(2);
  26397. var _events2 = _interopRequireDefault(_events);
  26398. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26399. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  26400. function Swap16(src) {
  26401. return src >>> 8 & 0xFF | (src & 0xFF) << 8;
  26402. }
  26403. function Swap32(src) {
  26404. return (src & 0xFF000000) >>> 24 | (src & 0x00FF0000) >>> 8 | (src & 0x0000FF00) << 8 | (src & 0x000000FF) << 24;
  26405. }
  26406. function ReadBig32(array, index) {
  26407. return array[index] << 24 | array[index + 1] << 16 | array[index + 2] << 8 | array[index + 3];
  26408. }
  26409. var FLVDemuxer = function () {
  26410. function FLVDemuxer(probeData, config) {
  26411. _classCallCheck(this, FLVDemuxer);
  26412. this.TAG = 'FLVDemuxer';
  26413. this._emitter = new _events2.default();
  26414. this._config = config;
  26415. this._onError = null;
  26416. this._onMediaInfo = null;
  26417. this._onTrackMetadata = null;
  26418. this._onDataAvailable = null;
  26419. this._dataOffset = probeData.dataOffset;
  26420. this._firstParse = true;
  26421. this._dispatch = false;
  26422. this._hasAudio = probeData.hasAudioTrack;
  26423. this._hasVideo = probeData.hasVideoTrack;
  26424. this._hasAudioFlagOverrided = false;
  26425. this._hasVideoFlagOverrided = false;
  26426. this._audioInitialMetadataDispatched = false;
  26427. this._videoInitialMetadataDispatched = false;
  26428. this._mediaInfo = new _mediaInfo2.default();
  26429. this._mediaInfo.hasAudio = this._hasAudio;
  26430. this._mediaInfo.hasVideo = this._hasVideo;
  26431. this._metadata = null;
  26432. this._audioMetadata = null;
  26433. this._videoMetadata = null;
  26434. this._naluLengthSize = 4;
  26435. this._timestampBase = 0; // int32, in milliseconds
  26436. this._timescale = 1000;
  26437. this._duration = 0; // int32, in milliseconds
  26438. this._durationOverrided = false;
  26439. this._referenceFrameRate = {
  26440. fixed: true,
  26441. fps: 23.976,
  26442. fps_num: 23976,
  26443. fps_den: 1000
  26444. };
  26445. this._flvSoundRateTable = [5500, 11025, 22050, 44100, 48000];
  26446. this._mpegSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  26447. this._mpegAudioV10SampleRateTable = [44100, 48000, 32000, 0];
  26448. this._mpegAudioV20SampleRateTable = [22050, 24000, 16000, 0];
  26449. this._mpegAudioV25SampleRateTable = [11025, 12000, 8000, 0];
  26450. this._mpegAudioL1BitRateTable = [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, -1];
  26451. this._mpegAudioL2BitRateTable = [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, -1];
  26452. this._mpegAudioL3BitRateTable = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1];
  26453. this._videoTrack = { type: 'video', id: 1, sequenceNumber: 0, samples: [], length: 0 };
  26454. this._audioTrack = { type: 'audio', id: 2, sequenceNumber: 0, samples: [], length: 0 };
  26455. this._littleEndian = function () {
  26456. var buf = new ArrayBuffer(2);
  26457. new DataView(buf).setInt16(0, 256, true); // little-endian write
  26458. return new Int16Array(buf)[0] === 256; // platform-spec read, if equal then LE
  26459. }();
  26460. }
  26461. _createClass(FLVDemuxer, [{
  26462. key: 'destroy',
  26463. value: function destroy() {
  26464. this._mediaInfo = null;
  26465. this._metadata = null;
  26466. this._audioMetadata = null;
  26467. this._videoMetadata = null;
  26468. this._videoTrack = null;
  26469. this._audioTrack = null;
  26470. this._onError = null;
  26471. this._onMediaInfo = null;
  26472. this._onTrackMetadata = null;
  26473. this._onDataAvailable = null;
  26474. this._emitter.removeAllListeners();
  26475. this._emitter = null;
  26476. }
  26477. }, {
  26478. key: 'bindDataSource',
  26479. value: function bindDataSource(loader) {
  26480. loader.onDataArrival = this.parseChunks.bind(this);
  26481. return this;
  26482. }
  26483. // prototype: function(type: string, metadata: any): void
  26484. }, {
  26485. key: 'resetMediaInfo',
  26486. value: function resetMediaInfo() {
  26487. this._mediaInfo = new _mediaInfo2.default();
  26488. }
  26489. }, {
  26490. key: '_isInitialMetadataDispatched',
  26491. value: function _isInitialMetadataDispatched() {
  26492. if (this._hasAudio && this._hasVideo) {
  26493. // both audio & video
  26494. return this._audioInitialMetadataDispatched && this._videoInitialMetadataDispatched;
  26495. }
  26496. if (this._hasAudio && !this._hasVideo) {
  26497. // audio only
  26498. return this._audioInitialMetadataDispatched;
  26499. }
  26500. if (!this._hasAudio && this._hasVideo) {
  26501. // video only
  26502. return this._videoInitialMetadataDispatched;
  26503. }
  26504. return false;
  26505. }
  26506. // function parseChunks(chunk: ArrayBuffer, byteStart: number): number;
  26507. }, {
  26508. key: 'parseChunks',
  26509. value: function parseChunks(chunk, byteStart) {
  26510. if (!this._onError || !this._onMediaInfo || !this._onTrackMetadata || !this._onDataAvailable) {
  26511. throw new _exception.IllegalStateException('Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified');
  26512. }
  26513. var offset = 0;
  26514. var le = this._littleEndian;
  26515. if (byteStart === 0) {
  26516. // buffer with FLV header
  26517. if (chunk.byteLength > 13) {
  26518. var probeData = FLVDemuxer.probe(chunk);
  26519. offset = probeData.dataOffset;
  26520. } else {
  26521. return 0;
  26522. }
  26523. }
  26524. if (this._firstParse) {
  26525. // handle PreviousTagSize0 before Tag1
  26526. this._firstParse = false;
  26527. if (byteStart + offset !== this._dataOffset) {
  26528. _logger2.default.w(this.TAG, 'First time parsing but chunk byteStart invalid!');
  26529. }
  26530. var v = new DataView(chunk, offset);
  26531. var prevTagSize0 = v.getUint32(0, !le);
  26532. if (prevTagSize0 !== 0) {
  26533. _logger2.default.w(this.TAG, 'PrevTagSize0 !== 0 !!!');
  26534. }
  26535. offset += 4;
  26536. }
  26537. while (offset < chunk.byteLength) {
  26538. this._dispatch = true;
  26539. var _v = new DataView(chunk, offset);
  26540. if (offset + 11 + 4 > chunk.byteLength) {
  26541. // data not enough for parsing an flv tag
  26542. break;
  26543. }
  26544. var tagType = _v.getUint8(0);
  26545. var dataSize = _v.getUint32(0, !le) & 0x00FFFFFF;
  26546. if (offset + 11 + dataSize + 4 > chunk.byteLength) {
  26547. // data not enough for parsing actual data body
  26548. break;
  26549. }
  26550. if (tagType !== 8 && tagType !== 9 && tagType !== 18) {
  26551. _logger2.default.w(this.TAG, 'Unsupported tag type ' + tagType + ', skipped');
  26552. // consume the whole tag (skip it)
  26553. offset += 11 + dataSize + 4;
  26554. continue;
  26555. }
  26556. var ts2 = _v.getUint8(4);
  26557. var ts1 = _v.getUint8(5);
  26558. var ts0 = _v.getUint8(6);
  26559. var ts3 = _v.getUint8(7);
  26560. var timestamp = ts0 | ts1 << 8 | ts2 << 16 | ts3 << 24;
  26561. var streamId = _v.getUint32(7, !le) & 0x00FFFFFF;
  26562. if (streamId !== 0) {
  26563. _logger2.default.w(this.TAG, 'Meet tag which has StreamID != 0!');
  26564. }
  26565. var dataOffset = offset + 11;
  26566. switch (tagType) {
  26567. case 8:
  26568. // Audio
  26569. this._parseAudioData(chunk, dataOffset, dataSize, timestamp);
  26570. break;
  26571. case 9:
  26572. // Video
  26573. this._parseVideoData(chunk, dataOffset, dataSize, timestamp, byteStart + offset);
  26574. break;
  26575. case 18:
  26576. // ScriptDataObject
  26577. this._parseScriptData(chunk, dataOffset, dataSize);
  26578. break;
  26579. }
  26580. var prevTagSize = _v.getUint32(11 + dataSize, !le);
  26581. if (prevTagSize !== 11 + dataSize) {
  26582. _logger2.default.w(this.TAG, 'Invalid PrevTagSize ' + prevTagSize);
  26583. }
  26584. offset += 11 + dataSize + 4; // tagBody + dataSize + prevTagSize
  26585. }
  26586. // dispatch parsed frames to consumer (typically, the remuxer)
  26587. if (this._isInitialMetadataDispatched()) {
  26588. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  26589. this._onDataAvailable(this._audioTrack, this._videoTrack);
  26590. }
  26591. }
  26592. return offset; // consumed bytes, just equals latest offset index
  26593. }
  26594. }, {
  26595. key: '_parseScriptData',
  26596. value: function _parseScriptData(arrayBuffer, dataOffset, dataSize) {
  26597. var scriptData = _amfParser2.default.parseScriptData(arrayBuffer, dataOffset, dataSize);
  26598. if (scriptData.hasOwnProperty('onMetaData')) {
  26599. if (scriptData.onMetaData == null || _typeof(scriptData.onMetaData) !== 'object') {
  26600. _logger2.default.w(this.TAG, 'Invalid onMetaData structure!');
  26601. return;
  26602. }
  26603. if (this._metadata) {
  26604. _logger2.default.w(this.TAG, 'Found another onMetaData tag!');
  26605. }
  26606. this._metadata = scriptData;
  26607. var onMetaData = this._metadata.onMetaData;
  26608. this._emitter.emit('metadata_arrived', onMetaData);
  26609. if (typeof onMetaData.hasAudio === 'boolean') {
  26610. // hasAudio
  26611. if (this._hasAudioFlagOverrided === false) {
  26612. this._hasAudio = onMetaData.hasAudio;
  26613. this._mediaInfo.hasAudio = this._hasAudio;
  26614. }
  26615. }
  26616. if (typeof onMetaData.hasVideo === 'boolean') {
  26617. // hasVideo
  26618. if (this._hasVideoFlagOverrided === false) {
  26619. this._hasVideo = onMetaData.hasVideo;
  26620. this._mediaInfo.hasVideo = this._hasVideo;
  26621. }
  26622. }
  26623. if (typeof onMetaData.audiodatarate === 'number') {
  26624. // audiodatarate
  26625. this._mediaInfo.audioDataRate = onMetaData.audiodatarate;
  26626. }
  26627. if (typeof onMetaData.videodatarate === 'number') {
  26628. // videodatarate
  26629. this._mediaInfo.videoDataRate = onMetaData.videodatarate;
  26630. }
  26631. if (typeof onMetaData.width === 'number') {
  26632. // width
  26633. this._mediaInfo.width = onMetaData.width;
  26634. }
  26635. if (typeof onMetaData.height === 'number') {
  26636. // height
  26637. this._mediaInfo.height = onMetaData.height;
  26638. }
  26639. if (typeof onMetaData.duration === 'number') {
  26640. // duration
  26641. if (!this._durationOverrided) {
  26642. var duration = Math.floor(onMetaData.duration * this._timescale);
  26643. this._duration = duration;
  26644. this._mediaInfo.duration = duration;
  26645. }
  26646. } else {
  26647. this._mediaInfo.duration = 0;
  26648. }
  26649. if (typeof onMetaData.framerate === 'number') {
  26650. // framerate
  26651. var fps_num = Math.floor(onMetaData.framerate * 1000);
  26652. if (fps_num > 0) {
  26653. var fps = fps_num / 1000;
  26654. this._referenceFrameRate.fixed = true;
  26655. this._referenceFrameRate.fps = fps;
  26656. this._referenceFrameRate.fps_num = fps_num;
  26657. this._referenceFrameRate.fps_den = 1000;
  26658. this._mediaInfo.fps = fps;
  26659. }
  26660. }
  26661. if (_typeof(onMetaData.keyframes) === 'object') {
  26662. // keyframes
  26663. this._mediaInfo.hasKeyframesIndex = true;
  26664. var keyframes = onMetaData.keyframes;
  26665. this._mediaInfo.keyframesIndex = this._parseKeyframesIndex(keyframes);
  26666. onMetaData.keyframes = null; // keyframes has been extracted, remove it
  26667. } else {
  26668. this._mediaInfo.hasKeyframesIndex = false;
  26669. }
  26670. this._dispatch = false;
  26671. this._mediaInfo.metadata = onMetaData;
  26672. _logger2.default.v(this.TAG, 'Parsed onMetaData');
  26673. if (this._mediaInfo.isComplete()) {
  26674. this._onMediaInfo(this._mediaInfo);
  26675. }
  26676. }
  26677. }
  26678. }, {
  26679. key: '_parseKeyframesIndex',
  26680. value: function _parseKeyframesIndex(keyframes) {
  26681. var times = [];
  26682. var filepositions = [];
  26683. // ignore first keyframe which is actually AVC Sequence Header (AVCDecoderConfigurationRecord)
  26684. for (var i = 1; i < keyframes.times.length; i++) {
  26685. var time = this._timestampBase + Math.floor(keyframes.times[i] * 1000);
  26686. times.push(time);
  26687. filepositions.push(keyframes.filepositions[i]);
  26688. }
  26689. return {
  26690. times: times,
  26691. filepositions: filepositions
  26692. };
  26693. }
  26694. }, {
  26695. key: '_parseAudioData',
  26696. value: function _parseAudioData(arrayBuffer, dataOffset, dataSize, tagTimestamp) {
  26697. if (dataSize <= 1) {
  26698. _logger2.default.w(this.TAG, 'Flv: Invalid audio packet, missing SoundData payload!');
  26699. return;
  26700. }
  26701. if (this._hasAudioFlagOverrided === true && this._hasAudio === false) {
  26702. // If hasAudio: false indicated explicitly in MediaDataSource,
  26703. // Ignore all the audio packets
  26704. return;
  26705. }
  26706. var le = this._littleEndian;
  26707. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  26708. var soundSpec = v.getUint8(0);
  26709. var soundFormat = soundSpec >>> 4;
  26710. if (soundFormat !== 2 && soundFormat !== 10) {
  26711. // MP3 or AAC
  26712. this._onError(_demuxErrors2.default.CODEC_UNSUPPORTED, 'Flv: Unsupported audio codec idx: ' + soundFormat);
  26713. return;
  26714. }
  26715. var soundRate = 0;
  26716. var soundRateIndex = (soundSpec & 12) >>> 2;
  26717. if (soundRateIndex >= 0 && soundRateIndex <= 4) {
  26718. soundRate = this._flvSoundRateTable[soundRateIndex];
  26719. } else {
  26720. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid audio sample rate idx: ' + soundRateIndex);
  26721. return;
  26722. }
  26723. var soundSize = (soundSpec & 2) >>> 1; // unused
  26724. var soundType = soundSpec & 1;
  26725. var meta = this._audioMetadata;
  26726. var track = this._audioTrack;
  26727. if (!meta) {
  26728. if (this._hasAudio === false && this._hasAudioFlagOverrided === false) {
  26729. this._hasAudio = true;
  26730. this._mediaInfo.hasAudio = true;
  26731. }
  26732. // initial metadata
  26733. meta = this._audioMetadata = {};
  26734. meta.type = 'audio';
  26735. meta.id = track.id;
  26736. meta.timescale = this._timescale;
  26737. meta.duration = this._duration;
  26738. meta.audioSampleRate = soundRate;
  26739. meta.channelCount = soundType === 0 ? 1 : 2;
  26740. }
  26741. if (soundFormat === 10) {
  26742. // AAC
  26743. var aacData = this._parseAACAudioData(arrayBuffer, dataOffset + 1, dataSize - 1);
  26744. if (aacData == undefined) {
  26745. return;
  26746. }
  26747. if (aacData.packetType === 0) {
  26748. // AAC sequence header (AudioSpecificConfig)
  26749. if (meta.config) {
  26750. _logger2.default.w(this.TAG, 'Found another AudioSpecificConfig!');
  26751. }
  26752. var misc = aacData.data;
  26753. meta.audioSampleRate = misc.samplingRate;
  26754. meta.channelCount = misc.channelCount;
  26755. meta.codec = misc.codec;
  26756. meta.originalCodec = misc.originalCodec;
  26757. meta.config = misc.config;
  26758. // The decode result of an aac sample is 1024 PCM samples
  26759. meta.refSampleDuration = 1024 / meta.audioSampleRate * meta.timescale;
  26760. _logger2.default.v(this.TAG, 'Parsed AudioSpecificConfig');
  26761. if (this._isInitialMetadataDispatched()) {
  26762. // Non-initial metadata, force dispatch (or flush) parsed frames to remuxer
  26763. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  26764. this._onDataAvailable(this._audioTrack, this._videoTrack);
  26765. }
  26766. } else {
  26767. this._audioInitialMetadataDispatched = true;
  26768. }
  26769. // then notify new metadata
  26770. this._dispatch = false;
  26771. this._onTrackMetadata('audio', meta);
  26772. var mi = this._mediaInfo;
  26773. mi.audioCodec = meta.originalCodec;
  26774. mi.audioSampleRate = meta.audioSampleRate;
  26775. mi.audioChannelCount = meta.channelCount;
  26776. if (mi.hasVideo) {
  26777. if (mi.videoCodec != null) {
  26778. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
  26779. }
  26780. } else {
  26781. mi.mimeType = 'video/x-flv; codecs="' + mi.audioCodec + '"';
  26782. }
  26783. if (mi.isComplete()) {
  26784. this._onMediaInfo(mi);
  26785. }
  26786. } else if (aacData.packetType === 1) {
  26787. // AAC raw frame data
  26788. var dts = this._timestampBase + tagTimestamp;
  26789. var aacSample = { unit: aacData.data, length: aacData.data.byteLength, dts: dts, pts: dts };
  26790. track.samples.push(aacSample);
  26791. track.length += aacData.data.length;
  26792. } else {
  26793. _logger2.default.e(this.TAG, 'Flv: Unsupported AAC data type ' + aacData.packetType);
  26794. }
  26795. } else if (soundFormat === 2) {
  26796. // MP3
  26797. if (!meta.codec) {
  26798. // We need metadata for mp3 audio track, extract info from frame header
  26799. var _misc = this._parseMP3AudioData(arrayBuffer, dataOffset + 1, dataSize - 1, true);
  26800. if (_misc == undefined) {
  26801. return;
  26802. }
  26803. meta.audioSampleRate = _misc.samplingRate;
  26804. meta.channelCount = _misc.channelCount;
  26805. meta.codec = _misc.codec;
  26806. meta.originalCodec = _misc.originalCodec;
  26807. // The decode result of an mp3 sample is 1152 PCM samples
  26808. meta.refSampleDuration = 1152 / meta.audioSampleRate * meta.timescale;
  26809. _logger2.default.v(this.TAG, 'Parsed MPEG Audio Frame Header');
  26810. this._audioInitialMetadataDispatched = true;
  26811. this._onTrackMetadata('audio', meta);
  26812. var _mi = this._mediaInfo;
  26813. _mi.audioCodec = meta.codec;
  26814. _mi.audioSampleRate = meta.audioSampleRate;
  26815. _mi.audioChannelCount = meta.channelCount;
  26816. _mi.audioDataRate = _misc.bitRate;
  26817. if (_mi.hasVideo) {
  26818. if (_mi.videoCodec != null) {
  26819. _mi.mimeType = 'video/x-flv; codecs="' + _mi.videoCodec + ',' + _mi.audioCodec + '"';
  26820. }
  26821. } else {
  26822. _mi.mimeType = 'video/x-flv; codecs="' + _mi.audioCodec + '"';
  26823. }
  26824. if (_mi.isComplete()) {
  26825. this._onMediaInfo(_mi);
  26826. }
  26827. }
  26828. // This packet is always a valid audio packet, extract it
  26829. var data = this._parseMP3AudioData(arrayBuffer, dataOffset + 1, dataSize - 1, false);
  26830. if (data == undefined) {
  26831. return;
  26832. }
  26833. var _dts = this._timestampBase + tagTimestamp;
  26834. var mp3Sample = { unit: data, length: data.byteLength, dts: _dts, pts: _dts };
  26835. track.samples.push(mp3Sample);
  26836. track.length += data.length;
  26837. }
  26838. }
  26839. }, {
  26840. key: '_parseAACAudioData',
  26841. value: function _parseAACAudioData(arrayBuffer, dataOffset, dataSize) {
  26842. if (dataSize <= 1) {
  26843. _logger2.default.w(this.TAG, 'Flv: Invalid AAC packet, missing AACPacketType or/and Data!');
  26844. return;
  26845. }
  26846. var result = {};
  26847. var array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  26848. result.packetType = array[0];
  26849. if (array[0] === 0) {
  26850. result.data = this._parseAACAudioSpecificConfig(arrayBuffer, dataOffset + 1, dataSize - 1);
  26851. } else {
  26852. result.data = array.subarray(1);
  26853. }
  26854. return result;
  26855. }
  26856. }, {
  26857. key: '_parseAACAudioSpecificConfig',
  26858. value: function _parseAACAudioSpecificConfig(arrayBuffer, dataOffset, dataSize) {
  26859. var array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  26860. var config = null;
  26861. /* Audio Object Type:
  26862. 0: Null
  26863. 1: AAC Main
  26864. 2: AAC LC
  26865. 3: AAC SSR (Scalable Sample Rate)
  26866. 4: AAC LTP (Long Term Prediction)
  26867. 5: HE-AAC / SBR (Spectral Band Replication)
  26868. 6: AAC Scalable
  26869. */
  26870. var audioObjectType = 0;
  26871. var originalAudioObjectType = 0;
  26872. var audioExtensionObjectType = null;
  26873. var samplingIndex = 0;
  26874. var extensionSamplingIndex = null;
  26875. // 5 bits
  26876. audioObjectType = originalAudioObjectType = array[0] >>> 3;
  26877. // 4 bits
  26878. samplingIndex = (array[0] & 0x07) << 1 | array[1] >>> 7;
  26879. if (samplingIndex < 0 || samplingIndex >= this._mpegSamplingRates.length) {
  26880. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: AAC invalid sampling frequency index!');
  26881. return;
  26882. }
  26883. var samplingFrequence = this._mpegSamplingRates[samplingIndex];
  26884. // 4 bits
  26885. var channelConfig = (array[1] & 0x78) >>> 3;
  26886. if (channelConfig < 0 || channelConfig >= 8) {
  26887. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: AAC invalid channel configuration');
  26888. return;
  26889. }
  26890. if (audioObjectType === 5) {
  26891. // HE-AAC?
  26892. // 4 bits
  26893. extensionSamplingIndex = (array[1] & 0x07) << 1 | array[2] >>> 7;
  26894. // 5 bits
  26895. audioExtensionObjectType = (array[2] & 0x7C) >>> 2;
  26896. }
  26897. // workarounds for various browsers
  26898. var userAgent = self.navigator.userAgent.toLowerCase();
  26899. if (userAgent.indexOf('firefox') !== -1) {
  26900. // firefox: use SBR (HE-AAC) if freq less than 24kHz
  26901. if (samplingIndex >= 6) {
  26902. audioObjectType = 5;
  26903. config = new Array(4);
  26904. extensionSamplingIndex = samplingIndex - 3;
  26905. } else {
  26906. // use LC-AAC
  26907. audioObjectType = 2;
  26908. config = new Array(2);
  26909. extensionSamplingIndex = samplingIndex;
  26910. }
  26911. } else if (userAgent.indexOf('android') !== -1) {
  26912. // android: always use LC-AAC
  26913. audioObjectType = 2;
  26914. config = new Array(2);
  26915. extensionSamplingIndex = samplingIndex;
  26916. } else {
  26917. // for other browsers, e.g. chrome...
  26918. // Always use HE-AAC to make it easier to switch aac codec profile
  26919. audioObjectType = 5;
  26920. extensionSamplingIndex = samplingIndex;
  26921. config = new Array(4);
  26922. if (samplingIndex >= 6) {
  26923. extensionSamplingIndex = samplingIndex - 3;
  26924. } else if (channelConfig === 1) {
  26925. // Mono channel
  26926. audioObjectType = 2;
  26927. config = new Array(2);
  26928. extensionSamplingIndex = samplingIndex;
  26929. }
  26930. }
  26931. config[0] = audioObjectType << 3;
  26932. config[0] |= (samplingIndex & 0x0F) >>> 1;
  26933. config[1] = (samplingIndex & 0x0F) << 7;
  26934. config[1] |= (channelConfig & 0x0F) << 3;
  26935. if (audioObjectType === 5) {
  26936. config[1] |= (extensionSamplingIndex & 0x0F) >>> 1;
  26937. config[2] = (extensionSamplingIndex & 0x01) << 7;
  26938. // extended audio object type: force to 2 (LC-AAC)
  26939. config[2] |= 2 << 2;
  26940. config[3] = 0;
  26941. }
  26942. return {
  26943. config: config,
  26944. samplingRate: samplingFrequence,
  26945. channelCount: channelConfig,
  26946. codec: 'mp4a.40.' + audioObjectType,
  26947. originalCodec: 'mp4a.40.' + originalAudioObjectType
  26948. };
  26949. }
  26950. }, {
  26951. key: '_parseMP3AudioData',
  26952. value: function _parseMP3AudioData(arrayBuffer, dataOffset, dataSize, requestHeader) {
  26953. if (dataSize < 4) {
  26954. _logger2.default.w(this.TAG, 'Flv: Invalid MP3 packet, header missing!');
  26955. return;
  26956. }
  26957. var le = this._littleEndian;
  26958. var array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  26959. var result = null;
  26960. if (requestHeader) {
  26961. if (array[0] !== 0xFF) {
  26962. return;
  26963. }
  26964. var ver = array[1] >>> 3 & 0x03;
  26965. var layer = (array[1] & 0x06) >> 1;
  26966. var bitrate_index = (array[2] & 0xF0) >>> 4;
  26967. var sampling_freq_index = (array[2] & 0x0C) >>> 2;
  26968. var channel_mode = array[3] >>> 6 & 0x03;
  26969. var channel_count = channel_mode !== 3 ? 2 : 1;
  26970. var sample_rate = 0;
  26971. var bit_rate = 0;
  26972. var object_type = 34; // Layer-3, listed in MPEG-4 Audio Object Types
  26973. var codec = 'mp3';
  26974. switch (ver) {
  26975. case 0:
  26976. // MPEG 2.5
  26977. sample_rate = this._mpegAudioV25SampleRateTable[sampling_freq_index];
  26978. break;
  26979. case 2:
  26980. // MPEG 2
  26981. sample_rate = this._mpegAudioV20SampleRateTable[sampling_freq_index];
  26982. break;
  26983. case 3:
  26984. // MPEG 1
  26985. sample_rate = this._mpegAudioV10SampleRateTable[sampling_freq_index];
  26986. break;
  26987. }
  26988. switch (layer) {
  26989. case 1:
  26990. // Layer 3
  26991. object_type = 34;
  26992. if (bitrate_index < this._mpegAudioL3BitRateTable.length) {
  26993. bit_rate = this._mpegAudioL3BitRateTable[bitrate_index];
  26994. }
  26995. break;
  26996. case 2:
  26997. // Layer 2
  26998. object_type = 33;
  26999. if (bitrate_index < this._mpegAudioL2BitRateTable.length) {
  27000. bit_rate = this._mpegAudioL2BitRateTable[bitrate_index];
  27001. }
  27002. break;
  27003. case 3:
  27004. // Layer 1
  27005. object_type = 32;
  27006. if (bitrate_index < this._mpegAudioL1BitRateTable.length) {
  27007. bit_rate = this._mpegAudioL1BitRateTable[bitrate_index];
  27008. }
  27009. break;
  27010. }
  27011. result = {
  27012. bitRate: bit_rate,
  27013. samplingRate: sample_rate,
  27014. channelCount: channel_count,
  27015. codec: codec,
  27016. originalCodec: codec
  27017. };
  27018. } else {
  27019. result = array;
  27020. }
  27021. return result;
  27022. }
  27023. }, {
  27024. key: '_parseVideoData',
  27025. value: function _parseVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition) {
  27026. if (dataSize <= 1) {
  27027. _logger2.default.w(this.TAG, 'Flv: Invalid video packet, missing VideoData payload!');
  27028. return;
  27029. }
  27030. if (this._hasVideoFlagOverrided === true && this._hasVideo === false) {
  27031. // If hasVideo: false indicated explicitly in MediaDataSource,
  27032. // Ignore all the video packets
  27033. return;
  27034. }
  27035. var spec = new Uint8Array(arrayBuffer, dataOffset, dataSize)[0];
  27036. var frameType = (spec & 240) >>> 4;
  27037. var codecId = spec & 15;
  27038. if (codecId !== 7) {
  27039. this._onError(_demuxErrors2.default.CODEC_UNSUPPORTED, 'Flv: Unsupported codec in video frame: ' + codecId);
  27040. return;
  27041. }
  27042. this._parseAVCVideoPacket(arrayBuffer, dataOffset + 1, dataSize - 1, tagTimestamp, tagPosition, frameType);
  27043. }
  27044. }, {
  27045. key: '_parseAVCVideoPacket',
  27046. value: function _parseAVCVideoPacket(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType) {
  27047. if (dataSize < 4) {
  27048. _logger2.default.w(this.TAG, 'Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime');
  27049. return;
  27050. }
  27051. var le = this._littleEndian;
  27052. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  27053. var packetType = v.getUint8(0);
  27054. var cts_unsigned = v.getUint32(0, !le) & 0x00FFFFFF;
  27055. var cts = cts_unsigned << 8 >> 8; // convert to 24-bit signed int
  27056. if (packetType === 0) {
  27057. // AVCDecoderConfigurationRecord
  27058. this._parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset + 4, dataSize - 4);
  27059. } else if (packetType === 1) {
  27060. // One or more Nalus
  27061. this._parseAVCVideoData(arrayBuffer, dataOffset + 4, dataSize - 4, tagTimestamp, tagPosition, frameType, cts);
  27062. } else if (packetType === 2) {
  27063. // empty, AVC end of sequence
  27064. } else {
  27065. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid video packet type ' + packetType);
  27066. return;
  27067. }
  27068. }
  27069. }, {
  27070. key: '_parseAVCDecoderConfigurationRecord',
  27071. value: function _parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset, dataSize) {
  27072. if (dataSize < 7) {
  27073. _logger2.default.w(this.TAG, 'Flv: Invalid AVCDecoderConfigurationRecord, lack of data!');
  27074. return;
  27075. }
  27076. var meta = this._videoMetadata;
  27077. var track = this._videoTrack;
  27078. var le = this._littleEndian;
  27079. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  27080. if (!meta) {
  27081. if (this._hasVideo === false && this._hasVideoFlagOverrided === false) {
  27082. this._hasVideo = true;
  27083. this._mediaInfo.hasVideo = true;
  27084. }
  27085. meta = this._videoMetadata = {};
  27086. meta.type = 'video';
  27087. meta.id = track.id;
  27088. meta.timescale = this._timescale;
  27089. meta.duration = this._duration;
  27090. } else {
  27091. if (typeof meta.avcc !== 'undefined') {
  27092. _logger2.default.w(this.TAG, 'Found another AVCDecoderConfigurationRecord!');
  27093. }
  27094. }
  27095. var version = v.getUint8(0); // configurationVersion
  27096. var avcProfile = v.getUint8(1); // avcProfileIndication
  27097. var profileCompatibility = v.getUint8(2); // profile_compatibility
  27098. var avcLevel = v.getUint8(3); // AVCLevelIndication
  27099. if (version !== 1 || avcProfile === 0) {
  27100. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord');
  27101. return;
  27102. }
  27103. this._naluLengthSize = (v.getUint8(4) & 3) + 1; // lengthSizeMinusOne
  27104. if (this._naluLengthSize !== 3 && this._naluLengthSize !== 4) {
  27105. // holy shit!!!
  27106. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Strange NaluLengthSizeMinusOne: ' + (this._naluLengthSize - 1));
  27107. return;
  27108. }
  27109. var spsCount = v.getUint8(5) & 31; // numOfSequenceParameterSets
  27110. if (spsCount === 0) {
  27111. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord: No SPS');
  27112. return;
  27113. } else if (spsCount > 1) {
  27114. _logger2.default.w(this.TAG, 'Flv: Strange AVCDecoderConfigurationRecord: SPS Count = ' + spsCount);
  27115. }
  27116. var offset = 6;
  27117. for (var i = 0; i < spsCount; i++) {
  27118. var len = v.getUint16(offset, !le); // sequenceParameterSetLength
  27119. offset += 2;
  27120. if (len === 0) {
  27121. continue;
  27122. }
  27123. // Notice: Nalu without startcode header (00 00 00 01)
  27124. var sps = new Uint8Array(arrayBuffer, dataOffset + offset, len);
  27125. offset += len;
  27126. var config = _spsParser2.default.parseSPS(sps);
  27127. if (i !== 0) {
  27128. // ignore other sps's config
  27129. continue;
  27130. }
  27131. meta.codecWidth = config.codec_size.width;
  27132. meta.codecHeight = config.codec_size.height;
  27133. meta.presentWidth = config.present_size.width;
  27134. meta.presentHeight = config.present_size.height;
  27135. meta.profile = config.profile_string;
  27136. meta.level = config.level_string;
  27137. meta.bitDepth = config.bit_depth;
  27138. meta.chromaFormat = config.chroma_format;
  27139. meta.sarRatio = config.par_ratio;
  27140. meta.frameRate = config.frame_rate;
  27141. if (config.frame_rate.fixed === false || config.frame_rate.fps_num === 0 || config.frame_rate.fps_den === 0) {
  27142. meta.frameRate = this._referenceFrameRate;
  27143. }
  27144. var fps_den = meta.frameRate.fps_den;
  27145. var fps_num = meta.frameRate.fps_num;
  27146. meta.refSampleDuration = meta.timescale * (fps_den / fps_num);
  27147. var codecArray = sps.subarray(1, 4);
  27148. var codecString = 'avc1.';
  27149. for (var j = 0; j < 3; j++) {
  27150. var h = codecArray[j].toString(16);
  27151. if (h.length < 2) {
  27152. h = '0' + h;
  27153. }
  27154. codecString += h;
  27155. }
  27156. meta.codec = codecString;
  27157. var mi = this._mediaInfo;
  27158. mi.width = meta.codecWidth;
  27159. mi.height = meta.codecHeight;
  27160. mi.fps = meta.frameRate.fps;
  27161. mi.profile = meta.profile;
  27162. mi.level = meta.level;
  27163. mi.refFrames = config.ref_frames;
  27164. mi.chromaFormat = config.chroma_format_string;
  27165. mi.sarNum = meta.sarRatio.width;
  27166. mi.sarDen = meta.sarRatio.height;
  27167. mi.videoCodec = codecString;
  27168. if (mi.hasAudio) {
  27169. if (mi.audioCodec != null) {
  27170. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
  27171. }
  27172. } else {
  27173. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + '"';
  27174. }
  27175. if (mi.isComplete()) {
  27176. this._onMediaInfo(mi);
  27177. }
  27178. }
  27179. var ppsCount = v.getUint8(offset); // numOfPictureParameterSets
  27180. if (ppsCount === 0) {
  27181. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord: No PPS');
  27182. return;
  27183. } else if (ppsCount > 1) {
  27184. _logger2.default.w(this.TAG, 'Flv: Strange AVCDecoderConfigurationRecord: PPS Count = ' + ppsCount);
  27185. }
  27186. offset++;
  27187. for (var _i = 0; _i < ppsCount; _i++) {
  27188. var _len = v.getUint16(offset, !le); // pictureParameterSetLength
  27189. offset += 2;
  27190. if (_len === 0) {
  27191. continue;
  27192. }
  27193. // pps is useless for extracting video information
  27194. offset += _len;
  27195. }
  27196. meta.avcc = new Uint8Array(dataSize);
  27197. meta.avcc.set(new Uint8Array(arrayBuffer, dataOffset, dataSize), 0);
  27198. _logger2.default.v(this.TAG, 'Parsed AVCDecoderConfigurationRecord');
  27199. if (this._isInitialMetadataDispatched()) {
  27200. // flush parsed frames
  27201. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  27202. this._onDataAvailable(this._audioTrack, this._videoTrack);
  27203. }
  27204. } else {
  27205. this._videoInitialMetadataDispatched = true;
  27206. }
  27207. // notify new metadata
  27208. this._dispatch = false;
  27209. this._onTrackMetadata('video', meta);
  27210. }
  27211. }, {
  27212. key: '_parseAVCVideoData',
  27213. value: function _parseAVCVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType, cts) {
  27214. var le = this._littleEndian;
  27215. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  27216. var units = [],
  27217. length = 0;
  27218. var offset = 0;
  27219. var lengthSize = this._naluLengthSize;
  27220. var dts = this._timestampBase + tagTimestamp;
  27221. var keyframe = frameType === 1; // from FLV Frame Type constants
  27222. while (offset < dataSize) {
  27223. if (offset + 4 >= dataSize) {
  27224. _logger2.default.w(this.TAG, 'Malformed Nalu near timestamp ' + dts + ', offset = ' + offset + ', dataSize = ' + dataSize);
  27225. break; // data not enough for next Nalu
  27226. }
  27227. // Nalu with length-header (AVC1)
  27228. var naluSize = v.getUint32(offset, !le); // Big-Endian read
  27229. if (lengthSize === 3) {
  27230. naluSize >>>= 8;
  27231. }
  27232. if (naluSize > dataSize - lengthSize) {
  27233. _logger2.default.w(this.TAG, 'Malformed Nalus near timestamp ' + dts + ', NaluSize > DataSize!');
  27234. return;
  27235. }
  27236. var unitType = v.getUint8(offset + lengthSize) & 0x1F;
  27237. if (unitType === 5) {
  27238. // IDR
  27239. keyframe = true;
  27240. }
  27241. var data = new Uint8Array(arrayBuffer, dataOffset + offset, lengthSize + naluSize);
  27242. var unit = { type: unitType, data: data };
  27243. units.push(unit);
  27244. length += data.byteLength;
  27245. offset += lengthSize + naluSize;
  27246. }
  27247. if (units.length) {
  27248. var track = this._videoTrack;
  27249. var avcSample = {
  27250. units: units,
  27251. length: length,
  27252. isKeyframe: keyframe,
  27253. dts: dts,
  27254. cts: cts,
  27255. pts: dts + cts
  27256. };
  27257. if (keyframe) {
  27258. avcSample.fileposition = tagPosition;
  27259. }
  27260. track.samples.push(avcSample);
  27261. track.length += length;
  27262. }
  27263. }
  27264. }, {
  27265. key: 'onTrackMetadata',
  27266. get: function get() {
  27267. return this._onTrackMetadata;
  27268. },
  27269. set: function set(callback) {
  27270. this._onTrackMetadata = callback;
  27271. }
  27272. // prototype: function(mediaInfo: MediaInfo): void
  27273. }, {
  27274. key: 'onMediaInfo',
  27275. get: function get() {
  27276. return this._onMediaInfo;
  27277. },
  27278. set: function set(callback) {
  27279. this._onMediaInfo = callback;
  27280. }
  27281. // prototype: function(type: number, info: string): void
  27282. }, {
  27283. key: 'onError',
  27284. get: function get() {
  27285. return this._onError;
  27286. },
  27287. set: function set(callback) {
  27288. this._onError = callback;
  27289. }
  27290. // prototype: function(videoTrack: any, audioTrack: any): void
  27291. }, {
  27292. key: 'onDataAvailable',
  27293. get: function get() {
  27294. return this._onDataAvailable;
  27295. },
  27296. set: function set(callback) {
  27297. this._onDataAvailable = callback;
  27298. }
  27299. // timestamp base for output samples, must be in milliseconds
  27300. }, {
  27301. key: 'timestampBase',
  27302. get: function get() {
  27303. return this._timestampBase;
  27304. },
  27305. set: function set(base) {
  27306. this._timestampBase = base;
  27307. }
  27308. }, {
  27309. key: 'overridedDuration',
  27310. get: function get() {
  27311. return this._duration;
  27312. }
  27313. // Force-override media duration. Must be in milliseconds, int32
  27314. ,
  27315. set: function set(duration) {
  27316. this._durationOverrided = true;
  27317. this._duration = duration;
  27318. this._mediaInfo.duration = duration;
  27319. }
  27320. // Force-override audio track present flag, boolean
  27321. }, {
  27322. key: 'overridedHasAudio',
  27323. set: function set(hasAudio) {
  27324. this._hasAudioFlagOverrided = true;
  27325. this._hasAudio = hasAudio;
  27326. this._mediaInfo.hasAudio = hasAudio;
  27327. }
  27328. // Force-override video track present flag, boolean
  27329. }, {
  27330. key: 'overridedHasVideo',
  27331. set: function set(hasVideo) {
  27332. this._hasVideoFlagOverrided = true;
  27333. this._hasVideo = hasVideo;
  27334. this._mediaInfo.hasVideo = hasVideo;
  27335. }
  27336. }], [{
  27337. key: 'probe',
  27338. value: function probe(buffer) {
  27339. var data = new Uint8Array(buffer);
  27340. var mismatch = { match: false };
  27341. if (data[0] !== 0x46 || data[1] !== 0x4C || data[2] !== 0x56 || data[3] !== 0x01) {
  27342. return mismatch;
  27343. }
  27344. var hasAudio = (data[4] & 4) >>> 2 !== 0;
  27345. var hasVideo = (data[4] & 1) !== 0;
  27346. var offset = ReadBig32(data, 5);
  27347. if (offset < 9) {
  27348. return mismatch;
  27349. }
  27350. return {
  27351. match: true,
  27352. consumed: offset,
  27353. dataOffset: offset,
  27354. hasAudioTrack: hasAudio,
  27355. hasVideoTrack: hasVideo
  27356. };
  27357. }
  27358. }]);
  27359. return FLVDemuxer;
  27360. }();
  27361. exports.default = FLVDemuxer;
  27362. module.exports = exports['default'];
  27363. /***/ }),
  27364. /* 36 */
  27365. /***/ (function(module, exports, __webpack_require__) {
  27366. "use strict";
  27367. Object.defineProperty(exports, "__esModule", {
  27368. value: true
  27369. });
  27370. 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; }; }(); /*
  27371. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  27372. *
  27373. * @author zheng qian <xqq@xqq.im>
  27374. *
  27375. * Licensed under the Apache License, Version 2.0 (the "License");
  27376. * you may not use this file except in compliance with the License.
  27377. * You may obtain a copy of the License at
  27378. *
  27379. * http://www.apache.org/licenses/LICENSE-2.0
  27380. *
  27381. * Unless required by applicable law or agreed to in writing, software
  27382. * distributed under the License is distributed on an "AS IS" BASIS,
  27383. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  27384. * See the License for the specific language governing permissions and
  27385. * limitations under the License.
  27386. */
  27387. var _logger = __webpack_require__(0);
  27388. var _logger2 = _interopRequireDefault(_logger);
  27389. var _utf8Conv = __webpack_require__(37);
  27390. var _utf8Conv2 = _interopRequireDefault(_utf8Conv);
  27391. var _exception = __webpack_require__(1);
  27392. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27393. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27394. var le = function () {
  27395. var buf = new ArrayBuffer(2);
  27396. new DataView(buf).setInt16(0, 256, true); // little-endian write
  27397. return new Int16Array(buf)[0] === 256; // platform-spec read, if equal then LE
  27398. }();
  27399. var AMF = function () {
  27400. function AMF() {
  27401. _classCallCheck(this, AMF);
  27402. }
  27403. _createClass(AMF, null, [{
  27404. key: 'parseScriptData',
  27405. value: function parseScriptData(arrayBuffer, dataOffset, dataSize) {
  27406. var data = {};
  27407. try {
  27408. var name = AMF.parseValue(arrayBuffer, dataOffset, dataSize);
  27409. var value = AMF.parseValue(arrayBuffer, dataOffset + name.size, dataSize - name.size);
  27410. data[name.data] = value.data;
  27411. } catch (e) {
  27412. _logger2.default.e('AMF', e.toString());
  27413. }
  27414. return data;
  27415. }
  27416. }, {
  27417. key: 'parseObject',
  27418. value: function parseObject(arrayBuffer, dataOffset, dataSize) {
  27419. if (dataSize < 3) {
  27420. throw new _exception.IllegalStateException('Data not enough when parse ScriptDataObject');
  27421. }
  27422. var name = AMF.parseString(arrayBuffer, dataOffset, dataSize);
  27423. var value = AMF.parseValue(arrayBuffer, dataOffset + name.size, dataSize - name.size);
  27424. var isObjectEnd = value.objectEnd;
  27425. return {
  27426. data: {
  27427. name: name.data,
  27428. value: value.data
  27429. },
  27430. size: name.size + value.size,
  27431. objectEnd: isObjectEnd
  27432. };
  27433. }
  27434. }, {
  27435. key: 'parseVariable',
  27436. value: function parseVariable(arrayBuffer, dataOffset, dataSize) {
  27437. return AMF.parseObject(arrayBuffer, dataOffset, dataSize);
  27438. }
  27439. }, {
  27440. key: 'parseString',
  27441. value: function parseString(arrayBuffer, dataOffset, dataSize) {
  27442. if (dataSize < 2) {
  27443. throw new _exception.IllegalStateException('Data not enough when parse String');
  27444. }
  27445. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  27446. var length = v.getUint16(0, !le);
  27447. var str = void 0;
  27448. if (length > 0) {
  27449. str = (0, _utf8Conv2.default)(new Uint8Array(arrayBuffer, dataOffset + 2, length));
  27450. } else {
  27451. str = '';
  27452. }
  27453. return {
  27454. data: str,
  27455. size: 2 + length
  27456. };
  27457. }
  27458. }, {
  27459. key: 'parseLongString',
  27460. value: function parseLongString(arrayBuffer, dataOffset, dataSize) {
  27461. if (dataSize < 4) {
  27462. throw new _exception.IllegalStateException('Data not enough when parse LongString');
  27463. }
  27464. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  27465. var length = v.getUint32(0, !le);
  27466. var str = void 0;
  27467. if (length > 0) {
  27468. str = (0, _utf8Conv2.default)(new Uint8Array(arrayBuffer, dataOffset + 4, length));
  27469. } else {
  27470. str = '';
  27471. }
  27472. return {
  27473. data: str,
  27474. size: 4 + length
  27475. };
  27476. }
  27477. }, {
  27478. key: 'parseDate',
  27479. value: function parseDate(arrayBuffer, dataOffset, dataSize) {
  27480. if (dataSize < 10) {
  27481. throw new _exception.IllegalStateException('Data size invalid when parse Date');
  27482. }
  27483. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  27484. var timestamp = v.getFloat64(0, !le);
  27485. var localTimeOffset = v.getInt16(8, !le);
  27486. timestamp += localTimeOffset * 60 * 1000; // get UTC time
  27487. return {
  27488. data: new Date(timestamp),
  27489. size: 8 + 2
  27490. };
  27491. }
  27492. }, {
  27493. key: 'parseValue',
  27494. value: function parseValue(arrayBuffer, dataOffset, dataSize) {
  27495. if (dataSize < 1) {
  27496. throw new _exception.IllegalStateException('Data not enough when parse Value');
  27497. }
  27498. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  27499. var offset = 1;
  27500. var type = v.getUint8(0);
  27501. var value = void 0;
  27502. var objectEnd = false;
  27503. try {
  27504. switch (type) {
  27505. case 0:
  27506. // Number(Double) type
  27507. value = v.getFloat64(1, !le);
  27508. offset += 8;
  27509. break;
  27510. case 1:
  27511. {
  27512. // Boolean type
  27513. var b = v.getUint8(1);
  27514. value = b ? true : false;
  27515. offset += 1;
  27516. break;
  27517. }
  27518. case 2:
  27519. {
  27520. // String type
  27521. var amfstr = AMF.parseString(arrayBuffer, dataOffset + 1, dataSize - 1);
  27522. value = amfstr.data;
  27523. offset += amfstr.size;
  27524. break;
  27525. }
  27526. case 3:
  27527. {
  27528. // Object(s) type
  27529. value = {};
  27530. var terminal = 0; // workaround for malformed Objects which has missing ScriptDataObjectEnd
  27531. if ((v.getUint32(dataSize - 4, !le) & 0x00FFFFFF) === 9) {
  27532. terminal = 3;
  27533. }
  27534. var maxLoop = 10000;
  27535. while (offset < dataSize - 4 && maxLoop-- > 0) {
  27536. // 4 === type(UI8) + ScriptDataObjectEnd(UI24)
  27537. var amfobj = AMF.parseObject(arrayBuffer, dataOffset + offset, dataSize - offset - terminal);
  27538. if (amfobj.objectEnd) break;
  27539. value[amfobj.data.name] = amfobj.data.value;
  27540. offset += amfobj.size;
  27541. }
  27542. if (offset <= dataSize - 3) {
  27543. var marker = v.getUint32(offset - 1, !le) & 0x00FFFFFF;
  27544. if (marker === 9) {
  27545. offset += 3;
  27546. }
  27547. }
  27548. break;
  27549. }
  27550. case 8:
  27551. {
  27552. // ECMA array type (Mixed array)
  27553. value = {};
  27554. offset += 4; // ECMAArrayLength(UI32)
  27555. var _terminal = 0; // workaround for malformed MixedArrays which has missing ScriptDataObjectEnd
  27556. if ((v.getUint32(dataSize - 4, !le) & 0x00FFFFFF) === 9) {
  27557. _terminal = 3;
  27558. }
  27559. var _maxLoop = 10000;
  27560. while (offset < dataSize - 8 && _maxLoop-- > 0) {
  27561. // 8 === type(UI8) + ECMAArrayLength(UI32) + ScriptDataVariableEnd(UI24)
  27562. var amfvar = AMF.parseVariable(arrayBuffer, dataOffset + offset, dataSize - offset - _terminal);
  27563. if (amfvar.objectEnd) break;
  27564. value[amfvar.data.name] = amfvar.data.value;
  27565. offset += amfvar.size;
  27566. }
  27567. if (offset <= dataSize - 3) {
  27568. var _marker = v.getUint32(offset - 1, !le) & 0x00FFFFFF;
  27569. if (_marker === 9) {
  27570. offset += 3;
  27571. }
  27572. }
  27573. break;
  27574. }
  27575. case 9:
  27576. // ScriptDataObjectEnd
  27577. value = undefined;
  27578. offset = 1;
  27579. objectEnd = true;
  27580. break;
  27581. case 10:
  27582. {
  27583. // Strict array type
  27584. // ScriptDataValue[n]. NOTE: according to video_file_format_spec_v10_1.pdf
  27585. value = [];
  27586. var strictArrayLength = v.getUint32(1, !le);
  27587. offset += 4;
  27588. for (var i = 0; i < strictArrayLength; i++) {
  27589. var val = AMF.parseValue(arrayBuffer, dataOffset + offset, dataSize - offset);
  27590. value.push(val.data);
  27591. offset += val.size;
  27592. }
  27593. break;
  27594. }
  27595. case 11:
  27596. {
  27597. // Date type
  27598. var date = AMF.parseDate(arrayBuffer, dataOffset + 1, dataSize - 1);
  27599. value = date.data;
  27600. offset += date.size;
  27601. break;
  27602. }
  27603. case 12:
  27604. {
  27605. // Long string type
  27606. var amfLongStr = AMF.parseString(arrayBuffer, dataOffset + 1, dataSize - 1);
  27607. value = amfLongStr.data;
  27608. offset += amfLongStr.size;
  27609. break;
  27610. }
  27611. default:
  27612. // ignore and skip
  27613. offset = dataSize;
  27614. _logger2.default.w('AMF', 'Unsupported AMF value type ' + type);
  27615. }
  27616. } catch (e) {
  27617. _logger2.default.e('AMF', e.toString());
  27618. }
  27619. return {
  27620. data: value,
  27621. size: offset,
  27622. objectEnd: objectEnd
  27623. };
  27624. }
  27625. }]);
  27626. return AMF;
  27627. }();
  27628. exports.default = AMF;
  27629. module.exports = exports['default'];
  27630. /***/ }),
  27631. /* 37 */
  27632. /***/ (function(module, exports, __webpack_require__) {
  27633. "use strict";
  27634. Object.defineProperty(exports, "__esModule", {
  27635. value: true
  27636. });
  27637. /*
  27638. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  27639. *
  27640. * This file is derived from C++ project libWinTF8 (https://github.com/m13253/libWinTF8)
  27641. * @author zheng qian <xqq@xqq.im>
  27642. *
  27643. * Licensed under the Apache License, Version 2.0 (the "License");
  27644. * you may not use this file except in compliance with the License.
  27645. * You may obtain a copy of the License at
  27646. *
  27647. * http://www.apache.org/licenses/LICENSE-2.0
  27648. *
  27649. * Unless required by applicable law or agreed to in writing, software
  27650. * distributed under the License is distributed on an "AS IS" BASIS,
  27651. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  27652. * See the License for the specific language governing permissions and
  27653. * limitations under the License.
  27654. */
  27655. function checkContinuation(uint8array, start, checkLength) {
  27656. var array = uint8array;
  27657. if (start + checkLength < array.length) {
  27658. while (checkLength--) {
  27659. if ((array[++start] & 0xC0) !== 0x80) return false;
  27660. }
  27661. return true;
  27662. } else {
  27663. return false;
  27664. }
  27665. }
  27666. function decodeUTF8(uint8array) {
  27667. var out = [];
  27668. var input = uint8array;
  27669. var i = 0;
  27670. var length = uint8array.length;
  27671. while (i < length) {
  27672. if (input[i] < 0x80) {
  27673. out.push(String.fromCharCode(input[i]));
  27674. ++i;
  27675. continue;
  27676. } else if (input[i] < 0xC0) {
  27677. // fallthrough
  27678. } else if (input[i] < 0xE0) {
  27679. if (checkContinuation(input, i, 1)) {
  27680. var ucs4 = (input[i] & 0x1F) << 6 | input[i + 1] & 0x3F;
  27681. if (ucs4 >= 0x80) {
  27682. out.push(String.fromCharCode(ucs4 & 0xFFFF));
  27683. i += 2;
  27684. continue;
  27685. }
  27686. }
  27687. } else if (input[i] < 0xF0) {
  27688. if (checkContinuation(input, i, 2)) {
  27689. var _ucs = (input[i] & 0xF) << 12 | (input[i + 1] & 0x3F) << 6 | input[i + 2] & 0x3F;
  27690. if (_ucs >= 0x800 && (_ucs & 0xF800) !== 0xD800) {
  27691. out.push(String.fromCharCode(_ucs & 0xFFFF));
  27692. i += 3;
  27693. continue;
  27694. }
  27695. }
  27696. } else if (input[i] < 0xF8) {
  27697. if (checkContinuation(input, i, 3)) {
  27698. var _ucs2 = (input[i] & 0x7) << 18 | (input[i + 1] & 0x3F) << 12 | (input[i + 2] & 0x3F) << 6 | input[i + 3] & 0x3F;
  27699. if (_ucs2 > 0x10000 && _ucs2 < 0x110000) {
  27700. _ucs2 -= 0x10000;
  27701. out.push(String.fromCharCode(_ucs2 >>> 10 | 0xD800));
  27702. out.push(String.fromCharCode(_ucs2 & 0x3FF | 0xDC00));
  27703. i += 4;
  27704. continue;
  27705. }
  27706. }
  27707. }
  27708. out.push(String.fromCharCode(0xFFFD));
  27709. ++i;
  27710. }
  27711. return out.join('');
  27712. }
  27713. exports.default = decodeUTF8;
  27714. module.exports = exports['default'];
  27715. /***/ }),
  27716. /* 38 */
  27717. /***/ (function(module, exports, __webpack_require__) {
  27718. "use strict";
  27719. Object.defineProperty(exports, "__esModule", {
  27720. value: true
  27721. });
  27722. 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; }; }(); /*
  27723. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  27724. *
  27725. * @author zheng qian <xqq@xqq.im>
  27726. *
  27727. * Licensed under the Apache License, Version 2.0 (the "License");
  27728. * you may not use this file except in compliance with the License.
  27729. * You may obtain a copy of the License at
  27730. *
  27731. * http://www.apache.org/licenses/LICENSE-2.0
  27732. *
  27733. * Unless required by applicable law or agreed to in writing, software
  27734. * distributed under the License is distributed on an "AS IS" BASIS,
  27735. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  27736. * See the License for the specific language governing permissions and
  27737. * limitations under the License.
  27738. */
  27739. var _expGolomb = __webpack_require__(39);
  27740. var _expGolomb2 = _interopRequireDefault(_expGolomb);
  27741. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27742. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27743. var SPSParser = function () {
  27744. function SPSParser() {
  27745. _classCallCheck(this, SPSParser);
  27746. }
  27747. _createClass(SPSParser, null, [{
  27748. key: '_ebsp2rbsp',
  27749. value: function _ebsp2rbsp(uint8array) {
  27750. var src = uint8array;
  27751. var src_length = src.byteLength;
  27752. var dst = new Uint8Array(src_length);
  27753. var dst_idx = 0;
  27754. for (var i = 0; i < src_length; i++) {
  27755. if (i >= 2) {
  27756. // Unescape: Skip 0x03 after 00 00
  27757. if (src[i] === 0x03 && src[i - 1] === 0x00 && src[i - 2] === 0x00) {
  27758. continue;
  27759. }
  27760. }
  27761. dst[dst_idx] = src[i];
  27762. dst_idx++;
  27763. }
  27764. return new Uint8Array(dst.buffer, 0, dst_idx);
  27765. }
  27766. }, {
  27767. key: 'parseSPS',
  27768. value: function parseSPS(uint8array) {
  27769. var rbsp = SPSParser._ebsp2rbsp(uint8array);
  27770. var gb = new _expGolomb2.default(rbsp);
  27771. gb.readByte();
  27772. var profile_idc = gb.readByte(); // profile_idc
  27773. gb.readByte(); // constraint_set_flags[5] + reserved_zero[3]
  27774. var level_idc = gb.readByte(); // level_idc
  27775. gb.readUEG(); // seq_parameter_set_id
  27776. var profile_string = SPSParser.getProfileString(profile_idc);
  27777. var level_string = SPSParser.getLevelString(level_idc);
  27778. var chroma_format_idc = 1;
  27779. var chroma_format = 420;
  27780. var chroma_format_table = [0, 420, 422, 444];
  27781. var bit_depth = 8;
  27782. 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) {
  27783. chroma_format_idc = gb.readUEG();
  27784. if (chroma_format_idc === 3) {
  27785. gb.readBits(1); // separate_colour_plane_flag
  27786. }
  27787. if (chroma_format_idc <= 3) {
  27788. chroma_format = chroma_format_table[chroma_format_idc];
  27789. }
  27790. bit_depth = gb.readUEG() + 8; // bit_depth_luma_minus8
  27791. gb.readUEG(); // bit_depth_chroma_minus8
  27792. gb.readBits(1); // qpprime_y_zero_transform_bypass_flag
  27793. if (gb.readBool()) {
  27794. // seq_scaling_matrix_present_flag
  27795. var scaling_list_count = chroma_format_idc !== 3 ? 8 : 12;
  27796. for (var i = 0; i < scaling_list_count; i++) {
  27797. if (gb.readBool()) {
  27798. // seq_scaling_list_present_flag
  27799. if (i < 6) {
  27800. SPSParser._skipScalingList(gb, 16);
  27801. } else {
  27802. SPSParser._skipScalingList(gb, 64);
  27803. }
  27804. }
  27805. }
  27806. }
  27807. }
  27808. gb.readUEG(); // log2_max_frame_num_minus4
  27809. var pic_order_cnt_type = gb.readUEG();
  27810. if (pic_order_cnt_type === 0) {
  27811. gb.readUEG(); // log2_max_pic_order_cnt_lsb_minus_4
  27812. } else if (pic_order_cnt_type === 1) {
  27813. gb.readBits(1); // delta_pic_order_always_zero_flag
  27814. gb.readSEG(); // offset_for_non_ref_pic
  27815. gb.readSEG(); // offset_for_top_to_bottom_field
  27816. var num_ref_frames_in_pic_order_cnt_cycle = gb.readUEG();
  27817. for (var _i = 0; _i < num_ref_frames_in_pic_order_cnt_cycle; _i++) {
  27818. gb.readSEG(); // offset_for_ref_frame
  27819. }
  27820. }
  27821. var ref_frames = gb.readUEG(); // max_num_ref_frames
  27822. gb.readBits(1); // gaps_in_frame_num_value_allowed_flag
  27823. var pic_width_in_mbs_minus1 = gb.readUEG();
  27824. var pic_height_in_map_units_minus1 = gb.readUEG();
  27825. var frame_mbs_only_flag = gb.readBits(1);
  27826. if (frame_mbs_only_flag === 0) {
  27827. gb.readBits(1); // mb_adaptive_frame_field_flag
  27828. }
  27829. gb.readBits(1); // direct_8x8_inference_flag
  27830. var frame_crop_left_offset = 0;
  27831. var frame_crop_right_offset = 0;
  27832. var frame_crop_top_offset = 0;
  27833. var frame_crop_bottom_offset = 0;
  27834. var frame_cropping_flag = gb.readBool();
  27835. if (frame_cropping_flag) {
  27836. frame_crop_left_offset = gb.readUEG();
  27837. frame_crop_right_offset = gb.readUEG();
  27838. frame_crop_top_offset = gb.readUEG();
  27839. frame_crop_bottom_offset = gb.readUEG();
  27840. }
  27841. var sar_width = 1,
  27842. sar_height = 1;
  27843. var fps = 0,
  27844. fps_fixed = true,
  27845. fps_num = 0,
  27846. fps_den = 0;
  27847. var vui_parameters_present_flag = gb.readBool();
  27848. if (vui_parameters_present_flag) {
  27849. if (gb.readBool()) {
  27850. // aspect_ratio_info_present_flag
  27851. var aspect_ratio_idc = gb.readByte();
  27852. var sar_w_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2];
  27853. var sar_h_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
  27854. if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) {
  27855. sar_width = sar_w_table[aspect_ratio_idc - 1];
  27856. sar_height = sar_h_table[aspect_ratio_idc - 1];
  27857. } else if (aspect_ratio_idc === 255) {
  27858. sar_width = gb.readByte() << 8 | gb.readByte();
  27859. sar_height = gb.readByte() << 8 | gb.readByte();
  27860. }
  27861. }
  27862. if (gb.readBool()) {
  27863. // overscan_info_present_flag
  27864. gb.readBool(); // overscan_appropriate_flag
  27865. }
  27866. if (gb.readBool()) {
  27867. // video_signal_type_present_flag
  27868. gb.readBits(4); // video_format & video_full_range_flag
  27869. if (gb.readBool()) {
  27870. // colour_description_present_flag
  27871. gb.readBits(24); // colour_primaries & transfer_characteristics & matrix_coefficients
  27872. }
  27873. }
  27874. if (gb.readBool()) {
  27875. // chroma_loc_info_present_flag
  27876. gb.readUEG(); // chroma_sample_loc_type_top_field
  27877. gb.readUEG(); // chroma_sample_loc_type_bottom_field
  27878. }
  27879. if (gb.readBool()) {
  27880. // timing_info_present_flag
  27881. var num_units_in_tick = gb.readBits(32);
  27882. var time_scale = gb.readBits(32);
  27883. fps_fixed = gb.readBool(); // fixed_frame_rate_flag
  27884. fps_num = time_scale;
  27885. fps_den = num_units_in_tick * 2;
  27886. fps = fps_num / fps_den;
  27887. }
  27888. }
  27889. var sarScale = 1;
  27890. if (sar_width !== 1 || sar_height !== 1) {
  27891. sarScale = sar_width / sar_height;
  27892. }
  27893. var crop_unit_x = 0,
  27894. crop_unit_y = 0;
  27895. if (chroma_format_idc === 0) {
  27896. crop_unit_x = 1;
  27897. crop_unit_y = 2 - frame_mbs_only_flag;
  27898. } else {
  27899. var sub_wc = chroma_format_idc === 3 ? 1 : 2;
  27900. var sub_hc = chroma_format_idc === 1 ? 2 : 1;
  27901. crop_unit_x = sub_wc;
  27902. crop_unit_y = sub_hc * (2 - frame_mbs_only_flag);
  27903. }
  27904. var codec_width = (pic_width_in_mbs_minus1 + 1) * 16;
  27905. var codec_height = (2 - frame_mbs_only_flag) * ((pic_height_in_map_units_minus1 + 1) * 16);
  27906. codec_width -= (frame_crop_left_offset + frame_crop_right_offset) * crop_unit_x;
  27907. codec_height -= (frame_crop_top_offset + frame_crop_bottom_offset) * crop_unit_y;
  27908. var present_width = Math.ceil(codec_width * sarScale);
  27909. gb.destroy();
  27910. gb = null;
  27911. return {
  27912. profile_string: profile_string, // baseline, high, high10, ...
  27913. level_string: level_string, // 3, 3.1, 4, 4.1, 5, 5.1, ...
  27914. bit_depth: bit_depth, // 8bit, 10bit, ...
  27915. ref_frames: ref_frames,
  27916. chroma_format: chroma_format, // 4:2:0, 4:2:2, ...
  27917. chroma_format_string: SPSParser.getChromaFormatString(chroma_format),
  27918. frame_rate: {
  27919. fixed: fps_fixed,
  27920. fps: fps,
  27921. fps_den: fps_den,
  27922. fps_num: fps_num
  27923. },
  27924. par_ratio: {
  27925. width: sar_width,
  27926. height: sar_height
  27927. },
  27928. codec_size: {
  27929. width: codec_width,
  27930. height: codec_height
  27931. },
  27932. present_size: {
  27933. width: present_width,
  27934. height: codec_height
  27935. }
  27936. };
  27937. }
  27938. }, {
  27939. key: '_skipScalingList',
  27940. value: function _skipScalingList(gb, count) {
  27941. var last_scale = 8,
  27942. next_scale = 8;
  27943. var delta_scale = 0;
  27944. for (var i = 0; i < count; i++) {
  27945. if (next_scale !== 0) {
  27946. delta_scale = gb.readSEG();
  27947. next_scale = (last_scale + delta_scale + 256) % 256;
  27948. }
  27949. last_scale = next_scale === 0 ? last_scale : next_scale;
  27950. }
  27951. }
  27952. }, {
  27953. key: 'getProfileString',
  27954. value: function getProfileString(profile_idc) {
  27955. switch (profile_idc) {
  27956. case 66:
  27957. return 'Baseline';
  27958. case 77:
  27959. return 'Main';
  27960. case 88:
  27961. return 'Extended';
  27962. case 100:
  27963. return 'High';
  27964. case 110:
  27965. return 'High10';
  27966. case 122:
  27967. return 'High422';
  27968. case 244:
  27969. return 'High444';
  27970. default:
  27971. return 'Unknown';
  27972. }
  27973. }
  27974. }, {
  27975. key: 'getLevelString',
  27976. value: function getLevelString(level_idc) {
  27977. return (level_idc / 10).toFixed(1);
  27978. }
  27979. }, {
  27980. key: 'getChromaFormatString',
  27981. value: function getChromaFormatString(chroma) {
  27982. switch (chroma) {
  27983. case 420:
  27984. return '4:2:0';
  27985. case 422:
  27986. return '4:2:2';
  27987. case 444:
  27988. return '4:4:4';
  27989. default:
  27990. return 'Unknown';
  27991. }
  27992. }
  27993. }]);
  27994. return SPSParser;
  27995. }();
  27996. exports.default = SPSParser;
  27997. module.exports = exports['default'];
  27998. /***/ }),
  27999. /* 39 */
  28000. /***/ (function(module, exports, __webpack_require__) {
  28001. "use strict";
  28002. Object.defineProperty(exports, "__esModule", {
  28003. value: true
  28004. });
  28005. 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; }; }(); /*
  28006. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  28007. *
  28008. * @author zheng qian <xqq@xqq.im>
  28009. *
  28010. * Licensed under the Apache License, Version 2.0 (the "License");
  28011. * you may not use this file except in compliance with the License.
  28012. * You may obtain a copy of the License at
  28013. *
  28014. * http://www.apache.org/licenses/LICENSE-2.0
  28015. *
  28016. * Unless required by applicable law or agreed to in writing, software
  28017. * distributed under the License is distributed on an "AS IS" BASIS,
  28018. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  28019. * See the License for the specific language governing permissions and
  28020. * limitations under the License.
  28021. */
  28022. var _exception = __webpack_require__(1);
  28023. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  28024. // Exponential-Golomb buffer decoder
  28025. var ExpGolomb = function () {
  28026. function ExpGolomb(uint8array) {
  28027. _classCallCheck(this, ExpGolomb);
  28028. this.TAG = 'ExpGolomb';
  28029. this._buffer = uint8array;
  28030. this._buffer_index = 0;
  28031. this._total_bytes = uint8array.byteLength;
  28032. this._total_bits = uint8array.byteLength * 8;
  28033. this._current_word = 0;
  28034. this._current_word_bits_left = 0;
  28035. }
  28036. _createClass(ExpGolomb, [{
  28037. key: 'destroy',
  28038. value: function destroy() {
  28039. this._buffer = null;
  28040. }
  28041. }, {
  28042. key: '_fillCurrentWord',
  28043. value: function _fillCurrentWord() {
  28044. var buffer_bytes_left = this._total_bytes - this._buffer_index;
  28045. if (buffer_bytes_left <= 0) throw new _exception.IllegalStateException('ExpGolomb: _fillCurrentWord() but no bytes available');
  28046. var bytes_read = Math.min(4, buffer_bytes_left);
  28047. var word = new Uint8Array(4);
  28048. word.set(this._buffer.subarray(this._buffer_index, this._buffer_index + bytes_read));
  28049. this._current_word = new DataView(word.buffer).getUint32(0, false);
  28050. this._buffer_index += bytes_read;
  28051. this._current_word_bits_left = bytes_read * 8;
  28052. }
  28053. }, {
  28054. key: 'readBits',
  28055. value: function readBits(bits) {
  28056. if (bits > 32) throw new _exception.InvalidArgumentException('ExpGolomb: readBits() bits exceeded max 32bits!');
  28057. if (bits <= this._current_word_bits_left) {
  28058. var _result = this._current_word >>> 32 - bits;
  28059. this._current_word <<= bits;
  28060. this._current_word_bits_left -= bits;
  28061. return _result;
  28062. }
  28063. var result = this._current_word_bits_left ? this._current_word : 0;
  28064. result = result >>> 32 - this._current_word_bits_left;
  28065. var bits_need_left = bits - this._current_word_bits_left;
  28066. this._fillCurrentWord();
  28067. var bits_read_next = Math.min(bits_need_left, this._current_word_bits_left);
  28068. var result2 = this._current_word >>> 32 - bits_read_next;
  28069. this._current_word <<= bits_read_next;
  28070. this._current_word_bits_left -= bits_read_next;
  28071. result = result << bits_read_next | result2;
  28072. return result;
  28073. }
  28074. }, {
  28075. key: 'readBool',
  28076. value: function readBool() {
  28077. return this.readBits(1) === 1;
  28078. }
  28079. }, {
  28080. key: 'readByte',
  28081. value: function readByte() {
  28082. return this.readBits(8);
  28083. }
  28084. }, {
  28085. key: '_skipLeadingZero',
  28086. value: function _skipLeadingZero() {
  28087. var zero_count = void 0;
  28088. for (zero_count = 0; zero_count < this._current_word_bits_left; zero_count++) {
  28089. if (0 !== (this._current_word & 0x80000000 >>> zero_count)) {
  28090. this._current_word <<= zero_count;
  28091. this._current_word_bits_left -= zero_count;
  28092. return zero_count;
  28093. }
  28094. }
  28095. this._fillCurrentWord();
  28096. return zero_count + this._skipLeadingZero();
  28097. }
  28098. }, {
  28099. key: 'readUEG',
  28100. value: function readUEG() {
  28101. // unsigned exponential golomb
  28102. var leading_zeros = this._skipLeadingZero();
  28103. return this.readBits(leading_zeros + 1) - 1;
  28104. }
  28105. }, {
  28106. key: 'readSEG',
  28107. value: function readSEG() {
  28108. // signed exponential golomb
  28109. var value = this.readUEG();
  28110. if (value & 0x01) {
  28111. return value + 1 >>> 1;
  28112. } else {
  28113. return -1 * (value >>> 1);
  28114. }
  28115. }
  28116. }]);
  28117. return ExpGolomb;
  28118. }();
  28119. exports.default = ExpGolomb;
  28120. module.exports = exports['default'];
  28121. /***/ }),
  28122. /* 40 */
  28123. /***/ (function(module, exports, __webpack_require__) {
  28124. "use strict";
  28125. Object.defineProperty(exports, "__esModule", {
  28126. value: true
  28127. });
  28128. 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; }; }(); /*
  28129. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  28130. *
  28131. * @author zheng qian <xqq@xqq.im>
  28132. *
  28133. * Licensed under the Apache License, Version 2.0 (the "License");
  28134. * you may not use this file except in compliance with the License.
  28135. * You may obtain a copy of the License at
  28136. *
  28137. * http://www.apache.org/licenses/LICENSE-2.0
  28138. *
  28139. * Unless required by applicable law or agreed to in writing, software
  28140. * distributed under the License is distributed on an "AS IS" BASIS,
  28141. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  28142. * See the License for the specific language governing permissions and
  28143. * limitations under the License.
  28144. */
  28145. var _logger = __webpack_require__(0);
  28146. var _logger2 = _interopRequireDefault(_logger);
  28147. var _mp4Generator = __webpack_require__(41);
  28148. var _mp4Generator2 = _interopRequireDefault(_mp4Generator);
  28149. var _aacSilent = __webpack_require__(42);
  28150. var _aacSilent2 = _interopRequireDefault(_aacSilent);
  28151. var _browser = __webpack_require__(4);
  28152. var _browser2 = _interopRequireDefault(_browser);
  28153. var _mediaSegmentInfo = __webpack_require__(15);
  28154. var _exception = __webpack_require__(1);
  28155. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  28156. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  28157. // Fragmented mp4 remuxer
  28158. var MP4Remuxer = function () {
  28159. function MP4Remuxer(config) {
  28160. _classCallCheck(this, MP4Remuxer);
  28161. this.TAG = 'MP4Remuxer';
  28162. this._config = config;
  28163. this._isLive = config.isLive === true ? true : false;
  28164. this._dtsBase = -1;
  28165. this._dtsBaseInited = false;
  28166. this._audioDtsBase = Infinity;
  28167. this._videoDtsBase = Infinity;
  28168. this._audioNextDts = undefined;
  28169. this._videoNextDts = undefined;
  28170. this._audioStashedLastSample = null;
  28171. this._videoStashedLastSample = null;
  28172. this._audioMeta = null;
  28173. this._videoMeta = null;
  28174. this._audioSegmentInfoList = new _mediaSegmentInfo.MediaSegmentInfoList('audio');
  28175. this._videoSegmentInfoList = new _mediaSegmentInfo.MediaSegmentInfoList('video');
  28176. this._onInitSegment = null;
  28177. this._onMediaSegment = null;
  28178. // Workaround for chrome < 50: Always force first sample as a Random Access Point in media segment
  28179. // see https://bugs.chromium.org/p/chromium/issues/detail?id=229412
  28180. this._forceFirstIDR = _browser2.default.chrome && (_browser2.default.version.major < 50 || _browser2.default.version.major === 50 && _browser2.default.version.build < 2661) ? true : false;
  28181. // Workaround for IE11/Edge: Fill silent aac frame after keyframe-seeking
  28182. // Make audio beginDts equals with video beginDts, in order to fix seek freeze
  28183. this._fillSilentAfterSeek = _browser2.default.msedge || _browser2.default.msie;
  28184. // While only FireFox supports 'audio/mp4, codecs="mp3"', use 'audio/mpeg' for chrome, safari, ...
  28185. this._mp3UseMpegAudio = !_browser2.default.firefox;
  28186. this._fillAudioTimestampGap = this._config.fixAudioTimestampGap;
  28187. }
  28188. _createClass(MP4Remuxer, [{
  28189. key: 'destroy',
  28190. value: function destroy() {
  28191. this._dtsBase = -1;
  28192. this._dtsBaseInited = false;
  28193. this._audioMeta = null;
  28194. this._videoMeta = null;
  28195. this._audioSegmentInfoList.clear();
  28196. this._audioSegmentInfoList = null;
  28197. this._videoSegmentInfoList.clear();
  28198. this._videoSegmentInfoList = null;
  28199. this._onInitSegment = null;
  28200. this._onMediaSegment = null;
  28201. }
  28202. }, {
  28203. key: 'bindDataSource',
  28204. value: function bindDataSource(producer) {
  28205. producer.onDataAvailable = this.remux.bind(this);
  28206. producer.onTrackMetadata = this._onTrackMetadataReceived.bind(this);
  28207. return this;
  28208. }
  28209. /* prototype: function onInitSegment(type: string, initSegment: ArrayBuffer): void
  28210. InitSegment: {
  28211. type: string,
  28212. data: ArrayBuffer,
  28213. codec: string,
  28214. container: string
  28215. }
  28216. */
  28217. }, {
  28218. key: 'insertDiscontinuity',
  28219. value: function insertDiscontinuity() {
  28220. this._audioNextDts = this._videoNextDts = undefined;
  28221. }
  28222. }, {
  28223. key: 'seek',
  28224. value: function seek(originalDts) {
  28225. this._audioStashedLastSample = null;
  28226. this._videoStashedLastSample = null;
  28227. this._videoSegmentInfoList.clear();
  28228. this._audioSegmentInfoList.clear();
  28229. }
  28230. }, {
  28231. key: 'remux',
  28232. value: function remux(audioTrack, videoTrack) {
  28233. if (!this._onMediaSegment) {
  28234. throw new _exception.IllegalStateException('MP4Remuxer: onMediaSegment callback must be specificed!');
  28235. }
  28236. if (!this._dtsBaseInited) {
  28237. this._calculateDtsBase(audioTrack, videoTrack);
  28238. }
  28239. this._remuxVideo(videoTrack);
  28240. this._remuxAudio(audioTrack);
  28241. }
  28242. }, {
  28243. key: '_onTrackMetadataReceived',
  28244. value: function _onTrackMetadataReceived(type, metadata) {
  28245. var metabox = null;
  28246. var container = 'mp4';
  28247. var codec = metadata.codec;
  28248. if (type === 'audio') {
  28249. this._audioMeta = metadata;
  28250. if (metadata.codec === 'mp3' && this._mp3UseMpegAudio) {
  28251. // 'audio/mpeg' for MP3 audio track
  28252. container = 'mpeg';
  28253. codec = '';
  28254. metabox = new Uint8Array();
  28255. } else {
  28256. // 'audio/mp4, codecs="codec"'
  28257. metabox = _mp4Generator2.default.generateInitSegment(metadata);
  28258. }
  28259. } else if (type === 'video') {
  28260. this._videoMeta = metadata;
  28261. metabox = _mp4Generator2.default.generateInitSegment(metadata);
  28262. } else {
  28263. return;
  28264. }
  28265. // dispatch metabox (Initialization Segment)
  28266. if (!this._onInitSegment) {
  28267. throw new _exception.IllegalStateException('MP4Remuxer: onInitSegment callback must be specified!');
  28268. }
  28269. this._onInitSegment(type, {
  28270. type: type,
  28271. data: metabox.buffer,
  28272. codec: codec,
  28273. container: type + '/' + container,
  28274. mediaDuration: metadata.duration // in timescale 1000 (milliseconds)
  28275. });
  28276. }
  28277. }, {
  28278. key: '_calculateDtsBase',
  28279. value: function _calculateDtsBase(audioTrack, videoTrack) {
  28280. if (this._dtsBaseInited) {
  28281. return;
  28282. }
  28283. if (audioTrack.samples && audioTrack.samples.length) {
  28284. this._audioDtsBase = audioTrack.samples[0].dts;
  28285. }
  28286. if (videoTrack.samples && videoTrack.samples.length) {
  28287. this._videoDtsBase = videoTrack.samples[0].dts;
  28288. }
  28289. this._dtsBase = Math.min(this._audioDtsBase, this._videoDtsBase);
  28290. this._dtsBaseInited = true;
  28291. }
  28292. }, {
  28293. key: 'flushStashedSamples',
  28294. value: function flushStashedSamples() {
  28295. var videoSample = this._videoStashedLastSample;
  28296. var audioSample = this._audioStashedLastSample;
  28297. var videoTrack = {
  28298. type: 'video',
  28299. id: 1,
  28300. sequenceNumber: 0,
  28301. samples: [],
  28302. length: 0
  28303. };
  28304. if (videoSample != null) {
  28305. videoTrack.samples.push(videoSample);
  28306. videoTrack.length = videoSample.length;
  28307. }
  28308. var audioTrack = {
  28309. type: 'audio',
  28310. id: 2,
  28311. sequenceNumber: 0,
  28312. samples: [],
  28313. length: 0
  28314. };
  28315. if (audioSample != null) {
  28316. audioTrack.samples.push(audioSample);
  28317. audioTrack.length = audioSample.length;
  28318. }
  28319. this._videoStashedLastSample = null;
  28320. this._audioStashedLastSample = null;
  28321. this._remuxVideo(videoTrack, true);
  28322. this._remuxAudio(audioTrack, true);
  28323. }
  28324. }, {
  28325. key: '_remuxAudio',
  28326. value: function _remuxAudio(audioTrack, force) {
  28327. if (this._audioMeta == null) {
  28328. return;
  28329. }
  28330. var track = audioTrack;
  28331. var samples = track.samples;
  28332. var dtsCorrection = undefined;
  28333. var firstDts = -1,
  28334. lastDts = -1,
  28335. lastPts = -1;
  28336. var refSampleDuration = this._audioMeta.refSampleDuration;
  28337. var mpegRawTrack = this._audioMeta.codec === 'mp3' && this._mp3UseMpegAudio;
  28338. var firstSegmentAfterSeek = this._dtsBaseInited && this._audioNextDts === undefined;
  28339. var insertPrefixSilentFrame = false;
  28340. if (!samples || samples.length === 0) {
  28341. return;
  28342. }
  28343. if (samples.length === 1 && !force) {
  28344. // If [sample count in current batch] === 1 && (force != true)
  28345. // Ignore and keep in demuxer's queue
  28346. return;
  28347. } // else if (force === true) do remux
  28348. var offset = 0;
  28349. var mdatbox = null;
  28350. var mdatBytes = 0;
  28351. // calculate initial mdat size
  28352. if (mpegRawTrack) {
  28353. // for raw mpeg buffer
  28354. offset = 0;
  28355. mdatBytes = track.length;
  28356. } else {
  28357. // for fmp4 mdat box
  28358. offset = 8; // size + type
  28359. mdatBytes = 8 + track.length;
  28360. }
  28361. var lastSample = null;
  28362. // Pop the lastSample and waiting for stash
  28363. if (samples.length > 1) {
  28364. lastSample = samples.pop();
  28365. mdatBytes -= lastSample.length;
  28366. }
  28367. // Insert [stashed lastSample in the previous batch] to the front
  28368. if (this._audioStashedLastSample != null) {
  28369. var sample = this._audioStashedLastSample;
  28370. this._audioStashedLastSample = null;
  28371. samples.unshift(sample);
  28372. mdatBytes += sample.length;
  28373. }
  28374. // Stash the lastSample of current batch, waiting for next batch
  28375. if (lastSample != null) {
  28376. this._audioStashedLastSample = lastSample;
  28377. }
  28378. var firstSampleOriginalDts = samples[0].dts - this._dtsBase;
  28379. // calculate dtsCorrection
  28380. if (this._audioNextDts) {
  28381. dtsCorrection = firstSampleOriginalDts - this._audioNextDts;
  28382. } else {
  28383. // this._audioNextDts == undefined
  28384. if (this._audioSegmentInfoList.isEmpty()) {
  28385. dtsCorrection = 0;
  28386. if (this._fillSilentAfterSeek && !this._videoSegmentInfoList.isEmpty()) {
  28387. if (this._audioMeta.originalCodec !== 'mp3') {
  28388. insertPrefixSilentFrame = true;
  28389. }
  28390. }
  28391. } else {
  28392. var _lastSample = this._audioSegmentInfoList.getLastSampleBefore(firstSampleOriginalDts);
  28393. if (_lastSample != null) {
  28394. var distance = firstSampleOriginalDts - (_lastSample.originalDts + _lastSample.duration);
  28395. if (distance <= 3) {
  28396. distance = 0;
  28397. }
  28398. var expectedDts = _lastSample.dts + _lastSample.duration + distance;
  28399. dtsCorrection = firstSampleOriginalDts - expectedDts;
  28400. } else {
  28401. // lastSample == null, cannot found
  28402. dtsCorrection = 0;
  28403. }
  28404. }
  28405. }
  28406. if (insertPrefixSilentFrame) {
  28407. // align audio segment beginDts to match with current video segment's beginDts
  28408. var firstSampleDts = firstSampleOriginalDts - dtsCorrection;
  28409. var videoSegment = this._videoSegmentInfoList.getLastSegmentBefore(firstSampleOriginalDts);
  28410. if (videoSegment != null && videoSegment.beginDts < firstSampleDts) {
  28411. var silentUnit = _aacSilent2.default.getSilentFrame(this._audioMeta.originalCodec, this._audioMeta.channelCount);
  28412. if (silentUnit) {
  28413. var dts = videoSegment.beginDts;
  28414. var silentFrameDuration = firstSampleDts - videoSegment.beginDts;
  28415. _logger2.default.v(this.TAG, 'InsertPrefixSilentAudio: dts: ' + dts + ', duration: ' + silentFrameDuration);
  28416. samples.unshift({ unit: silentUnit, dts: dts, pts: dts });
  28417. mdatBytes += silentUnit.byteLength;
  28418. } // silentUnit == null: Cannot generate, skip
  28419. } else {
  28420. insertPrefixSilentFrame = false;
  28421. }
  28422. }
  28423. var mp4Samples = [];
  28424. // Correct dts for each sample, and calculate sample duration. Then output to mp4Samples
  28425. for (var i = 0; i < samples.length; i++) {
  28426. var _sample = samples[i];
  28427. var unit = _sample.unit;
  28428. var originalDts = _sample.dts - this._dtsBase;
  28429. var _dts = originalDts;
  28430. var needFillSilentFrames = false;
  28431. var silentFrames = null;
  28432. var sampleDuration = 0;
  28433. if (originalDts < -0.001) {
  28434. continue; //pass the first sample with the invalid dts
  28435. }
  28436. if (this._audioMeta.codec !== 'mp3') {
  28437. // for AAC codec, we need to keep dts increase based on refSampleDuration
  28438. var curRefDts = originalDts;
  28439. var maxAudioFramesDrift = 3;
  28440. if (this._audioNextDts) {
  28441. curRefDts = this._audioNextDts;
  28442. }
  28443. dtsCorrection = originalDts - curRefDts;
  28444. if (dtsCorrection <= -maxAudioFramesDrift * refSampleDuration) {
  28445. // If we're overlapping by more than maxAudioFramesDrift number of frame, drop this sample
  28446. _logger2.default.w(this.TAG, 'Dropping 1 audio frame (originalDts: ' + originalDts + ' ms ,curRefDts: ' + curRefDts + ' ms) due to dtsCorrection: ' + dtsCorrection + ' ms overlap.');
  28447. continue;
  28448. } else if (dtsCorrection >= maxAudioFramesDrift * refSampleDuration && this._fillAudioTimestampGap && !_browser2.default.safari) {
  28449. // Silent frame generation, if large timestamp gap detected && config.fixAudioTimestampGap
  28450. needFillSilentFrames = true;
  28451. // We need to insert silent frames to fill timestamp gap
  28452. var frameCount = Math.floor(dtsCorrection / refSampleDuration);
  28453. _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' + ('originalDts: ' + originalDts + ' ms, curRefDts: ' + curRefDts + ' ms, ') + ('dtsCorrection: ' + Math.round(dtsCorrection) + ' ms, generate: ' + frameCount + ' frames'));
  28454. _dts = Math.floor(curRefDts);
  28455. sampleDuration = Math.floor(curRefDts + refSampleDuration) - _dts;
  28456. var _silentUnit = _aacSilent2.default.getSilentFrame(this._audioMeta.originalCodec, this._audioMeta.channelCount);
  28457. if (_silentUnit == null) {
  28458. _logger2.default.w(this.TAG, 'Unable to generate silent frame for ' + (this._audioMeta.originalCodec + ' with ' + this._audioMeta.channelCount + ' channels, repeat last frame'));
  28459. // Repeat last frame
  28460. _silentUnit = unit;
  28461. }
  28462. silentFrames = [];
  28463. for (var j = 0; j < frameCount; j++) {
  28464. curRefDts = curRefDts + refSampleDuration;
  28465. var intDts = Math.floor(curRefDts); // change to integer
  28466. var intDuration = Math.floor(curRefDts + refSampleDuration) - intDts;
  28467. var frame = {
  28468. dts: intDts,
  28469. pts: intDts,
  28470. cts: 0,
  28471. unit: _silentUnit,
  28472. size: _silentUnit.byteLength,
  28473. duration: intDuration, // wait for next sample
  28474. originalDts: originalDts,
  28475. flags: {
  28476. isLeading: 0,
  28477. dependsOn: 1,
  28478. isDependedOn: 0,
  28479. hasRedundancy: 0
  28480. }
  28481. };
  28482. silentFrames.push(frame);
  28483. mdatBytes += unit.byteLength;
  28484. }
  28485. this._audioNextDts = curRefDts + refSampleDuration;
  28486. } else {
  28487. _dts = Math.floor(curRefDts);
  28488. sampleDuration = Math.floor(curRefDts + refSampleDuration) - _dts;
  28489. this._audioNextDts = curRefDts + refSampleDuration;
  28490. }
  28491. } else {
  28492. // keep the original dts calculate algorithm for mp3
  28493. _dts = originalDts - dtsCorrection;
  28494. if (i !== samples.length - 1) {
  28495. var nextDts = samples[i + 1].dts - this._dtsBase - dtsCorrection;
  28496. sampleDuration = nextDts - _dts;
  28497. } else {
  28498. // the last sample
  28499. if (lastSample != null) {
  28500. // use stashed sample's dts to calculate sample duration
  28501. var _nextDts = lastSample.dts - this._dtsBase - dtsCorrection;
  28502. sampleDuration = _nextDts - _dts;
  28503. } else if (mp4Samples.length >= 1) {
  28504. // use second last sample duration
  28505. sampleDuration = mp4Samples[mp4Samples.length - 1].duration;
  28506. } else {
  28507. // the only one sample, use reference sample duration
  28508. sampleDuration = Math.floor(refSampleDuration);
  28509. }
  28510. }
  28511. this._audioNextDts = _dts + sampleDuration;
  28512. }
  28513. if (firstDts === -1) {
  28514. firstDts = _dts;
  28515. }
  28516. mp4Samples.push({
  28517. dts: _dts,
  28518. pts: _dts,
  28519. cts: 0,
  28520. unit: _sample.unit,
  28521. size: _sample.unit.byteLength,
  28522. duration: sampleDuration,
  28523. originalDts: originalDts,
  28524. flags: {
  28525. isLeading: 0,
  28526. dependsOn: 1,
  28527. isDependedOn: 0,
  28528. hasRedundancy: 0
  28529. }
  28530. });
  28531. if (needFillSilentFrames) {
  28532. // Silent frames should be inserted after wrong-duration frame
  28533. mp4Samples.push.apply(mp4Samples, silentFrames);
  28534. }
  28535. }
  28536. if (mp4Samples.length === 0) {
  28537. //no samples need to remux
  28538. track.samples = [];
  28539. track.length = 0;
  28540. return;
  28541. }
  28542. // allocate mdatbox
  28543. if (mpegRawTrack) {
  28544. // allocate for raw mpeg buffer
  28545. mdatbox = new Uint8Array(mdatBytes);
  28546. } else {
  28547. // allocate for fmp4 mdat box
  28548. mdatbox = new Uint8Array(mdatBytes);
  28549. // size field
  28550. mdatbox[0] = mdatBytes >>> 24 & 0xFF;
  28551. mdatbox[1] = mdatBytes >>> 16 & 0xFF;
  28552. mdatbox[2] = mdatBytes >>> 8 & 0xFF;
  28553. mdatbox[3] = mdatBytes & 0xFF;
  28554. // type field (fourCC)
  28555. mdatbox.set(_mp4Generator2.default.types.mdat, 4);
  28556. }
  28557. // Write samples into mdatbox
  28558. for (var _i = 0; _i < mp4Samples.length; _i++) {
  28559. var _unit = mp4Samples[_i].unit;
  28560. mdatbox.set(_unit, offset);
  28561. offset += _unit.byteLength;
  28562. }
  28563. var latest = mp4Samples[mp4Samples.length - 1];
  28564. lastDts = latest.dts + latest.duration;
  28565. //this._audioNextDts = lastDts;
  28566. // fill media segment info & add to info list
  28567. var info = new _mediaSegmentInfo.MediaSegmentInfo();
  28568. info.beginDts = firstDts;
  28569. info.endDts = lastDts;
  28570. info.beginPts = firstDts;
  28571. info.endPts = lastDts;
  28572. info.originalBeginDts = mp4Samples[0].originalDts;
  28573. info.originalEndDts = latest.originalDts + latest.duration;
  28574. info.firstSample = new _mediaSegmentInfo.SampleInfo(mp4Samples[0].dts, mp4Samples[0].pts, mp4Samples[0].duration, mp4Samples[0].originalDts, false);
  28575. info.lastSample = new _mediaSegmentInfo.SampleInfo(latest.dts, latest.pts, latest.duration, latest.originalDts, false);
  28576. if (!this._isLive) {
  28577. this._audioSegmentInfoList.append(info);
  28578. }
  28579. track.samples = mp4Samples;
  28580. track.sequenceNumber++;
  28581. var moofbox = null;
  28582. if (mpegRawTrack) {
  28583. // Generate empty buffer, because useless for raw mpeg
  28584. moofbox = new Uint8Array();
  28585. } else {
  28586. // Generate moof for fmp4 segment
  28587. moofbox = _mp4Generator2.default.moof(track, firstDts);
  28588. }
  28589. track.samples = [];
  28590. track.length = 0;
  28591. var segment = {
  28592. type: 'audio',
  28593. data: this._mergeBoxes(moofbox, mdatbox).buffer,
  28594. sampleCount: mp4Samples.length,
  28595. info: info
  28596. };
  28597. if (mpegRawTrack && firstSegmentAfterSeek) {
  28598. // For MPEG audio stream in MSE, if seeking occurred, before appending new buffer
  28599. // We need explicitly set timestampOffset to the desired point in timeline for mpeg SourceBuffer.
  28600. segment.timestampOffset = firstDts;
  28601. }
  28602. this._onMediaSegment('audio', segment);
  28603. }
  28604. }, {
  28605. key: '_remuxVideo',
  28606. value: function _remuxVideo(videoTrack, force) {
  28607. if (this._videoMeta == null) {
  28608. return;
  28609. }
  28610. var track = videoTrack;
  28611. var samples = track.samples;
  28612. var dtsCorrection = undefined;
  28613. var firstDts = -1,
  28614. lastDts = -1;
  28615. var firstPts = -1,
  28616. lastPts = -1;
  28617. if (!samples || samples.length === 0) {
  28618. return;
  28619. }
  28620. if (samples.length === 1 && !force) {
  28621. // If [sample count in current batch] === 1 && (force != true)
  28622. // Ignore and keep in demuxer's queue
  28623. return;
  28624. } // else if (force === true) do remux
  28625. var offset = 8;
  28626. var mdatbox = null;
  28627. var mdatBytes = 8 + videoTrack.length;
  28628. var lastSample = null;
  28629. // Pop the lastSample and waiting for stash
  28630. if (samples.length > 1) {
  28631. lastSample = samples.pop();
  28632. mdatBytes -= lastSample.length;
  28633. }
  28634. // Insert [stashed lastSample in the previous batch] to the front
  28635. if (this._videoStashedLastSample != null) {
  28636. var sample = this._videoStashedLastSample;
  28637. this._videoStashedLastSample = null;
  28638. samples.unshift(sample);
  28639. mdatBytes += sample.length;
  28640. }
  28641. // Stash the lastSample of current batch, waiting for next batch
  28642. if (lastSample != null) {
  28643. this._videoStashedLastSample = lastSample;
  28644. }
  28645. var firstSampleOriginalDts = samples[0].dts - this._dtsBase;
  28646. // calculate dtsCorrection
  28647. if (this._videoNextDts) {
  28648. dtsCorrection = firstSampleOriginalDts - this._videoNextDts;
  28649. } else {
  28650. // this._videoNextDts == undefined
  28651. if (this._videoSegmentInfoList.isEmpty()) {
  28652. dtsCorrection = 0;
  28653. } else {
  28654. var _lastSample2 = this._videoSegmentInfoList.getLastSampleBefore(firstSampleOriginalDts);
  28655. if (_lastSample2 != null) {
  28656. var distance = firstSampleOriginalDts - (_lastSample2.originalDts + _lastSample2.duration);
  28657. if (distance <= 3) {
  28658. distance = 0;
  28659. }
  28660. var expectedDts = _lastSample2.dts + _lastSample2.duration + distance;
  28661. dtsCorrection = firstSampleOriginalDts - expectedDts;
  28662. } else {
  28663. // lastSample == null, cannot found
  28664. dtsCorrection = 0;
  28665. }
  28666. }
  28667. }
  28668. var info = new _mediaSegmentInfo.MediaSegmentInfo();
  28669. var mp4Samples = [];
  28670. // Correct dts for each sample, and calculate sample duration. Then output to mp4Samples
  28671. for (var i = 0; i < samples.length; i++) {
  28672. var _sample2 = samples[i];
  28673. var originalDts = _sample2.dts - this._dtsBase;
  28674. var isKeyframe = _sample2.isKeyframe;
  28675. var dts = originalDts - dtsCorrection;
  28676. var cts = _sample2.cts;
  28677. var pts = dts + cts;
  28678. if (firstDts === -1) {
  28679. firstDts = dts;
  28680. firstPts = pts;
  28681. }
  28682. var sampleDuration = 0;
  28683. if (i !== samples.length - 1) {
  28684. var nextDts = samples[i + 1].dts - this._dtsBase - dtsCorrection;
  28685. sampleDuration = nextDts - dts;
  28686. } else {
  28687. // the last sample
  28688. if (lastSample != null) {
  28689. // use stashed sample's dts to calculate sample duration
  28690. var _nextDts2 = lastSample.dts - this._dtsBase - dtsCorrection;
  28691. sampleDuration = _nextDts2 - dts;
  28692. } else if (mp4Samples.length >= 1) {
  28693. // use second last sample duration
  28694. sampleDuration = mp4Samples[mp4Samples.length - 1].duration;
  28695. } else {
  28696. // the only one sample, use reference sample duration
  28697. sampleDuration = Math.floor(this._videoMeta.refSampleDuration);
  28698. }
  28699. }
  28700. if (isKeyframe) {
  28701. var syncPoint = new _mediaSegmentInfo.SampleInfo(dts, pts, sampleDuration, _sample2.dts, true);
  28702. syncPoint.fileposition = _sample2.fileposition;
  28703. info.appendSyncPoint(syncPoint);
  28704. }
  28705. mp4Samples.push({
  28706. dts: dts,
  28707. pts: pts,
  28708. cts: cts,
  28709. units: _sample2.units,
  28710. size: _sample2.length,
  28711. isKeyframe: isKeyframe,
  28712. duration: sampleDuration,
  28713. originalDts: originalDts,
  28714. flags: {
  28715. isLeading: 0,
  28716. dependsOn: isKeyframe ? 2 : 1,
  28717. isDependedOn: isKeyframe ? 1 : 0,
  28718. hasRedundancy: 0,
  28719. isNonSync: isKeyframe ? 0 : 1
  28720. }
  28721. });
  28722. }
  28723. // allocate mdatbox
  28724. mdatbox = new Uint8Array(mdatBytes);
  28725. mdatbox[0] = mdatBytes >>> 24 & 0xFF;
  28726. mdatbox[1] = mdatBytes >>> 16 & 0xFF;
  28727. mdatbox[2] = mdatBytes >>> 8 & 0xFF;
  28728. mdatbox[3] = mdatBytes & 0xFF;
  28729. mdatbox.set(_mp4Generator2.default.types.mdat, 4);
  28730. // Write samples into mdatbox
  28731. for (var _i2 = 0; _i2 < mp4Samples.length; _i2++) {
  28732. var units = mp4Samples[_i2].units;
  28733. while (units.length) {
  28734. var unit = units.shift();
  28735. var data = unit.data;
  28736. mdatbox.set(data, offset);
  28737. offset += data.byteLength;
  28738. }
  28739. }
  28740. var latest = mp4Samples[mp4Samples.length - 1];
  28741. lastDts = latest.dts + latest.duration;
  28742. lastPts = latest.pts + latest.duration;
  28743. this._videoNextDts = lastDts;
  28744. // fill media segment info & add to info list
  28745. info.beginDts = firstDts;
  28746. info.endDts = lastDts;
  28747. info.beginPts = firstPts;
  28748. info.endPts = lastPts;
  28749. info.originalBeginDts = mp4Samples[0].originalDts;
  28750. info.originalEndDts = latest.originalDts + latest.duration;
  28751. info.firstSample = new _mediaSegmentInfo.SampleInfo(mp4Samples[0].dts, mp4Samples[0].pts, mp4Samples[0].duration, mp4Samples[0].originalDts, mp4Samples[0].isKeyframe);
  28752. info.lastSample = new _mediaSegmentInfo.SampleInfo(latest.dts, latest.pts, latest.duration, latest.originalDts, latest.isKeyframe);
  28753. if (!this._isLive) {
  28754. this._videoSegmentInfoList.append(info);
  28755. }
  28756. track.samples = mp4Samples;
  28757. track.sequenceNumber++;
  28758. // workaround for chrome < 50: force first sample as a random access point
  28759. // see https://bugs.chromium.org/p/chromium/issues/detail?id=229412
  28760. if (this._forceFirstIDR) {
  28761. var flags = mp4Samples[0].flags;
  28762. flags.dependsOn = 2;
  28763. flags.isNonSync = 0;
  28764. }
  28765. var moofbox = _mp4Generator2.default.moof(track, firstDts);
  28766. track.samples = [];
  28767. track.length = 0;
  28768. this._onMediaSegment('video', {
  28769. type: 'video',
  28770. data: this._mergeBoxes(moofbox, mdatbox).buffer,
  28771. sampleCount: mp4Samples.length,
  28772. info: info
  28773. });
  28774. }
  28775. }, {
  28776. key: '_mergeBoxes',
  28777. value: function _mergeBoxes(moof, mdat) {
  28778. var result = new Uint8Array(moof.byteLength + mdat.byteLength);
  28779. result.set(moof, 0);
  28780. result.set(mdat, moof.byteLength);
  28781. return result;
  28782. }
  28783. }, {
  28784. key: 'onInitSegment',
  28785. get: function get() {
  28786. return this._onInitSegment;
  28787. },
  28788. set: function set(callback) {
  28789. this._onInitSegment = callback;
  28790. }
  28791. /* prototype: function onMediaSegment(type: string, mediaSegment: MediaSegment): void
  28792. MediaSegment: {
  28793. type: string,
  28794. data: ArrayBuffer,
  28795. sampleCount: int32
  28796. info: MediaSegmentInfo
  28797. }
  28798. */
  28799. }, {
  28800. key: 'onMediaSegment',
  28801. get: function get() {
  28802. return this._onMediaSegment;
  28803. },
  28804. set: function set(callback) {
  28805. this._onMediaSegment = callback;
  28806. }
  28807. }]);
  28808. return MP4Remuxer;
  28809. }();
  28810. exports.default = MP4Remuxer;
  28811. module.exports = exports['default'];
  28812. /***/ }),
  28813. /* 41 */
  28814. /***/ (function(module, exports, __webpack_require__) {
  28815. "use strict";
  28816. Object.defineProperty(exports, "__esModule", {
  28817. value: true
  28818. });
  28819. 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; }; }();
  28820. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  28821. /*
  28822. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  28823. *
  28824. * This file is derived from dailymotion's hls.js library (hls.js/src/remux/mp4-generator.js)
  28825. * @author zheng qian <xqq@xqq.im>
  28826. *
  28827. * Licensed under the Apache License, Version 2.0 (the "License");
  28828. * you may not use this file except in compliance with the License.
  28829. * You may obtain a copy of the License at
  28830. *
  28831. * http://www.apache.org/licenses/LICENSE-2.0
  28832. *
  28833. * Unless required by applicable law or agreed to in writing, software
  28834. * distributed under the License is distributed on an "AS IS" BASIS,
  28835. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  28836. * See the License for the specific language governing permissions and
  28837. * limitations under the License.
  28838. */
  28839. // MP4 boxes generator for ISO BMFF (ISO Base Media File Format, defined in ISO/IEC 14496-12)
  28840. var MP4 = function () {
  28841. function MP4() {
  28842. _classCallCheck(this, MP4);
  28843. }
  28844. _createClass(MP4, null, [{
  28845. key: 'init',
  28846. value: function init() {
  28847. MP4.types = {
  28848. avc1: [],
  28849. avcC: [],
  28850. btrt: [],
  28851. dinf: [],
  28852. dref: [],
  28853. esds: [],
  28854. ftyp: [],
  28855. hdlr: [],
  28856. mdat: [],
  28857. mdhd: [],
  28858. mdia: [],
  28859. mfhd: [],
  28860. minf: [],
  28861. moof: [],
  28862. moov: [],
  28863. mp4a: [],
  28864. mvex: [],
  28865. mvhd: [],
  28866. sdtp: [],
  28867. stbl: [],
  28868. stco: [],
  28869. stsc: [],
  28870. stsd: [],
  28871. stsz: [],
  28872. stts: [],
  28873. tfdt: [],
  28874. tfhd: [],
  28875. traf: [],
  28876. trak: [],
  28877. trun: [],
  28878. trex: [],
  28879. tkhd: [],
  28880. vmhd: [],
  28881. smhd: [],
  28882. '.mp3': []
  28883. };
  28884. for (var name in MP4.types) {
  28885. if (MP4.types.hasOwnProperty(name)) {
  28886. MP4.types[name] = [name.charCodeAt(0), name.charCodeAt(1), name.charCodeAt(2), name.charCodeAt(3)];
  28887. }
  28888. }
  28889. var constants = MP4.constants = {};
  28890. constants.FTYP = new Uint8Array([0x69, 0x73, 0x6F, 0x6D, // major_brand: isom
  28891. 0x0, 0x0, 0x0, 0x1, // minor_version: 0x01
  28892. 0x69, 0x73, 0x6F, 0x6D, // isom
  28893. 0x61, 0x76, 0x63, 0x31 // avc1
  28894. ]);
  28895. constants.STSD_PREFIX = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  28896. 0x00, 0x00, 0x00, 0x01 // entry_count
  28897. ]);
  28898. constants.STTS = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  28899. 0x00, 0x00, 0x00, 0x00 // entry_count
  28900. ]);
  28901. constants.STSC = constants.STCO = constants.STTS;
  28902. constants.STSZ = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  28903. 0x00, 0x00, 0x00, 0x00, // sample_size
  28904. 0x00, 0x00, 0x00, 0x00 // sample_count
  28905. ]);
  28906. constants.HDLR_VIDEO = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  28907. 0x00, 0x00, 0x00, 0x00, // pre_defined
  28908. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  28909. 0x00, 0x00, 0x00, 0x00, // reserved: 3 * 4 bytes
  28910. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x69, 0x64, 0x65, 0x6F, 0x48, 0x61, 0x6E, 0x64, 0x6C, 0x65, 0x72, 0x00 // name: VideoHandler
  28911. ]);
  28912. constants.HDLR_AUDIO = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  28913. 0x00, 0x00, 0x00, 0x00, // pre_defined
  28914. 0x73, 0x6F, 0x75, 0x6E, // handler_type: 'soun'
  28915. 0x00, 0x00, 0x00, 0x00, // reserved: 3 * 4 bytes
  28916. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x6F, 0x75, 0x6E, 0x64, 0x48, 0x61, 0x6E, 0x64, 0x6C, 0x65, 0x72, 0x00 // name: SoundHandler
  28917. ]);
  28918. constants.DREF = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  28919. 0x00, 0x00, 0x00, 0x01, // entry_count
  28920. 0x00, 0x00, 0x00, 0x0C, // entry_size
  28921. 0x75, 0x72, 0x6C, 0x20, // type 'url '
  28922. 0x00, 0x00, 0x00, 0x01 // version(0) + flags
  28923. ]);
  28924. // Sound media header
  28925. constants.SMHD = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  28926. 0x00, 0x00, 0x00, 0x00 // balance(2) + reserved(2)
  28927. ]);
  28928. // video media header
  28929. constants.VMHD = new Uint8Array([0x00, 0x00, 0x00, 0x01, // version(0) + flags
  28930. 0x00, 0x00, // graphicsmode: 2 bytes
  28931. 0x00, 0x00, 0x00, 0x00, // opcolor: 3 * 2 bytes
  28932. 0x00, 0x00]);
  28933. }
  28934. // Generate a box
  28935. }, {
  28936. key: 'box',
  28937. value: function box(type) {
  28938. var size = 8;
  28939. var result = null;
  28940. var datas = Array.prototype.slice.call(arguments, 1);
  28941. var arrayCount = datas.length;
  28942. for (var i = 0; i < arrayCount; i++) {
  28943. size += datas[i].byteLength;
  28944. }
  28945. result = new Uint8Array(size);
  28946. result[0] = size >>> 24 & 0xFF; // size
  28947. result[1] = size >>> 16 & 0xFF;
  28948. result[2] = size >>> 8 & 0xFF;
  28949. result[3] = size & 0xFF;
  28950. result.set(type, 4); // type
  28951. var offset = 8;
  28952. for (var _i = 0; _i < arrayCount; _i++) {
  28953. // data body
  28954. result.set(datas[_i], offset);
  28955. offset += datas[_i].byteLength;
  28956. }
  28957. return result;
  28958. }
  28959. // emit ftyp & moov
  28960. }, {
  28961. key: 'generateInitSegment',
  28962. value: function generateInitSegment(meta) {
  28963. var ftyp = MP4.box(MP4.types.ftyp, MP4.constants.FTYP);
  28964. var moov = MP4.moov(meta);
  28965. var result = new Uint8Array(ftyp.byteLength + moov.byteLength);
  28966. result.set(ftyp, 0);
  28967. result.set(moov, ftyp.byteLength);
  28968. return result;
  28969. }
  28970. // Movie metadata box
  28971. }, {
  28972. key: 'moov',
  28973. value: function moov(meta) {
  28974. var mvhd = MP4.mvhd(meta.timescale, meta.duration);
  28975. var trak = MP4.trak(meta);
  28976. var mvex = MP4.mvex(meta);
  28977. return MP4.box(MP4.types.moov, mvhd, trak, mvex);
  28978. }
  28979. // Movie header box
  28980. }, {
  28981. key: 'mvhd',
  28982. value: function mvhd(timescale, duration) {
  28983. return MP4.box(MP4.types.mvhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  28984. 0x00, 0x00, 0x00, 0x00, // creation_time
  28985. 0x00, 0x00, 0x00, 0x00, // modification_time
  28986. timescale >>> 24 & 0xFF, // timescale: 4 bytes
  28987. timescale >>> 16 & 0xFF, timescale >>> 8 & 0xFF, timescale & 0xFF, duration >>> 24 & 0xFF, // duration: 4 bytes
  28988. duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x00, 0x01, 0x00, 0x00, // Preferred rate: 1.0
  28989. 0x01, 0x00, 0x00, 0x00, // PreferredVolume(1.0, 2bytes) + reserved(2bytes)
  28990. 0x00, 0x00, 0x00, 0x00, // reserved: 4 + 4 bytes
  28991. 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, // ----begin composition matrix----
  28992. 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----
  28993. 0x00, 0x00, 0x00, 0x00, // ----begin pre_defined 6 * 4 bytes----
  28994. 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----
  28995. 0xFF, 0xFF, 0xFF, 0xFF // next_track_ID
  28996. ]));
  28997. }
  28998. // Track box
  28999. }, {
  29000. key: 'trak',
  29001. value: function trak(meta) {
  29002. return MP4.box(MP4.types.trak, MP4.tkhd(meta), MP4.mdia(meta));
  29003. }
  29004. // Track header box
  29005. }, {
  29006. key: 'tkhd',
  29007. value: function tkhd(meta) {
  29008. var trackId = meta.id,
  29009. duration = meta.duration;
  29010. var width = meta.presentWidth,
  29011. height = meta.presentHeight;
  29012. return MP4.box(MP4.types.tkhd, new Uint8Array([0x00, 0x00, 0x00, 0x07, // version(0) + flags
  29013. 0x00, 0x00, 0x00, 0x00, // creation_time
  29014. 0x00, 0x00, 0x00, 0x00, // modification_time
  29015. trackId >>> 24 & 0xFF, // track_ID: 4 bytes
  29016. trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF, 0x00, 0x00, 0x00, 0x00, // reserved: 4 bytes
  29017. duration >>> 24 & 0xFF, // duration: 4 bytes
  29018. duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes
  29019. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // layer(2bytes) + alternate_group(2bytes)
  29020. 0x00, 0x00, 0x00, 0x00, // volume(2bytes) + reserved(2bytes)
  29021. 0x00, 0x01, 0x00, 0x00, // ----begin composition matrix----
  29022. 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----
  29023. width >>> 8 & 0xFF, // width and height
  29024. width & 0xFF, 0x00, 0x00, height >>> 8 & 0xFF, height & 0xFF, 0x00, 0x00]));
  29025. }
  29026. // Media Box
  29027. }, {
  29028. key: 'mdia',
  29029. value: function mdia(meta) {
  29030. return MP4.box(MP4.types.mdia, MP4.mdhd(meta), MP4.hdlr(meta), MP4.minf(meta));
  29031. }
  29032. // Media header box
  29033. }, {
  29034. key: 'mdhd',
  29035. value: function mdhd(meta) {
  29036. var timescale = meta.timescale;
  29037. var duration = meta.duration;
  29038. return MP4.box(MP4.types.mdhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  29039. 0x00, 0x00, 0x00, 0x00, // creation_time
  29040. 0x00, 0x00, 0x00, 0x00, // modification_time
  29041. timescale >>> 24 & 0xFF, // timescale: 4 bytes
  29042. timescale >>> 16 & 0xFF, timescale >>> 8 & 0xFF, timescale & 0xFF, duration >>> 24 & 0xFF, // duration: 4 bytes
  29043. duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x55, 0xC4, // language: und (undetermined)
  29044. 0x00, 0x00 // pre_defined = 0
  29045. ]));
  29046. }
  29047. // Media handler reference box
  29048. }, {
  29049. key: 'hdlr',
  29050. value: function hdlr(meta) {
  29051. var data = null;
  29052. if (meta.type === 'audio') {
  29053. data = MP4.constants.HDLR_AUDIO;
  29054. } else {
  29055. data = MP4.constants.HDLR_VIDEO;
  29056. }
  29057. return MP4.box(MP4.types.hdlr, data);
  29058. }
  29059. // Media infomation box
  29060. }, {
  29061. key: 'minf',
  29062. value: function minf(meta) {
  29063. var xmhd = null;
  29064. if (meta.type === 'audio') {
  29065. xmhd = MP4.box(MP4.types.smhd, MP4.constants.SMHD);
  29066. } else {
  29067. xmhd = MP4.box(MP4.types.vmhd, MP4.constants.VMHD);
  29068. }
  29069. return MP4.box(MP4.types.minf, xmhd, MP4.dinf(), MP4.stbl(meta));
  29070. }
  29071. // Data infomation box
  29072. }, {
  29073. key: 'dinf',
  29074. value: function dinf() {
  29075. var result = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, MP4.constants.DREF));
  29076. return result;
  29077. }
  29078. // Sample table box
  29079. }, {
  29080. key: 'stbl',
  29081. value: function stbl(meta) {
  29082. var result = MP4.box(MP4.types.stbl, // type: stbl
  29083. MP4.stsd(meta), // Sample Description Table
  29084. MP4.box(MP4.types.stts, MP4.constants.STTS), // Time-To-Sample
  29085. MP4.box(MP4.types.stsc, MP4.constants.STSC), // Sample-To-Chunk
  29086. MP4.box(MP4.types.stsz, MP4.constants.STSZ), // Sample size
  29087. MP4.box(MP4.types.stco, MP4.constants.STCO) // Chunk offset
  29088. );
  29089. return result;
  29090. }
  29091. // Sample description box
  29092. }, {
  29093. key: 'stsd',
  29094. value: function stsd(meta) {
  29095. if (meta.type === 'audio') {
  29096. if (meta.codec === 'mp3') {
  29097. return MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.mp3(meta));
  29098. }
  29099. // else: aac -> mp4a
  29100. return MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.mp4a(meta));
  29101. } else {
  29102. return MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.avc1(meta));
  29103. }
  29104. }
  29105. }, {
  29106. key: 'mp3',
  29107. value: function mp3(meta) {
  29108. var channelCount = meta.channelCount;
  29109. var sampleRate = meta.audioSampleRate;
  29110. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // reserved(4)
  29111. 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2)
  29112. 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes
  29113. 0x00, 0x00, 0x00, 0x00, 0x00, channelCount, // channelCount(2)
  29114. 0x00, 0x10, // sampleSize(2)
  29115. 0x00, 0x00, 0x00, 0x00, // reserved(4)
  29116. sampleRate >>> 8 & 0xFF, // Audio sample rate
  29117. sampleRate & 0xFF, 0x00, 0x00]);
  29118. return MP4.box(MP4.types['.mp3'], data);
  29119. }
  29120. }, {
  29121. key: 'mp4a',
  29122. value: function mp4a(meta) {
  29123. var channelCount = meta.channelCount;
  29124. var sampleRate = meta.audioSampleRate;
  29125. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // reserved(4)
  29126. 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2)
  29127. 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes
  29128. 0x00, 0x00, 0x00, 0x00, 0x00, channelCount, // channelCount(2)
  29129. 0x00, 0x10, // sampleSize(2)
  29130. 0x00, 0x00, 0x00, 0x00, // reserved(4)
  29131. sampleRate >>> 8 & 0xFF, // Audio sample rate
  29132. sampleRate & 0xFF, 0x00, 0x00]);
  29133. return MP4.box(MP4.types.mp4a, data, MP4.esds(meta));
  29134. }
  29135. }, {
  29136. key: 'esds',
  29137. value: function esds(meta) {
  29138. var config = meta.config || [];
  29139. var configSize = config.length;
  29140. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version 0 + flags
  29141. 0x03, // descriptor_type
  29142. 0x17 + configSize, // length3
  29143. 0x00, 0x01, // es_id
  29144. 0x00, // stream_priority
  29145. 0x04, // descriptor_type
  29146. 0x0F + configSize, // length
  29147. 0x40, // codec: mpeg4_audio
  29148. 0x15, // stream_type: Audio
  29149. 0x00, 0x00, 0x00, // buffer_size
  29150. 0x00, 0x00, 0x00, 0x00, // maxBitrate
  29151. 0x00, 0x00, 0x00, 0x00, // avgBitrate
  29152. 0x05 // descriptor_type
  29153. ].concat([configSize]).concat(config).concat([0x06, 0x01, 0x02 // GASpecificConfig
  29154. ]));
  29155. return MP4.box(MP4.types.esds, data);
  29156. }
  29157. }, {
  29158. key: 'avc1',
  29159. value: function avc1(meta) {
  29160. var avcc = meta.avcc;
  29161. var width = meta.codecWidth,
  29162. height = meta.codecHeight;
  29163. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // reserved(4)
  29164. 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2)
  29165. 0x00, 0x00, 0x00, 0x00, // pre_defined(2) + reserved(2)
  29166. 0x00, 0x00, 0x00, 0x00, // pre_defined: 3 * 4 bytes
  29167. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, width >>> 8 & 0xFF, // width: 2 bytes
  29168. width & 0xFF, height >>> 8 & 0xFF, // height: 2 bytes
  29169. height & 0xFF, 0x00, 0x48, 0x00, 0x00, // horizresolution: 4 bytes
  29170. 0x00, 0x48, 0x00, 0x00, // vertresolution: 4 bytes
  29171. 0x00, 0x00, 0x00, 0x00, // reserved: 4 bytes
  29172. 0x00, 0x01, // frame_count
  29173. 0x0A, // strlen
  29174. 0x78, 0x71, 0x71, 0x2F, // compressorname: 32 bytes
  29175. 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
  29176. 0xFF, 0xFF // pre_defined = -1
  29177. ]);
  29178. return MP4.box(MP4.types.avc1, data, MP4.box(MP4.types.avcC, avcc));
  29179. }
  29180. // Movie Extends box
  29181. }, {
  29182. key: 'mvex',
  29183. value: function mvex(meta) {
  29184. return MP4.box(MP4.types.mvex, MP4.trex(meta));
  29185. }
  29186. // Track Extends box
  29187. }, {
  29188. key: 'trex',
  29189. value: function trex(meta) {
  29190. var trackId = meta.id;
  29191. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  29192. trackId >>> 24 & 0xFF, // track_ID
  29193. trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF, 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  29194. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  29195. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  29196. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  29197. ]);
  29198. return MP4.box(MP4.types.trex, data);
  29199. }
  29200. // Movie fragment box
  29201. }, {
  29202. key: 'moof',
  29203. value: function moof(track, baseMediaDecodeTime) {
  29204. return MP4.box(MP4.types.moof, MP4.mfhd(track.sequenceNumber), MP4.traf(track, baseMediaDecodeTime));
  29205. }
  29206. }, {
  29207. key: 'mfhd',
  29208. value: function mfhd(sequenceNumber) {
  29209. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, sequenceNumber >>> 24 & 0xFF, // sequence_number: int32
  29210. sequenceNumber >>> 16 & 0xFF, sequenceNumber >>> 8 & 0xFF, sequenceNumber & 0xFF]);
  29211. return MP4.box(MP4.types.mfhd, data);
  29212. }
  29213. // Track fragment box
  29214. }, {
  29215. key: 'traf',
  29216. value: function traf(track, baseMediaDecodeTime) {
  29217. var trackId = track.id;
  29218. // Track fragment header box
  29219. var tfhd = MP4.box(MP4.types.tfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) & flags
  29220. trackId >>> 24 & 0xFF, // track_ID
  29221. trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF]));
  29222. // Track Fragment Decode Time
  29223. var tfdt = MP4.box(MP4.types.tfdt, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) & flags
  29224. baseMediaDecodeTime >>> 24 & 0xFF, // baseMediaDecodeTime: int32
  29225. baseMediaDecodeTime >>> 16 & 0xFF, baseMediaDecodeTime >>> 8 & 0xFF, baseMediaDecodeTime & 0xFF]));
  29226. var sdtp = MP4.sdtp(track);
  29227. var trun = MP4.trun(track, sdtp.byteLength + 16 + 16 + 8 + 16 + 8 + 8);
  29228. if (trackId === 1) {
  29229. // console.log(trun)
  29230. }
  29231. return MP4.box(MP4.types.traf, tfhd, tfdt, trun, sdtp);
  29232. }
  29233. // Sample Dependency Type box
  29234. }, {
  29235. key: 'sdtp',
  29236. value: function sdtp(track) {
  29237. var samples = track.samples || [];
  29238. var sampleCount = samples.length;
  29239. var data = new Uint8Array(4 + sampleCount);
  29240. // 0~4 bytes: version(0) & flags
  29241. for (var i = 0; i < sampleCount; i++) {
  29242. var flags = samples[i].flags;
  29243. data[i + 4] = flags.isLeading << 6 | // is_leading: 2 (bit)
  29244. flags.dependsOn << 4 | // sample_depends_on
  29245. flags.isDependedOn << 2 | // sample_is_depended_on
  29246. flags.hasRedundancy; // sample_has_redundancy
  29247. }
  29248. return MP4.box(MP4.types.sdtp, data);
  29249. }
  29250. // Track fragment run box
  29251. }, {
  29252. key: 'trun',
  29253. value: function trun(track, offset) {
  29254. var samples = track.samples || [];
  29255. var sampleCount = samples.length;
  29256. var dataSize = 12 + 16 * sampleCount;
  29257. var data = new Uint8Array(dataSize);
  29258. offset += 8 + dataSize;
  29259. data.set([0x00, 0x00, 0x0F, 0x01, // version(0) & flags
  29260. sampleCount >>> 24 & 0xFF, // sample_count
  29261. sampleCount >>> 16 & 0xFF, sampleCount >>> 8 & 0xFF, sampleCount & 0xFF, offset >>> 24 & 0xFF, // data_offset
  29262. offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF], 0);
  29263. for (var i = 0; i < sampleCount; i++) {
  29264. // console.log(samples[i].duration)
  29265. var duration = samples[i].duration;
  29266. var size = samples[i].size;
  29267. var flags = samples[i].flags;
  29268. var cts = samples[i].cts;
  29269. data.set([duration >>> 24 & 0xFF, // sample_duration
  29270. duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, size >>> 24 & 0xFF, // sample_size
  29271. size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, flags.isLeading << 2 | flags.dependsOn, // sample_flags
  29272. flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.isNonSync, 0x00, 0x00, // sample_degradation_priority
  29273. cts >>> 24 & 0xFF, // sample_composition_time_offset
  29274. cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF], 12 + 16 * i);
  29275. }
  29276. return MP4.box(MP4.types.trun, data);
  29277. }
  29278. }, {
  29279. key: 'mdat',
  29280. value: function mdat(data) {
  29281. return MP4.box(MP4.types.mdat, data);
  29282. }
  29283. }]);
  29284. return MP4;
  29285. }();
  29286. MP4.init();
  29287. exports.default = MP4;
  29288. module.exports = exports['default'];
  29289. /***/ }),
  29290. /* 42 */
  29291. /***/ (function(module, exports, __webpack_require__) {
  29292. "use strict";
  29293. Object.defineProperty(exports, "__esModule", {
  29294. value: true
  29295. });
  29296. 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; }; }();
  29297. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  29298. /*
  29299. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  29300. *
  29301. * This file is modified from dailymotion's hls.js library (hls.js/src/helper/aac.js)
  29302. * @author zheng qian <xqq@xqq.im>
  29303. *
  29304. * Licensed under the Apache License, Version 2.0 (the "License");
  29305. * you may not use this file except in compliance with the License.
  29306. * You may obtain a copy of the License at
  29307. *
  29308. * http://www.apache.org/licenses/LICENSE-2.0
  29309. *
  29310. * Unless required by applicable law or agreed to in writing, software
  29311. * distributed under the License is distributed on an "AS IS" BASIS,
  29312. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  29313. * See the License for the specific language governing permissions and
  29314. * limitations under the License.
  29315. */
  29316. var AAC = function () {
  29317. function AAC() {
  29318. _classCallCheck(this, AAC);
  29319. }
  29320. _createClass(AAC, null, [{
  29321. key: 'getSilentFrame',
  29322. value: function getSilentFrame(codec, channelCount) {
  29323. if (codec === 'mp4a.40.2') {
  29324. // handle LC-AAC
  29325. if (channelCount === 1) {
  29326. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  29327. } else if (channelCount === 2) {
  29328. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  29329. } else if (channelCount === 3) {
  29330. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  29331. } else if (channelCount === 4) {
  29332. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  29333. } else if (channelCount === 5) {
  29334. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  29335. } else if (channelCount === 6) {
  29336. 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]);
  29337. }
  29338. } else {
  29339. // handle HE-AAC (mp4a.40.5 / mp4a.40.29)
  29340. if (channelCount === 1) {
  29341. // 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
  29342. 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]);
  29343. } else if (channelCount === 2) {
  29344. // 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
  29345. 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]);
  29346. } else if (channelCount === 3) {
  29347. // 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
  29348. 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]);
  29349. }
  29350. }
  29351. return null;
  29352. }
  29353. }]);
  29354. return AAC;
  29355. }();
  29356. exports.default = AAC;
  29357. module.exports = exports['default'];
  29358. /***/ }),
  29359. /* 43 */
  29360. /***/ (function(module, exports, __webpack_require__) {
  29361. "use strict";
  29362. Object.defineProperty(exports, "__esModule", {
  29363. value: true
  29364. });
  29365. var _logger = __webpack_require__(0);
  29366. var _logger2 = _interopRequireDefault(_logger);
  29367. var _loggingControl = __webpack_require__(8);
  29368. var _loggingControl2 = _interopRequireDefault(_loggingControl);
  29369. var _polyfill = __webpack_require__(11);
  29370. var _polyfill2 = _interopRequireDefault(_polyfill);
  29371. var _transmuxingController = __webpack_require__(14);
  29372. var _transmuxingController2 = _interopRequireDefault(_transmuxingController);
  29373. var _transmuxingEvents = __webpack_require__(5);
  29374. var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
  29375. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  29376. /* post message to worker:
  29377. data: {
  29378. cmd: string
  29379. param: any
  29380. }
  29381. receive message from worker:
  29382. data: {
  29383. msg: string,
  29384. data: any
  29385. }
  29386. */
  29387. var TransmuxingWorker = function TransmuxingWorker(self) {
  29388. var TAG = 'TransmuxingWorker';
  29389. var controller = null;
  29390. var logcatListener = onLogcatCallback.bind(this);
  29391. _polyfill2.default.install();
  29392. self.addEventListener('message', function (e) {
  29393. switch (e.data.cmd) {
  29394. case 'init':
  29395. controller = new _transmuxingController2.default(e.data.param[0], e.data.param[1]);
  29396. controller.on(_transmuxingEvents2.default.IO_ERROR, onIOError.bind(this));
  29397. controller.on(_transmuxingEvents2.default.DEMUX_ERROR, onDemuxError.bind(this));
  29398. controller.on(_transmuxingEvents2.default.INIT_SEGMENT, onInitSegment.bind(this));
  29399. controller.on(_transmuxingEvents2.default.MEDIA_SEGMENT, onMediaSegment.bind(this));
  29400. controller.on(_transmuxingEvents2.default.LOADING_COMPLETE, onLoadingComplete.bind(this));
  29401. controller.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF, onRecoveredEarlyEof.bind(this));
  29402. controller.on(_transmuxingEvents2.default.MEDIA_INFO, onMediaInfo.bind(this));
  29403. controller.on(_transmuxingEvents2.default.STATISTICS_INFO, onStatisticsInfo.bind(this));
  29404. controller.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, onRecommendSeekpoint.bind(this));
  29405. break;
  29406. case 'destroy':
  29407. if (controller) {
  29408. controller.destroy();
  29409. controller = null;
  29410. }
  29411. self.postMessage({ msg: 'destroyed' });
  29412. break;
  29413. case 'start':
  29414. controller.start();
  29415. break;
  29416. case 'stop':
  29417. controller.stop();
  29418. break;
  29419. case 'seek':
  29420. controller.seek(e.data.param);
  29421. break;
  29422. case 'pause':
  29423. controller.pause();
  29424. break;
  29425. case 'resume':
  29426. controller.resume();
  29427. break;
  29428. case 'logging_config':
  29429. {
  29430. var config = e.data.param;
  29431. _loggingControl2.default.applyConfig(config);
  29432. if (config.enableCallback === true) {
  29433. _loggingControl2.default.addLogListener(logcatListener);
  29434. } else {
  29435. _loggingControl2.default.removeLogListener(logcatListener);
  29436. }
  29437. break;
  29438. }
  29439. }
  29440. });
  29441. function onInitSegment(type, initSegment) {
  29442. var obj = {
  29443. msg: _transmuxingEvents2.default.INIT_SEGMENT,
  29444. data: {
  29445. type: type,
  29446. data: initSegment
  29447. }
  29448. };
  29449. self.postMessage(obj, [initSegment.data]); // data: ArrayBuffer
  29450. }
  29451. function onMediaSegment(type, mediaSegment) {
  29452. var obj = {
  29453. msg: _transmuxingEvents2.default.MEDIA_SEGMENT,
  29454. data: {
  29455. type: type,
  29456. data: mediaSegment
  29457. }
  29458. };
  29459. self.postMessage(obj, [mediaSegment.data]); // data: ArrayBuffer
  29460. }
  29461. function onLoadingComplete() {
  29462. var obj = {
  29463. msg: _transmuxingEvents2.default.LOADING_COMPLETE
  29464. };
  29465. self.postMessage(obj);
  29466. }
  29467. function onRecoveredEarlyEof() {
  29468. var obj = {
  29469. msg: _transmuxingEvents2.default.RECOVERED_EARLY_EOF
  29470. };
  29471. self.postMessage(obj);
  29472. }
  29473. function onMediaInfo(mediaInfo) {
  29474. var obj = {
  29475. msg: _transmuxingEvents2.default.MEDIA_INFO,
  29476. data: mediaInfo
  29477. };
  29478. self.postMessage(obj);
  29479. }
  29480. function onStatisticsInfo(statInfo) {
  29481. var obj = {
  29482. msg: _transmuxingEvents2.default.STATISTICS_INFO,
  29483. data: statInfo
  29484. };
  29485. self.postMessage(obj);
  29486. }
  29487. function onIOError(type, info) {
  29488. self.postMessage({
  29489. msg: _transmuxingEvents2.default.IO_ERROR,
  29490. data: {
  29491. type: type,
  29492. info: info
  29493. }
  29494. });
  29495. }
  29496. function onDemuxError(type, info) {
  29497. self.postMessage({
  29498. msg: _transmuxingEvents2.default.DEMUX_ERROR,
  29499. data: {
  29500. type: type,
  29501. info: info
  29502. }
  29503. });
  29504. }
  29505. function onRecommendSeekpoint(milliseconds) {
  29506. self.postMessage({
  29507. msg: _transmuxingEvents2.default.RECOMMEND_SEEKPOINT,
  29508. data: milliseconds
  29509. });
  29510. }
  29511. function onLogcatCallback(type, str) {
  29512. self.postMessage({
  29513. msg: 'logcat_callback',
  29514. data: {
  29515. type: type,
  29516. logcat: str
  29517. }
  29518. });
  29519. }
  29520. }; /*
  29521. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  29522. *
  29523. * @author zheng qian <xqq@xqq.im>
  29524. *
  29525. * Licensed under the Apache License, Version 2.0 (the "License");
  29526. * you may not use this file except in compliance with the License.
  29527. * You may obtain a copy of the License at
  29528. *
  29529. * http://www.apache.org/licenses/LICENSE-2.0
  29530. *
  29531. * Unless required by applicable law or agreed to in writing, software
  29532. * distributed under the License is distributed on an "AS IS" BASIS,
  29533. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  29534. * See the License for the specific language governing permissions and
  29535. * limitations under the License.
  29536. */
  29537. exports.default = TransmuxingWorker;
  29538. module.exports = exports['default'];
  29539. /***/ }),
  29540. /* 44 */
  29541. /***/ (function(module, exports) {
  29542. var bundleFn = arguments[3];
  29543. var sources = arguments[4];
  29544. var cache = arguments[5];
  29545. var stringify = JSON.stringify;
  29546. module.exports = function (fn, options) {
  29547. var wkey;
  29548. var cacheKeys = Object.keys(cache);
  29549. for (var i = 0, l = cacheKeys.length; i < l; i++) {
  29550. var key = cacheKeys[i];
  29551. var exp = cache[key].exports;
  29552. // Using babel as a transpiler to use esmodule, the export will always
  29553. // be an object with the default export as a property of it. To ensure
  29554. // the existing api and babel esmodule exports are both supported we
  29555. // check for both
  29556. if (exp === fn || exp && exp.default === fn) {
  29557. wkey = key;
  29558. break;
  29559. }
  29560. }
  29561. if (!wkey) {
  29562. wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
  29563. var wcache = {};
  29564. for (var i = 0, l = cacheKeys.length; i < l; i++) {
  29565. var key = cacheKeys[i];
  29566. wcache[key] = key;
  29567. }
  29568. sources[wkey] = [
  29569. 'function(require,module,exports){' + fn + '(self); }',
  29570. wcache
  29571. ];
  29572. }
  29573. var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
  29574. var scache = {}; scache[wkey] = wkey;
  29575. sources[skey] = [
  29576. 'function(require,module,exports){' +
  29577. // try to call default if defined to also support babel esmodule exports
  29578. 'var f = require(' + stringify(wkey) + ');' +
  29579. '(f.default ? f.default : f)(self);' +
  29580. '}',
  29581. scache
  29582. ];
  29583. var workerSources = {};
  29584. resolveSources(skey);
  29585. function resolveSources(key) {
  29586. workerSources[key] = true;
  29587. for (var depPath in sources[key][1]) {
  29588. var depKey = sources[key][1][depPath];
  29589. if (!workerSources[depKey]) {
  29590. resolveSources(depKey);
  29591. }
  29592. }
  29593. }
  29594. var src = '(' + bundleFn + ')({'
  29595. + Object.keys(workerSources).map(function (key) {
  29596. return stringify(key) + ':['
  29597. + sources[key][0]
  29598. + ',' + stringify(sources[key][1]) + ']'
  29599. ;
  29600. }).join(',')
  29601. + '},{},[' + stringify(skey) + '])'
  29602. ;
  29603. var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  29604. var blob = new Blob([src], { type: 'text/javascript' });
  29605. if (options && options.bare) { return blob; }
  29606. var workerUrl = URL.createObjectURL(blob);
  29607. var worker = new Worker(workerUrl);
  29608. worker.objectURL = workerUrl;
  29609. return worker;
  29610. };
  29611. /***/ }),
  29612. /* 45 */
  29613. /***/ (function(module, exports, __webpack_require__) {
  29614. "use strict";
  29615. Object.defineProperty(exports, "__esModule", {
  29616. value: true
  29617. });
  29618. 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; }; }(); /*
  29619. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  29620. *
  29621. * @author zheng qian <xqq@xqq.im>
  29622. *
  29623. * Licensed under the Apache License, Version 2.0 (the "License");
  29624. * you may not use this file except in compliance with the License.
  29625. * You may obtain a copy of the License at
  29626. *
  29627. * http://www.apache.org/licenses/LICENSE-2.0
  29628. *
  29629. * Unless required by applicable law or agreed to in writing, software
  29630. * distributed under the License is distributed on an "AS IS" BASIS,
  29631. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  29632. * See the License for the specific language governing permissions and
  29633. * limitations under the License.
  29634. */
  29635. var _events = __webpack_require__(2);
  29636. var _events2 = _interopRequireDefault(_events);
  29637. var _logger = __webpack_require__(0);
  29638. var _logger2 = _interopRequireDefault(_logger);
  29639. var _browser = __webpack_require__(4);
  29640. var _browser2 = _interopRequireDefault(_browser);
  29641. var _mseEvents = __webpack_require__(16);
  29642. var _mseEvents2 = _interopRequireDefault(_mseEvents);
  29643. var _mediaSegmentInfo = __webpack_require__(15);
  29644. var _exception = __webpack_require__(1);
  29645. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  29646. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  29647. // Media Source Extensions controller
  29648. var MSEController = function () {
  29649. function MSEController(config) {
  29650. _classCallCheck(this, MSEController);
  29651. this.TAG = 'MSEController';
  29652. this._config = config;
  29653. this._emitter = new _events2.default();
  29654. if (this._config.isLive && this._config.autoCleanupSourceBuffer == undefined) {
  29655. // For live stream, do auto cleanup by default
  29656. this._config.autoCleanupSourceBuffer = true;
  29657. }
  29658. this.e = {
  29659. onSourceOpen: this._onSourceOpen.bind(this),
  29660. onSourceEnded: this._onSourceEnded.bind(this),
  29661. onSourceClose: this._onSourceClose.bind(this),
  29662. onSourceBufferError: this._onSourceBufferError.bind(this),
  29663. onSourceBufferUpdateEnd: this._onSourceBufferUpdateEnd.bind(this)
  29664. };
  29665. this._mediaSource = null;
  29666. this._mediaSourceObjectURL = null;
  29667. this._mediaElement = null;
  29668. this._isBufferFull = false;
  29669. this._hasPendingEos = false;
  29670. this._requireSetMediaDuration = false;
  29671. this._pendingMediaDuration = 0;
  29672. this._pendingSourceBufferInit = [];
  29673. this._mimeTypes = {
  29674. video: null,
  29675. audio: null
  29676. };
  29677. this._sourceBuffers = {
  29678. video: null,
  29679. audio: null
  29680. };
  29681. this._lastInitSegments = {
  29682. video: null,
  29683. audio: null
  29684. };
  29685. this._pendingSegments = {
  29686. video: [],
  29687. audio: []
  29688. };
  29689. this._pendingRemoveRanges = {
  29690. video: [],
  29691. audio: []
  29692. };
  29693. this._idrList = new _mediaSegmentInfo.IDRSampleList();
  29694. }
  29695. _createClass(MSEController, [{
  29696. key: 'destroy',
  29697. value: function destroy() {
  29698. if (this._mediaElement || this._mediaSource) {
  29699. this.detachMediaElement();
  29700. }
  29701. this.e = null;
  29702. this._emitter.removeAllListeners();
  29703. this._emitter = null;
  29704. }
  29705. }, {
  29706. key: 'on',
  29707. value: function on(event, listener) {
  29708. this._emitter.addListener(event, listener);
  29709. }
  29710. }, {
  29711. key: 'off',
  29712. value: function off(event, listener) {
  29713. this._emitter.removeListener(event, listener);
  29714. }
  29715. }, {
  29716. key: 'attachMediaElement',
  29717. value: function attachMediaElement(mediaElement) {
  29718. if (this._mediaSource) {
  29719. throw new _exception.IllegalStateException('MediaSource has been attached to an HTMLMediaElement!');
  29720. }
  29721. var ms = this._mediaSource = new window.MediaSource();
  29722. ms.addEventListener('sourceopen', this.e.onSourceOpen);
  29723. ms.addEventListener('sourceended', this.e.onSourceEnded);
  29724. ms.addEventListener('sourceclose', this.e.onSourceClose);
  29725. this._mediaElement = mediaElement;
  29726. this._mediaSourceObjectURL = window.URL.createObjectURL(this._mediaSource);
  29727. mediaElement.src = this._mediaSourceObjectURL;
  29728. }
  29729. }, {
  29730. key: 'detachMediaElement',
  29731. value: function detachMediaElement() {
  29732. if (this._mediaSource) {
  29733. var ms = this._mediaSource;
  29734. for (var type in this._sourceBuffers) {
  29735. // pending segments should be discard
  29736. var ps = this._pendingSegments[type];
  29737. ps.splice(0, ps.length);
  29738. this._pendingSegments[type] = null;
  29739. this._pendingRemoveRanges[type] = null;
  29740. this._lastInitSegments[type] = null;
  29741. // remove all sourcebuffers
  29742. var sb = this._sourceBuffers[type];
  29743. if (sb) {
  29744. if (ms.readyState !== 'closed') {
  29745. ms.removeSourceBuffer(sb);
  29746. sb.removeEventListener('error', this.e.onSourceBufferError);
  29747. sb.removeEventListener('updateend', this.e.onSourceBufferUpdateEnd);
  29748. }
  29749. this._mimeTypes[type] = null;
  29750. this._sourceBuffers[type] = null;
  29751. }
  29752. }
  29753. if (ms.readyState === 'open') {
  29754. try {
  29755. ms.endOfStream();
  29756. } catch (error) {
  29757. _logger2.default.e(this.TAG, error.message);
  29758. }
  29759. }
  29760. ms.removeEventListener('sourceopen', this.e.onSourceOpen);
  29761. ms.removeEventListener('sourceended', this.e.onSourceEnded);
  29762. ms.removeEventListener('sourceclose', this.e.onSourceClose);
  29763. this._pendingSourceBufferInit = [];
  29764. this._isBufferFull = false;
  29765. this._idrList.clear();
  29766. this._mediaSource = null;
  29767. }
  29768. if (this._mediaElement) {
  29769. this._mediaElement.src = '';
  29770. this._mediaElement.removeAttribute('src');
  29771. this._mediaElement = null;
  29772. }
  29773. if (this._mediaSourceObjectURL) {
  29774. window.URL.revokeObjectURL(this._mediaSourceObjectURL);
  29775. this._mediaSourceObjectURL = null;
  29776. }
  29777. }
  29778. }, {
  29779. key: 'appendInitSegment',
  29780. value: function appendInitSegment(initSegment, deferred) {
  29781. if (!this._mediaSource || this._mediaSource.readyState !== 'open') {
  29782. // sourcebuffer creation requires mediaSource.readyState === 'open'
  29783. // so we defer the sourcebuffer creation, until sourceopen event triggered
  29784. this._pendingSourceBufferInit.push(initSegment);
  29785. // make sure that this InitSegment is in the front of pending segments queue
  29786. this._pendingSegments[initSegment.type].push(initSegment);
  29787. // console.log(`${initSegment.type}`, initSegment)
  29788. return;
  29789. }
  29790. var is = initSegment;
  29791. var mimeType = '' + is.container;
  29792. if (is.codec && is.codec.length > 0) {
  29793. mimeType += ';codecs=' + is.codec;
  29794. }
  29795. var firstInitSegment = false;
  29796. _logger2.default.v(this.TAG, 'Received Initialization Segment, mimeType: ' + mimeType);
  29797. this._lastInitSegments[is.type] = is;
  29798. if (mimeType !== this._mimeTypes[is.type]) {
  29799. if (!this._mimeTypes[is.type]) {
  29800. // empty, first chance create sourcebuffer
  29801. firstInitSegment = true;
  29802. try {
  29803. var sb = this._sourceBuffers[is.type] = this._mediaSource.addSourceBuffer(mimeType);
  29804. sb.addEventListener('error', this.e.onSourceBufferError);
  29805. sb.addEventListener('updateend', this.e.onSourceBufferUpdateEnd);
  29806. } catch (error) {
  29807. _logger2.default.e(this.TAG, error.message);
  29808. this._emitter.emit(_mseEvents2.default.ERROR, { code: error.code, msg: error.message });
  29809. return;
  29810. }
  29811. } else {
  29812. _logger2.default.v(this.TAG, 'Notice: ' + is.type + ' mimeType changed, origin: ' + this._mimeTypes[is.type] + ', target: ' + mimeType);
  29813. }
  29814. this._mimeTypes[is.type] = mimeType;
  29815. }
  29816. if (!deferred) {
  29817. // deferred means this InitSegment has been pushed to pendingSegments queue
  29818. this._pendingSegments[is.type].push(is);
  29819. }
  29820. if (!firstInitSegment) {
  29821. // append immediately only if init segment in subsequence
  29822. if (this._sourceBuffers[is.type] && !this._sourceBuffers[is.type].updating) {
  29823. this._doAppendSegments();
  29824. }
  29825. }
  29826. if (_browser2.default.safari && is.container === 'audio/mpeg' && is.mediaDuration > 0) {
  29827. // 'audio/mpeg' track under Safari may cause MediaElement's duration to be NaN
  29828. // Manually correct MediaSource.duration to make progress bar seekable, and report right duration
  29829. this._requireSetMediaDuration = true;
  29830. this._pendingMediaDuration = is.mediaDuration / 1000; // in seconds
  29831. this._updateMediaSourceDuration();
  29832. }
  29833. }
  29834. }, {
  29835. key: 'appendMediaSegment',
  29836. value: function appendMediaSegment(mediaSegment) {
  29837. var ms = mediaSegment;
  29838. this._pendingSegments[ms.type].push(ms);
  29839. if (this._config.autoCleanupSourceBuffer && this._needCleanupSourceBuffer()) {
  29840. this._doCleanupSourceBuffer();
  29841. }
  29842. var sb = this._sourceBuffers[ms.type];
  29843. if (sb && !sb.updating && !this._hasPendingRemoveRanges()) {
  29844. this._doAppendSegments();
  29845. }
  29846. }
  29847. }, {
  29848. key: 'seek',
  29849. value: function seek(seconds) {
  29850. // remove all appended buffers
  29851. for (var type in this._sourceBuffers) {
  29852. if (!this._sourceBuffers[type]) {
  29853. continue;
  29854. }
  29855. // abort current buffer append algorithm
  29856. var sb = this._sourceBuffers[type];
  29857. if (this._mediaSource.readyState === 'open') {
  29858. try {
  29859. // If range removal algorithm is running, InvalidStateError will be throwed
  29860. // Ignore it.
  29861. sb.abort();
  29862. } catch (error) {
  29863. _logger2.default.e(this.TAG, error.message);
  29864. }
  29865. }
  29866. // IDRList should be clear
  29867. this._idrList.clear();
  29868. // pending segments should be discard
  29869. var ps = this._pendingSegments[type];
  29870. ps.splice(0, ps.length);
  29871. if (this._mediaSource.readyState === 'closed') {
  29872. // Parent MediaSource object has been detached from HTMLMediaElement
  29873. continue;
  29874. }
  29875. // record ranges to be remove from SourceBuffer
  29876. for (var i = 0; i < sb.buffered.length; i++) {
  29877. var start = sb.buffered.start(i);
  29878. var end = sb.buffered.end(i);
  29879. this._pendingRemoveRanges[type].push({ start: start, end: end });
  29880. }
  29881. // if sb is not updating, let's remove ranges now!
  29882. if (!sb.updating) {
  29883. this._doRemoveRanges();
  29884. }
  29885. // Safari 10 may get InvalidStateError in the later appendBuffer() after SourceBuffer.remove() call
  29886. // Internal parser's state may be invalid at this time. Re-append last InitSegment to workaround.
  29887. // Related issue: https://bugs.webkit.org/show_bug.cgi?id=159230
  29888. if (_browser2.default.safari) {
  29889. var lastInitSegment = this._lastInitSegments[type];
  29890. if (lastInitSegment) {
  29891. this._pendingSegments[type].push(lastInitSegment);
  29892. if (!sb.updating) {
  29893. this._doAppendSegments();
  29894. }
  29895. }
  29896. }
  29897. }
  29898. }
  29899. }, {
  29900. key: 'endOfStream',
  29901. value: function endOfStream() {
  29902. var ms = this._mediaSource;
  29903. var sb = this._sourceBuffers;
  29904. if (!ms || ms.readyState !== 'open') {
  29905. if (ms && ms.readyState === 'closed' && this._hasPendingSegments()) {
  29906. // If MediaSource hasn't turned into open state, and there're pending segments
  29907. // Mark pending endOfStream, defer call until all pending segments appended complete
  29908. this._hasPendingEos = true;
  29909. }
  29910. return;
  29911. }
  29912. if (sb.video && sb.video.updating || sb.audio && sb.audio.updating) {
  29913. // If any sourcebuffer is updating, defer endOfStream operation
  29914. // See _onSourceBufferUpdateEnd()
  29915. this._hasPendingEos = true;
  29916. } else {
  29917. this._hasPendingEos = false;
  29918. // Notify media data loading complete
  29919. // This is helpful for correcting total duration to match last media segment
  29920. // Otherwise MediaElement's ended event may not be triggered
  29921. ms.endOfStream();
  29922. }
  29923. }
  29924. }, {
  29925. key: 'getNearestKeyframe',
  29926. value: function getNearestKeyframe(dts) {
  29927. return this._idrList.getLastSyncPointBeforeDts(dts);
  29928. }
  29929. }, {
  29930. key: '_needCleanupSourceBuffer',
  29931. value: function _needCleanupSourceBuffer() {
  29932. if (!this._config.autoCleanupSourceBuffer) {
  29933. return false;
  29934. }
  29935. var currentTime = this._mediaElement.currentTime;
  29936. for (var type in this._sourceBuffers) {
  29937. var sb = this._sourceBuffers[type];
  29938. if (sb) {
  29939. var buffered = sb.buffered;
  29940. if (buffered.length >= 1) {
  29941. if (currentTime - buffered.start(0) >= this._config.autoCleanupMaxBackwardDuration) {
  29942. return true;
  29943. }
  29944. }
  29945. }
  29946. }
  29947. return false;
  29948. }
  29949. }, {
  29950. key: '_doCleanupSourceBuffer',
  29951. value: function _doCleanupSourceBuffer() {
  29952. var currentTime = this._mediaElement.currentTime;
  29953. for (var type in this._sourceBuffers) {
  29954. var sb = this._sourceBuffers[type];
  29955. if (sb) {
  29956. var buffered = sb.buffered;
  29957. var doRemove = false;
  29958. for (var i = 0; i < buffered.length; i++) {
  29959. var start = buffered.start(i);
  29960. var end = buffered.end(i);
  29961. if (start <= currentTime && currentTime < end + 3) {
  29962. // padding 3 seconds
  29963. if (currentTime - start >= this._config.autoCleanupMaxBackwardDuration) {
  29964. doRemove = true;
  29965. var removeEnd = currentTime - this._config.autoCleanupMinBackwardDuration;
  29966. this._pendingRemoveRanges[type].push({ start: start, end: removeEnd });
  29967. }
  29968. } else if (end < currentTime) {
  29969. doRemove = true;
  29970. this._pendingRemoveRanges[type].push({ start: start, end: end });
  29971. }
  29972. }
  29973. if (doRemove && !sb.updating) {
  29974. this._doRemoveRanges();
  29975. }
  29976. }
  29977. }
  29978. }
  29979. }, {
  29980. key: '_updateMediaSourceDuration',
  29981. value: function _updateMediaSourceDuration() {
  29982. var sb = this._sourceBuffers;
  29983. if (this._mediaElement.readyState === 0 || this._mediaSource.readyState !== 'open') {
  29984. return;
  29985. }
  29986. if (sb.video && sb.video.updating || sb.audio && sb.audio.updating) {
  29987. return;
  29988. }
  29989. var current = this._mediaSource.duration;
  29990. var target = this._pendingMediaDuration;
  29991. if (target > 0 && (isNaN(current) || target > current)) {
  29992. _logger2.default.v(this.TAG, 'Update MediaSource duration from ' + current + ' to ' + target);
  29993. this._mediaSource.duration = target;
  29994. }
  29995. this._requireSetMediaDuration = false;
  29996. this._pendingMediaDuration = 0;
  29997. }
  29998. }, {
  29999. key: '_doRemoveRanges',
  30000. value: function _doRemoveRanges() {
  30001. for (var type in this._pendingRemoveRanges) {
  30002. if (!this._sourceBuffers[type] || this._sourceBuffers[type].updating) {
  30003. continue;
  30004. }
  30005. var sb = this._sourceBuffers[type];
  30006. var ranges = this._pendingRemoveRanges[type];
  30007. while (ranges.length && !sb.updating) {
  30008. var range = ranges.shift();
  30009. sb.remove(range.start, range.end);
  30010. }
  30011. }
  30012. }
  30013. }, {
  30014. key: '_doAppendSegments',
  30015. value: function _doAppendSegments() {
  30016. var pendingSegments = this._pendingSegments;
  30017. for (var type in pendingSegments) {
  30018. if (!this._sourceBuffers[type] || this._sourceBuffers[type].updating) {
  30019. continue;
  30020. }
  30021. if (pendingSegments[type].length > 0) {
  30022. var segment = pendingSegments[type].shift();
  30023. if (segment.timestampOffset) {
  30024. // For MPEG audio stream in MSE, if unbuffered-seeking occurred
  30025. // We need explicitly set timestampOffset to the desired point in timeline for mpeg SourceBuffer.
  30026. var currentOffset = this._sourceBuffers[type].timestampOffset;
  30027. var targetOffset = segment.timestampOffset / 1000; // in seconds
  30028. var delta = Math.abs(currentOffset - targetOffset);
  30029. if (delta > 0.1) {
  30030. // If time delta > 100ms
  30031. _logger2.default.v(this.TAG, 'Update MPEG audio timestampOffset from ' + currentOffset + ' to ' + targetOffset);
  30032. this._sourceBuffers[type].timestampOffset = targetOffset;
  30033. }
  30034. delete segment.timestampOffset;
  30035. }
  30036. if (!segment.data || segment.data.byteLength === 0) {
  30037. // Ignore empty buffer
  30038. continue;
  30039. }
  30040. try {
  30041. this._sourceBuffers[type].appendBuffer(segment.data);
  30042. this._isBufferFull = false;
  30043. if (type === 'video' && segment.hasOwnProperty('info')) {
  30044. this._idrList.appendArray(segment.info.syncPoints);
  30045. }
  30046. } catch (error) {
  30047. this._pendingSegments[type].unshift(segment);
  30048. if (error.code === 22) {
  30049. // QuotaExceededError
  30050. /* Notice that FireFox may not throw QuotaExceededError if SourceBuffer is full
  30051. * Currently we can only do lazy-load to avoid SourceBuffer become scattered.
  30052. * SourceBuffer eviction policy may be changed in future version of FireFox.
  30053. *
  30054. * Related issues:
  30055. * https://bugzilla.mozilla.org/show_bug.cgi?id=1279885
  30056. * https://bugzilla.mozilla.org/show_bug.cgi?id=1280023
  30057. */
  30058. // report buffer full, abort network IO
  30059. if (!this._isBufferFull) {
  30060. this._emitter.emit(_mseEvents2.default.BUFFER_FULL);
  30061. }
  30062. this._isBufferFull = true;
  30063. } else {
  30064. _logger2.default.e(this.TAG, error.message);
  30065. this._emitter.emit(_mseEvents2.default.ERROR, { code: error.code, msg: error.message });
  30066. }
  30067. }
  30068. }
  30069. }
  30070. }
  30071. }, {
  30072. key: '_onSourceOpen',
  30073. value: function _onSourceOpen() {
  30074. _logger2.default.v(this.TAG, 'MediaSource onSourceOpen');
  30075. this._mediaSource.removeEventListener('sourceopen', this.e.onSourceOpen);
  30076. // deferred sourcebuffer creation / initialization
  30077. if (this._pendingSourceBufferInit.length > 0) {
  30078. var pendings = this._pendingSourceBufferInit;
  30079. while (pendings.length) {
  30080. var segment = pendings.shift();
  30081. this.appendInitSegment(segment, true);
  30082. }
  30083. }
  30084. // there may be some pending media segments, append them
  30085. if (this._hasPendingSegments()) {
  30086. this._doAppendSegments();
  30087. }
  30088. this._emitter.emit(_mseEvents2.default.SOURCE_OPEN);
  30089. }
  30090. }, {
  30091. key: '_onSourceEnded',
  30092. value: function _onSourceEnded() {
  30093. // fired on endOfStream
  30094. _logger2.default.v(this.TAG, 'MediaSource onSourceEnded');
  30095. }
  30096. }, {
  30097. key: '_onSourceClose',
  30098. value: function _onSourceClose() {
  30099. // fired on detaching from media element
  30100. _logger2.default.v(this.TAG, 'MediaSource onSourceClose');
  30101. if (this._mediaSource && this.e != null) {
  30102. this._mediaSource.removeEventListener('sourceopen', this.e.onSourceOpen);
  30103. this._mediaSource.removeEventListener('sourceended', this.e.onSourceEnded);
  30104. this._mediaSource.removeEventListener('sourceclose', this.e.onSourceClose);
  30105. }
  30106. }
  30107. }, {
  30108. key: '_hasPendingSegments',
  30109. value: function _hasPendingSegments() {
  30110. var ps = this._pendingSegments;
  30111. return ps.video.length > 0 || ps.audio.length > 0;
  30112. }
  30113. }, {
  30114. key: '_hasPendingRemoveRanges',
  30115. value: function _hasPendingRemoveRanges() {
  30116. var prr = this._pendingRemoveRanges;
  30117. return prr.video.length > 0 || prr.audio.length > 0;
  30118. }
  30119. }, {
  30120. key: '_onSourceBufferUpdateEnd',
  30121. value: function _onSourceBufferUpdateEnd() {
  30122. if (this._requireSetMediaDuration) {
  30123. this._updateMediaSourceDuration();
  30124. } else if (this._hasPendingRemoveRanges()) {
  30125. this._doRemoveRanges();
  30126. } else if (this._hasPendingSegments()) {
  30127. this._doAppendSegments();
  30128. } else if (this._hasPendingEos) {
  30129. this.endOfStream();
  30130. }
  30131. this._emitter.emit(_mseEvents2.default.UPDATE_END);
  30132. }
  30133. }, {
  30134. key: '_onSourceBufferError',
  30135. value: function _onSourceBufferError(e) {
  30136. _logger2.default.e(this.TAG, 'SourceBuffer Error: ' + e);
  30137. // this error might not always be fatal, just ignore it
  30138. }
  30139. }]);
  30140. return MSEController;
  30141. }();
  30142. exports.default = MSEController;
  30143. module.exports = exports['default'];
  30144. /***/ }),
  30145. /* 46 */
  30146. /***/ (function(module, exports, __webpack_require__) {
  30147. "use strict";
  30148. Object.defineProperty(exports, "__esModule", {
  30149. value: true
  30150. });
  30151. 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; };
  30152. 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; }; }(); /*
  30153. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  30154. *
  30155. * @author zheng qian <xqq@xqq.im>
  30156. *
  30157. * Licensed under the Apache License, Version 2.0 (the "License");
  30158. * you may not use this file except in compliance with the License.
  30159. * You may obtain a copy of the License at
  30160. *
  30161. * http://www.apache.org/licenses/LICENSE-2.0
  30162. *
  30163. * Unless required by applicable law or agreed to in writing, software
  30164. * distributed under the License is distributed on an "AS IS" BASIS,
  30165. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  30166. * See the License for the specific language governing permissions and
  30167. * limitations under the License.
  30168. */
  30169. var _events = __webpack_require__(2);
  30170. var _events2 = _interopRequireDefault(_events);
  30171. var _playerEvents = __webpack_require__(7);
  30172. var _playerEvents2 = _interopRequireDefault(_playerEvents);
  30173. var _config = __webpack_require__(6);
  30174. var _exception = __webpack_require__(1);
  30175. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  30176. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  30177. // Player wrapper for browser's native player (HTMLVideoElement) without MediaSource src.
  30178. var NativePlayer = function () {
  30179. function NativePlayer(mediaDataSource, config) {
  30180. _classCallCheck(this, NativePlayer);
  30181. this.TAG = 'NativePlayer';
  30182. this._type = 'NativePlayer';
  30183. this._emitter = new _events2.default();
  30184. this._config = (0, _config.createDefaultConfig)();
  30185. if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object') {
  30186. Object.assign(this._config, config);
  30187. }
  30188. if (mediaDataSource.type.toLowerCase() === 'flv') {
  30189. throw new _exception.InvalidArgumentException('NativePlayer does\'t support flv MediaDataSource input!');
  30190. }
  30191. if (mediaDataSource.hasOwnProperty('segments')) {
  30192. throw new _exception.InvalidArgumentException('NativePlayer(' + mediaDataSource.type + ') doesn\'t support multipart playback!');
  30193. }
  30194. this.e = {
  30195. onvLoadedMetadata: this._onvLoadedMetadata.bind(this)
  30196. };
  30197. this._pendingSeekTime = null;
  30198. this._statisticsReporter = null;
  30199. this._mediaDataSource = mediaDataSource;
  30200. this._mediaElement = null;
  30201. }
  30202. _createClass(NativePlayer, [{
  30203. key: 'destroy',
  30204. value: function destroy() {
  30205. if (this._mediaElement) {
  30206. this.unload();
  30207. this.detachMediaElement();
  30208. }
  30209. this.e = null;
  30210. this._mediaDataSource = null;
  30211. this._emitter.removeAllListeners();
  30212. this._emitter = null;
  30213. }
  30214. }, {
  30215. key: 'on',
  30216. value: function on(event, listener) {
  30217. var _this = this;
  30218. if (event === _playerEvents2.default.MEDIA_INFO) {
  30219. if (this._mediaElement != null && this._mediaElement.readyState !== 0) {
  30220. // HAVE_NOTHING
  30221. Promise.resolve().then(function () {
  30222. _this._emitter.emit(_playerEvents2.default.MEDIA_INFO, _this.mediaInfo);
  30223. });
  30224. }
  30225. } else if (event === _playerEvents2.default.STATISTICS_INFO) {
  30226. if (this._mediaElement != null && this._mediaElement.readyState !== 0) {
  30227. Promise.resolve().then(function () {
  30228. _this._emitter.emit(_playerEvents2.default.STATISTICS_INFO, _this.statisticsInfo);
  30229. });
  30230. }
  30231. }
  30232. this._emitter.addListener(event, listener);
  30233. }
  30234. }, {
  30235. key: 'off',
  30236. value: function off(event, listener) {
  30237. this._emitter.removeListener(event, listener);
  30238. }
  30239. }, {
  30240. key: 'attachMediaElement',
  30241. value: function attachMediaElement(mediaElement) {
  30242. this._mediaElement = mediaElement;
  30243. mediaElement.addEventListener('loadedmetadata', this.e.onvLoadedMetadata);
  30244. if (this._pendingSeekTime != null) {
  30245. try {
  30246. mediaElement.currentTime = this._pendingSeekTime;
  30247. this._pendingSeekTime = null;
  30248. } catch (e) {
  30249. // IE11 may throw InvalidStateError if readyState === 0
  30250. // Defer set currentTime operation after loadedmetadata
  30251. }
  30252. }
  30253. }
  30254. }, {
  30255. key: 'detachMediaElement',
  30256. value: function detachMediaElement() {
  30257. if (this._mediaElement) {
  30258. this._mediaElement.src = '';
  30259. this._mediaElement.removeAttribute('src');
  30260. this._mediaElement.removeEventListener('loadedmetadata', this.e.onvLoadedMetadata);
  30261. this._mediaElement = null;
  30262. }
  30263. if (this._statisticsReporter != null) {
  30264. window.clearInterval(this._statisticsReporter);
  30265. this._statisticsReporter = null;
  30266. }
  30267. }
  30268. }, {
  30269. key: 'load',
  30270. value: function load() {
  30271. if (!this._mediaElement) {
  30272. throw new _exception.IllegalStateException('HTMLMediaElement must be attached before load()!');
  30273. }
  30274. this._mediaElement.src = this._mediaDataSource.url;
  30275. if (this._mediaElement.readyState > 0) {
  30276. this._mediaElement.currentTime = 0;
  30277. }
  30278. this._mediaElement.preload = 'auto';
  30279. this._mediaElement.load();
  30280. this._statisticsReporter = window.setInterval(this._reportStatisticsInfo.bind(this), this._config.statisticsInfoReportInterval);
  30281. }
  30282. }, {
  30283. key: 'unload',
  30284. value: function unload() {
  30285. if (this._mediaElement) {
  30286. this._mediaElement.src = '';
  30287. this._mediaElement.removeAttribute('src');
  30288. }
  30289. if (this._statisticsReporter != null) {
  30290. window.clearInterval(this._statisticsReporter);
  30291. this._statisticsReporter = null;
  30292. }
  30293. }
  30294. }, {
  30295. key: 'play',
  30296. value: function play() {
  30297. var playPromise = this._mediaElement.play();
  30298. if (playPromise !== undefined && playPromise) {
  30299. return playPromise.catch(function () {});
  30300. } else return undefined;
  30301. }
  30302. }, {
  30303. key: 'pause',
  30304. value: function pause() {
  30305. this._mediaElement.pause();
  30306. }
  30307. }, {
  30308. key: '_onvLoadedMetadata',
  30309. value: function _onvLoadedMetadata(e) {
  30310. if (this._pendingSeekTime != null) {
  30311. this._mediaElement.currentTime = this._pendingSeekTime;
  30312. this._pendingSeekTime = null;
  30313. }
  30314. this._emitter.emit(_playerEvents2.default.MEDIA_INFO, this.mediaInfo);
  30315. }
  30316. }, {
  30317. key: '_reportStatisticsInfo',
  30318. value: function _reportStatisticsInfo() {
  30319. this._emitter.emit(_playerEvents2.default.STATISTICS_INFO, this.statisticsInfo);
  30320. }
  30321. }, {
  30322. key: 'type',
  30323. get: function get() {
  30324. return this._type;
  30325. }
  30326. }, {
  30327. key: 'buffered',
  30328. get: function get() {
  30329. return this._mediaElement.buffered;
  30330. }
  30331. }, {
  30332. key: 'duration',
  30333. get: function get() {
  30334. return this._mediaElement.duration;
  30335. }
  30336. }, {
  30337. key: 'volume',
  30338. get: function get() {
  30339. return this._mediaElement.volume;
  30340. },
  30341. set: function set(value) {
  30342. this._mediaElement.volume = value;
  30343. }
  30344. }, {
  30345. key: 'muted',
  30346. get: function get() {
  30347. return this._mediaElement.muted;
  30348. },
  30349. set: function set(muted) {
  30350. this._mediaElement.muted = muted;
  30351. }
  30352. }, {
  30353. key: 'currentTime',
  30354. get: function get() {
  30355. if (this._mediaElement) {
  30356. return this._mediaElement.currentTime;
  30357. }
  30358. return 0;
  30359. },
  30360. set: function set(seconds) {
  30361. if (this._mediaElement) {
  30362. this._mediaElement.currentTime = seconds;
  30363. } else {
  30364. this._pendingSeekTime = seconds;
  30365. }
  30366. }
  30367. }, {
  30368. key: 'mediaInfo',
  30369. get: function get() {
  30370. var mediaPrefix = this._mediaElement instanceof HTMLAudioElement ? 'audio/' : 'video/';
  30371. var info = {
  30372. mimeType: mediaPrefix + this._mediaDataSource.type
  30373. };
  30374. if (this._mediaElement) {
  30375. info.duration = Math.floor(this._mediaElement.duration * 1000);
  30376. if (this._mediaElement instanceof HTMLVideoElement) {
  30377. info.width = this._mediaElement.videoWidth;
  30378. info.height = this._mediaElement.videoHeight;
  30379. }
  30380. }
  30381. return info;
  30382. }
  30383. }, {
  30384. key: 'statisticsInfo',
  30385. get: function get() {
  30386. var info = {
  30387. playerType: this._type,
  30388. url: this._mediaDataSource.url
  30389. };
  30390. if (!(this._mediaElement instanceof HTMLVideoElement)) {
  30391. return info;
  30392. }
  30393. var hasQualityInfo = true;
  30394. var decoded = 0;
  30395. var dropped = 0;
  30396. if (this._mediaElement.getVideoPlaybackQuality) {
  30397. var quality = this._mediaElement.getVideoPlaybackQuality();
  30398. decoded = quality.totalVideoFrames;
  30399. dropped = quality.droppedVideoFrames;
  30400. } else if (this._mediaElement.webkitDecodedFrameCount != undefined) {
  30401. decoded = this._mediaElement.webkitDecodedFrameCount;
  30402. dropped = this._mediaElement.webkitDroppedFrameCount;
  30403. } else {
  30404. hasQualityInfo = false;
  30405. }
  30406. if (hasQualityInfo) {
  30407. info.decodedFrames = decoded;
  30408. info.droppedFrames = dropped;
  30409. }
  30410. return info;
  30411. }
  30412. }]);
  30413. return NativePlayer;
  30414. }();
  30415. exports.default = NativePlayer;
  30416. module.exports = exports['default'];
  30417. /***/ })
  30418. /******/ ]);
  30419. });
  30420. /***/ }),
  30421. /***/ "c04e":
  30422. /***/ (function(module, exports, __webpack_require__) {
  30423. var isObject = __webpack_require__("861d");
  30424. // `ToPrimitive` abstract operation
  30425. // https://tc39.github.io/ecma262/#sec-toprimitive
  30426. // instead of the ES6 spec version, we didn't implement @@toPrimitive case
  30427. // and the second argument - flag - preferred type is a string
  30428. module.exports = function (input, PREFERRED_STRING) {
  30429. if (!isObject(input)) return input;
  30430. var fn, val;
  30431. if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
  30432. if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;
  30433. if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
  30434. throw TypeError("Can't convert object to primitive value");
  30435. };
  30436. /***/ }),
  30437. /***/ "c430":
  30438. /***/ (function(module, exports) {
  30439. module.exports = false;
  30440. /***/ }),
  30441. /***/ "c6b6":
  30442. /***/ (function(module, exports) {
  30443. var toString = {}.toString;
  30444. module.exports = function (it) {
  30445. return toString.call(it).slice(8, -1);
  30446. };
  30447. /***/ }),
  30448. /***/ "c6cd":
  30449. /***/ (function(module, exports, __webpack_require__) {
  30450. var global = __webpack_require__("da84");
  30451. var setGlobal = __webpack_require__("ce4e");
  30452. var SHARED = '__core-js_shared__';
  30453. var store = global[SHARED] || setGlobal(SHARED, {});
  30454. module.exports = store;
  30455. /***/ }),
  30456. /***/ "c8ba":
  30457. /***/ (function(module, exports) {
  30458. var g;
  30459. // This works in non-strict mode
  30460. g = (function() {
  30461. return this;
  30462. })();
  30463. try {
  30464. // This works if eval is allowed (see CSP)
  30465. g = g || new Function("return this")();
  30466. } catch (e) {
  30467. // This works if the window reference is available
  30468. if (typeof window === "object") g = window;
  30469. }
  30470. // g can still be undefined, but nothing to do about it...
  30471. // We return undefined, instead of nothing here, so it's
  30472. // easier to handle this case. if(!global) { ...}
  30473. module.exports = g;
  30474. /***/ }),
  30475. /***/ "ca84":
  30476. /***/ (function(module, exports, __webpack_require__) {
  30477. var has = __webpack_require__("5135");
  30478. var toIndexedObject = __webpack_require__("fc6a");
  30479. var indexOf = __webpack_require__("4d64").indexOf;
  30480. var hiddenKeys = __webpack_require__("d012");
  30481. module.exports = function (object, names) {
  30482. var O = toIndexedObject(object);
  30483. var i = 0;
  30484. var result = [];
  30485. var key;
  30486. for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key);
  30487. // Don't enum bug & hidden keys
  30488. while (names.length > i) if (has(O, key = names[i++])) {
  30489. ~indexOf(result, key) || result.push(key);
  30490. }
  30491. return result;
  30492. };
  30493. /***/ }),
  30494. /***/ "cc12":
  30495. /***/ (function(module, exports, __webpack_require__) {
  30496. var global = __webpack_require__("da84");
  30497. var isObject = __webpack_require__("861d");
  30498. var document = global.document;
  30499. // typeof document.createElement is 'object' in old IE
  30500. var EXISTS = isObject(document) && isObject(document.createElement);
  30501. module.exports = function (it) {
  30502. return EXISTS ? document.createElement(it) : {};
  30503. };
  30504. /***/ }),
  30505. /***/ "cca6":
  30506. /***/ (function(module, exports, __webpack_require__) {
  30507. var $ = __webpack_require__("23e7");
  30508. var assign = __webpack_require__("60da");
  30509. // `Object.assign` method
  30510. // https://tc39.github.io/ecma262/#sec-object.assign
  30511. $({ target: 'Object', stat: true, forced: Object.assign !== assign }, {
  30512. assign: assign
  30513. });
  30514. /***/ }),
  30515. /***/ "ce4e":
  30516. /***/ (function(module, exports, __webpack_require__) {
  30517. var global = __webpack_require__("da84");
  30518. var createNonEnumerableProperty = __webpack_require__("9112");
  30519. module.exports = function (key, value) {
  30520. try {
  30521. createNonEnumerableProperty(global, key, value);
  30522. } catch (error) {
  30523. global[key] = value;
  30524. } return value;
  30525. };
  30526. /***/ }),
  30527. /***/ "d012":
  30528. /***/ (function(module, exports) {
  30529. module.exports = {};
  30530. /***/ }),
  30531. /***/ "d039":
  30532. /***/ (function(module, exports) {
  30533. module.exports = function (exec) {
  30534. try {
  30535. return !!exec();
  30536. } catch (error) {
  30537. return true;
  30538. }
  30539. };
  30540. /***/ }),
  30541. /***/ "d066":
  30542. /***/ (function(module, exports, __webpack_require__) {
  30543. var path = __webpack_require__("428f");
  30544. var global = __webpack_require__("da84");
  30545. var aFunction = function (variable) {
  30546. return typeof variable == 'function' ? variable : undefined;
  30547. };
  30548. module.exports = function (namespace, method) {
  30549. return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global[namespace])
  30550. : path[namespace] && path[namespace][method] || global[namespace] && global[namespace][method];
  30551. };
  30552. /***/ }),
  30553. /***/ "d1e7":
  30554. /***/ (function(module, exports, __webpack_require__) {
  30555. "use strict";
  30556. var nativePropertyIsEnumerable = {}.propertyIsEnumerable;
  30557. var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  30558. // Nashorn ~ JDK8 bug
  30559. var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1);
  30560. // `Object.prototype.propertyIsEnumerable` method implementation
  30561. // https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable
  30562. exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
  30563. var descriptor = getOwnPropertyDescriptor(this, V);
  30564. return !!descriptor && descriptor.enumerable;
  30565. } : nativePropertyIsEnumerable;
  30566. /***/ }),
  30567. /***/ "da84":
  30568. /***/ (function(module, exports, __webpack_require__) {
  30569. /* WEBPACK VAR INJECTION */(function(global) {var check = function (it) {
  30570. return it && it.Math == Math && it;
  30571. };
  30572. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  30573. module.exports =
  30574. // eslint-disable-next-line no-undef
  30575. check(typeof globalThis == 'object' && globalThis) ||
  30576. check(typeof window == 'object' && window) ||
  30577. check(typeof self == 'object' && self) ||
  30578. check(typeof global == 'object' && global) ||
  30579. // eslint-disable-next-line no-new-func
  30580. Function('return this')();
  30581. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__("c8ba")))
  30582. /***/ }),
  30583. /***/ "df75":
  30584. /***/ (function(module, exports, __webpack_require__) {
  30585. var internalObjectKeys = __webpack_require__("ca84");
  30586. var enumBugKeys = __webpack_require__("7839");
  30587. // `Object.keys` method
  30588. // https://tc39.github.io/ecma262/#sec-object.keys
  30589. module.exports = Object.keys || function keys(O) {
  30590. return internalObjectKeys(O, enumBugKeys);
  30591. };
  30592. /***/ }),
  30593. /***/ "e893":
  30594. /***/ (function(module, exports, __webpack_require__) {
  30595. var has = __webpack_require__("5135");
  30596. var ownKeys = __webpack_require__("56ef");
  30597. var getOwnPropertyDescriptorModule = __webpack_require__("06cf");
  30598. var definePropertyModule = __webpack_require__("9bf2");
  30599. module.exports = function (target, source) {
  30600. var keys = ownKeys(source);
  30601. var defineProperty = definePropertyModule.f;
  30602. var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
  30603. for (var i = 0; i < keys.length; i++) {
  30604. var key = keys[i];
  30605. if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
  30606. }
  30607. };
  30608. /***/ }),
  30609. /***/ "f772":
  30610. /***/ (function(module, exports, __webpack_require__) {
  30611. var shared = __webpack_require__("5692");
  30612. var uid = __webpack_require__("90e3");
  30613. var keys = shared('keys');
  30614. module.exports = function (key) {
  30615. return keys[key] || (keys[key] = uid(key));
  30616. };
  30617. /***/ }),
  30618. /***/ "fae3":
  30619. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  30620. "use strict";
  30621. // ESM COMPAT FLAG
  30622. __webpack_require__.r(__webpack_exports__);
  30623. // EXPORTS
  30624. __webpack_require__.d(__webpack_exports__, "Mp4", function() { return /* reexport */ Mp4; });
  30625. __webpack_require__.d(__webpack_exports__, "Hls", function() { return /* reexport */ Hls; });
  30626. __webpack_require__.d(__webpack_exports__, "Flv", function() { return /* reexport */ Flv; });
  30627. // CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/setPublicPath.js
  30628. // This file is imported into lib/wc client bundles.
  30629. if (typeof window !== 'undefined') {
  30630. var currentScript = window.document.currentScript
  30631. if (true) {
  30632. var getCurrentScript = __webpack_require__("8875")
  30633. currentScript = getCurrentScript()
  30634. // for backward compatibility, because previously we directly included the polyfill
  30635. if (!('currentScript' in document)) {
  30636. Object.defineProperty(document, 'currentScript', { get: getCurrentScript })
  30637. }
  30638. }
  30639. var src = currentScript && currentScript.src.match(/(.+\/)[^/]+\.js(\?.*)?$/)
  30640. if (src) {
  30641. __webpack_require__.p = src[1] // eslint-disable-line
  30642. }
  30643. }
  30644. // Indicate to webpack that this file can be concatenated
  30645. /* harmony default export */ var setPublicPath = (null);
  30646. // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"0f4fd5cb-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Mp4.vue?vue&type=template&id=cedd472c&
  30647. var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{style:(_vm.rootStyle),attrs:{"id":_vm.config.id}})}
  30648. var staticRenderFns = []
  30649. // CONCATENATED MODULE: ./src/components/Mp4.vue?vue&type=template&id=cedd472c&
  30650. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.object.assign.js
  30651. var es_object_assign = __webpack_require__("cca6");
  30652. // EXTERNAL MODULE: ./node_modules/xgplayer/dist/index.js
  30653. var dist = __webpack_require__("5392");
  30654. var dist_default = /*#__PURE__*/__webpack_require__.n(dist);
  30655. // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Mp4.vue?vue&type=script&lang=js&
  30656. //
  30657. //
  30658. //
  30659. //
  30660. /* harmony default export */ var Mp4vue_type_script_lang_js_ = ({
  30661. name: "Mp4",
  30662. props: {
  30663. config: {
  30664. type: Object,
  30665. default: function _default() {
  30666. return {
  30667. id: "mse",
  30668. url: ""
  30669. };
  30670. }
  30671. },
  30672. rootStyle: {
  30673. type: Object,
  30674. default: function _default() {
  30675. return {};
  30676. }
  30677. }
  30678. },
  30679. data: function data() {
  30680. return {
  30681. player: null,
  30682. finalConfig: {
  30683. volume: 0,
  30684. autoplayMuted: true,
  30685. //解决浏览器非静音阻止自动播放机制
  30686. autoplay: true,
  30687. //自动播放
  30688. loop: true,
  30689. //循环播放
  30690. fluid: true,
  30691. //流式布局
  30692. videoInit: true,
  30693. //加载首屏
  30694. playbackRate: [0.5, 0.75, 1, 1.5, 2],
  30695. //快进设置
  30696. pip: true,
  30697. //画中画
  30698. screenShot: true,
  30699. //开启截屏
  30700. lang: "zh-cn",
  30701. enterLogo: {
  30702. url: "",
  30703. width: 231,
  30704. height: 42
  30705. },
  30706. enterBg: {
  30707. color: "rgba(0,0,0,0.87)"
  30708. },
  30709. enterTips: {
  30710. background: "linear-gradient(to right, rgba(0,0,0,0.87), #3D96FD, rgba(86,195,248), #3D96FD, rgba(0,0,0,0.87))"
  30711. }
  30712. }
  30713. };
  30714. },
  30715. mounted: function mounted() {
  30716. this.init();
  30717. },
  30718. beforeUpdate: function beforeUpdate() {
  30719. this.init();
  30720. },
  30721. beforeDestroy: function beforeDestroy() {
  30722. this.player && typeof this.player.destroy === "function" && this.player.destroy();
  30723. },
  30724. methods: {
  30725. init: function init() {
  30726. this.finalConfig = Object.assign(this.finalConfig, this.config);
  30727. if (this.finalConfig.url && this.finalConfig.url !== "") {
  30728. this.player = new dist_default.a(this.finalConfig);
  30729. this.$emit("player", this.player);
  30730. }
  30731. }
  30732. }
  30733. });
  30734. // CONCATENATED MODULE: ./src/components/Mp4.vue?vue&type=script&lang=js&
  30735. /* harmony default export */ var components_Mp4vue_type_script_lang_js_ = (Mp4vue_type_script_lang_js_);
  30736. // CONCATENATED MODULE: ./node_modules/vue-loader/lib/runtime/componentNormalizer.js
  30737. /* globals __VUE_SSR_CONTEXT__ */
  30738. // IMPORTANT: Do NOT use ES2015 features in this file (except for modules).
  30739. // This module is a runtime utility for cleaner component module output and will
  30740. // be included in the final webpack user bundle.
  30741. function normalizeComponent (
  30742. scriptExports,
  30743. render,
  30744. staticRenderFns,
  30745. functionalTemplate,
  30746. injectStyles,
  30747. scopeId,
  30748. moduleIdentifier, /* server only */
  30749. shadowMode /* vue-cli only */
  30750. ) {
  30751. // Vue.extend constructor export interop
  30752. var options = typeof scriptExports === 'function'
  30753. ? scriptExports.options
  30754. : scriptExports
  30755. // render functions
  30756. if (render) {
  30757. options.render = render
  30758. options.staticRenderFns = staticRenderFns
  30759. options._compiled = true
  30760. }
  30761. // functional template
  30762. if (functionalTemplate) {
  30763. options.functional = true
  30764. }
  30765. // scopedId
  30766. if (scopeId) {
  30767. options._scopeId = 'data-v-' + scopeId
  30768. }
  30769. var hook
  30770. if (moduleIdentifier) { // server build
  30771. hook = function (context) {
  30772. // 2.3 injection
  30773. context =
  30774. context || // cached call
  30775. (this.$vnode && this.$vnode.ssrContext) || // stateful
  30776. (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
  30777. // 2.2 with runInNewContext: true
  30778. if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
  30779. context = __VUE_SSR_CONTEXT__
  30780. }
  30781. // inject component styles
  30782. if (injectStyles) {
  30783. injectStyles.call(this, context)
  30784. }
  30785. // register component module identifier for async chunk inferrence
  30786. if (context && context._registeredComponents) {
  30787. context._registeredComponents.add(moduleIdentifier)
  30788. }
  30789. }
  30790. // used by ssr in case component is cached and beforeCreate
  30791. // never gets called
  30792. options._ssrRegister = hook
  30793. } else if (injectStyles) {
  30794. hook = shadowMode
  30795. ? function () {
  30796. injectStyles.call(
  30797. this,
  30798. (options.functional ? this.parent : this).$root.$options.shadowRoot
  30799. )
  30800. }
  30801. : injectStyles
  30802. }
  30803. if (hook) {
  30804. if (options.functional) {
  30805. // for template-only hot-reload because in that case the render fn doesn't
  30806. // go through the normalizer
  30807. options._injectStyles = hook
  30808. // register for functional component in vue file
  30809. var originalRender = options.render
  30810. options.render = function renderWithStyleInjection (h, context) {
  30811. hook.call(context)
  30812. return originalRender(h, context)
  30813. }
  30814. } else {
  30815. // inject component registration as beforeCreate hook
  30816. var existing = options.beforeCreate
  30817. options.beforeCreate = existing
  30818. ? [].concat(existing, hook)
  30819. : [hook]
  30820. }
  30821. }
  30822. return {
  30823. exports: scriptExports,
  30824. options: options
  30825. }
  30826. }
  30827. // CONCATENATED MODULE: ./src/components/Mp4.vue
  30828. /* normalize component */
  30829. var component = normalizeComponent(
  30830. components_Mp4vue_type_script_lang_js_,
  30831. render,
  30832. staticRenderFns,
  30833. false,
  30834. null,
  30835. null,
  30836. null
  30837. )
  30838. /* harmony default export */ var Mp4 = (component.exports);
  30839. // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"0f4fd5cb-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Hls.vue?vue&type=template&id=5bef744a&
  30840. var Hlsvue_type_template_id_5bef744a_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{style:(_vm.rootStyle),attrs:{"id":_vm.config.id}})}
  30841. var Hlsvue_type_template_id_5bef744a_staticRenderFns = []
  30842. // CONCATENATED MODULE: ./src/components/Hls.vue?vue&type=template&id=5bef744a&
  30843. // EXTERNAL MODULE: ./node_modules/xgplayer-hls.js/dist/index.js
  30844. var xgplayer_hls_js_dist = __webpack_require__("9000");
  30845. var xgplayer_hls_js_dist_default = /*#__PURE__*/__webpack_require__.n(xgplayer_hls_js_dist);
  30846. // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Hls.vue?vue&type=script&lang=js&
  30847. //
  30848. //
  30849. //
  30850. //
  30851. /* harmony default export */ var Hlsvue_type_script_lang_js_ = ({
  30852. name: "Hls",
  30853. props: {
  30854. config: {
  30855. type: Object,
  30856. default: function _default() {
  30857. return {
  30858. id: "mse",
  30859. url: ""
  30860. };
  30861. }
  30862. },
  30863. rootStyle: {
  30864. type: Object,
  30865. default: function _default() {
  30866. return {};
  30867. }
  30868. }
  30869. },
  30870. data: function data() {
  30871. return {
  30872. player: null,
  30873. finalConfig: {
  30874. volume: 0,
  30875. autoplayMuted: true,
  30876. //解决浏览器非静音阻止自动播放机制
  30877. autoplay: true,
  30878. //自动播放
  30879. loop: true,
  30880. //循环播放
  30881. fluid: true,
  30882. //流式布局
  30883. videoInit: true,
  30884. //加载首屏
  30885. playbackRate: [0.5, 0.75, 1, 1.5, 2],
  30886. //快进设置
  30887. pip: true,
  30888. //画中画
  30889. screenShot: true,
  30890. //开启截屏
  30891. lang: "zh-cn",
  30892. enterLogo: {
  30893. url: "",
  30894. width: 231,
  30895. height: 42
  30896. },
  30897. enterBg: {
  30898. color: "rgba(0,0,0,0.87)"
  30899. },
  30900. enterTips: {
  30901. background: "linear-gradient(to right, rgba(0,0,0,0.87), #3D96FD, rgba(86,195,248), #3D96FD, rgba(0,0,0,0.87))"
  30902. }
  30903. }
  30904. };
  30905. },
  30906. mounted: function mounted() {
  30907. this.init();
  30908. },
  30909. beforeUpdate: function beforeUpdate() {
  30910. this.init();
  30911. },
  30912. beforeDestroy: function beforeDestroy() {
  30913. this.player && typeof this.player.destroy === "function" && this.player.destroy();
  30914. },
  30915. methods: {
  30916. init: function init() {
  30917. this.finalConfig = Object.assign(this.finalConfig, this.config);
  30918. if (this.finalConfig.url && this.finalConfig.url !== "") {
  30919. this.player = new xgplayer_hls_js_dist_default.a(this.finalConfig);
  30920. this.$emit("player", this.player);
  30921. }
  30922. }
  30923. }
  30924. });
  30925. // CONCATENATED MODULE: ./src/components/Hls.vue?vue&type=script&lang=js&
  30926. /* harmony default export */ var components_Hlsvue_type_script_lang_js_ = (Hlsvue_type_script_lang_js_);
  30927. // CONCATENATED MODULE: ./src/components/Hls.vue
  30928. /* normalize component */
  30929. var Hls_component = normalizeComponent(
  30930. components_Hlsvue_type_script_lang_js_,
  30931. Hlsvue_type_template_id_5bef744a_render,
  30932. Hlsvue_type_template_id_5bef744a_staticRenderFns,
  30933. false,
  30934. null,
  30935. null,
  30936. null
  30937. )
  30938. /* harmony default export */ var Hls = (Hls_component.exports);
  30939. // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"0f4fd5cb-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Flv.vue?vue&type=template&id=e5412e0a&
  30940. var Flvvue_type_template_id_e5412e0a_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{style:(_vm.rootStyle),attrs:{"id":_vm.config.id}})}
  30941. var Flvvue_type_template_id_e5412e0a_staticRenderFns = []
  30942. // CONCATENATED MODULE: ./src/components/Flv.vue?vue&type=template&id=e5412e0a&
  30943. // EXTERNAL MODULE: ./node_modules/xgplayer-flv.js/dist/index.js
  30944. var xgplayer_flv_js_dist = __webpack_require__("b402");
  30945. var xgplayer_flv_js_dist_default = /*#__PURE__*/__webpack_require__.n(xgplayer_flv_js_dist);
  30946. // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Flv.vue?vue&type=script&lang=js&
  30947. //
  30948. //
  30949. //
  30950. //
  30951. /* harmony default export */ var Flvvue_type_script_lang_js_ = ({
  30952. name: "Flv",
  30953. props: {
  30954. config: {
  30955. type: Object,
  30956. default: function _default() {
  30957. return {
  30958. id: "mse",
  30959. url: ""
  30960. };
  30961. }
  30962. },
  30963. rootStyle: {
  30964. type: Object,
  30965. default: function _default() {
  30966. return {};
  30967. }
  30968. }
  30969. },
  30970. data: function data() {
  30971. return {
  30972. player: null,
  30973. finalConfig: {
  30974. volume: 0,
  30975. autoplayMuted: true,
  30976. //解决浏览器非静音阻止自动播放机制
  30977. autoplay: true,
  30978. //自动播放
  30979. loop: true,
  30980. //循环播放
  30981. fluid: true,
  30982. //流式布局
  30983. videoInit: true,
  30984. //加载首屏
  30985. playbackRate: [0.5, 0.75, 1, 1.5, 2],
  30986. //快进设置
  30987. pip: true,
  30988. //画中画
  30989. screenShot: true,
  30990. //开启截屏
  30991. lang: "zh-cn",
  30992. hasVideo: true,
  30993. hasAudio: true,
  30994. flvOptionalConfig: {
  30995. enableWorker: true
  30996. },
  30997. enterLogo: {
  30998. url: "",
  30999. width: 231,
  31000. height: 42
  31001. },
  31002. enterBg: {
  31003. color: "rgba(0,0,0,0.87)"
  31004. },
  31005. enterTips: {
  31006. background: "linear-gradient(to right, rgba(0,0,0,0.87), #3D96FD, rgba(86,195,248), #3D96FD, rgba(0,0,0,0.87))"
  31007. }
  31008. }
  31009. };
  31010. },
  31011. mounted: function mounted() {
  31012. this.init();
  31013. },
  31014. beforeUpdate: function beforeUpdate() {
  31015. this.init();
  31016. },
  31017. beforeDestroy: function beforeDestroy() {
  31018. this.player && typeof this.player.destroy === "function" && this.player.destroy();
  31019. },
  31020. methods: {
  31021. init: function init() {
  31022. this.finalConfig = Object.assign(this.finalConfig, this.config);
  31023. if (this.finalConfig.url && this.finalConfig.url !== "") {
  31024. this.player = new xgplayer_flv_js_dist_default.a(this.finalConfig);
  31025. this.$emit("player", this.player);
  31026. }
  31027. }
  31028. }
  31029. });
  31030. // CONCATENATED MODULE: ./src/components/Flv.vue?vue&type=script&lang=js&
  31031. /* harmony default export */ var components_Flvvue_type_script_lang_js_ = (Flvvue_type_script_lang_js_);
  31032. // CONCATENATED MODULE: ./src/components/Flv.vue
  31033. /* normalize component */
  31034. var Flv_component = normalizeComponent(
  31035. components_Flvvue_type_script_lang_js_,
  31036. Flvvue_type_template_id_e5412e0a_render,
  31037. Flvvue_type_template_id_e5412e0a_staticRenderFns,
  31038. false,
  31039. null,
  31040. null,
  31041. null
  31042. )
  31043. /* harmony default export */ var Flv = (Flv_component.exports);
  31044. // CONCATENATED MODULE: ./src/components/export.js
  31045. if (typeof window !== "undefined" && window.Vue) {
  31046. window.Vue.component("zx-player-mp4", Mp4);
  31047. window.Vue.component("zx-player-hls", Hls);
  31048. window.Vue.component("zx-player-flv", Flv);
  31049. }
  31050. // CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/entry-lib-no-default.js
  31051. /***/ }),
  31052. /***/ "fc6a":
  31053. /***/ (function(module, exports, __webpack_require__) {
  31054. // toObject with fallback for non-array-like ES3 strings
  31055. var IndexedObject = __webpack_require__("44ad");
  31056. var requireObjectCoercible = __webpack_require__("1d80");
  31057. module.exports = function (it) {
  31058. return IndexedObject(requireObjectCoercible(it));
  31059. };
  31060. /***/ })
  31061. /******/ });
  31062. //# sourceMappingURL=zx-player.common.js.map