zx-player.umd.js 1.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259
  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define([], factory);
  6. else if(typeof exports === 'object')
  7. exports["zx-player"] = factory();
  8. else
  9. root["zx-player"] = factory();
  10. })((typeof self !== 'undefined' ? self : this), function() {
  11. return /******/ (function(modules) { // webpackBootstrap
  12. /******/ // The module cache
  13. /******/ var installedModules = {};
  14. /******/
  15. /******/ // The require function
  16. /******/ function __webpack_require__(moduleId) {
  17. /******/
  18. /******/ // Check if module is in cache
  19. /******/ if(installedModules[moduleId]) {
  20. /******/ return installedModules[moduleId].exports;
  21. /******/ }
  22. /******/ // Create a new module (and put it into the cache)
  23. /******/ var module = installedModules[moduleId] = {
  24. /******/ i: moduleId,
  25. /******/ l: false,
  26. /******/ exports: {}
  27. /******/ };
  28. /******/
  29. /******/ // Execute the module function
  30. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  31. /******/
  32. /******/ // Flag the module as loaded
  33. /******/ module.l = true;
  34. /******/
  35. /******/ // Return the exports of the module
  36. /******/ return module.exports;
  37. /******/ }
  38. /******/
  39. /******/
  40. /******/ // expose the modules object (__webpack_modules__)
  41. /******/ __webpack_require__.m = modules;
  42. /******/
  43. /******/ // expose the module cache
  44. /******/ __webpack_require__.c = installedModules;
  45. /******/
  46. /******/ // define getter function for harmony exports
  47. /******/ __webpack_require__.d = function(exports, name, getter) {
  48. /******/ if(!__webpack_require__.o(exports, name)) {
  49. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  50. /******/ }
  51. /******/ };
  52. /******/
  53. /******/ // define __esModule on exports
  54. /******/ __webpack_require__.r = function(exports) {
  55. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  56. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  57. /******/ }
  58. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  59. /******/ };
  60. /******/
  61. /******/ // create a fake namespace object
  62. /******/ // mode & 1: value is a module id, require it
  63. /******/ // mode & 2: merge all properties of value into the ns
  64. /******/ // mode & 4: return value when already ns object
  65. /******/ // mode & 8|1: behave like require
  66. /******/ __webpack_require__.t = function(value, mode) {
  67. /******/ if(mode & 1) value = __webpack_require__(value);
  68. /******/ if(mode & 8) return value;
  69. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  70. /******/ var ns = Object.create(null);
  71. /******/ __webpack_require__.r(ns);
  72. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  73. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  74. /******/ return ns;
  75. /******/ };
  76. /******/
  77. /******/ // getDefaultExport function for compatibility with non-harmony modules
  78. /******/ __webpack_require__.n = function(module) {
  79. /******/ var getter = module && module.__esModule ?
  80. /******/ function getDefault() { return module['default']; } :
  81. /******/ function getModuleExports() { return module; };
  82. /******/ __webpack_require__.d(getter, 'a', getter);
  83. /******/ return getter;
  84. /******/ };
  85. /******/
  86. /******/ // Object.prototype.hasOwnProperty.call
  87. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  88. /******/
  89. /******/ // __webpack_public_path__
  90. /******/ __webpack_require__.p = "";
  91. /******/
  92. /******/
  93. /******/ // Load entry module and return exports
  94. /******/ return __webpack_require__(__webpack_require__.s = "fae3");
  95. /******/ })
  96. /************************************************************************/
  97. /******/ ({
  98. /***/ "06cf":
  99. /***/ (function(module, exports, __webpack_require__) {
  100. var DESCRIPTORS = __webpack_require__("83ab");
  101. var propertyIsEnumerableModule = __webpack_require__("d1e7");
  102. var createPropertyDescriptor = __webpack_require__("5c6c");
  103. var toIndexedObject = __webpack_require__("fc6a");
  104. var toPrimitive = __webpack_require__("c04e");
  105. var has = __webpack_require__("5135");
  106. var IE8_DOM_DEFINE = __webpack_require__("0cfb");
  107. var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  108. // `Object.getOwnPropertyDescriptor` method
  109. // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
  110. exports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
  111. O = toIndexedObject(O);
  112. P = toPrimitive(P, true);
  113. if (IE8_DOM_DEFINE) try {
  114. return nativeGetOwnPropertyDescriptor(O, P);
  115. } catch (error) { /* empty */ }
  116. if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]);
  117. };
  118. /***/ }),
  119. /***/ "0cfb":
  120. /***/ (function(module, exports, __webpack_require__) {
  121. var DESCRIPTORS = __webpack_require__("83ab");
  122. var fails = __webpack_require__("d039");
  123. var createElement = __webpack_require__("cc12");
  124. // Thank's IE8 for his funny defineProperty
  125. module.exports = !DESCRIPTORS && !fails(function () {
  126. return Object.defineProperty(createElement('div'), 'a', {
  127. get: function () { return 7; }
  128. }).a != 7;
  129. });
  130. /***/ }),
  131. /***/ "1d80":
  132. /***/ (function(module, exports) {
  133. // `RequireObjectCoercible` abstract operation
  134. // https://tc39.github.io/ecma262/#sec-requireobjectcoercible
  135. module.exports = function (it) {
  136. if (it == undefined) throw TypeError("Can't call method on " + it);
  137. return it;
  138. };
  139. /***/ }),
  140. /***/ "23cb":
  141. /***/ (function(module, exports, __webpack_require__) {
  142. var toInteger = __webpack_require__("a691");
  143. var max = Math.max;
  144. var min = Math.min;
  145. // Helper for a popular repeating case of the spec:
  146. // Let integer be ? ToInteger(index).
  147. // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
  148. module.exports = function (index, length) {
  149. var integer = toInteger(index);
  150. return integer < 0 ? max(integer + length, 0) : min(integer, length);
  151. };
  152. /***/ }),
  153. /***/ "23e7":
  154. /***/ (function(module, exports, __webpack_require__) {
  155. var global = __webpack_require__("da84");
  156. var getOwnPropertyDescriptor = __webpack_require__("06cf").f;
  157. var createNonEnumerableProperty = __webpack_require__("9112");
  158. var redefine = __webpack_require__("6eeb");
  159. var setGlobal = __webpack_require__("ce4e");
  160. var copyConstructorProperties = __webpack_require__("e893");
  161. var isForced = __webpack_require__("94ca");
  162. /*
  163. options.target - name of the target object
  164. options.global - target is the global object
  165. options.stat - export as static methods of target
  166. options.proto - export as prototype methods of target
  167. options.real - real prototype method for the `pure` version
  168. options.forced - export even if the native feature is available
  169. options.bind - bind methods to the target, required for the `pure` version
  170. options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
  171. options.unsafe - use the simple assignment of property instead of delete + defineProperty
  172. options.sham - add a flag to not completely full polyfills
  173. options.enumerable - export as enumerable property
  174. options.noTargetGet - prevent calling a getter on target
  175. */
  176. module.exports = function (options, source) {
  177. var TARGET = options.target;
  178. var GLOBAL = options.global;
  179. var STATIC = options.stat;
  180. var FORCED, target, key, targetProperty, sourceProperty, descriptor;
  181. if (GLOBAL) {
  182. target = global;
  183. } else if (STATIC) {
  184. target = global[TARGET] || setGlobal(TARGET, {});
  185. } else {
  186. target = (global[TARGET] || {}).prototype;
  187. }
  188. if (target) for (key in source) {
  189. sourceProperty = source[key];
  190. if (options.noTargetGet) {
  191. descriptor = getOwnPropertyDescriptor(target, key);
  192. targetProperty = descriptor && descriptor.value;
  193. } else targetProperty = target[key];
  194. FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
  195. // contained in target
  196. if (!FORCED && targetProperty !== undefined) {
  197. if (typeof sourceProperty === typeof targetProperty) continue;
  198. copyConstructorProperties(sourceProperty, targetProperty);
  199. }
  200. // add a flag to not completely full polyfills
  201. if (options.sham || (targetProperty && targetProperty.sham)) {
  202. createNonEnumerableProperty(sourceProperty, 'sham', true);
  203. }
  204. // extend global
  205. redefine(target, key, sourceProperty, options);
  206. }
  207. };
  208. /***/ }),
  209. /***/ "241c":
  210. /***/ (function(module, exports, __webpack_require__) {
  211. var internalObjectKeys = __webpack_require__("ca84");
  212. var enumBugKeys = __webpack_require__("7839");
  213. var hiddenKeys = enumBugKeys.concat('length', 'prototype');
  214. // `Object.getOwnPropertyNames` method
  215. // https://tc39.github.io/ecma262/#sec-object.getownpropertynames
  216. exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
  217. return internalObjectKeys(O, hiddenKeys);
  218. };
  219. /***/ }),
  220. /***/ "428f":
  221. /***/ (function(module, exports, __webpack_require__) {
  222. var global = __webpack_require__("da84");
  223. module.exports = global;
  224. /***/ }),
  225. /***/ "44ad":
  226. /***/ (function(module, exports, __webpack_require__) {
  227. var fails = __webpack_require__("d039");
  228. var classof = __webpack_require__("c6b6");
  229. var split = ''.split;
  230. // fallback for non-array-like ES3 and non-enumerable old V8 strings
  231. module.exports = fails(function () {
  232. // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
  233. // eslint-disable-next-line no-prototype-builtins
  234. return !Object('z').propertyIsEnumerable(0);
  235. }) ? function (it) {
  236. return classof(it) == 'String' ? split.call(it, '') : Object(it);
  237. } : Object;
  238. /***/ }),
  239. /***/ "4d64":
  240. /***/ (function(module, exports, __webpack_require__) {
  241. var toIndexedObject = __webpack_require__("fc6a");
  242. var toLength = __webpack_require__("50c4");
  243. var toAbsoluteIndex = __webpack_require__("23cb");
  244. // `Array.prototype.{ indexOf, includes }` methods implementation
  245. var createMethod = function (IS_INCLUDES) {
  246. return function ($this, el, fromIndex) {
  247. var O = toIndexedObject($this);
  248. var length = toLength(O.length);
  249. var index = toAbsoluteIndex(fromIndex, length);
  250. var value;
  251. // Array#includes uses SameValueZero equality algorithm
  252. // eslint-disable-next-line no-self-compare
  253. if (IS_INCLUDES && el != el) while (length > index) {
  254. value = O[index++];
  255. // eslint-disable-next-line no-self-compare
  256. if (value != value) return true;
  257. // Array#indexOf ignores holes, Array#includes - not
  258. } else for (;length > index; index++) {
  259. if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
  260. } return !IS_INCLUDES && -1;
  261. };
  262. };
  263. module.exports = {
  264. // `Array.prototype.includes` method
  265. // https://tc39.github.io/ecma262/#sec-array.prototype.includes
  266. includes: createMethod(true),
  267. // `Array.prototype.indexOf` method
  268. // https://tc39.github.io/ecma262/#sec-array.prototype.indexof
  269. indexOf: createMethod(false)
  270. };
  271. /***/ }),
  272. /***/ "50c4":
  273. /***/ (function(module, exports, __webpack_require__) {
  274. var toInteger = __webpack_require__("a691");
  275. var min = Math.min;
  276. // `ToLength` abstract operation
  277. // https://tc39.github.io/ecma262/#sec-tolength
  278. module.exports = function (argument) {
  279. return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
  280. };
  281. /***/ }),
  282. /***/ "5135":
  283. /***/ (function(module, exports) {
  284. var hasOwnProperty = {}.hasOwnProperty;
  285. module.exports = function (it, key) {
  286. return hasOwnProperty.call(it, key);
  287. };
  288. /***/ }),
  289. /***/ "5392":
  290. /***/ (function(module, exports, __webpack_require__) {
  291. !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;
  292. /*!
  293. * Draggabilly v2.3.0
  294. * Make that shiz draggable
  295. * https://draggabilly.desandro.com
  296. * MIT license
  297. */
  298. !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;
  299. /*!
  300. * Unidragger v2.3.1
  301. * Draggable base class
  302. * MIT license
  303. */
  304. !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;
  305. /*!
  306. * Unipointer v2.3.0
  307. * base class for doing one thing with pointer event
  308. * MIT license
  309. */
  310. !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)}}))}])}));
  311. //# sourceMappingURL=index.js.map
  312. /***/ }),
  313. /***/ "5692":
  314. /***/ (function(module, exports, __webpack_require__) {
  315. var IS_PURE = __webpack_require__("c430");
  316. var store = __webpack_require__("c6cd");
  317. (module.exports = function (key, value) {
  318. return store[key] || (store[key] = value !== undefined ? value : {});
  319. })('versions', []).push({
  320. version: '3.6.5',
  321. mode: IS_PURE ? 'pure' : 'global',
  322. copyright: '© 2020 Denis Pushkarev (zloirock.ru)'
  323. });
  324. /***/ }),
  325. /***/ "56ef":
  326. /***/ (function(module, exports, __webpack_require__) {
  327. var getBuiltIn = __webpack_require__("d066");
  328. var getOwnPropertyNamesModule = __webpack_require__("241c");
  329. var getOwnPropertySymbolsModule = __webpack_require__("7418");
  330. var anObject = __webpack_require__("825a");
  331. // all object keys, includes non-enumerable and symbols
  332. module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
  333. var keys = getOwnPropertyNamesModule.f(anObject(it));
  334. var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
  335. return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;
  336. };
  337. /***/ }),
  338. /***/ "5c6c":
  339. /***/ (function(module, exports) {
  340. module.exports = function (bitmap, value) {
  341. return {
  342. enumerable: !(bitmap & 1),
  343. configurable: !(bitmap & 2),
  344. writable: !(bitmap & 4),
  345. value: value
  346. };
  347. };
  348. /***/ }),
  349. /***/ "60da":
  350. /***/ (function(module, exports, __webpack_require__) {
  351. "use strict";
  352. var DESCRIPTORS = __webpack_require__("83ab");
  353. var fails = __webpack_require__("d039");
  354. var objectKeys = __webpack_require__("df75");
  355. var getOwnPropertySymbolsModule = __webpack_require__("7418");
  356. var propertyIsEnumerableModule = __webpack_require__("d1e7");
  357. var toObject = __webpack_require__("7b0b");
  358. var IndexedObject = __webpack_require__("44ad");
  359. var nativeAssign = Object.assign;
  360. var defineProperty = Object.defineProperty;
  361. // `Object.assign` method
  362. // https://tc39.github.io/ecma262/#sec-object.assign
  363. module.exports = !nativeAssign || fails(function () {
  364. // should have correct order of operations (Edge bug)
  365. if (DESCRIPTORS && nativeAssign({ b: 1 }, nativeAssign(defineProperty({}, 'a', {
  366. enumerable: true,
  367. get: function () {
  368. defineProperty(this, 'b', {
  369. value: 3,
  370. enumerable: false
  371. });
  372. }
  373. }), { b: 2 })).b !== 1) return true;
  374. // should work with symbols and should have deterministic property order (V8 bug)
  375. var A = {};
  376. var B = {};
  377. // eslint-disable-next-line no-undef
  378. var symbol = Symbol();
  379. var alphabet = 'abcdefghijklmnopqrst';
  380. A[symbol] = 7;
  381. alphabet.split('').forEach(function (chr) { B[chr] = chr; });
  382. return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet;
  383. }) ? function assign(target, source) { // eslint-disable-line no-unused-vars
  384. var T = toObject(target);
  385. var argumentsLength = arguments.length;
  386. var index = 1;
  387. var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
  388. var propertyIsEnumerable = propertyIsEnumerableModule.f;
  389. while (argumentsLength > index) {
  390. var S = IndexedObject(arguments[index++]);
  391. var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S);
  392. var length = keys.length;
  393. var j = 0;
  394. var key;
  395. while (length > j) {
  396. key = keys[j++];
  397. if (!DESCRIPTORS || propertyIsEnumerable.call(S, key)) T[key] = S[key];
  398. }
  399. } return T;
  400. } : nativeAssign;
  401. /***/ }),
  402. /***/ "69f3":
  403. /***/ (function(module, exports, __webpack_require__) {
  404. var NATIVE_WEAK_MAP = __webpack_require__("7f9a");
  405. var global = __webpack_require__("da84");
  406. var isObject = __webpack_require__("861d");
  407. var createNonEnumerableProperty = __webpack_require__("9112");
  408. var objectHas = __webpack_require__("5135");
  409. var sharedKey = __webpack_require__("f772");
  410. var hiddenKeys = __webpack_require__("d012");
  411. var WeakMap = global.WeakMap;
  412. var set, get, has;
  413. var enforce = function (it) {
  414. return has(it) ? get(it) : set(it, {});
  415. };
  416. var getterFor = function (TYPE) {
  417. return function (it) {
  418. var state;
  419. if (!isObject(it) || (state = get(it)).type !== TYPE) {
  420. throw TypeError('Incompatible receiver, ' + TYPE + ' required');
  421. } return state;
  422. };
  423. };
  424. if (NATIVE_WEAK_MAP) {
  425. var store = new WeakMap();
  426. var wmget = store.get;
  427. var wmhas = store.has;
  428. var wmset = store.set;
  429. set = function (it, metadata) {
  430. wmset.call(store, it, metadata);
  431. return metadata;
  432. };
  433. get = function (it) {
  434. return wmget.call(store, it) || {};
  435. };
  436. has = function (it) {
  437. return wmhas.call(store, it);
  438. };
  439. } else {
  440. var STATE = sharedKey('state');
  441. hiddenKeys[STATE] = true;
  442. set = function (it, metadata) {
  443. createNonEnumerableProperty(it, STATE, metadata);
  444. return metadata;
  445. };
  446. get = function (it) {
  447. return objectHas(it, STATE) ? it[STATE] : {};
  448. };
  449. has = function (it) {
  450. return objectHas(it, STATE);
  451. };
  452. }
  453. module.exports = {
  454. set: set,
  455. get: get,
  456. has: has,
  457. enforce: enforce,
  458. getterFor: getterFor
  459. };
  460. /***/ }),
  461. /***/ "6eeb":
  462. /***/ (function(module, exports, __webpack_require__) {
  463. var global = __webpack_require__("da84");
  464. var createNonEnumerableProperty = __webpack_require__("9112");
  465. var has = __webpack_require__("5135");
  466. var setGlobal = __webpack_require__("ce4e");
  467. var inspectSource = __webpack_require__("8925");
  468. var InternalStateModule = __webpack_require__("69f3");
  469. var getInternalState = InternalStateModule.get;
  470. var enforceInternalState = InternalStateModule.enforce;
  471. var TEMPLATE = String(String).split('String');
  472. (module.exports = function (O, key, value, options) {
  473. var unsafe = options ? !!options.unsafe : false;
  474. var simple = options ? !!options.enumerable : false;
  475. var noTargetGet = options ? !!options.noTargetGet : false;
  476. if (typeof value == 'function') {
  477. if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key);
  478. enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : '');
  479. }
  480. if (O === global) {
  481. if (simple) O[key] = value;
  482. else setGlobal(key, value);
  483. return;
  484. } else if (!unsafe) {
  485. delete O[key];
  486. } else if (!noTargetGet && O[key]) {
  487. simple = true;
  488. }
  489. if (simple) O[key] = value;
  490. else createNonEnumerableProperty(O, key, value);
  491. // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
  492. })(Function.prototype, 'toString', function toString() {
  493. return typeof this == 'function' && getInternalState(this).source || inspectSource(this);
  494. });
  495. /***/ }),
  496. /***/ "7418":
  497. /***/ (function(module, exports) {
  498. exports.f = Object.getOwnPropertySymbols;
  499. /***/ }),
  500. /***/ "7839":
  501. /***/ (function(module, exports) {
  502. // IE8- don't enum bug keys
  503. module.exports = [
  504. 'constructor',
  505. 'hasOwnProperty',
  506. 'isPrototypeOf',
  507. 'propertyIsEnumerable',
  508. 'toLocaleString',
  509. 'toString',
  510. 'valueOf'
  511. ];
  512. /***/ }),
  513. /***/ "7b0b":
  514. /***/ (function(module, exports, __webpack_require__) {
  515. var requireObjectCoercible = __webpack_require__("1d80");
  516. // `ToObject` abstract operation
  517. // https://tc39.github.io/ecma262/#sec-toobject
  518. module.exports = function (argument) {
  519. return Object(requireObjectCoercible(argument));
  520. };
  521. /***/ }),
  522. /***/ "7f9a":
  523. /***/ (function(module, exports, __webpack_require__) {
  524. var global = __webpack_require__("da84");
  525. var inspectSource = __webpack_require__("8925");
  526. var WeakMap = global.WeakMap;
  527. module.exports = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap));
  528. /***/ }),
  529. /***/ "825a":
  530. /***/ (function(module, exports, __webpack_require__) {
  531. var isObject = __webpack_require__("861d");
  532. module.exports = function (it) {
  533. if (!isObject(it)) {
  534. throw TypeError(String(it) + ' is not an object');
  535. } return it;
  536. };
  537. /***/ }),
  538. /***/ "83ab":
  539. /***/ (function(module, exports, __webpack_require__) {
  540. var fails = __webpack_require__("d039");
  541. // Thank's IE8 for his funny defineProperty
  542. module.exports = !fails(function () {
  543. return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;
  544. });
  545. /***/ }),
  546. /***/ "861d":
  547. /***/ (function(module, exports) {
  548. module.exports = function (it) {
  549. return typeof it === 'object' ? it !== null : typeof it === 'function';
  550. };
  551. /***/ }),
  552. /***/ "8875":
  553. /***/ (function(module, exports, __webpack_require__) {
  554. var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// addapted from the document.currentScript polyfill by Adam Miller
  555. // MIT license
  556. // source: https://github.com/amiller-gh/currentScript-polyfill
  557. // added support for Firefox https://bugzilla.mozilla.org/show_bug.cgi?id=1620505
  558. (function (root, factory) {
  559. if (true) {
  560. !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
  561. __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
  562. (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
  563. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  564. } else {}
  565. }(typeof self !== 'undefined' ? self : this, function () {
  566. function getCurrentScript () {
  567. var descriptor = Object.getOwnPropertyDescriptor(document, 'currentScript')
  568. // for chrome
  569. if (!descriptor && 'currentScript' in document && document.currentScript) {
  570. return document.currentScript
  571. }
  572. // for other browsers with native support for currentScript
  573. if (descriptor && descriptor.get !== getCurrentScript && document.currentScript) {
  574. return document.currentScript
  575. }
  576. // IE 8-10 support script readyState
  577. // IE 11+ & Firefox support stack trace
  578. try {
  579. throw new Error();
  580. }
  581. catch (err) {
  582. // Find the second match for the "at" string to get file src url from stack.
  583. var ieStackRegExp = /.*at [^(]*\((.*):(.+):(.+)\)$/ig,
  584. ffStackRegExp = /@([^@]*):(\d+):(\d+)\s*$/ig,
  585. stackDetails = ieStackRegExp.exec(err.stack) || ffStackRegExp.exec(err.stack),
  586. scriptLocation = (stackDetails && stackDetails[1]) || false,
  587. line = (stackDetails && stackDetails[2]) || false,
  588. currentLocation = document.location.href.replace(document.location.hash, ''),
  589. pageSource,
  590. inlineScriptSourceRegExp,
  591. inlineScriptSource,
  592. scripts = document.getElementsByTagName('script'); // Live NodeList collection
  593. if (scriptLocation === currentLocation) {
  594. pageSource = document.documentElement.outerHTML;
  595. inlineScriptSourceRegExp = new RegExp('(?:[^\\n]+?\\n){0,' + (line - 2) + '}[^<]*<script>([\\d\\D]*?)<\\/script>[\\d\\D]*', 'i');
  596. inlineScriptSource = pageSource.replace(inlineScriptSourceRegExp, '$1').trim();
  597. }
  598. for (var i = 0; i < scripts.length; i++) {
  599. // If ready state is interactive, return the script tag
  600. if (scripts[i].readyState === 'interactive') {
  601. return scripts[i];
  602. }
  603. // If src matches, return the script tag
  604. if (scripts[i].src === scriptLocation) {
  605. return scripts[i];
  606. }
  607. // If inline source matches, return the script tag
  608. if (
  609. scriptLocation === currentLocation &&
  610. scripts[i].innerHTML &&
  611. scripts[i].innerHTML.trim() === inlineScriptSource
  612. ) {
  613. return scripts[i];
  614. }
  615. }
  616. // If no match, return null
  617. return null;
  618. }
  619. };
  620. return getCurrentScript
  621. }));
  622. /***/ }),
  623. /***/ "8925":
  624. /***/ (function(module, exports, __webpack_require__) {
  625. var store = __webpack_require__("c6cd");
  626. var functionToString = Function.toString;
  627. // this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper
  628. if (typeof store.inspectSource != 'function') {
  629. store.inspectSource = function (it) {
  630. return functionToString.call(it);
  631. };
  632. }
  633. module.exports = store.inspectSource;
  634. /***/ }),
  635. /***/ "9000":
  636. /***/ (function(module, exports, __webpack_require__) {
  637. (function webpackUniversalModuleDefinition(root, factory) {
  638. if(true)
  639. module.exports = factory(__webpack_require__("5392"));
  640. else {}
  641. })(window, function(__WEBPACK_EXTERNAL_MODULE__33__) {
  642. return /******/ (function(modules) { // webpackBootstrap
  643. /******/ // The module cache
  644. /******/ var installedModules = {};
  645. /******/
  646. /******/ // The require function
  647. /******/ function __webpack_require__(moduleId) {
  648. /******/
  649. /******/ // Check if module is in cache
  650. /******/ if(installedModules[moduleId]) {
  651. /******/ return installedModules[moduleId].exports;
  652. /******/ }
  653. /******/ // Create a new module (and put it into the cache)
  654. /******/ var module = installedModules[moduleId] = {
  655. /******/ i: moduleId,
  656. /******/ l: false,
  657. /******/ exports: {}
  658. /******/ };
  659. /******/
  660. /******/ // Execute the module function
  661. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  662. /******/
  663. /******/ // Flag the module as loaded
  664. /******/ module.l = true;
  665. /******/
  666. /******/ // Return the exports of the module
  667. /******/ return module.exports;
  668. /******/ }
  669. /******/
  670. /******/
  671. /******/ // expose the modules object (__webpack_modules__)
  672. /******/ __webpack_require__.m = modules;
  673. /******/
  674. /******/ // expose the module cache
  675. /******/ __webpack_require__.c = installedModules;
  676. /******/
  677. /******/ // define getter function for harmony exports
  678. /******/ __webpack_require__.d = function(exports, name, getter) {
  679. /******/ if(!__webpack_require__.o(exports, name)) {
  680. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  681. /******/ }
  682. /******/ };
  683. /******/
  684. /******/ // define __esModule on exports
  685. /******/ __webpack_require__.r = function(exports) {
  686. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  687. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  688. /******/ }
  689. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  690. /******/ };
  691. /******/
  692. /******/ // create a fake namespace object
  693. /******/ // mode & 1: value is a module id, require it
  694. /******/ // mode & 2: merge all properties of value into the ns
  695. /******/ // mode & 4: return value when already ns object
  696. /******/ // mode & 8|1: behave like require
  697. /******/ __webpack_require__.t = function(value, mode) {
  698. /******/ if(mode & 1) value = __webpack_require__(value);
  699. /******/ if(mode & 8) return value;
  700. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  701. /******/ var ns = Object.create(null);
  702. /******/ __webpack_require__.r(ns);
  703. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  704. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  705. /******/ return ns;
  706. /******/ };
  707. /******/
  708. /******/ // getDefaultExport function for compatibility with non-harmony modules
  709. /******/ __webpack_require__.n = function(module) {
  710. /******/ var getter = module && module.__esModule ?
  711. /******/ function getDefault() { return module['default']; } :
  712. /******/ function getModuleExports() { return module; };
  713. /******/ __webpack_require__.d(getter, 'a', getter);
  714. /******/ return getter;
  715. /******/ };
  716. /******/
  717. /******/ // Object.prototype.hasOwnProperty.call
  718. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  719. /******/
  720. /******/ // __webpack_public_path__
  721. /******/ __webpack_require__.p = "";
  722. /******/
  723. /******/
  724. /******/ // Load entry module and return exports
  725. /******/ return __webpack_require__(__webpack_require__.s = 31);
  726. /******/ })
  727. /************************************************************************/
  728. /******/ ([
  729. /* 0 */
  730. /***/ (function(module, exports, __webpack_require__) {
  731. "use strict";
  732. Object.defineProperty(exports, "__esModule", {
  733. value: true
  734. });
  735. exports.logger = exports.enableLogs = undefined;
  736. 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; };
  737. var _getSelfScope = __webpack_require__(5);
  738. function noop() {}
  739. var fakeLogger = {
  740. trace: noop,
  741. debug: noop,
  742. log: noop,
  743. warn: noop,
  744. info: noop,
  745. error: noop
  746. };
  747. var exportedLogger = fakeLogger;
  748. // let lastCallTime;
  749. // function formatMsgWithTimeInfo(type, msg) {
  750. // const now = Date.now();
  751. // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
  752. // lastCallTime = now;
  753. // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
  754. // return msg;
  755. // }
  756. function formatMsg(type, msg) {
  757. msg = '[' + type + '] > ' + msg;
  758. return msg;
  759. }
  760. var global = (0, _getSelfScope.getSelfScope)();
  761. function consolePrintFn(type) {
  762. var func = global.console[type];
  763. if (func) {
  764. return function () {
  765. for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  766. args[_key] = arguments[_key];
  767. }
  768. if (args[0]) {
  769. args[0] = formatMsg(type, args[0]);
  770. }
  771. func.apply(global.console, args);
  772. };
  773. }
  774. return noop;
  775. }
  776. function exportLoggerFunctions(debugConfig) {
  777. for (var _len2 = arguments.length, functions = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  778. functions[_key2 - 1] = arguments[_key2];
  779. }
  780. functions.forEach(function (type) {
  781. exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
  782. });
  783. }
  784. var enableLogs = exports.enableLogs = function enableLogs(debugConfig) {
  785. if (debugConfig === true || (typeof debugConfig === 'undefined' ? 'undefined' : _typeof(debugConfig)) === 'object') {
  786. exportLoggerFunctions(debugConfig,
  787. // Remove out from list here to hard-disable a log-level
  788. // 'trace',
  789. 'debug', 'log', 'info', 'warn', 'error');
  790. // Some browsers don't allow to use bind on console object anyway
  791. // fallback to default if needed
  792. try {
  793. exportedLogger.log();
  794. } catch (e) {
  795. exportedLogger = fakeLogger;
  796. }
  797. } else {
  798. exportedLogger = fakeLogger;
  799. }
  800. };
  801. var logger = exports.logger = exportedLogger;
  802. /***/ }),
  803. /* 1 */
  804. /***/ (function(module, exports, __webpack_require__) {
  805. "use strict";
  806. Object.defineProperty(exports, "__esModule", {
  807. value: true
  808. });
  809. /**
  810. * @readonly
  811. * @enum {string}
  812. */
  813. var HlsEvents = {
  814. // fired before MediaSource is attaching to media element - data: { media }
  815. MEDIA_ATTACHING: 'hlsMediaAttaching',
  816. // fired when MediaSource has been succesfully attached to media element - data: { }
  817. MEDIA_ATTACHED: 'hlsMediaAttached',
  818. // fired before detaching MediaSource from media element - data: { }
  819. MEDIA_DETACHING: 'hlsMediaDetaching',
  820. // fired when MediaSource has been detached from media element - data: { }
  821. MEDIA_DETACHED: 'hlsMediaDetached',
  822. // fired when we buffer is going to be reset - data: { }
  823. BUFFER_RESET: 'hlsBufferReset',
  824. // fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}
  825. BUFFER_CODECS: 'hlsBufferCodecs',
  826. // fired when sourcebuffers have been created - data: { tracks : tracks }
  827. BUFFER_CREATED: 'hlsBufferCreated',
  828. // fired when we append a segment to the buffer - data: { segment: segment object }
  829. BUFFER_APPENDING: 'hlsBufferAppending',
  830. // 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}
  831. BUFFER_APPENDED: 'hlsBufferAppended',
  832. // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }
  833. BUFFER_EOS: 'hlsBufferEos',
  834. // fired when the media buffer should be flushed - data { startOffset, endOffset }
  835. BUFFER_FLUSHING: 'hlsBufferFlushing',
  836. // fired when the media buffer has been flushed - data: { }
  837. BUFFER_FLUSHED: 'hlsBufferFlushed',
  838. // fired to signal that a manifest loading starts - data: { url : manifestURL}
  839. MANIFEST_LOADING: 'hlsManifestLoading',
  840. // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}}
  841. MANIFEST_LOADED: 'hlsManifestLoaded',
  842. // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}
  843. MANIFEST_PARSED: 'hlsManifestParsed',
  844. // fired when a level switch is requested - data: { level : id of new level }
  845. LEVEL_SWITCHING: 'hlsLevelSwitching',
  846. // fired when a level switch is effective - data: { level : id of new level }
  847. LEVEL_SWITCHED: 'hlsLevelSwitched',
  848. // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}
  849. LEVEL_LOADING: 'hlsLevelLoading',
  850. // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }
  851. LEVEL_LOADED: 'hlsLevelLoaded',
  852. // 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 }
  853. LEVEL_UPDATED: 'hlsLevelUpdated',
  854. // 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 }
  855. LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',
  856. // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }
  857. AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated',
  858. // fired when an audio track switching is requested - data: { id : audio track id }
  859. AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching',
  860. // fired when an audio track switch actually occurs - data: { id : audio track id }
  861. AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched',
  862. // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }
  863. AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading',
  864. // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } }
  865. AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded',
  866. // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }
  867. SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated',
  868. // fired when an subtitle track switch occurs - data: { id : subtitle track id }
  869. SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch',
  870. // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }
  871. SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading',
  872. // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } }
  873. SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded',
  874. // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }
  875. SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed',
  876. // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object }
  877. INIT_PTS_FOUND: 'hlsInitPtsFound',
  878. // fired when a fragment loading starts - data: { frag : fragment object }
  879. FRAG_LOADING: 'hlsFragLoading',
  880. // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }
  881. FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',
  882. // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }
  883. FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',
  884. // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } }
  885. FRAG_LOADED: 'hlsFragLoaded',
  886. // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }
  887. FRAG_DECRYPTED: 'hlsFragDecrypted',
  888. // 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 }
  889. FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',
  890. // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }
  891. FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',
  892. // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }
  893. FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',
  894. // 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}
  895. FRAG_PARSING_DATA: 'hlsFragParsingData',
  896. // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }
  897. FRAG_PARSED: 'hlsFragParsed',
  898. // 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 } }
  899. FRAG_BUFFERED: 'hlsFragBuffered',
  900. // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }
  901. FRAG_CHANGED: 'hlsFragChanged',
  902. // Identifier for a FPS drop event - data: { curentDropped, currentDecoded, totalDroppedFrames }
  903. FPS_DROP: 'hlsFpsDrop',
  904. // triggered when FPS drop triggers auto level capping - data: { level, droppedlevel }
  905. FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',
  906. // 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 }
  907. ERROR: 'hlsError',
  908. // 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: { }
  909. DESTROYING: 'hlsDestroying',
  910. // fired when a decrypt key loading starts - data: { frag : fragment object }
  911. KEY_LOADING: 'hlsKeyLoading',
  912. // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length } }
  913. KEY_LOADED: 'hlsKeyLoaded',
  914. // fired upon stream controller state transitions - data: { previousState, nextState }
  915. STREAM_STATE_TRANSITION: 'hlsStreamStateTransition'
  916. };
  917. exports.default = HlsEvents;
  918. module.exports = exports['default'];
  919. /***/ }),
  920. /* 2 */
  921. /***/ (function(module, exports, __webpack_require__) {
  922. "use strict";
  923. Object.defineProperty(exports, "__esModule", {
  924. value: true
  925. });
  926. var ErrorTypes = exports.ErrorTypes = {
  927. // Identifier for a network error (loading error / timeout ...)
  928. NETWORK_ERROR: 'networkError',
  929. // Identifier for a media Error (video/parsing/mediasource error)
  930. MEDIA_ERROR: 'mediaError',
  931. // EME (encrypted media extensions) errors
  932. KEY_SYSTEM_ERROR: 'keySystemError',
  933. // Identifier for a mux Error (demuxing/remuxing)
  934. MUX_ERROR: 'muxError',
  935. // Identifier for all other errors
  936. OTHER_ERROR: 'otherError'
  937. };
  938. /**
  939. * @enum {ErrorDetails}
  940. * @typedef {string} ErrorDetail
  941. */
  942. var ErrorDetails = exports.ErrorDetails = {
  943. KEY_SYSTEM_NO_KEYS: 'keySystemNoKeys',
  944. KEY_SYSTEM_NO_ACCESS: 'keySystemNoAccess',
  945. KEY_SYSTEM_NO_SESSION: 'keySystemNoSession',
  946. KEY_SYSTEM_LICENSE_REQUEST_FAILED: 'keySystemLicenseRequestFailed',
  947. // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  948. MANIFEST_LOAD_ERROR: 'manifestLoadError',
  949. // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  950. MANIFEST_LOAD_TIMEOUT: 'manifestLoadTimeOut',
  951. // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}
  952. MANIFEST_PARSING_ERROR: 'manifestParsingError',
  953. // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}
  954. MANIFEST_INCOMPATIBLE_CODECS_ERROR: 'manifestIncompatibleCodecsError',
  955. // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  956. LEVEL_LOAD_ERROR: 'levelLoadError',
  957. // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  958. LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut',
  959. // Identifier for a level switch error - data: { level : faulty level Id, event : error description}
  960. LEVEL_SWITCH_ERROR: 'levelSwitchError',
  961. // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  962. AUDIO_TRACK_LOAD_ERROR: 'audioTrackLoadError',
  963. // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  964. AUDIO_TRACK_LOAD_TIMEOUT: 'audioTrackLoadTimeOut',
  965. // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  966. FRAG_LOAD_ERROR: 'fragLoadError',
  967. // Identifier for fragment load timeout error - data: { frag : fragment object}
  968. FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut',
  969. // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }
  970. FRAG_DECRYPT_ERROR: 'fragDecryptError',
  971. // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }
  972. // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release
  973. FRAG_PARSING_ERROR: 'fragParsingError',
  974. // 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 }
  975. REMUX_ALLOC_ERROR: 'remuxAllocError',
  976. // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  977. KEY_LOAD_ERROR: 'keyLoadError',
  978. // Identifier for decrypt key load timeout error - data: { frag : fragment object}
  979. KEY_LOAD_TIMEOUT: 'keyLoadTimeOut',
  980. // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { err : exception , mimeType : mimeType }
  981. BUFFER_ADD_CODEC_ERROR: 'bufferAddCodecError',
  982. // Identifier for a buffer append error - data: append error description
  983. BUFFER_APPEND_ERROR: 'bufferAppendError',
  984. // Identifier for a buffer appending error event - data: appending error description
  985. BUFFER_APPENDING_ERROR: 'bufferAppendingError',
  986. // Identifier for a buffer stalled error event
  987. BUFFER_STALLED_ERROR: 'bufferStalledError',
  988. // Identifier for a buffer full event
  989. BUFFER_FULL_ERROR: 'bufferFullError',
  990. // Identifier for a buffer seek over hole event
  991. BUFFER_SEEK_OVER_HOLE: 'bufferSeekOverHole',
  992. // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)
  993. BUFFER_NUDGE_ON_STALL: 'bufferNudgeOnStall',
  994. // Identifier for an internal exception happening inside hls.js while handling an event
  995. INTERNAL_EXCEPTION: 'internalException'
  996. };
  997. /***/ }),
  998. /* 3 */
  999. /***/ (function(module, exports, __webpack_require__) {
  1000. "use strict";
  1001. Object.defineProperty(exports, "__esModule", {
  1002. value: true
  1003. });
  1004. 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; };
  1005. 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; }; }(); /*
  1006. *
  1007. * All objects in the event handling chain should inherit from this class
  1008. *
  1009. */
  1010. var _logger = __webpack_require__(0);
  1011. var _errors = __webpack_require__(2);
  1012. var _events = __webpack_require__(1);
  1013. var _events2 = _interopRequireDefault(_events);
  1014. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1015. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1016. var FORBIDDEN_EVENT_NAMES = {
  1017. 'hlsEventGeneric': true,
  1018. 'hlsHandlerDestroying': true,
  1019. 'hlsHandlerDestroyed': true
  1020. };
  1021. var EventHandler = function () {
  1022. function EventHandler(hls) {
  1023. _classCallCheck(this, EventHandler);
  1024. this.hls = hls;
  1025. this.onEvent = this.onEvent.bind(this);
  1026. for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  1027. events[_key - 1] = arguments[_key];
  1028. }
  1029. this.handledEvents = events;
  1030. this.useGenericHandler = true;
  1031. this.registerListeners();
  1032. }
  1033. _createClass(EventHandler, [{
  1034. key: 'destroy',
  1035. value: function destroy() {
  1036. this.onHandlerDestroying();
  1037. this.unregisterListeners();
  1038. this.onHandlerDestroyed();
  1039. }
  1040. }, {
  1041. key: 'onHandlerDestroying',
  1042. value: function onHandlerDestroying() {}
  1043. }, {
  1044. key: 'onHandlerDestroyed',
  1045. value: function onHandlerDestroyed() {}
  1046. }, {
  1047. key: 'isEventHandler',
  1048. value: function isEventHandler() {
  1049. return _typeof(this.handledEvents) === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';
  1050. }
  1051. }, {
  1052. key: 'registerListeners',
  1053. value: function registerListeners() {
  1054. if (this.isEventHandler()) {
  1055. this.handledEvents.forEach(function (event) {
  1056. if (FORBIDDEN_EVENT_NAMES[event]) {
  1057. throw new Error('Forbidden event-name: ' + event);
  1058. }
  1059. this.hls.on(event, this.onEvent);
  1060. }, this);
  1061. }
  1062. }
  1063. }, {
  1064. key: 'unregisterListeners',
  1065. value: function unregisterListeners() {
  1066. if (this.isEventHandler()) {
  1067. this.handledEvents.forEach(function (event) {
  1068. this.hls.off(event, this.onEvent);
  1069. }, this);
  1070. }
  1071. }
  1072. /**
  1073. * arguments: event (string), data (any)
  1074. */
  1075. }, {
  1076. key: 'onEvent',
  1077. value: function onEvent(event, data) {
  1078. this.onEventGeneric(event, data);
  1079. }
  1080. }, {
  1081. key: 'onEventGeneric',
  1082. value: function onEventGeneric(event, data) {
  1083. var eventToFunction = function eventToFunction(event, data) {
  1084. var funcName = 'on' + event.replace('hls', '');
  1085. if (typeof this[funcName] !== 'function') {
  1086. throw new Error('Event ' + event + ' has no generic handler in this ' + this.constructor.name + ' class (tried ' + funcName + ')');
  1087. }
  1088. return this[funcName].bind(this, data);
  1089. };
  1090. try {
  1091. eventToFunction.call(this, event, data).call();
  1092. } catch (err) {
  1093. _logger.logger.error('An internal error happened while handling event ' + event + '. Error message: "' + err.message + '". Here is a stacktrace:', err);
  1094. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.INTERNAL_EXCEPTION, fatal: false, event: event, err: err });
  1095. }
  1096. }
  1097. }]);
  1098. return EventHandler;
  1099. }();
  1100. exports.default = EventHandler;
  1101. module.exports = exports['default'];
  1102. /***/ }),
  1103. /* 4 */
  1104. /***/ (function(module, exports, __webpack_require__) {
  1105. "use strict";
  1106. Object.defineProperty(exports, "__esModule", {
  1107. value: true
  1108. });
  1109. 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; }; }();
  1110. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1111. /**
  1112. * @module BufferHelper
  1113. *
  1114. * Providing methods dealing with buffer length retrieval for example.
  1115. *
  1116. * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
  1117. *
  1118. * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
  1119. */
  1120. var BufferHelper = exports.BufferHelper = function () {
  1121. function BufferHelper() {
  1122. _classCallCheck(this, BufferHelper);
  1123. }
  1124. _createClass(BufferHelper, null, [{
  1125. key: "isBuffered",
  1126. /**
  1127. * Return true if `media`'s buffered include `position`
  1128. * @param {HTMLMediaElement|SourceBuffer} media
  1129. * @param {number} position
  1130. * @returns {boolean}
  1131. */
  1132. value: function isBuffered(media, position) {
  1133. try {
  1134. if (media) {
  1135. var buffered = media.buffered;
  1136. for (var i = 0; i < buffered.length; i++) {
  1137. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  1138. return true;
  1139. }
  1140. }
  1141. }
  1142. } catch (error) {
  1143. // this is to catch
  1144. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  1145. // This SourceBuffer has been removed from the parent media source
  1146. }
  1147. return false;
  1148. }
  1149. }, {
  1150. key: "bufferInfo",
  1151. value: function bufferInfo(media, pos, maxHoleDuration) {
  1152. try {
  1153. if (media) {
  1154. var vbuffered = media.buffered,
  1155. buffered = [],
  1156. i = void 0;
  1157. for (i = 0; i < vbuffered.length; i++) {
  1158. buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) });
  1159. }
  1160. return this.bufferedInfo(buffered, pos, maxHoleDuration);
  1161. }
  1162. } catch (error) {
  1163. // this is to catch
  1164. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  1165. // This SourceBuffer has been removed from the parent media source
  1166. }
  1167. return { len: 0, start: pos, end: pos, nextStart: undefined };
  1168. }
  1169. }, {
  1170. key: "bufferedInfo",
  1171. value: function bufferedInfo(buffered, pos, maxHoleDuration) {
  1172. var buffered2 = [],
  1173. // bufferStart and bufferEnd are buffer boundaries around current video position
  1174. bufferLen = void 0,
  1175. bufferStart = void 0,
  1176. bufferEnd = void 0,
  1177. bufferStartNext = void 0,
  1178. i = void 0;
  1179. // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
  1180. buffered.sort(function (a, b) {
  1181. var diff = a.start - b.start;
  1182. if (diff) {
  1183. return diff;
  1184. } else {
  1185. return b.end - a.end;
  1186. }
  1187. });
  1188. // there might be some small holes between buffer time range
  1189. // consider that holes smaller than maxHoleDuration are irrelevant and build another
  1190. // buffer time range representations that discards those holes
  1191. for (i = 0; i < buffered.length; i++) {
  1192. var buf2len = buffered2.length;
  1193. if (buf2len) {
  1194. var buf2end = buffered2[buf2len - 1].end;
  1195. // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
  1196. if (buffered[i].start - buf2end < maxHoleDuration) {
  1197. // merge overlapping time ranges
  1198. // update lastRange.end only if smaller than item.end
  1199. // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
  1200. // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
  1201. if (buffered[i].end > buf2end) {
  1202. buffered2[buf2len - 1].end = buffered[i].end;
  1203. }
  1204. } else {
  1205. // big hole
  1206. buffered2.push(buffered[i]);
  1207. }
  1208. } else {
  1209. // first value
  1210. buffered2.push(buffered[i]);
  1211. }
  1212. }
  1213. for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) {
  1214. var start = buffered2[i].start,
  1215. end = buffered2[i].end;
  1216. // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
  1217. if (pos + maxHoleDuration >= start && pos < end) {
  1218. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  1219. bufferStart = start;
  1220. bufferEnd = end;
  1221. bufferLen = bufferEnd - pos;
  1222. } else if (pos + maxHoleDuration < start) {
  1223. bufferStartNext = start;
  1224. break;
  1225. }
  1226. }
  1227. return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext };
  1228. }
  1229. }]);
  1230. return BufferHelper;
  1231. }();
  1232. /***/ }),
  1233. /* 5 */
  1234. /***/ (function(module, exports, __webpack_require__) {
  1235. "use strict";
  1236. Object.defineProperty(exports, "__esModule", {
  1237. value: true
  1238. });
  1239. exports.getSelfScope = getSelfScope;
  1240. function getSelfScope() {
  1241. // see https://stackoverflow.com/a/11237259/589493
  1242. if (typeof window === 'undefined') {
  1243. /* eslint-disable-next-line no-undef */
  1244. return self;
  1245. } else {
  1246. return window;
  1247. }
  1248. }
  1249. /***/ }),
  1250. /* 6 */
  1251. /***/ (function(module, exports, __webpack_require__) {
  1252. "use strict";
  1253. Object.defineProperty(exports, "__esModule", {
  1254. value: true
  1255. });
  1256. exports.FragmentTracker = exports.FragmentState = undefined;
  1257. 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; }; }();
  1258. 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); } };
  1259. var _eventHandler = __webpack_require__(3);
  1260. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  1261. var _events = __webpack_require__(1);
  1262. var _events2 = _interopRequireDefault(_events);
  1263. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1264. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1265. 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; }
  1266. 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; }
  1267. var FragmentState = exports.FragmentState = {
  1268. NOT_LOADED: 'NOT_LOADED',
  1269. APPENDING: 'APPENDING',
  1270. PARTIAL: 'PARTIAL',
  1271. OK: 'OK'
  1272. };
  1273. var FragmentTracker = exports.FragmentTracker = function (_EventHandler) {
  1274. _inherits(FragmentTracker, _EventHandler);
  1275. function FragmentTracker(hls) {
  1276. _classCallCheck(this, FragmentTracker);
  1277. var _this = _possibleConstructorReturn(this, (FragmentTracker.__proto__ || Object.getPrototypeOf(FragmentTracker)).call(this, hls, _events2.default.BUFFER_APPENDED, _events2.default.FRAG_BUFFERED, _events2.default.FRAG_LOADED));
  1278. _this.bufferPadding = 0.2;
  1279. _this.fragments = Object.create(null);
  1280. _this.timeRanges = Object.create(null);
  1281. _this.config = hls.config;
  1282. return _this;
  1283. }
  1284. _createClass(FragmentTracker, [{
  1285. key: 'destroy',
  1286. value: function destroy() {
  1287. this.fragments = Object.create(null);
  1288. this.timeRanges = Object.create(null);
  1289. this.config = null;
  1290. _eventHandler2.default.prototype.destroy.call(this);
  1291. _get(FragmentTracker.prototype.__proto__ || Object.getPrototypeOf(FragmentTracker.prototype), 'destroy', this).call(this);
  1292. }
  1293. /**
  1294. * Return a Fragment that match the position and levelType.
  1295. * If not found any Fragment, return null
  1296. * @param {number} position
  1297. * @param {LevelType} levelType
  1298. * @returns {Fragment|null}
  1299. */
  1300. }, {
  1301. key: 'getBufferedFrag',
  1302. value: function getBufferedFrag(position, levelType) {
  1303. var fragments = this.fragments;
  1304. var bufferedFrags = Object.keys(fragments).filter(function (key) {
  1305. var fragmentEntity = fragments[key];
  1306. if (fragmentEntity.body.type !== levelType) {
  1307. return false;
  1308. }
  1309. if (!fragmentEntity.buffered) {
  1310. return false;
  1311. }
  1312. var frag = fragmentEntity.body;
  1313. return frag.startPTS <= position && position <= frag.endPTS;
  1314. });
  1315. if (bufferedFrags.length === 0) {
  1316. return null;
  1317. } else {
  1318. // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566
  1319. var bufferedFragKey = bufferedFrags.pop();
  1320. return fragments[bufferedFragKey].body;
  1321. }
  1322. }
  1323. /**
  1324. * Partial fragments effected by coded frame eviction will be removed
  1325. * The browser will unload parts of the buffer to free up memory for new buffer data
  1326. * 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)
  1327. * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)
  1328. * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer
  1329. */
  1330. }, {
  1331. key: 'detectEvictedFragments',
  1332. value: function detectEvictedFragments(elementaryStream, timeRange) {
  1333. var _this2 = this;
  1334. var fragmentTimes = void 0,
  1335. time = void 0;
  1336. // Check if any flagged fragments have been unloaded
  1337. Object.keys(this.fragments).forEach(function (key) {
  1338. var fragmentEntity = _this2.fragments[key];
  1339. if (fragmentEntity.buffered === true) {
  1340. var esData = fragmentEntity.range[elementaryStream];
  1341. if (esData) {
  1342. fragmentTimes = esData.time;
  1343. for (var i = 0; i < fragmentTimes.length; i++) {
  1344. time = fragmentTimes[i];
  1345. if (_this2.isTimeBuffered(time.startPTS, time.endPTS, timeRange) === false) {
  1346. // Unregister partial fragment as it needs to load again to be reused
  1347. _this2.removeFragment(fragmentEntity.body);
  1348. break;
  1349. }
  1350. }
  1351. }
  1352. }
  1353. });
  1354. }
  1355. /**
  1356. * Checks if the fragment passed in is loaded in the buffer properly
  1357. * Partially loaded fragments will be registered as a partial fragment
  1358. * @param {Object} fragment Check the fragment against all sourceBuffers loaded
  1359. */
  1360. }, {
  1361. key: 'detectPartialFragments',
  1362. value: function detectPartialFragments(fragment) {
  1363. var _this3 = this;
  1364. var fragKey = this.getFragmentKey(fragment);
  1365. var fragmentEntity = this.fragments[fragKey];
  1366. if (fragmentEntity) {
  1367. fragmentEntity.buffered = true;
  1368. Object.keys(this.timeRanges).forEach(function (elementaryStream) {
  1369. if (fragment.hasElementaryStream(elementaryStream)) {
  1370. var timeRange = _this3.timeRanges[elementaryStream];
  1371. // Check for malformed fragments
  1372. // Gaps need to be calculated for each elementaryStream
  1373. fragmentEntity.range[elementaryStream] = _this3.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);
  1374. }
  1375. });
  1376. }
  1377. }
  1378. }, {
  1379. key: 'getBufferedTimes',
  1380. value: function getBufferedTimes(startPTS, endPTS, timeRange) {
  1381. var fragmentTimes = [];
  1382. var startTime = void 0,
  1383. endTime = void 0;
  1384. var fragmentPartial = false;
  1385. for (var i = 0; i < timeRange.length; i++) {
  1386. startTime = timeRange.start(i) - this.bufferPadding;
  1387. endTime = timeRange.end(i) + this.bufferPadding;
  1388. if (startPTS >= startTime && endPTS <= endTime) {
  1389. // Fragment is entirely contained in buffer
  1390. // No need to check the other timeRange times since it's completely playable
  1391. fragmentTimes.push({
  1392. startPTS: Math.max(startPTS, timeRange.start(i)),
  1393. endPTS: Math.min(endPTS, timeRange.end(i))
  1394. });
  1395. break;
  1396. } else if (startPTS < endTime && endPTS > startTime) {
  1397. // Check for intersection with buffer
  1398. // Get playable sections of the fragment
  1399. fragmentTimes.push({
  1400. startPTS: Math.max(startPTS, timeRange.start(i)),
  1401. endPTS: Math.min(endPTS, timeRange.end(i))
  1402. });
  1403. fragmentPartial = true;
  1404. } else if (endPTS <= startTime) {
  1405. // No need to check the rest of the timeRange as it is in order
  1406. break;
  1407. }
  1408. }
  1409. return {
  1410. time: fragmentTimes,
  1411. partial: fragmentPartial
  1412. };
  1413. }
  1414. }, {
  1415. key: 'getFragmentKey',
  1416. value: function getFragmentKey(fragment) {
  1417. return fragment.type + '_' + fragment.level + '_' + fragment.urlId + '_' + fragment.sn;
  1418. }
  1419. /**
  1420. * Gets the partial fragment for a certain time
  1421. * @param {Number} time
  1422. * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment
  1423. */
  1424. }, {
  1425. key: 'getPartialFragment',
  1426. value: function getPartialFragment(time) {
  1427. var _this4 = this;
  1428. var timePadding = void 0,
  1429. startTime = void 0,
  1430. endTime = void 0;
  1431. var bestFragment = null;
  1432. var bestOverlap = 0;
  1433. Object.keys(this.fragments).forEach(function (key) {
  1434. var fragmentEntity = _this4.fragments[key];
  1435. if (_this4.isPartial(fragmentEntity)) {
  1436. startTime = fragmentEntity.body.startPTS - _this4.bufferPadding;
  1437. endTime = fragmentEntity.body.endPTS + _this4.bufferPadding;
  1438. if (time >= startTime && time <= endTime) {
  1439. // Use the fragment that has the most padding from start and end time
  1440. timePadding = Math.min(time - startTime, endTime - time);
  1441. if (bestOverlap <= timePadding) {
  1442. bestFragment = fragmentEntity.body;
  1443. bestOverlap = timePadding;
  1444. }
  1445. }
  1446. }
  1447. });
  1448. return bestFragment;
  1449. }
  1450. /**
  1451. * @param {Object} fragment The fragment to check
  1452. * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded
  1453. */
  1454. }, {
  1455. key: 'getState',
  1456. value: function getState(fragment) {
  1457. var fragKey = this.getFragmentKey(fragment);
  1458. var fragmentEntity = this.fragments[fragKey];
  1459. var state = FragmentState.NOT_LOADED;
  1460. if (fragmentEntity !== undefined) {
  1461. if (!fragmentEntity.buffered) {
  1462. state = FragmentState.APPENDING;
  1463. } else if (this.isPartial(fragmentEntity) === true) {
  1464. state = FragmentState.PARTIAL;
  1465. } else {
  1466. state = FragmentState.OK;
  1467. }
  1468. }
  1469. return state;
  1470. }
  1471. }, {
  1472. key: 'isPartial',
  1473. value: function isPartial(fragmentEntity) {
  1474. return fragmentEntity.buffered === true && (fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true || fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true);
  1475. }
  1476. }, {
  1477. key: 'isTimeBuffered',
  1478. value: function isTimeBuffered(startPTS, endPTS, timeRange) {
  1479. var startTime = void 0,
  1480. endTime = void 0;
  1481. for (var i = 0; i < timeRange.length; i++) {
  1482. startTime = timeRange.start(i) - this.bufferPadding;
  1483. endTime = timeRange.end(i) + this.bufferPadding;
  1484. if (startPTS >= startTime && endPTS <= endTime) {
  1485. return true;
  1486. }
  1487. if (endPTS <= startTime) {
  1488. // No need to check the rest of the timeRange as it is in order
  1489. return false;
  1490. }
  1491. }
  1492. return false;
  1493. }
  1494. /**
  1495. * Fires when a fragment loading is completed
  1496. */
  1497. }, {
  1498. key: 'onFragLoaded',
  1499. value: function onFragLoaded(e) {
  1500. var fragment = e.frag;
  1501. // don't track initsegment (for which sn is not a number)
  1502. // don't track frags used for bitrateTest, they're irrelevant.
  1503. if (!Number.isFinite(fragment.sn) || fragment.bitrateTest) {
  1504. return;
  1505. }
  1506. this.fragments[this.getFragmentKey(fragment)] = {
  1507. body: fragment,
  1508. range: Object.create(null),
  1509. buffered: false
  1510. };
  1511. }
  1512. /**
  1513. * Fires when the buffer is updated
  1514. */
  1515. }, {
  1516. key: 'onBufferAppended',
  1517. value: function onBufferAppended(e) {
  1518. var _this5 = this;
  1519. // Store the latest timeRanges loaded in the buffer
  1520. this.timeRanges = e.timeRanges;
  1521. Object.keys(this.timeRanges).forEach(function (elementaryStream) {
  1522. var timeRange = _this5.timeRanges[elementaryStream];
  1523. _this5.detectEvictedFragments(elementaryStream, timeRange);
  1524. });
  1525. }
  1526. /**
  1527. * Fires after a fragment has been loaded into the source buffer
  1528. */
  1529. }, {
  1530. key: 'onFragBuffered',
  1531. value: function onFragBuffered(e) {
  1532. this.detectPartialFragments(e.frag);
  1533. }
  1534. /**
  1535. * Return true if fragment tracker has the fragment.
  1536. * @param {Object} fragment
  1537. * @returns {boolean}
  1538. */
  1539. }, {
  1540. key: 'hasFragment',
  1541. value: function hasFragment(fragment) {
  1542. var fragKey = this.getFragmentKey(fragment);
  1543. return this.fragments[fragKey] !== undefined;
  1544. }
  1545. /**
  1546. * Remove a fragment from fragment tracker until it is loaded again
  1547. * @param {Object} fragment The fragment to remove
  1548. */
  1549. }, {
  1550. key: 'removeFragment',
  1551. value: function removeFragment(fragment) {
  1552. var fragKey = this.getFragmentKey(fragment);
  1553. delete this.fragments[fragKey];
  1554. }
  1555. /**
  1556. * Remove all fragments from fragment tracker.
  1557. */
  1558. }, {
  1559. key: 'removeAllFragments',
  1560. value: function removeAllFragments() {
  1561. this.fragments = Object.create(null);
  1562. }
  1563. }]);
  1564. return FragmentTracker;
  1565. }(_eventHandler2.default);
  1566. /***/ }),
  1567. /* 7 */
  1568. /***/ (function(module, exports, __webpack_require__) {
  1569. "use strict";
  1570. Object.defineProperty(exports, "__esModule", {
  1571. value: true
  1572. });
  1573. exports.addGroupId = addGroupId;
  1574. exports.updatePTS = updatePTS;
  1575. exports.updateFragPTSDTS = updateFragPTSDTS;
  1576. exports.mergeDetails = mergeDetails;
  1577. exports.mergeSubtitlePlaylists = mergeSubtitlePlaylists;
  1578. exports.mapFragmentIntersection = mapFragmentIntersection;
  1579. exports.adjustSliding = adjustSliding;
  1580. exports.computeReloadInterval = computeReloadInterval;
  1581. var _logger = __webpack_require__(0);
  1582. function addGroupId(level, type, id) {
  1583. switch (type) {
  1584. case 'audio':
  1585. if (!level.audioGroupIds) {
  1586. level.audioGroupIds = [];
  1587. }
  1588. level.audioGroupIds.push(id);
  1589. break;
  1590. case 'text':
  1591. if (!level.textGroupIds) {
  1592. level.textGroupIds = [];
  1593. }
  1594. level.textGroupIds.push(id);
  1595. break;
  1596. }
  1597. } /**
  1598. * @module LevelHelper
  1599. *
  1600. * Providing methods dealing with playlist sliding and drift
  1601. *
  1602. * TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner.
  1603. *
  1604. * */
  1605. function updatePTS(fragments, fromIdx, toIdx) {
  1606. var fragFrom = fragments[fromIdx],
  1607. fragTo = fragments[toIdx],
  1608. fragToPTS = fragTo.startPTS;
  1609. // if we know startPTS[toIdx]
  1610. if (Number.isFinite(fragToPTS)) {
  1611. // update fragment duration.
  1612. // it helps to fix drifts between playlist reported duration and fragment real duration
  1613. if (toIdx > fromIdx) {
  1614. fragFrom.duration = fragToPTS - fragFrom.start;
  1615. if (fragFrom.duration < 0) {
  1616. _logger.logger.warn('negative duration computed for frag ' + fragFrom.sn + ',level ' + fragFrom.level + ', there should be some duration drift between playlist and fragment!');
  1617. }
  1618. } else {
  1619. fragTo.duration = fragFrom.start - fragToPTS;
  1620. if (fragTo.duration < 0) {
  1621. _logger.logger.warn('negative duration computed for frag ' + fragTo.sn + ',level ' + fragTo.level + ', there should be some duration drift between playlist and fragment!');
  1622. }
  1623. }
  1624. } else {
  1625. // we dont know startPTS[toIdx]
  1626. if (toIdx > fromIdx) {
  1627. fragTo.start = fragFrom.start + fragFrom.duration;
  1628. } else {
  1629. fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
  1630. }
  1631. }
  1632. }
  1633. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  1634. // update frag PTS/DTS
  1635. var maxStartPTS = startPTS;
  1636. if (Number.isFinite(frag.startPTS)) {
  1637. // delta PTS between audio and video
  1638. var deltaPTS = Math.abs(frag.startPTS - startPTS);
  1639. if (!Number.isFinite(frag.deltaPTS)) {
  1640. frag.deltaPTS = deltaPTS;
  1641. } else {
  1642. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  1643. }
  1644. maxStartPTS = Math.max(startPTS, frag.startPTS);
  1645. startPTS = Math.min(startPTS, frag.startPTS);
  1646. endPTS = Math.max(endPTS, frag.endPTS);
  1647. startDTS = Math.min(startDTS, frag.startDTS);
  1648. endDTS = Math.max(endDTS, frag.endDTS);
  1649. }
  1650. var drift = startPTS - frag.start;
  1651. frag.start = frag.startPTS = startPTS;
  1652. frag.maxStartPTS = maxStartPTS;
  1653. frag.endPTS = endPTS;
  1654. frag.startDTS = startDTS;
  1655. frag.endDTS = endDTS;
  1656. frag.duration = endPTS - startPTS;
  1657. var sn = frag.sn;
  1658. // exit if sn out of range
  1659. if (!details || sn < details.startSN || sn > details.endSN) {
  1660. return 0;
  1661. }
  1662. var fragIdx = void 0,
  1663. fragments = void 0,
  1664. i = void 0;
  1665. fragIdx = sn - details.startSN;
  1666. fragments = details.fragments;
  1667. // update frag reference in fragments array
  1668. // rationale is that fragments array might not contain this frag object.
  1669. // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
  1670. // if we don't update frag, we won't be able to propagate PTS info on the playlist
  1671. // resulting in invalid sliding computation
  1672. fragments[fragIdx] = frag;
  1673. // adjust fragment PTS/duration from seqnum-1 to frag 0
  1674. for (i = fragIdx; i > 0; i--) {
  1675. updatePTS(fragments, i, i - 1);
  1676. }
  1677. // adjust fragment PTS/duration from seqnum to last frag
  1678. for (i = fragIdx; i < fragments.length - 1; i++) {
  1679. updatePTS(fragments, i, i + 1);
  1680. }
  1681. details.PTSKnown = true;
  1682. return drift;
  1683. }
  1684. function mergeDetails(oldDetails, newDetails) {
  1685. // potentially retrieve cached initsegment
  1686. if (newDetails.initSegment && oldDetails.initSegment) {
  1687. newDetails.initSegment = oldDetails.initSegment;
  1688. }
  1689. // check if old/new playlists have fragments in common
  1690. // loop through overlapping SN and update startPTS , cc, and duration if any found
  1691. var ccOffset = 0;
  1692. var PTSFrag = void 0;
  1693. mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) {
  1694. ccOffset = oldFrag.cc - newFrag.cc;
  1695. if (Number.isFinite(oldFrag.startPTS)) {
  1696. newFrag.start = newFrag.startPTS = oldFrag.startPTS;
  1697. newFrag.endPTS = oldFrag.endPTS;
  1698. newFrag.duration = oldFrag.duration;
  1699. newFrag.backtracked = oldFrag.backtracked;
  1700. newFrag.dropped = oldFrag.dropped;
  1701. PTSFrag = newFrag;
  1702. }
  1703. // PTS is known when there are overlapping segments
  1704. newDetails.PTSKnown = true;
  1705. });
  1706. if (!newDetails.PTSKnown) {
  1707. return;
  1708. }
  1709. if (ccOffset) {
  1710. _logger.logger.log('discontinuity sliding from playlist, take drift into account');
  1711. var newFragments = newDetails.fragments;
  1712. for (var i = 0; i < newFragments.length; i++) {
  1713. newFragments[i].cc += ccOffset;
  1714. }
  1715. }
  1716. // if at least one fragment contains PTS info, recompute PTS information for all fragments
  1717. if (PTSFrag) {
  1718. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  1719. } else {
  1720. // ensure that delta is within oldFragments range
  1721. // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
  1722. // in that case we also need to adjust start offset of all fragments
  1723. adjustSliding(oldDetails, newDetails);
  1724. }
  1725. // if we are here, it means we have fragments overlapping between
  1726. // old and new level. reliable PTS info is thus relying on old level
  1727. newDetails.PTSKnown = oldDetails.PTSKnown;
  1728. }
  1729. function mergeSubtitlePlaylists(oldPlaylist, newPlaylist) {
  1730. var referenceStart = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  1731. var lastIndex = -1;
  1732. mapFragmentIntersection(oldPlaylist, newPlaylist, function (oldFrag, newFrag, index) {
  1733. newFrag.start = oldFrag.start;
  1734. lastIndex = index;
  1735. });
  1736. var frags = newPlaylist.fragments;
  1737. if (lastIndex < 0) {
  1738. frags.forEach(function (frag) {
  1739. frag.start += referenceStart;
  1740. });
  1741. return;
  1742. }
  1743. for (var i = lastIndex + 1; i < frags.length; i++) {
  1744. frags[i].start = frags[i - 1].start + frags[i - 1].duration;
  1745. }
  1746. }
  1747. function mapFragmentIntersection(oldPlaylist, newPlaylist, intersectionFn) {
  1748. if (!oldPlaylist || !newPlaylist) {
  1749. return;
  1750. }
  1751. var start = Math.max(oldPlaylist.startSN, newPlaylist.startSN) - newPlaylist.startSN;
  1752. var end = Math.min(oldPlaylist.endSN, newPlaylist.endSN) - newPlaylist.startSN;
  1753. var delta = newPlaylist.startSN - oldPlaylist.startSN;
  1754. for (var i = start; i <= end; i++) {
  1755. var oldFrag = oldPlaylist.fragments[delta + i];
  1756. var newFrag = newPlaylist.fragments[i];
  1757. if (!oldFrag || !newFrag) {
  1758. break;
  1759. }
  1760. intersectionFn(oldFrag, newFrag, i);
  1761. }
  1762. }
  1763. function adjustSliding(oldPlaylist, newPlaylist) {
  1764. var delta = newPlaylist.startSN - oldPlaylist.startSN;
  1765. var oldFragments = oldPlaylist.fragments;
  1766. var newFragments = newPlaylist.fragments;
  1767. if (delta < 0 || delta > oldFragments.length) {
  1768. return;
  1769. }
  1770. for (var i = 0; i < newFragments.length; i++) {
  1771. newFragments[i].start += oldFragments[delta].start;
  1772. }
  1773. }
  1774. function computeReloadInterval(currentPlaylist, newPlaylist, lastRequestTime) {
  1775. var reloadInterval = 1000 * (newPlaylist.averagetargetduration ? newPlaylist.averagetargetduration : newPlaylist.targetduration);
  1776. var minReloadInterval = reloadInterval / 2;
  1777. if (currentPlaylist && newPlaylist.endSN === currentPlaylist.endSN) {
  1778. // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
  1779. // changed then it MUST wait for a period of one-half the target
  1780. // duration before retrying.
  1781. reloadInterval = minReloadInterval;
  1782. }
  1783. if (lastRequestTime) {
  1784. reloadInterval = Math.max(minReloadInterval, reloadInterval - (window.performance.now() - lastRequestTime));
  1785. }
  1786. // in any case, don't reload more than half of target duration
  1787. return Math.round(reloadInterval);
  1788. }
  1789. /***/ }),
  1790. /* 8 */
  1791. /***/ (function(module, exports, __webpack_require__) {
  1792. // see https://tools.ietf.org/html/rfc1808
  1793. /* jshint ignore:start */
  1794. (function(root) {
  1795. /* jshint ignore:end */
  1796. var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/\?#]*\/)*.*?)??(;.*?)?(\?.*?)?(#.*?)?$/;
  1797. var FIRST_SEGMENT_REGEX = /^([^\/?#]*)(.*)$/;
  1798. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  1799. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/g;
  1800. var URLToolkit = { // jshint ignore:line
  1801. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  1802. // E.g
  1803. // With opts.alwaysNormalize = false (default, spec compliant)
  1804. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  1805. // With opts.alwaysNormalize = true (not spec compliant)
  1806. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  1807. buildAbsoluteURL: function(baseURL, relativeURL, opts) {
  1808. opts = opts || {};
  1809. // remove any remaining space and CRLF
  1810. baseURL = baseURL.trim();
  1811. relativeURL = relativeURL.trim();
  1812. if (!relativeURL) {
  1813. // 2a) If the embedded URL is entirely empty, it inherits the
  1814. // entire base URL (i.e., is set equal to the base URL)
  1815. // and we are done.
  1816. if (!opts.alwaysNormalize) {
  1817. return baseURL;
  1818. }
  1819. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  1820. if (!basePartsForNormalise) {
  1821. throw new Error('Error trying to parse base URL.');
  1822. }
  1823. basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
  1824. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  1825. }
  1826. var relativeParts = URLToolkit.parseURL(relativeURL);
  1827. if (!relativeParts) {
  1828. throw new Error('Error trying to parse relative URL.');
  1829. }
  1830. if (relativeParts.scheme) {
  1831. // 2b) If the embedded URL starts with a scheme name, it is
  1832. // interpreted as an absolute URL and we are done.
  1833. if (!opts.alwaysNormalize) {
  1834. return relativeURL;
  1835. }
  1836. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  1837. return URLToolkit.buildURLFromParts(relativeParts);
  1838. }
  1839. var baseParts = URLToolkit.parseURL(baseURL);
  1840. if (!baseParts) {
  1841. throw new Error('Error trying to parse base URL.');
  1842. }
  1843. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  1844. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  1845. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  1846. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  1847. baseParts.netLoc = pathParts[1];
  1848. baseParts.path = pathParts[2];
  1849. }
  1850. if (baseParts.netLoc && !baseParts.path) {
  1851. baseParts.path = '/';
  1852. }
  1853. var builtParts = {
  1854. // 2c) Otherwise, the embedded URL inherits the scheme of
  1855. // the base URL.
  1856. scheme: baseParts.scheme,
  1857. netLoc: relativeParts.netLoc,
  1858. path: null,
  1859. params: relativeParts.params,
  1860. query: relativeParts.query,
  1861. fragment: relativeParts.fragment
  1862. };
  1863. if (!relativeParts.netLoc) {
  1864. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  1865. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  1866. // (if any) of the base URL.
  1867. builtParts.netLoc = baseParts.netLoc;
  1868. // 4) If the embedded URL path is preceded by a slash "/", the
  1869. // path is not relative and we skip to Step 7.
  1870. if (relativeParts.path[0] !== '/') {
  1871. if (!relativeParts.path) {
  1872. // 5) If the embedded URL path is empty (and not preceded by a
  1873. // slash), then the embedded URL inherits the base URL path
  1874. builtParts.path = baseParts.path;
  1875. // 5a) if the embedded URL's <params> is non-empty, we skip to
  1876. // step 7; otherwise, it inherits the <params> of the base
  1877. // URL (if any) and
  1878. if (!relativeParts.params) {
  1879. builtParts.params = baseParts.params;
  1880. // 5b) if the embedded URL's <query> is non-empty, we skip to
  1881. // step 7; otherwise, it inherits the <query> of the base
  1882. // URL (if any) and we skip to step 7.
  1883. if (!relativeParts.query) {
  1884. builtParts.query = baseParts.query;
  1885. }
  1886. }
  1887. } else {
  1888. // 6) The last segment of the base URL's path (anything
  1889. // following the rightmost slash "/", or the entire path if no
  1890. // slash is present) is removed and the embedded URL's path is
  1891. // appended in its place.
  1892. var baseURLPath = baseParts.path;
  1893. var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;
  1894. builtParts.path = URLToolkit.normalizePath(newPath);
  1895. }
  1896. }
  1897. }
  1898. if (builtParts.path === null) {
  1899. builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
  1900. }
  1901. return URLToolkit.buildURLFromParts(builtParts);
  1902. },
  1903. parseURL: function(url) {
  1904. var parts = URL_REGEX.exec(url);
  1905. if (!parts) {
  1906. return null;
  1907. }
  1908. return {
  1909. scheme: parts[1] || '',
  1910. netLoc: parts[2] || '',
  1911. path: parts[3] || '',
  1912. params: parts[4] || '',
  1913. query: parts[5] || '',
  1914. fragment: parts[6] || ''
  1915. };
  1916. },
  1917. normalizePath: function(path) {
  1918. // The following operations are
  1919. // then applied, in order, to the new path:
  1920. // 6a) All occurrences of "./", where "." is a complete path
  1921. // segment, are removed.
  1922. // 6b) If the path ends with "." as a complete path segment,
  1923. // that "." is removed.
  1924. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
  1925. // 6c) All occurrences of "<segment>/../", where <segment> is a
  1926. // complete path segment not equal to "..", are removed.
  1927. // Removal of these path segments is performed iteratively,
  1928. // removing the leftmost matching pattern on each iteration,
  1929. // until no matching pattern remains.
  1930. // 6d) If the path ends with "<segment>/..", where <segment> is a
  1931. // complete path segment not equal to "..", that
  1932. // "<segment>/.." is removed.
  1933. while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {} // jshint ignore:line
  1934. return path.split('').reverse().join('');
  1935. },
  1936. buildURLFromParts: function(parts) {
  1937. return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
  1938. }
  1939. };
  1940. /* jshint ignore:start */
  1941. if(true)
  1942. module.exports = URLToolkit;
  1943. else {}
  1944. })(this);
  1945. /* jshint ignore:end */
  1946. /***/ }),
  1947. /* 9 */
  1948. /***/ (function(module, exports, __webpack_require__) {
  1949. "use strict";
  1950. Object.defineProperty(exports, "__esModule", {
  1951. value: true
  1952. });
  1953. var BinarySearch = {
  1954. /**
  1955. * Searches for an item in an array which matches a certain condition.
  1956. * This requires the condition to only match one item in the array,
  1957. * and for the array to be ordered.
  1958. *
  1959. * @param {Array} list The array to search.
  1960. * @param {Function} comparisonFunction
  1961. * Called and provided a candidate item as the first argument.
  1962. * Should return:
  1963. * > -1 if the item should be located at a lower index than the provided item.
  1964. * > 1 if the item should be located at a higher index than the provided item.
  1965. * > 0 if the item is the item you're looking for.
  1966. *
  1967. * @return {*} The object if it is found or null otherwise.
  1968. */
  1969. search: function search(list, comparisonFunction) {
  1970. var minIndex = 0;
  1971. var maxIndex = list.length - 1;
  1972. var currentIndex = null;
  1973. var currentElement = null;
  1974. while (minIndex <= maxIndex) {
  1975. currentIndex = (minIndex + maxIndex) / 2 | 0;
  1976. currentElement = list[currentIndex];
  1977. var comparisonResult = comparisonFunction(currentElement);
  1978. if (comparisonResult > 0) {
  1979. minIndex = currentIndex + 1;
  1980. } else if (comparisonResult < 0) {
  1981. maxIndex = currentIndex - 1;
  1982. } else {
  1983. return currentElement;
  1984. }
  1985. }
  1986. return null;
  1987. }
  1988. };
  1989. exports.default = BinarySearch;
  1990. module.exports = exports["default"];
  1991. /***/ }),
  1992. /* 10 */
  1993. /***/ (function(module, exports, __webpack_require__) {
  1994. "use strict";
  1995. Object.defineProperty(exports, "__esModule", {
  1996. value: true
  1997. });
  1998. 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; }; }();
  1999. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2000. /**
  2001. * ID3 parser
  2002. */
  2003. var ID3 = function () {
  2004. function ID3() {
  2005. _classCallCheck(this, ID3);
  2006. }
  2007. _createClass(ID3, null, [{
  2008. key: 'isHeader',
  2009. /**
  2010. * Returns true if an ID3 header can be found at offset in data
  2011. * @param {Uint8Array} data - The data to search in
  2012. * @param {number} offset - The offset at which to start searching
  2013. * @return {boolean} - True if an ID3 header is found
  2014. */
  2015. value: function isHeader(data, offset) {
  2016. /*
  2017. * http://id3.org/id3v2.3.0
  2018. * [0] = 'I'
  2019. * [1] = 'D'
  2020. * [2] = '3'
  2021. * [3,4] = {Version}
  2022. * [5] = {Flags}
  2023. * [6-9] = {ID3 Size}
  2024. *
  2025. * An ID3v2 tag can be detected with the following pattern:
  2026. * $49 44 33 yy yy xx zz zz zz zz
  2027. * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
  2028. */
  2029. if (offset + 10 <= data.length) {
  2030. // look for 'ID3' identifier
  2031. if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
  2032. // check version is within range
  2033. if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
  2034. // check size is within range
  2035. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  2036. return true;
  2037. }
  2038. }
  2039. }
  2040. }
  2041. return false;
  2042. }
  2043. /**
  2044. * Returns true if an ID3 footer can be found at offset in data
  2045. * @param {Uint8Array} data - The data to search in
  2046. * @param {number} offset - The offset at which to start searching
  2047. * @return {boolean} - True if an ID3 footer is found
  2048. */
  2049. }, {
  2050. key: 'isFooter',
  2051. value: function isFooter(data, offset) {
  2052. /*
  2053. * The footer is a copy of the header, but with a different identifier
  2054. */
  2055. if (offset + 10 <= data.length) {
  2056. // look for '3DI' identifier
  2057. if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
  2058. // check version is within range
  2059. if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
  2060. // check size is within range
  2061. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  2062. return true;
  2063. }
  2064. }
  2065. }
  2066. }
  2067. return false;
  2068. }
  2069. /**
  2070. * Returns any adjacent ID3 tags found in data starting at offset, as one block of data
  2071. * @param {Uint8Array} data - The data to search in
  2072. * @param {number} offset - The offset at which to start searching
  2073. * @return {Uint8Array} - The block of data containing any ID3 tags found
  2074. */
  2075. }, {
  2076. key: 'getID3Data',
  2077. value: function getID3Data(data, offset) {
  2078. var front = offset;
  2079. var length = 0;
  2080. while (ID3.isHeader(data, offset)) {
  2081. // ID3 header is 10 bytes
  2082. length += 10;
  2083. var size = ID3._readSize(data, offset + 6);
  2084. length += size;
  2085. if (ID3.isFooter(data, offset + 10)) {
  2086. // ID3 footer is 10 bytes
  2087. length += 10;
  2088. }
  2089. offset += length;
  2090. }
  2091. if (length > 0) {
  2092. return data.subarray(front, front + length);
  2093. }
  2094. return undefined;
  2095. }
  2096. }, {
  2097. key: '_readSize',
  2098. value: function _readSize(data, offset) {
  2099. var size = 0;
  2100. size = (data[offset] & 0x7f) << 21;
  2101. size |= (data[offset + 1] & 0x7f) << 14;
  2102. size |= (data[offset + 2] & 0x7f) << 7;
  2103. size |= data[offset + 3] & 0x7f;
  2104. return size;
  2105. }
  2106. /**
  2107. * Searches for the Elementary Stream timestamp found in the ID3 data chunk
  2108. * @param {Uint8Array} data - Block of data containing one or more ID3 tags
  2109. * @return {number} - The timestamp
  2110. */
  2111. }, {
  2112. key: 'getTimeStamp',
  2113. value: function getTimeStamp(data) {
  2114. var frames = ID3.getID3Frames(data);
  2115. for (var i = 0; i < frames.length; i++) {
  2116. var frame = frames[i];
  2117. if (ID3.isTimeStampFrame(frame)) {
  2118. return ID3._readTimeStamp(frame);
  2119. }
  2120. }
  2121. return undefined;
  2122. }
  2123. /**
  2124. * Returns true if the ID3 frame is an Elementary Stream timestamp frame
  2125. * @param {ID3 frame} frame
  2126. */
  2127. }, {
  2128. key: 'isTimeStampFrame',
  2129. value: function isTimeStampFrame(frame) {
  2130. return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
  2131. }
  2132. }, {
  2133. key: '_getFrameData',
  2134. value: function _getFrameData(data) {
  2135. /*
  2136. Frame ID $xx xx xx xx (four characters)
  2137. Size $xx xx xx xx
  2138. Flags $xx xx
  2139. */
  2140. var type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  2141. var size = ID3._readSize(data, 4);
  2142. // skip frame id, size, and flags
  2143. var offset = 10;
  2144. return { type: type, size: size, data: data.subarray(offset, offset + size) };
  2145. }
  2146. /**
  2147. * Returns an array of ID3 frames found in all the ID3 tags in the id3Data
  2148. * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags
  2149. * @return {ID3 frame[]} - Array of ID3 frame objects
  2150. */
  2151. }, {
  2152. key: 'getID3Frames',
  2153. value: function getID3Frames(id3Data) {
  2154. var offset = 0;
  2155. var frames = [];
  2156. while (ID3.isHeader(id3Data, offset)) {
  2157. var size = ID3._readSize(id3Data, offset + 6);
  2158. // skip past ID3 header
  2159. offset += 10;
  2160. var end = offset + size;
  2161. // loop through frames in the ID3 tag
  2162. while (offset + 8 < end) {
  2163. var frameData = ID3._getFrameData(id3Data.subarray(offset));
  2164. var frame = ID3._decodeFrame(frameData);
  2165. if (frame) {
  2166. frames.push(frame);
  2167. }
  2168. // skip frame header and frame data
  2169. offset += frameData.size + 10;
  2170. }
  2171. if (ID3.isFooter(id3Data, offset)) {
  2172. offset += 10;
  2173. }
  2174. }
  2175. return frames;
  2176. }
  2177. }, {
  2178. key: '_decodeFrame',
  2179. value: function _decodeFrame(frame) {
  2180. if (frame.type === 'PRIV') {
  2181. return ID3._decodePrivFrame(frame);
  2182. } else if (frame.type[0] === 'T') {
  2183. return ID3._decodeTextFrame(frame);
  2184. } else if (frame.type[0] === 'W') {
  2185. return ID3._decodeURLFrame(frame);
  2186. }
  2187. return undefined;
  2188. }
  2189. }, {
  2190. key: '_readTimeStamp',
  2191. value: function _readTimeStamp(timeStampFrame) {
  2192. if (timeStampFrame.data.byteLength === 8) {
  2193. var data = new Uint8Array(timeStampFrame.data);
  2194. // timestamp is 33 bit expressed as a big-endian eight-octet number,
  2195. // with the upper 31 bits set to zero.
  2196. var pts33Bit = data[3] & 0x1;
  2197. var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  2198. timestamp /= 45;
  2199. if (pts33Bit) {
  2200. timestamp += 47721858.84;
  2201. } // 2^32 / 90
  2202. return Math.round(timestamp);
  2203. }
  2204. return undefined;
  2205. }
  2206. }, {
  2207. key: '_decodePrivFrame',
  2208. value: function _decodePrivFrame(frame) {
  2209. /*
  2210. Format: <text string>\0<binary data>
  2211. */
  2212. if (frame.size < 2) {
  2213. return undefined;
  2214. }
  2215. var owner = ID3._utf8ArrayToStr(frame.data, true);
  2216. var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  2217. return { key: frame.type, info: owner, data: privateData.buffer };
  2218. }
  2219. }, {
  2220. key: '_decodeTextFrame',
  2221. value: function _decodeTextFrame(frame) {
  2222. if (frame.size < 2) {
  2223. return undefined;
  2224. }
  2225. if (frame.type === 'TXXX') {
  2226. /*
  2227. Format:
  2228. [0] = {Text Encoding}
  2229. [1-?] = {Description}\0{Value}
  2230. */
  2231. var index = 1;
  2232. var description = ID3._utf8ArrayToStr(frame.data.subarray(index));
  2233. index += description.length + 1;
  2234. var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
  2235. return { key: frame.type, info: description, data: value };
  2236. } else {
  2237. /*
  2238. Format:
  2239. [0] = {Text Encoding}
  2240. [1-?] = {Value}
  2241. */
  2242. var text = ID3._utf8ArrayToStr(frame.data.subarray(1));
  2243. return { key: frame.type, data: text };
  2244. }
  2245. }
  2246. }, {
  2247. key: '_decodeURLFrame',
  2248. value: function _decodeURLFrame(frame) {
  2249. if (frame.type === 'WXXX') {
  2250. /*
  2251. Format:
  2252. [0] = {Text Encoding}
  2253. [1-?] = {Description}\0{URL}
  2254. */
  2255. if (frame.size < 2) {
  2256. return undefined;
  2257. }
  2258. var index = 1;
  2259. var description = ID3._utf8ArrayToStr(frame.data.subarray(index));
  2260. index += description.length + 1;
  2261. var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
  2262. return { key: frame.type, info: description, data: value };
  2263. } else {
  2264. /*
  2265. Format:
  2266. [0-?] = {URL}
  2267. */
  2268. var url = ID3._utf8ArrayToStr(frame.data);
  2269. return { key: frame.type, data: url };
  2270. }
  2271. }
  2272. // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
  2273. // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
  2274. /* utf.js - UTF-8 <=> UTF-16 convertion
  2275. *
  2276. * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
  2277. * Version: 1.0
  2278. * LastModified: Dec 25 1999
  2279. * This library is free. You can redistribute it and/or modify it.
  2280. */
  2281. }, {
  2282. key: '_utf8ArrayToStr',
  2283. value: function _utf8ArrayToStr(array) {
  2284. var exitOnNull = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  2285. var len = array.length;
  2286. var c = void 0;
  2287. var char2 = void 0;
  2288. var char3 = void 0;
  2289. var out = '';
  2290. var i = 0;
  2291. while (i < len) {
  2292. c = array[i++];
  2293. if (c === 0x00 && exitOnNull) {
  2294. return out;
  2295. } else if (c === 0x00 || c === 0x03) {
  2296. // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
  2297. continue;
  2298. }
  2299. switch (c >> 4) {
  2300. case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:
  2301. // 0xxxxxxx
  2302. out += String.fromCharCode(c);
  2303. break;
  2304. case 12:case 13:
  2305. // 110x xxxx 10xx xxxx
  2306. char2 = array[i++];
  2307. out += String.fromCharCode((c & 0x1F) << 6 | char2 & 0x3F);
  2308. break;
  2309. case 14:
  2310. // 1110 xxxx 10xx xxxx 10xx xxxx
  2311. char2 = array[i++];
  2312. char3 = array[i++];
  2313. out += String.fromCharCode((c & 0x0F) << 12 | (char2 & 0x3F) << 6 | (char3 & 0x3F) << 0);
  2314. break;
  2315. default:
  2316. }
  2317. }
  2318. return out;
  2319. }
  2320. }]);
  2321. return ID3;
  2322. }();
  2323. var utf8ArrayToStr = ID3._utf8ArrayToStr;
  2324. exports.default = ID3;
  2325. exports.utf8ArrayToStr = utf8ArrayToStr;
  2326. /***/ }),
  2327. /* 11 */
  2328. /***/ (function(module, exports, __webpack_require__) {
  2329. "use strict";
  2330. Object.defineProperty(exports, "__esModule", {
  2331. value: true
  2332. });
  2333. 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; }; }();
  2334. var _urlToolkit = __webpack_require__(8);
  2335. var URLToolkit = _interopRequireWildcard(_urlToolkit);
  2336. var _levelKey = __webpack_require__(17);
  2337. var _levelKey2 = _interopRequireDefault(_levelKey);
  2338. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2339. 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; } }
  2340. 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; }
  2341. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2342. var Fragment = function () {
  2343. function Fragment() {
  2344. var _elementaryStreams;
  2345. _classCallCheck(this, Fragment);
  2346. this._url = null;
  2347. this._byteRange = null;
  2348. this._decryptdata = null;
  2349. this.tagList = [];
  2350. this.programDateTime = null;
  2351. this.rawProgramDateTime = null;
  2352. // Holds the types of data this fragment supports
  2353. this._elementaryStreams = (_elementaryStreams = {}, _defineProperty(_elementaryStreams, Fragment.ElementaryStreamTypes.AUDIO, false), _defineProperty(_elementaryStreams, Fragment.ElementaryStreamTypes.VIDEO, false), _elementaryStreams);
  2354. }
  2355. /**
  2356. * `type` property for this._elementaryStreams
  2357. *
  2358. * @enum
  2359. */
  2360. _createClass(Fragment, [{
  2361. key: 'addElementaryStream',
  2362. /**
  2363. * @param {ElementaryStreamType} type
  2364. */
  2365. value: function addElementaryStream(type) {
  2366. this._elementaryStreams[type] = true;
  2367. }
  2368. /**
  2369. * @param {ElementaryStreamType} type
  2370. */
  2371. }, {
  2372. key: 'hasElementaryStream',
  2373. value: function hasElementaryStream(type) {
  2374. return this._elementaryStreams[type] === true;
  2375. }
  2376. /**
  2377. * Utility method for parseLevelPlaylist to create an initialization vector for a given segment
  2378. * @returns {Uint8Array}
  2379. */
  2380. }, {
  2381. key: 'createInitializationVector',
  2382. value: function createInitializationVector(segmentNumber) {
  2383. var uint8View = new Uint8Array(16);
  2384. for (var i = 12; i < 16; i++) {
  2385. uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
  2386. }
  2387. return uint8View;
  2388. }
  2389. /**
  2390. * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data
  2391. * @param levelkey - a playlist's encryption info
  2392. * @param segmentNumber - the fragment's segment number
  2393. * @returns {*} - an object to be applied as a fragment's decryptdata
  2394. */
  2395. }, {
  2396. key: 'fragmentDecryptdataFromLevelkey',
  2397. value: function fragmentDecryptdataFromLevelkey(levelkey, segmentNumber) {
  2398. var decryptdata = levelkey;
  2399. if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) {
  2400. decryptdata = new _levelKey2.default();
  2401. decryptdata.method = levelkey.method;
  2402. decryptdata.baseuri = levelkey.baseuri;
  2403. decryptdata.reluri = levelkey.reluri;
  2404. decryptdata.iv = this.createInitializationVector(segmentNumber);
  2405. }
  2406. return decryptdata;
  2407. }
  2408. }, {
  2409. key: 'url',
  2410. get: function get() {
  2411. if (!this._url && this.relurl) {
  2412. this._url = URLToolkit.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });
  2413. }
  2414. return this._url;
  2415. },
  2416. set: function set(value) {
  2417. this._url = value;
  2418. }
  2419. }, {
  2420. key: 'byteRange',
  2421. get: function get() {
  2422. if (!this._byteRange && !this.rawByteRange) {
  2423. return [];
  2424. }
  2425. if (this._byteRange) {
  2426. return this._byteRange;
  2427. }
  2428. var byteRange = [];
  2429. if (this.rawByteRange) {
  2430. var params = this.rawByteRange.split('@', 2);
  2431. if (params.length === 1) {
  2432. var lastByteRangeEndOffset = this.lastByteRangeEndOffset;
  2433. byteRange[0] = lastByteRangeEndOffset || 0;
  2434. } else {
  2435. byteRange[0] = parseInt(params[1]);
  2436. }
  2437. byteRange[1] = parseInt(params[0]) + byteRange[0];
  2438. this._byteRange = byteRange;
  2439. }
  2440. return byteRange;
  2441. }
  2442. /**
  2443. * @type {number}
  2444. */
  2445. }, {
  2446. key: 'byteRangeStartOffset',
  2447. get: function get() {
  2448. return this.byteRange[0];
  2449. }
  2450. }, {
  2451. key: 'byteRangeEndOffset',
  2452. get: function get() {
  2453. return this.byteRange[1];
  2454. }
  2455. }, {
  2456. key: 'decryptdata',
  2457. get: function get() {
  2458. if (!this._decryptdata) {
  2459. this._decryptdata = this.fragmentDecryptdataFromLevelkey(this.levelkey, this.sn);
  2460. }
  2461. return this._decryptdata;
  2462. }
  2463. }, {
  2464. key: 'endProgramDateTime',
  2465. get: function get() {
  2466. if (!Number.isFinite(this.programDateTime)) {
  2467. return null;
  2468. }
  2469. var duration = !Number.isFinite(this.duration) ? 0 : this.duration;
  2470. return this.programDateTime + duration * 1000;
  2471. }
  2472. }, {
  2473. key: 'encrypted',
  2474. get: function get() {
  2475. return !!(this.decryptdata && this.decryptdata.uri !== null && this.decryptdata.key === null);
  2476. }
  2477. }], [{
  2478. key: 'ElementaryStreamTypes',
  2479. get: function get() {
  2480. return {
  2481. AUDIO: 'audio',
  2482. VIDEO: 'video'
  2483. };
  2484. }
  2485. }]);
  2486. return Fragment;
  2487. }();
  2488. exports.default = Fragment;
  2489. module.exports = exports['default'];
  2490. /***/ }),
  2491. /* 12 */
  2492. /***/ (function(module, exports, __webpack_require__) {
  2493. "use strict";
  2494. Object.defineProperty(exports, "__esModule", {
  2495. value: true
  2496. });
  2497. 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; }; }();
  2498. var _aesCrypto = __webpack_require__(42);
  2499. var _aesCrypto2 = _interopRequireDefault(_aesCrypto);
  2500. var _fastAesKey = __webpack_require__(43);
  2501. var _fastAesKey2 = _interopRequireDefault(_fastAesKey);
  2502. var _aesDecryptor = __webpack_require__(44);
  2503. var _aesDecryptor2 = _interopRequireDefault(_aesDecryptor);
  2504. var _errors = __webpack_require__(2);
  2505. var _logger = __webpack_require__(0);
  2506. var _events = __webpack_require__(1);
  2507. var _events2 = _interopRequireDefault(_events);
  2508. var _getSelfScope = __webpack_require__(5);
  2509. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2510. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2511. // see https://stackoverflow.com/a/11237259/589493
  2512. var global = (0, _getSelfScope.getSelfScope)(); // safeguard for code that might run both on worker and main thread
  2513. var Decrypter = function () {
  2514. function Decrypter(observer, config) {
  2515. var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
  2516. _ref$removePKCS7Paddi = _ref.removePKCS7Padding,
  2517. removePKCS7Padding = _ref$removePKCS7Paddi === undefined ? true : _ref$removePKCS7Paddi;
  2518. _classCallCheck(this, Decrypter);
  2519. this.logEnabled = true;
  2520. this.observer = observer;
  2521. this.config = config;
  2522. this.removePKCS7Padding = removePKCS7Padding;
  2523. // built in decryptor expects PKCS7 padding
  2524. if (removePKCS7Padding) {
  2525. try {
  2526. var browserCrypto = global.crypto;
  2527. if (browserCrypto) {
  2528. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  2529. }
  2530. } catch (e) {}
  2531. }
  2532. this.disableWebCrypto = !this.subtle;
  2533. }
  2534. _createClass(Decrypter, [{
  2535. key: 'isSync',
  2536. value: function isSync() {
  2537. return this.disableWebCrypto && this.config.enableSoftwareAES;
  2538. }
  2539. }, {
  2540. key: 'decrypt',
  2541. value: function decrypt(data, key, iv, callback) {
  2542. var _this = this;
  2543. if (this.disableWebCrypto && this.config.enableSoftwareAES) {
  2544. if (this.logEnabled) {
  2545. _logger.logger.log('JS AES decrypt');
  2546. this.logEnabled = false;
  2547. }
  2548. var decryptor = this.decryptor;
  2549. if (!decryptor) {
  2550. this.decryptor = decryptor = new _aesDecryptor2.default();
  2551. }
  2552. decryptor.expandKey(key);
  2553. callback(decryptor.decrypt(data, 0, iv, this.removePKCS7Padding));
  2554. } else {
  2555. if (this.logEnabled) {
  2556. _logger.logger.log('WebCrypto AES decrypt');
  2557. this.logEnabled = false;
  2558. }
  2559. var subtle = this.subtle;
  2560. if (this.key !== key) {
  2561. this.key = key;
  2562. this.fastAesKey = new _fastAesKey2.default(subtle, key);
  2563. }
  2564. this.fastAesKey.expandKey().then(function (aesKey) {
  2565. // decrypt using web crypto
  2566. var crypto = new _aesCrypto2.default(subtle, iv);
  2567. crypto.decrypt(data, aesKey).catch(function (err) {
  2568. _this.onWebCryptoError(err, data, key, iv, callback);
  2569. }).then(function (result) {
  2570. callback(result);
  2571. });
  2572. }).catch(function (err) {
  2573. _this.onWebCryptoError(err, data, key, iv, callback);
  2574. });
  2575. }
  2576. }
  2577. }, {
  2578. key: 'onWebCryptoError',
  2579. value: function onWebCryptoError(err, data, key, iv, callback) {
  2580. if (this.config.enableSoftwareAES) {
  2581. _logger.logger.log('WebCrypto Error, disable WebCrypto API');
  2582. this.disableWebCrypto = true;
  2583. this.logEnabled = true;
  2584. this.decrypt(data, key, iv, callback);
  2585. } else {
  2586. _logger.logger.error('decrypting error : ' + err.message);
  2587. this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_DECRYPT_ERROR, fatal: true, reason: err.message });
  2588. }
  2589. }
  2590. }, {
  2591. key: 'destroy',
  2592. value: function destroy() {
  2593. var decryptor = this.decryptor;
  2594. if (decryptor) {
  2595. decryptor.destroy();
  2596. this.decryptor = undefined;
  2597. }
  2598. }
  2599. }]);
  2600. return Decrypter;
  2601. }();
  2602. exports.default = Decrypter;
  2603. module.exports = exports['default'];
  2604. /***/ }),
  2605. /* 13 */
  2606. /***/ (function(module, exports, __webpack_require__) {
  2607. "use strict";
  2608. Object.defineProperty(exports, "__esModule", {
  2609. value: true
  2610. });
  2611. exports.getMediaSource = getMediaSource;
  2612. /**
  2613. * MediaSource helper
  2614. */
  2615. function getMediaSource() {
  2616. if (typeof window !== 'undefined') {
  2617. return window.MediaSource || window.WebKitMediaSource;
  2618. }
  2619. }
  2620. /***/ }),
  2621. /* 14 */
  2622. /***/ (function(module, exports, __webpack_require__) {
  2623. "use strict";
  2624. Object.defineProperty(exports, "__esModule", {
  2625. value: true
  2626. });
  2627. exports.State = undefined;
  2628. 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; }; }();
  2629. 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); } };
  2630. var _taskLoop = __webpack_require__(28);
  2631. var _taskLoop2 = _interopRequireDefault(_taskLoop);
  2632. var _fragmentTracker = __webpack_require__(6);
  2633. var _bufferHelper = __webpack_require__(4);
  2634. var _logger = __webpack_require__(0);
  2635. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2636. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2637. 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; }
  2638. 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; }
  2639. var State = exports.State = {
  2640. STOPPED: 'STOPPED',
  2641. STARTING: 'STARTING',
  2642. IDLE: 'IDLE',
  2643. PAUSED: 'PAUSED',
  2644. KEY_LOADING: 'KEY_LOADING',
  2645. FRAG_LOADING: 'FRAG_LOADING',
  2646. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  2647. WAITING_TRACK: 'WAITING_TRACK',
  2648. PARSING: 'PARSING',
  2649. PARSED: 'PARSED',
  2650. BUFFER_FLUSHING: 'BUFFER_FLUSHING',
  2651. ENDED: 'ENDED',
  2652. ERROR: 'ERROR',
  2653. WAITING_INIT_PTS: 'WAITING_INIT_PTS',
  2654. WAITING_LEVEL: 'WAITING_LEVEL'
  2655. };
  2656. var BaseStreamController = function (_TaskLoop) {
  2657. _inherits(BaseStreamController, _TaskLoop);
  2658. function BaseStreamController() {
  2659. _classCallCheck(this, BaseStreamController);
  2660. return _possibleConstructorReturn(this, (BaseStreamController.__proto__ || Object.getPrototypeOf(BaseStreamController)).apply(this, arguments));
  2661. }
  2662. _createClass(BaseStreamController, [{
  2663. key: 'doTick',
  2664. value: function doTick() {}
  2665. }, {
  2666. key: 'startLoad',
  2667. value: function startLoad() {}
  2668. }, {
  2669. key: 'stopLoad',
  2670. value: function stopLoad() {
  2671. var frag = this.fragCurrent;
  2672. if (frag) {
  2673. if (frag.loader) {
  2674. frag.loader.abort();
  2675. }
  2676. this.fragmentTracker.removeFragment(frag);
  2677. }
  2678. if (this.demuxer) {
  2679. this.demuxer.destroy();
  2680. this.demuxer = null;
  2681. }
  2682. this.fragCurrent = null;
  2683. this.fragPrevious = null;
  2684. this.clearInterval();
  2685. this.clearNextTick();
  2686. this.state = State.STOPPED;
  2687. }
  2688. }, {
  2689. key: '_streamEnded',
  2690. value: function _streamEnded(bufferInfo, levelDetails) {
  2691. var fragCurrent = this.fragCurrent,
  2692. fragmentTracker = this.fragmentTracker;
  2693. // we just got done loading the final fragment and there is no other buffered range after ...
  2694. // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
  2695. // so we should not switch to ENDED in that case, to be able to buffer them
  2696. // dont switch to ENDED if we need to backtrack last fragment
  2697. if (!levelDetails.live && fragCurrent && !fragCurrent.backtracked && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) {
  2698. var fragState = fragmentTracker.getState(fragCurrent);
  2699. return fragState === _fragmentTracker.FragmentState.PARTIAL || fragState === _fragmentTracker.FragmentState.OK;
  2700. }
  2701. return false;
  2702. }
  2703. }, {
  2704. key: 'onMediaSeeking',
  2705. value: function onMediaSeeking() {
  2706. var config = this.config,
  2707. media = this.media,
  2708. mediaBuffer = this.mediaBuffer,
  2709. state = this.state;
  2710. var currentTime = media ? media.currentTime : null;
  2711. var bufferInfo = _bufferHelper.BufferHelper.bufferInfo(mediaBuffer || media, currentTime, this.config.maxBufferHole);
  2712. if (Number.isFinite(currentTime)) {
  2713. _logger.logger.log('media seeking to ' + currentTime.toFixed(3));
  2714. }
  2715. if (state === State.FRAG_LOADING) {
  2716. var fragCurrent = this.fragCurrent;
  2717. // check if we are seeking to a unbuffered area AND if frag loading is in progress
  2718. if (bufferInfo.len === 0 && fragCurrent) {
  2719. var tolerance = config.maxFragLookUpTolerance;
  2720. var fragStartOffset = fragCurrent.start - tolerance;
  2721. var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  2722. // check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything
  2723. if (currentTime < fragStartOffset || currentTime > fragEndOffset) {
  2724. if (fragCurrent.loader) {
  2725. _logger.logger.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
  2726. fragCurrent.loader.abort();
  2727. }
  2728. this.fragCurrent = null;
  2729. this.fragPrevious = null;
  2730. // switch to IDLE state to load new fragment
  2731. this.state = State.IDLE;
  2732. } else {
  2733. _logger.logger.log('seeking outside of buffer but within currently loaded fragment range');
  2734. }
  2735. }
  2736. } else if (state === State.ENDED) {
  2737. // if seeking to unbuffered area, clean up fragPrevious
  2738. if (bufferInfo.len === 0) {
  2739. this.fragPrevious = null;
  2740. this.fragCurrent = null;
  2741. }
  2742. // switch to IDLE state to check for potential new fragment
  2743. this.state = State.IDLE;
  2744. }
  2745. if (media) {
  2746. this.lastCurrentTime = currentTime;
  2747. }
  2748. // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
  2749. if (!this.loadedmetadata) {
  2750. this.nextLoadPosition = this.startPosition = currentTime;
  2751. }
  2752. // tick to speed up processing
  2753. this.tick();
  2754. }
  2755. }, {
  2756. key: 'onMediaEnded',
  2757. value: function onMediaEnded() {
  2758. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  2759. this.startPosition = this.lastCurrentTime = 0;
  2760. }
  2761. }, {
  2762. key: 'onHandlerDestroying',
  2763. value: function onHandlerDestroying() {
  2764. this.stopLoad();
  2765. _get(BaseStreamController.prototype.__proto__ || Object.getPrototypeOf(BaseStreamController.prototype), 'onHandlerDestroying', this).call(this);
  2766. }
  2767. }, {
  2768. key: 'onHandlerDestroyed',
  2769. value: function onHandlerDestroyed() {
  2770. this.state = State.STOPPED;
  2771. this.fragmentTracker = null;
  2772. }
  2773. }]);
  2774. return BaseStreamController;
  2775. }(_taskLoop2.default);
  2776. exports.default = BaseStreamController;
  2777. /***/ }),
  2778. /* 15 */
  2779. /***/ (function(module, exports, __webpack_require__) {
  2780. "use strict";
  2781. Object.defineProperty(exports, "__esModule", {
  2782. value: true
  2783. });
  2784. 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; }; }();
  2785. 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); } };
  2786. var _events = __webpack_require__(1);
  2787. var _events2 = _interopRequireDefault(_events);
  2788. var _eventHandler = __webpack_require__(3);
  2789. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  2790. var _errors = __webpack_require__(2);
  2791. var _logger = __webpack_require__(0);
  2792. var _mp4demuxer = __webpack_require__(16);
  2793. var _mp4demuxer2 = _interopRequireDefault(_mp4demuxer);
  2794. var _m3u8Parser = __webpack_require__(35);
  2795. var _m3u8Parser2 = _interopRequireDefault(_m3u8Parser);
  2796. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2797. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2798. 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; }
  2799. 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; } /**
  2800. * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.
  2801. *
  2802. * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.
  2803. *
  2804. * Uses loader(s) set in config to do actual internal loading of resource tasks.
  2805. *
  2806. * @module
  2807. *
  2808. */
  2809. var _window = window,
  2810. performance = _window.performance;
  2811. /**
  2812. * `type` property values for this loaders' context object
  2813. * @enum
  2814. *
  2815. */
  2816. var ContextType = {
  2817. MANIFEST: 'manifest',
  2818. LEVEL: 'level',
  2819. AUDIO_TRACK: 'audioTrack',
  2820. SUBTITLE_TRACK: 'subtitleTrack'
  2821. };
  2822. /**
  2823. * @enum {string}
  2824. */
  2825. var LevelType = {
  2826. MAIN: 'main',
  2827. AUDIO: 'audio',
  2828. SUBTITLE: 'subtitle'
  2829. };
  2830. /**
  2831. * @constructor
  2832. */
  2833. var PlaylistLoader = function (_EventHandler) {
  2834. _inherits(PlaylistLoader, _EventHandler);
  2835. /**
  2836. * @constructs
  2837. * @param {Hls} hls
  2838. */
  2839. function PlaylistLoader(hls) {
  2840. _classCallCheck(this, PlaylistLoader);
  2841. 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));
  2842. _this.loaders = {};
  2843. return _this;
  2844. }
  2845. _createClass(PlaylistLoader, [{
  2846. key: 'createInternalLoader',
  2847. /**
  2848. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  2849. * Default loader is XHRLoader (see utils)
  2850. * @param {object} context
  2851. * @returns {XHRLoader} or other compatible configured overload
  2852. */
  2853. value: function createInternalLoader(context) {
  2854. var config = this.hls.config;
  2855. var PLoader = config.pLoader;
  2856. var Loader = config.loader;
  2857. var InternalLoader = PLoader || Loader;
  2858. var loader = new InternalLoader(config);
  2859. context.loader = loader;
  2860. this.loaders[context.type] = loader;
  2861. return loader;
  2862. }
  2863. }, {
  2864. key: 'getInternalLoader',
  2865. value: function getInternalLoader(context) {
  2866. return this.loaders[context.type];
  2867. }
  2868. }, {
  2869. key: 'resetInternalLoader',
  2870. value: function resetInternalLoader(contextType) {
  2871. if (this.loaders[contextType]) {
  2872. delete this.loaders[contextType];
  2873. }
  2874. }
  2875. /**
  2876. * Call `destroy` on all internal loader instances mapped (one per context type)
  2877. */
  2878. }, {
  2879. key: 'destroyInternalLoaders',
  2880. value: function destroyInternalLoaders() {
  2881. for (var contextType in this.loaders) {
  2882. var loader = this.loaders[contextType];
  2883. if (loader) {
  2884. loader.destroy();
  2885. }
  2886. this.resetInternalLoader(contextType);
  2887. }
  2888. }
  2889. }, {
  2890. key: 'destroy',
  2891. value: function destroy() {
  2892. this.destroyInternalLoaders();
  2893. _get(PlaylistLoader.prototype.__proto__ || Object.getPrototypeOf(PlaylistLoader.prototype), 'destroy', this).call(this);
  2894. }
  2895. }, {
  2896. key: 'onManifestLoading',
  2897. value: function onManifestLoading(data) {
  2898. this.load(data.url, { type: ContextType.MANIFEST, level: 0, id: null });
  2899. }
  2900. }, {
  2901. key: 'onLevelLoading',
  2902. value: function onLevelLoading(data) {
  2903. this.load(data.url, { type: ContextType.LEVEL, level: data.level, id: data.id });
  2904. }
  2905. }, {
  2906. key: 'onAudioTrackLoading',
  2907. value: function onAudioTrackLoading(data) {
  2908. this.load(data.url, { type: ContextType.AUDIO_TRACK, level: null, id: data.id });
  2909. }
  2910. }, {
  2911. key: 'onSubtitleTrackLoading',
  2912. value: function onSubtitleTrackLoading(data) {
  2913. this.load(data.url, { type: ContextType.SUBTITLE_TRACK, level: null, id: data.id });
  2914. }
  2915. }, {
  2916. key: 'load',
  2917. value: function load(url, context) {
  2918. var config = this.hls.config;
  2919. _logger.logger.debug('Loading playlist of type ' + context.type + ', level: ' + context.level + ', id: ' + context.id);
  2920. // Check if a loader for this context already exists
  2921. var loader = this.getInternalLoader(context);
  2922. if (loader) {
  2923. var loaderContext = loader.context;
  2924. if (loaderContext && loaderContext.url === url) {
  2925. // same URL can't overlap
  2926. _logger.logger.trace('playlist request ongoing');
  2927. return false;
  2928. } else {
  2929. _logger.logger.warn('aborting previous loader for type: ' + context.type);
  2930. loader.abort();
  2931. }
  2932. }
  2933. var maxRetry = void 0,
  2934. timeout = void 0,
  2935. retryDelay = void 0,
  2936. maxRetryDelay = void 0;
  2937. // apply different configs for retries depending on
  2938. // context (manifest, level, audio/subs playlist)
  2939. switch (context.type) {
  2940. case ContextType.MANIFEST:
  2941. maxRetry = config.manifestLoadingMaxRetry;
  2942. timeout = config.manifestLoadingTimeOut;
  2943. retryDelay = config.manifestLoadingRetryDelay;
  2944. maxRetryDelay = config.manifestLoadingMaxRetryTimeout;
  2945. break;
  2946. case ContextType.LEVEL:
  2947. // Disable internal loader retry logic, since we are managing retries in Level Controller
  2948. maxRetry = 0;
  2949. timeout = config.levelLoadingTimeOut;
  2950. // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config
  2951. break;
  2952. default:
  2953. maxRetry = config.levelLoadingMaxRetry;
  2954. timeout = config.levelLoadingTimeOut;
  2955. retryDelay = config.levelLoadingRetryDelay;
  2956. maxRetryDelay = config.levelLoadingMaxRetryTimeout;
  2957. break;
  2958. }
  2959. loader = this.createInternalLoader(context);
  2960. context.url = url;
  2961. context.responseType = context.responseType || ''; // FIXME: (should not be necessary to do this)
  2962. var loaderConfig = {
  2963. timeout: timeout,
  2964. maxRetry: maxRetry,
  2965. retryDelay: retryDelay,
  2966. maxRetryDelay: maxRetryDelay
  2967. };
  2968. var loaderCallbacks = {
  2969. onSuccess: this.loadsuccess.bind(this),
  2970. onError: this.loaderror.bind(this),
  2971. onTimeout: this.loadtimeout.bind(this)
  2972. };
  2973. _logger.logger.debug('Calling internal loader delegate for URL: ' + url);
  2974. loader.load(context, loaderConfig, loaderCallbacks);
  2975. return true;
  2976. }
  2977. }, {
  2978. key: 'loadsuccess',
  2979. value: function loadsuccess(response, stats, context) {
  2980. var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  2981. if (context.isSidxRequest) {
  2982. this._handleSidxRequest(response, context);
  2983. this._handlePlaylistLoaded(response, stats, context, networkDetails);
  2984. return;
  2985. }
  2986. this.resetInternalLoader(context.type);
  2987. var string = response.data;
  2988. stats.tload = performance.now();
  2989. // stats.mtime = new Date(target.getResponseHeader('Last-Modified'));
  2990. // Validate if it is an M3U8 at all
  2991. if (string.indexOf('#EXTM3U') !== 0) {
  2992. this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);
  2993. return;
  2994. }
  2995. // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)
  2996. if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {
  2997. this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);
  2998. } else {
  2999. this._handleMasterPlaylist(response, stats, context, networkDetails);
  3000. }
  3001. }
  3002. }, {
  3003. key: 'loaderror',
  3004. value: function loaderror(response, context) {
  3005. var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  3006. this._handleNetworkError(context, networkDetails, false, response);
  3007. }
  3008. }, {
  3009. key: 'loadtimeout',
  3010. value: function loadtimeout(stats, context) {
  3011. var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  3012. this._handleNetworkError(context, networkDetails, true);
  3013. }
  3014. }, {
  3015. key: '_handleMasterPlaylist',
  3016. value: function _handleMasterPlaylist(response, stats, context, networkDetails) {
  3017. var hls = this.hls;
  3018. var string = response.data;
  3019. var url = PlaylistLoader.getResponseUrl(response, context);
  3020. var levels = _m3u8Parser2.default.parseMasterPlaylist(string, url);
  3021. if (!levels.length) {
  3022. this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);
  3023. return;
  3024. }
  3025. // multi level playlist, parse level info
  3026. var audioGroups = levels.map(function (level) {
  3027. return {
  3028. id: level.attrs.AUDIO,
  3029. codec: level.audioCodec
  3030. };
  3031. });
  3032. var audioTracks = _m3u8Parser2.default.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);
  3033. var subtitles = _m3u8Parser2.default.parseMasterPlaylistMedia(string, url, 'SUBTITLES');
  3034. if (audioTracks.length) {
  3035. // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
  3036. var embeddedAudioFound = false;
  3037. audioTracks.forEach(function (audioTrack) {
  3038. if (!audioTrack.url) {
  3039. embeddedAudioFound = true;
  3040. }
  3041. });
  3042. // if no embedded audio track defined, but audio codec signaled in quality level,
  3043. // we need to signal this main audio track this could happen with playlists with
  3044. // alt audio rendition in which quality levels (main)
  3045. // contains both audio+video. but with mixed audio track not signaled
  3046. if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  3047. _logger.logger.log('audio codec signaled in quality level, but no embedded audio track signaled, create one');
  3048. audioTracks.unshift({
  3049. type: 'main',
  3050. name: 'main'
  3051. });
  3052. }
  3053. }
  3054. hls.trigger(_events2.default.MANIFEST_LOADED, {
  3055. levels: levels,
  3056. audioTracks: audioTracks,
  3057. subtitles: subtitles,
  3058. url: url,
  3059. stats: stats,
  3060. networkDetails: networkDetails
  3061. });
  3062. }
  3063. }, {
  3064. key: '_handleTrackOrLevelPlaylist',
  3065. value: function _handleTrackOrLevelPlaylist(response, stats, context, networkDetails) {
  3066. var hls = this.hls;
  3067. var id = context.id,
  3068. level = context.level,
  3069. type = context.type;
  3070. var url = PlaylistLoader.getResponseUrl(response, context);
  3071. var levelUrlId = Number.isFinite(id) ? id : 0;
  3072. var levelId = Number.isFinite(level) ? level : levelUrlId;
  3073. var levelType = PlaylistLoader.mapContextToLevelType(context);
  3074. var levelDetails = _m3u8Parser2.default.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);
  3075. // set stats on level structure
  3076. levelDetails.tload = stats.tload;
  3077. // We have done our first request (Manifest-type) and receive
  3078. // not a master playlist but a chunk-list (track/level)
  3079. // We fire the manifest-loaded event anyway with the parsed level-details
  3080. // by creating a single-level structure for it.
  3081. if (type === ContextType.MANIFEST) {
  3082. var singleLevel = {
  3083. url: url,
  3084. details: levelDetails
  3085. };
  3086. hls.trigger(_events2.default.MANIFEST_LOADED, {
  3087. levels: [singleLevel],
  3088. audioTracks: [],
  3089. url: url,
  3090. stats: stats,
  3091. networkDetails: networkDetails
  3092. });
  3093. }
  3094. // save parsing time
  3095. stats.tparsed = performance.now();
  3096. // in case we need SIDX ranges
  3097. // return early after calling load for
  3098. // the SIDX box.
  3099. if (levelDetails.needSidxRanges) {
  3100. var sidxUrl = levelDetails.initSegment.url;
  3101. this.load(sidxUrl, {
  3102. isSidxRequest: true,
  3103. type: type,
  3104. level: level,
  3105. levelDetails: levelDetails,
  3106. id: id,
  3107. rangeStart: 0,
  3108. rangeEnd: 2048,
  3109. responseType: 'arraybuffer'
  3110. });
  3111. return;
  3112. }
  3113. // extend the context with the new levelDetails property
  3114. context.levelDetails = levelDetails;
  3115. this._handlePlaylistLoaded(response, stats, context, networkDetails);
  3116. }
  3117. }, {
  3118. key: '_handleSidxRequest',
  3119. value: function _handleSidxRequest(response, context) {
  3120. var sidxInfo = _mp4demuxer2.default.parseSegmentIndex(new Uint8Array(response.data));
  3121. // if provided fragment does not contain sidx, early return
  3122. if (!sidxInfo) {
  3123. return;
  3124. }
  3125. var sidxReferences = sidxInfo.references;
  3126. var levelDetails = context.levelDetails;
  3127. sidxReferences.forEach(function (segmentRef, index) {
  3128. var segRefInfo = segmentRef.info;
  3129. var frag = levelDetails.fragments[index];
  3130. if (frag.byteRange.length === 0) {
  3131. frag.rawByteRange = String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start);
  3132. }
  3133. });
  3134. levelDetails.initSegment.rawByteRange = String(sidxInfo.moovEndOffset) + '@0';
  3135. }
  3136. }, {
  3137. key: '_handleManifestParsingError',
  3138. value: function _handleManifestParsingError(response, context, reason, networkDetails) {
  3139. this.hls.trigger(_events2.default.ERROR, {
  3140. type: _errors.ErrorTypes.NETWORK_ERROR,
  3141. details: _errors.ErrorDetails.MANIFEST_PARSING_ERROR,
  3142. fatal: true,
  3143. url: response.url,
  3144. reason: reason,
  3145. networkDetails: networkDetails
  3146. });
  3147. }
  3148. }, {
  3149. key: '_handleNetworkError',
  3150. value: function _handleNetworkError(context, networkDetails) {
  3151. var timeout = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  3152. var response = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  3153. _logger.logger.info('A network error occured while loading a ' + context.type + '-type playlist');
  3154. var details = void 0;
  3155. var fatal = void 0;
  3156. var loader = this.getInternalLoader(context);
  3157. switch (context.type) {
  3158. case ContextType.MANIFEST:
  3159. details = timeout ? _errors.ErrorDetails.MANIFEST_LOAD_TIMEOUT : _errors.ErrorDetails.MANIFEST_LOAD_ERROR;
  3160. fatal = true;
  3161. break;
  3162. case ContextType.LEVEL:
  3163. details = timeout ? _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT : _errors.ErrorDetails.LEVEL_LOAD_ERROR;
  3164. fatal = false;
  3165. break;
  3166. case ContextType.AUDIO_TRACK:
  3167. details = timeout ? _errors.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : _errors.ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  3168. fatal = false;
  3169. break;
  3170. default:
  3171. // details = ...?
  3172. fatal = false;
  3173. }
  3174. if (loader) {
  3175. loader.abort();
  3176. this.resetInternalLoader(context.type);
  3177. }
  3178. var errorData = {
  3179. type: _errors.ErrorTypes.NETWORK_ERROR,
  3180. details: details,
  3181. fatal: fatal,
  3182. url: loader.url,
  3183. loader: loader,
  3184. context: context,
  3185. networkDetails: networkDetails
  3186. };
  3187. if (response) {
  3188. errorData.response = response;
  3189. }
  3190. this.hls.trigger(_events2.default.ERROR, errorData);
  3191. }
  3192. }, {
  3193. key: '_handlePlaylistLoaded',
  3194. value: function _handlePlaylistLoaded(response, stats, context, networkDetails) {
  3195. var type = context.type,
  3196. level = context.level,
  3197. id = context.id,
  3198. levelDetails = context.levelDetails;
  3199. if (!levelDetails.targetduration) {
  3200. this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails);
  3201. return;
  3202. }
  3203. var canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type);
  3204. if (canHaveLevels) {
  3205. this.hls.trigger(_events2.default.LEVEL_LOADED, {
  3206. details: levelDetails,
  3207. level: level || 0,
  3208. id: id || 0,
  3209. stats: stats,
  3210. networkDetails: networkDetails
  3211. });
  3212. } else {
  3213. switch (type) {
  3214. case ContextType.AUDIO_TRACK:
  3215. this.hls.trigger(_events2.default.AUDIO_TRACK_LOADED, {
  3216. details: levelDetails,
  3217. id: id,
  3218. stats: stats,
  3219. networkDetails: networkDetails
  3220. });
  3221. break;
  3222. case ContextType.SUBTITLE_TRACK:
  3223. this.hls.trigger(_events2.default.SUBTITLE_TRACK_LOADED, {
  3224. details: levelDetails,
  3225. id: id,
  3226. stats: stats,
  3227. networkDetails: networkDetails
  3228. });
  3229. break;
  3230. }
  3231. }
  3232. }
  3233. }], [{
  3234. key: 'canHaveQualityLevels',
  3235. /**
  3236. * @param {ContextType} type
  3237. * @returns {boolean}
  3238. */
  3239. value: function canHaveQualityLevels(type) {
  3240. return type !== ContextType.AUDIO_TRACK && type !== ContextType.SUBTITLE_TRACK;
  3241. }
  3242. /**
  3243. * Map context.type to LevelType
  3244. * @param {{type: ContextType}} context
  3245. * @returns {LevelType}
  3246. */
  3247. }, {
  3248. key: 'mapContextToLevelType',
  3249. value: function mapContextToLevelType(context) {
  3250. var type = context.type;
  3251. switch (type) {
  3252. case ContextType.AUDIO_TRACK:
  3253. return LevelType.AUDIO;
  3254. case ContextType.SUBTITLE_TRACK:
  3255. return LevelType.SUBTITLE;
  3256. default:
  3257. return LevelType.MAIN;
  3258. }
  3259. }
  3260. }, {
  3261. key: 'getResponseUrl',
  3262. value: function getResponseUrl(response, context) {
  3263. var url = response.url;
  3264. // responseURL not supported on some browsers (it is used to detect URL redirection)
  3265. // data-uri mode also not supported (but no need to detect redirection)
  3266. if (url === undefined || url.indexOf('data:') === 0) {
  3267. // fallback to initial URL
  3268. url = context.url;
  3269. }
  3270. return url;
  3271. }
  3272. }, {
  3273. key: 'ContextType',
  3274. get: function get() {
  3275. return ContextType;
  3276. }
  3277. }, {
  3278. key: 'LevelType',
  3279. get: function get() {
  3280. return LevelType;
  3281. }
  3282. }]);
  3283. return PlaylistLoader;
  3284. }(_eventHandler2.default);
  3285. exports.default = PlaylistLoader;
  3286. module.exports = exports['default'];
  3287. /***/ }),
  3288. /* 16 */
  3289. /***/ (function(module, exports, __webpack_require__) {
  3290. "use strict";
  3291. Object.defineProperty(exports, "__esModule", {
  3292. value: true
  3293. });
  3294. 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; }; }(); /**
  3295. * MP4 demuxer
  3296. */
  3297. var _logger = __webpack_require__(0);
  3298. var _events = __webpack_require__(1);
  3299. var _events2 = _interopRequireDefault(_events);
  3300. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  3301. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3302. var UINT32_MAX = Math.pow(2, 32) - 1;
  3303. var MP4Demuxer = function () {
  3304. function MP4Demuxer(observer, remuxer) {
  3305. _classCallCheck(this, MP4Demuxer);
  3306. this.observer = observer;
  3307. this.remuxer = remuxer;
  3308. }
  3309. _createClass(MP4Demuxer, [{
  3310. key: 'resetTimeStamp',
  3311. value: function resetTimeStamp(initPTS) {
  3312. this.initPTS = initPTS;
  3313. }
  3314. }, {
  3315. key: 'resetInitSegment',
  3316. value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  3317. // jshint unused:false
  3318. if (initSegment && initSegment.byteLength) {
  3319. var initData = this.initData = MP4Demuxer.parseInitSegment(initSegment);
  3320. // default audio codec if nothing specified
  3321. // TODO : extract that from initsegment
  3322. if (audioCodec == null) {
  3323. audioCodec = 'mp4a.40.5';
  3324. }
  3325. if (videoCodec == null) {
  3326. videoCodec = 'avc1.42e01e';
  3327. }
  3328. var tracks = {};
  3329. if (initData.audio && initData.video) {
  3330. tracks.audiovideo = { container: 'video/mp4', codec: audioCodec + ',' + videoCodec, initSegment: duration ? initSegment : null };
  3331. } else {
  3332. if (initData.audio) {
  3333. tracks.audio = { container: 'audio/mp4', codec: audioCodec, initSegment: duration ? initSegment : null };
  3334. }
  3335. if (initData.video) {
  3336. tracks.video = { container: 'video/mp4', codec: videoCodec, initSegment: duration ? initSegment : null };
  3337. }
  3338. }
  3339. this.observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, { tracks: tracks });
  3340. } else {
  3341. if (audioCodec) {
  3342. this.audioCodec = audioCodec;
  3343. }
  3344. if (videoCodec) {
  3345. this.videoCodec = videoCodec;
  3346. }
  3347. }
  3348. }
  3349. }, {
  3350. key: 'append',
  3351. // feed incoming data to the front of the parsing pipeline
  3352. value: function append(data, timeOffset, contiguous, accurateTimeOffset) {
  3353. var initData = this.initData;
  3354. if (!initData) {
  3355. this.resetInitSegment(data, this.audioCodec, this.videoCodec, false);
  3356. initData = this.initData;
  3357. }
  3358. var startDTS = void 0,
  3359. initPTS = this.initPTS;
  3360. if (initPTS === undefined) {
  3361. var _startDTS = MP4Demuxer.getStartDTS(initData, data);
  3362. this.initPTS = initPTS = _startDTS - timeOffset;
  3363. this.observer.trigger(_events2.default.INIT_PTS_FOUND, { initPTS: initPTS });
  3364. }
  3365. MP4Demuxer.offsetStartDTS(initData, data, initPTS);
  3366. startDTS = MP4Demuxer.getStartDTS(initData, data);
  3367. this.remuxer.remux(initData.audio, initData.video, null, null, startDTS, contiguous, accurateTimeOffset, data);
  3368. }
  3369. }, {
  3370. key: 'destroy',
  3371. value: function destroy() {}
  3372. }], [{
  3373. key: 'probe',
  3374. value: function probe(data) {
  3375. // ensure we find a moof box in the first 16 kB
  3376. return MP4Demuxer.findBox({ data: data, start: 0, end: Math.min(data.length, 16384) }, ['moof']).length > 0;
  3377. }
  3378. }, {
  3379. key: 'bin2str',
  3380. value: function bin2str(buffer) {
  3381. return String.fromCharCode.apply(null, buffer);
  3382. }
  3383. }, {
  3384. key: 'readUint16',
  3385. value: function readUint16(buffer, offset) {
  3386. if (buffer.data) {
  3387. offset += buffer.start;
  3388. buffer = buffer.data;
  3389. }
  3390. var val = buffer[offset] << 8 | buffer[offset + 1];
  3391. return val < 0 ? 65536 + val : val;
  3392. }
  3393. }, {
  3394. key: 'readUint32',
  3395. value: function readUint32(buffer, offset) {
  3396. if (buffer.data) {
  3397. offset += buffer.start;
  3398. buffer = buffer.data;
  3399. }
  3400. var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
  3401. return val < 0 ? 4294967296 + val : val;
  3402. }
  3403. }, {
  3404. key: 'writeUint32',
  3405. value: function writeUint32(buffer, offset, value) {
  3406. if (buffer.data) {
  3407. offset += buffer.start;
  3408. buffer = buffer.data;
  3409. }
  3410. buffer[offset] = value >> 24;
  3411. buffer[offset + 1] = value >> 16 & 0xff;
  3412. buffer[offset + 2] = value >> 8 & 0xff;
  3413. buffer[offset + 3] = value & 0xff;
  3414. }
  3415. // Find the data for a box specified by its path
  3416. }, {
  3417. key: 'findBox',
  3418. value: function findBox(data, path) {
  3419. var results = [],
  3420. i = void 0,
  3421. size = void 0,
  3422. type = void 0,
  3423. end = void 0,
  3424. subresults = void 0,
  3425. start = void 0,
  3426. endbox = void 0;
  3427. if (data.data) {
  3428. start = data.start;
  3429. end = data.end;
  3430. data = data.data;
  3431. } else {
  3432. start = 0;
  3433. end = data.byteLength;
  3434. }
  3435. if (!path.length) {
  3436. // short-circuit the search for empty paths
  3437. return null;
  3438. }
  3439. for (i = start; i < end;) {
  3440. size = MP4Demuxer.readUint32(data, i);
  3441. type = MP4Demuxer.bin2str(data.subarray(i + 4, i + 8));
  3442. endbox = size > 1 ? i + size : end;
  3443. if (type === path[0]) {
  3444. if (path.length === 1) {
  3445. // this is the end of the path and we've found the box we were
  3446. // looking for
  3447. results.push({ data: data, start: i + 8, end: endbox });
  3448. } else {
  3449. // recursively search for the next box along the path
  3450. subresults = MP4Demuxer.findBox({ data: data, start: i + 8, end: endbox }, path.slice(1));
  3451. if (subresults.length) {
  3452. results = results.concat(subresults);
  3453. }
  3454. }
  3455. }
  3456. i = endbox;
  3457. }
  3458. // we've finished searching all of data
  3459. return results;
  3460. }
  3461. }, {
  3462. key: 'parseSegmentIndex',
  3463. value: function parseSegmentIndex(initSegment) {
  3464. var moov = MP4Demuxer.findBox(initSegment, ['moov'])[0];
  3465. var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data
  3466. var index = 0;
  3467. var sidx = MP4Demuxer.findBox(initSegment, ['sidx']);
  3468. var references = void 0;
  3469. if (!sidx || !sidx[0]) {
  3470. return null;
  3471. }
  3472. references = [];
  3473. sidx = sidx[0];
  3474. var version = sidx.data[0];
  3475. // set initial offset, we skip the reference ID (not needed)
  3476. index = version === 0 ? 8 : 16;
  3477. var timescale = MP4Demuxer.readUint32(sidx, index);
  3478. index += 4;
  3479. // TODO: parse earliestPresentationTime and firstOffset
  3480. // usually zero in our case
  3481. var earliestPresentationTime = 0;
  3482. var firstOffset = 0;
  3483. if (version === 0) {
  3484. index += 8;
  3485. } else {
  3486. index += 16;
  3487. }
  3488. // skip reserved
  3489. index += 2;
  3490. var startByte = sidx.end + firstOffset;
  3491. var referencesCount = MP4Demuxer.readUint16(sidx, index);
  3492. index += 2;
  3493. for (var i = 0; i < referencesCount; i++) {
  3494. var referenceIndex = index;
  3495. var referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex);
  3496. referenceIndex += 4;
  3497. var referenceSize = referenceInfo & 0x7FFFFFFF;
  3498. var referenceType = (referenceInfo & 0x80000000) >>> 31;
  3499. if (referenceType === 1) {
  3500. console.warn('SIDX has hierarchical references (not supported)');
  3501. return;
  3502. }
  3503. var subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex);
  3504. referenceIndex += 4;
  3505. references.push({
  3506. referenceSize: referenceSize,
  3507. subsegmentDuration: subsegmentDuration, // unscaled
  3508. info: {
  3509. duration: subsegmentDuration / timescale,
  3510. start: startByte,
  3511. end: startByte + referenceSize - 1
  3512. }
  3513. });
  3514. startByte += referenceSize;
  3515. // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
  3516. // for |sapDelta|.
  3517. referenceIndex += 4;
  3518. // skip to next ref
  3519. index = referenceIndex;
  3520. }
  3521. return {
  3522. earliestPresentationTime: earliestPresentationTime,
  3523. timescale: timescale,
  3524. version: version,
  3525. referencesCount: referencesCount,
  3526. references: references,
  3527. moovEndOffset: moovEndOffset
  3528. };
  3529. }
  3530. /**
  3531. * Parses an MP4 initialization segment and extracts stream type and
  3532. * timescale values for any declared tracks. Timescale values indicate the
  3533. * number of clock ticks per second to assume for time-based values
  3534. * elsewhere in the MP4.
  3535. *
  3536. * To determine the start time of an MP4, you need two pieces of
  3537. * information: the timescale unit and the earliest base media decode
  3538. * time. Multiple timescales can be specified within an MP4 but the
  3539. * base media decode time is always expressed in the timescale from
  3540. * the media header box for the track:
  3541. * ```
  3542. * moov > trak > mdia > mdhd.timescale
  3543. * moov > trak > mdia > hdlr
  3544. * ```
  3545. * @param init {Uint8Array} the bytes of the init segment
  3546. * @return {object} a hash of track type to timescale values or null if
  3547. * the init segment is malformed.
  3548. */
  3549. }, {
  3550. key: 'parseInitSegment',
  3551. value: function parseInitSegment(initSegment) {
  3552. var result = [];
  3553. var traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']);
  3554. traks.forEach(function (trak) {
  3555. var tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0];
  3556. if (tkhd) {
  3557. var version = tkhd.data[tkhd.start];
  3558. var index = version === 0 ? 12 : 20;
  3559. var trackId = MP4Demuxer.readUint32(tkhd, index);
  3560. var mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0];
  3561. if (mdhd) {
  3562. version = mdhd.data[mdhd.start];
  3563. index = version === 0 ? 12 : 20;
  3564. var timescale = MP4Demuxer.readUint32(mdhd, index);
  3565. var hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0];
  3566. if (hdlr) {
  3567. var hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));
  3568. var type = { 'soun': 'audio', 'vide': 'video' }[hdlrType];
  3569. if (type) {
  3570. // extract codec info. TODO : parse codec details to be able to build MIME type
  3571. var codecBox = MP4Demuxer.findBox(trak, ['mdia', 'minf', 'stbl', 'stsd']);
  3572. if (codecBox.length) {
  3573. codecBox = codecBox[0];
  3574. var codecType = MP4Demuxer.bin2str(codecBox.data.subarray(codecBox.start + 12, codecBox.start + 16));
  3575. _logger.logger.log('MP4Demuxer:' + type + ':' + codecType + ' found');
  3576. }
  3577. result[trackId] = { timescale: timescale, type: type };
  3578. result[type] = { timescale: timescale, id: trackId };
  3579. }
  3580. }
  3581. }
  3582. }
  3583. });
  3584. return result;
  3585. }
  3586. /**
  3587. * Determine the base media decode start time, in seconds, for an MP4
  3588. * fragment. If multiple fragments are specified, the earliest time is
  3589. * returned.
  3590. *
  3591. * The base media decode time can be parsed from track fragment
  3592. * metadata:
  3593. * ```
  3594. * moof > traf > tfdt.baseMediaDecodeTime
  3595. * ```
  3596. * It requires the timescale value from the mdhd to interpret.
  3597. *
  3598. * @param timescale {object} a hash of track ids to timescale values.
  3599. * @return {number} the earliest base media decode start time for the
  3600. * fragment, in seconds
  3601. */
  3602. }, {
  3603. key: 'getStartDTS',
  3604. value: function getStartDTS(initData, fragment) {
  3605. var trafs = void 0,
  3606. baseTimes = void 0,
  3607. result = void 0;
  3608. // we need info from two childrend of each track fragment box
  3609. trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']);
  3610. // determine the start times for each track
  3611. baseTimes = [].concat.apply([], trafs.map(function (traf) {
  3612. return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
  3613. var id = void 0,
  3614. scale = void 0,
  3615. baseTime = void 0;
  3616. // get the track id from the tfhd
  3617. id = MP4Demuxer.readUint32(tfhd, 4);
  3618. // assume a 90kHz clock if no timescale was specified
  3619. scale = initData[id].timescale || 90e3;
  3620. // get the base media decode time from the tfdt
  3621. baseTime = MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
  3622. var version = void 0,
  3623. result = void 0;
  3624. version = tfdt.data[tfdt.start];
  3625. result = MP4Demuxer.readUint32(tfdt, 4);
  3626. if (version === 1) {
  3627. result *= Math.pow(2, 32);
  3628. result += MP4Demuxer.readUint32(tfdt, 8);
  3629. }
  3630. return result;
  3631. })[0];
  3632. // convert base time to seconds
  3633. return baseTime / scale;
  3634. });
  3635. }));
  3636. // return the minimum
  3637. result = Math.min.apply(null, baseTimes);
  3638. return isFinite(result) ? result : 0;
  3639. }
  3640. }, {
  3641. key: 'offsetStartDTS',
  3642. value: function offsetStartDTS(initData, fragment, timeOffset) {
  3643. MP4Demuxer.findBox(fragment, ['moof', 'traf']).map(function (traf) {
  3644. return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
  3645. // get the track id from the tfhd
  3646. var id = MP4Demuxer.readUint32(tfhd, 4);
  3647. // assume a 90kHz clock if no timescale was specified
  3648. var timescale = initData[id].timescale || 90e3;
  3649. // get the base media decode time from the tfdt
  3650. MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
  3651. var version = tfdt.data[tfdt.start];
  3652. var baseMediaDecodeTime = MP4Demuxer.readUint32(tfdt, 4);
  3653. if (version === 0) {
  3654. MP4Demuxer.writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);
  3655. } else {
  3656. baseMediaDecodeTime *= Math.pow(2, 32);
  3657. baseMediaDecodeTime += MP4Demuxer.readUint32(tfdt, 8);
  3658. baseMediaDecodeTime -= timeOffset * timescale;
  3659. baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
  3660. var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  3661. var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  3662. MP4Demuxer.writeUint32(tfdt, 4, upper);
  3663. MP4Demuxer.writeUint32(tfdt, 8, lower);
  3664. }
  3665. });
  3666. });
  3667. });
  3668. }
  3669. }]);
  3670. return MP4Demuxer;
  3671. }();
  3672. exports.default = MP4Demuxer;
  3673. module.exports = exports['default'];
  3674. /***/ }),
  3675. /* 17 */
  3676. /***/ (function(module, exports, __webpack_require__) {
  3677. "use strict";
  3678. Object.defineProperty(exports, "__esModule", {
  3679. value: true
  3680. });
  3681. 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; }; }();
  3682. var _urlToolkit = __webpack_require__(8);
  3683. var URLToolkit = _interopRequireWildcard(_urlToolkit);
  3684. 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; } }
  3685. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3686. var LevelKey = function () {
  3687. function LevelKey() {
  3688. _classCallCheck(this, LevelKey);
  3689. this.method = null;
  3690. this.key = null;
  3691. this.iv = null;
  3692. this._uri = null;
  3693. }
  3694. _createClass(LevelKey, [{
  3695. key: 'uri',
  3696. get: function get() {
  3697. if (!this._uri && this.reluri) {
  3698. this._uri = URLToolkit.buildAbsoluteURL(this.baseuri, this.reluri, { alwaysNormalize: true });
  3699. }
  3700. return this._uri;
  3701. }
  3702. }]);
  3703. return LevelKey;
  3704. }();
  3705. exports.default = LevelKey;
  3706. module.exports = exports['default'];
  3707. /***/ }),
  3708. /* 18 */
  3709. /***/ (function(module, exports, __webpack_require__) {
  3710. "use strict";
  3711. Object.defineProperty(exports, "__esModule", {
  3712. value: true
  3713. });
  3714. // from http://mp4ra.org/codecs.html
  3715. var sampleEntryCodesISO = {
  3716. audio: {
  3717. 'a3ds': true,
  3718. 'ac-3': true,
  3719. 'ac-4': true,
  3720. 'alac': true,
  3721. 'alaw': true,
  3722. 'dra1': true,
  3723. 'dts+': true,
  3724. 'dts-': true,
  3725. 'dtsc': true,
  3726. 'dtse': true,
  3727. 'dtsh': true,
  3728. 'ec-3': true,
  3729. 'enca': true,
  3730. 'g719': true,
  3731. 'g726': true,
  3732. 'm4ae': true,
  3733. 'mha1': true,
  3734. 'mha2': true,
  3735. 'mhm1': true,
  3736. 'mhm2': true,
  3737. 'mlpa': true,
  3738. 'mp4a': true,
  3739. 'raw ': true,
  3740. 'Opus': true,
  3741. 'samr': true,
  3742. 'sawb': true,
  3743. 'sawp': true,
  3744. 'sevc': true,
  3745. 'sqcp': true,
  3746. 'ssmv': true,
  3747. 'twos': true,
  3748. 'ulaw': true
  3749. },
  3750. video: {
  3751. 'avc1': true,
  3752. 'avc2': true,
  3753. 'avc3': true,
  3754. 'avc4': true,
  3755. 'avcp': true,
  3756. 'drac': true,
  3757. 'dvav': true,
  3758. 'dvhe': true,
  3759. 'encv': true,
  3760. 'hev1': true,
  3761. 'hvc1': true,
  3762. 'mjp2': true,
  3763. 'mp4v': true,
  3764. 'mvc1': true,
  3765. 'mvc2': true,
  3766. 'mvc3': true,
  3767. 'mvc4': true,
  3768. 'resv': true,
  3769. 'rv60': true,
  3770. 's263': true,
  3771. 'svc1': true,
  3772. 'svc2': true,
  3773. 'vc-1': true,
  3774. 'vp08': true,
  3775. 'vp09': true
  3776. }
  3777. };
  3778. function isCodecType(codec, type) {
  3779. var typeCodes = sampleEntryCodesISO[type];
  3780. return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;
  3781. }
  3782. function isCodecSupportedInMp4(codec, type) {
  3783. return window.MediaSource.isTypeSupported((type || 'video') + '/mp4;codecs="' + codec + '"');
  3784. }
  3785. exports.isCodecType = isCodecType;
  3786. exports.isCodecSupportedInMp4 = isCodecSupportedInMp4;
  3787. /***/ }),
  3788. /* 19 */
  3789. /***/ (function(module, exports, __webpack_require__) {
  3790. "use strict";
  3791. Object.defineProperty(exports, "__esModule", {
  3792. value: true
  3793. });
  3794. 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; }; }();
  3795. var _events = __webpack_require__(20);
  3796. var _webworkifyWebpack = __webpack_require__(41);
  3797. var work = _interopRequireWildcard(_webworkifyWebpack);
  3798. var _events2 = __webpack_require__(1);
  3799. var _events3 = _interopRequireDefault(_events2);
  3800. var _demuxerInline = __webpack_require__(21);
  3801. var _demuxerInline2 = _interopRequireDefault(_demuxerInline);
  3802. var _logger = __webpack_require__(0);
  3803. var _errors = __webpack_require__(2);
  3804. var _mediasourceHelper = __webpack_require__(13);
  3805. var _getSelfScope = __webpack_require__(5);
  3806. var _observer = __webpack_require__(24);
  3807. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  3808. 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; } }
  3809. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3810. // see https://stackoverflow.com/a/11237259/589493
  3811. var global = (0, _getSelfScope.getSelfScope)(); // safeguard for code that might run both on worker and main thread
  3812. var MediaSource = (0, _mediasourceHelper.getMediaSource)();
  3813. var Demuxer = function () {
  3814. function Demuxer(hls, id) {
  3815. var _this = this;
  3816. _classCallCheck(this, Demuxer);
  3817. this.hls = hls;
  3818. this.id = id;
  3819. var observer = this.observer = new _observer.Observer();
  3820. var config = hls.config;
  3821. var forwardMessage = function forwardMessage(ev, data) {
  3822. data = data || {};
  3823. data.frag = _this.frag;
  3824. data.id = _this.id;
  3825. hls.trigger(ev, data);
  3826. };
  3827. // forward events to main thread
  3828. observer.on(_events3.default.FRAG_DECRYPTED, forwardMessage);
  3829. observer.on(_events3.default.FRAG_PARSING_INIT_SEGMENT, forwardMessage);
  3830. observer.on(_events3.default.FRAG_PARSING_DATA, forwardMessage);
  3831. observer.on(_events3.default.FRAG_PARSED, forwardMessage);
  3832. observer.on(_events3.default.ERROR, forwardMessage);
  3833. observer.on(_events3.default.FRAG_PARSING_METADATA, forwardMessage);
  3834. observer.on(_events3.default.FRAG_PARSING_USERDATA, forwardMessage);
  3835. observer.on(_events3.default.INIT_PTS_FOUND, forwardMessage);
  3836. var typeSupported = {
  3837. mp4: MediaSource.isTypeSupported('video/mp4'),
  3838. mpeg: MediaSource.isTypeSupported('audio/mpeg'),
  3839. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"')
  3840. };
  3841. // navigator.vendor is not always available in Web Worker
  3842. // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator
  3843. var vendor = navigator.vendor;
  3844. if (config.enableWorker && typeof Worker !== 'undefined') {
  3845. _logger.logger.log('demuxing in webworker');
  3846. var w = void 0;
  3847. try {
  3848. w = this.w = work(/*require.resolve*/(55));
  3849. this.onwmsg = this.onWorkerMessage.bind(this);
  3850. w.addEventListener('message', this.onwmsg);
  3851. w.onerror = function (event) {
  3852. 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 + ')' } });
  3853. };
  3854. w.postMessage({ cmd: 'init', typeSupported: typeSupported, vendor: vendor, id: id, config: JSON.stringify(config) });
  3855. } catch (err) {
  3856. _logger.logger.warn('Error in worker:', err);
  3857. _logger.logger.error('Error while initializing DemuxerWorker, fallback on DemuxerInline');
  3858. if (w) {
  3859. // revoke the Object URL that was used to create demuxer worker, so as not to leak it
  3860. global.URL.revokeObjectURL(w.objectURL);
  3861. }
  3862. this.demuxer = new _demuxerInline2.default(observer, typeSupported, config, vendor);
  3863. this.w = undefined;
  3864. }
  3865. } else {
  3866. this.demuxer = new _demuxerInline2.default(observer, typeSupported, config, vendor);
  3867. }
  3868. }
  3869. _createClass(Demuxer, [{
  3870. key: 'destroy',
  3871. value: function destroy() {
  3872. var w = this.w;
  3873. if (w) {
  3874. w.removeEventListener('message', this.onwmsg);
  3875. w.terminate();
  3876. this.w = null;
  3877. } else {
  3878. var demuxer = this.demuxer;
  3879. if (demuxer) {
  3880. demuxer.destroy();
  3881. this.demuxer = null;
  3882. }
  3883. }
  3884. var observer = this.observer;
  3885. if (observer) {
  3886. observer.removeAllListeners();
  3887. this.observer = null;
  3888. }
  3889. }
  3890. }, {
  3891. key: 'push',
  3892. value: function push(data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) {
  3893. var w = this.w;
  3894. var timeOffset = Number.isFinite(frag.startPTS) ? frag.startPTS : frag.start;
  3895. var decryptdata = frag.decryptdata;
  3896. var lastFrag = this.frag;
  3897. var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  3898. var trackSwitch = !(lastFrag && frag.level === lastFrag.level);
  3899. var nextSN = lastFrag && frag.sn === lastFrag.sn + 1;
  3900. var contiguous = !trackSwitch && nextSN;
  3901. if (discontinuity) {
  3902. _logger.logger.log(this.id + ':discontinuity detected');
  3903. }
  3904. if (trackSwitch) {
  3905. _logger.logger.log(this.id + ':switch detected');
  3906. }
  3907. this.frag = frag;
  3908. if (w) {
  3909. // post fragment payload as transferable objects for ArrayBuffer (no copy)
  3910. 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] : []);
  3911. } else {
  3912. var demuxer = this.demuxer;
  3913. if (demuxer) {
  3914. demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  3915. }
  3916. }
  3917. }
  3918. }, {
  3919. key: 'onWorkerMessage',
  3920. value: function onWorkerMessage(ev) {
  3921. var data = ev.data,
  3922. hls = this.hls;
  3923. switch (data.event) {
  3924. case 'init':
  3925. // revoke the Object URL that was used to create demuxer worker, so as not to leak it
  3926. global.URL.revokeObjectURL(this.w.objectURL);
  3927. break;
  3928. // special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects
  3929. case _events3.default.FRAG_PARSING_DATA:
  3930. data.data.data1 = new Uint8Array(data.data1);
  3931. if (data.data2) {
  3932. data.data.data2 = new Uint8Array(data.data2);
  3933. }
  3934. /* falls through */
  3935. default:
  3936. data.data = data.data || {};
  3937. data.data.frag = this.frag;
  3938. data.data.id = this.id;
  3939. hls.trigger(data.event, data.data);
  3940. break;
  3941. }
  3942. }
  3943. }]);
  3944. return Demuxer;
  3945. }();
  3946. exports.default = Demuxer;
  3947. module.exports = exports['default'];
  3948. /***/ }),
  3949. /* 20 */
  3950. /***/ (function(module, exports, __webpack_require__) {
  3951. "use strict";
  3952. // Copyright Joyent, Inc. and other Node contributors.
  3953. //
  3954. // Permission is hereby granted, free of charge, to any person obtaining a
  3955. // copy of this software and associated documentation files (the
  3956. // "Software"), to deal in the Software without restriction, including
  3957. // without limitation the rights to use, copy, modify, merge, publish,
  3958. // distribute, sublicense, and/or sell copies of the Software, and to permit
  3959. // persons to whom the Software is furnished to do so, subject to the
  3960. // following conditions:
  3961. //
  3962. // The above copyright notice and this permission notice shall be included
  3963. // in all copies or substantial portions of the Software.
  3964. //
  3965. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3966. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3967. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  3968. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  3969. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  3970. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  3971. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  3972. var R = typeof Reflect === 'object' ? Reflect : null
  3973. var ReflectApply = R && typeof R.apply === 'function'
  3974. ? R.apply
  3975. : function ReflectApply(target, receiver, args) {
  3976. return Function.prototype.apply.call(target, receiver, args);
  3977. }
  3978. var ReflectOwnKeys
  3979. if (R && typeof R.ownKeys === 'function') {
  3980. ReflectOwnKeys = R.ownKeys
  3981. } else if (Object.getOwnPropertySymbols) {
  3982. ReflectOwnKeys = function ReflectOwnKeys(target) {
  3983. return Object.getOwnPropertyNames(target)
  3984. .concat(Object.getOwnPropertySymbols(target));
  3985. };
  3986. } else {
  3987. ReflectOwnKeys = function ReflectOwnKeys(target) {
  3988. return Object.getOwnPropertyNames(target);
  3989. };
  3990. }
  3991. function ProcessEmitWarning(warning) {
  3992. if (console && console.warn) console.warn(warning);
  3993. }
  3994. var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
  3995. return value !== value;
  3996. }
  3997. function EventEmitter() {
  3998. EventEmitter.init.call(this);
  3999. }
  4000. module.exports = EventEmitter;
  4001. // Backwards-compat with node 0.10.x
  4002. EventEmitter.EventEmitter = EventEmitter;
  4003. EventEmitter.prototype._events = undefined;
  4004. EventEmitter.prototype._eventsCount = 0;
  4005. EventEmitter.prototype._maxListeners = undefined;
  4006. // By default EventEmitters will print a warning if more than 10 listeners are
  4007. // added to it. This is a useful default which helps finding memory leaks.
  4008. var defaultMaxListeners = 10;
  4009. function checkListener(listener) {
  4010. if (typeof listener !== 'function') {
  4011. throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
  4012. }
  4013. }
  4014. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  4015. enumerable: true,
  4016. get: function() {
  4017. return defaultMaxListeners;
  4018. },
  4019. set: function(arg) {
  4020. if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
  4021. throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
  4022. }
  4023. defaultMaxListeners = arg;
  4024. }
  4025. });
  4026. EventEmitter.init = function() {
  4027. if (this._events === undefined ||
  4028. this._events === Object.getPrototypeOf(this)._events) {
  4029. this._events = Object.create(null);
  4030. this._eventsCount = 0;
  4031. }
  4032. this._maxListeners = this._maxListeners || undefined;
  4033. };
  4034. // Obviously not all Emitters should be limited to 10. This function allows
  4035. // that to be increased. Set to zero for unlimited.
  4036. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  4037. if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
  4038. throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
  4039. }
  4040. this._maxListeners = n;
  4041. return this;
  4042. };
  4043. function _getMaxListeners(that) {
  4044. if (that._maxListeners === undefined)
  4045. return EventEmitter.defaultMaxListeners;
  4046. return that._maxListeners;
  4047. }
  4048. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  4049. return _getMaxListeners(this);
  4050. };
  4051. EventEmitter.prototype.emit = function emit(type) {
  4052. var args = [];
  4053. for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
  4054. var doError = (type === 'error');
  4055. var events = this._events;
  4056. if (events !== undefined)
  4057. doError = (doError && events.error === undefined);
  4058. else if (!doError)
  4059. return false;
  4060. // If there is no 'error' event listener then throw.
  4061. if (doError) {
  4062. var er;
  4063. if (args.length > 0)
  4064. er = args[0];
  4065. if (er instanceof Error) {
  4066. // Note: The comments on the `throw` lines are intentional, they show
  4067. // up in Node's output if this results in an unhandled exception.
  4068. throw er; // Unhandled 'error' event
  4069. }
  4070. // At least give some kind of context to the user
  4071. var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
  4072. err.context = er;
  4073. throw err; // Unhandled 'error' event
  4074. }
  4075. var handler = events[type];
  4076. if (handler === undefined)
  4077. return false;
  4078. if (typeof handler === 'function') {
  4079. ReflectApply(handler, this, args);
  4080. } else {
  4081. var len = handler.length;
  4082. var listeners = arrayClone(handler, len);
  4083. for (var i = 0; i < len; ++i)
  4084. ReflectApply(listeners[i], this, args);
  4085. }
  4086. return true;
  4087. };
  4088. function _addListener(target, type, listener, prepend) {
  4089. var m;
  4090. var events;
  4091. var existing;
  4092. checkListener(listener);
  4093. events = target._events;
  4094. if (events === undefined) {
  4095. events = target._events = Object.create(null);
  4096. target._eventsCount = 0;
  4097. } else {
  4098. // To avoid recursion in the case that type === "newListener"! Before
  4099. // adding it to the listeners, first emit "newListener".
  4100. if (events.newListener !== undefined) {
  4101. target.emit('newListener', type,
  4102. listener.listener ? listener.listener : listener);
  4103. // Re-assign `events` because a newListener handler could have caused the
  4104. // this._events to be assigned to a new object
  4105. events = target._events;
  4106. }
  4107. existing = events[type];
  4108. }
  4109. if (existing === undefined) {
  4110. // Optimize the case of one listener. Don't need the extra array object.
  4111. existing = events[type] = listener;
  4112. ++target._eventsCount;
  4113. } else {
  4114. if (typeof existing === 'function') {
  4115. // Adding the second element, need to change to array.
  4116. existing = events[type] =
  4117. prepend ? [listener, existing] : [existing, listener];
  4118. // If we've already got an array, just append.
  4119. } else if (prepend) {
  4120. existing.unshift(listener);
  4121. } else {
  4122. existing.push(listener);
  4123. }
  4124. // Check for listener leak
  4125. m = _getMaxListeners(target);
  4126. if (m > 0 && existing.length > m && !existing.warned) {
  4127. existing.warned = true;
  4128. // No error code for this since it is a Warning
  4129. // eslint-disable-next-line no-restricted-syntax
  4130. var w = new Error('Possible EventEmitter memory leak detected. ' +
  4131. existing.length + ' ' + String(type) + ' listeners ' +
  4132. 'added. Use emitter.setMaxListeners() to ' +
  4133. 'increase limit');
  4134. w.name = 'MaxListenersExceededWarning';
  4135. w.emitter = target;
  4136. w.type = type;
  4137. w.count = existing.length;
  4138. ProcessEmitWarning(w);
  4139. }
  4140. }
  4141. return target;
  4142. }
  4143. EventEmitter.prototype.addListener = function addListener(type, listener) {
  4144. return _addListener(this, type, listener, false);
  4145. };
  4146. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  4147. EventEmitter.prototype.prependListener =
  4148. function prependListener(type, listener) {
  4149. return _addListener(this, type, listener, true);
  4150. };
  4151. function onceWrapper() {
  4152. if (!this.fired) {
  4153. this.target.removeListener(this.type, this.wrapFn);
  4154. this.fired = true;
  4155. if (arguments.length === 0)
  4156. return this.listener.call(this.target);
  4157. return this.listener.apply(this.target, arguments);
  4158. }
  4159. }
  4160. function _onceWrap(target, type, listener) {
  4161. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  4162. var wrapped = onceWrapper.bind(state);
  4163. wrapped.listener = listener;
  4164. state.wrapFn = wrapped;
  4165. return wrapped;
  4166. }
  4167. EventEmitter.prototype.once = function once(type, listener) {
  4168. checkListener(listener);
  4169. this.on(type, _onceWrap(this, type, listener));
  4170. return this;
  4171. };
  4172. EventEmitter.prototype.prependOnceListener =
  4173. function prependOnceListener(type, listener) {
  4174. checkListener(listener);
  4175. this.prependListener(type, _onceWrap(this, type, listener));
  4176. return this;
  4177. };
  4178. // Emits a 'removeListener' event if and only if the listener was removed.
  4179. EventEmitter.prototype.removeListener =
  4180. function removeListener(type, listener) {
  4181. var list, events, position, i, originalListener;
  4182. checkListener(listener);
  4183. events = this._events;
  4184. if (events === undefined)
  4185. return this;
  4186. list = events[type];
  4187. if (list === undefined)
  4188. return this;
  4189. if (list === listener || list.listener === listener) {
  4190. if (--this._eventsCount === 0)
  4191. this._events = Object.create(null);
  4192. else {
  4193. delete events[type];
  4194. if (events.removeListener)
  4195. this.emit('removeListener', type, list.listener || listener);
  4196. }
  4197. } else if (typeof list !== 'function') {
  4198. position = -1;
  4199. for (i = list.length - 1; i >= 0; i--) {
  4200. if (list[i] === listener || list[i].listener === listener) {
  4201. originalListener = list[i].listener;
  4202. position = i;
  4203. break;
  4204. }
  4205. }
  4206. if (position < 0)
  4207. return this;
  4208. if (position === 0)
  4209. list.shift();
  4210. else {
  4211. spliceOne(list, position);
  4212. }
  4213. if (list.length === 1)
  4214. events[type] = list[0];
  4215. if (events.removeListener !== undefined)
  4216. this.emit('removeListener', type, originalListener || listener);
  4217. }
  4218. return this;
  4219. };
  4220. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  4221. EventEmitter.prototype.removeAllListeners =
  4222. function removeAllListeners(type) {
  4223. var listeners, events, i;
  4224. events = this._events;
  4225. if (events === undefined)
  4226. return this;
  4227. // not listening for removeListener, no need to emit
  4228. if (events.removeListener === undefined) {
  4229. if (arguments.length === 0) {
  4230. this._events = Object.create(null);
  4231. this._eventsCount = 0;
  4232. } else if (events[type] !== undefined) {
  4233. if (--this._eventsCount === 0)
  4234. this._events = Object.create(null);
  4235. else
  4236. delete events[type];
  4237. }
  4238. return this;
  4239. }
  4240. // emit removeListener for all listeners on all events
  4241. if (arguments.length === 0) {
  4242. var keys = Object.keys(events);
  4243. var key;
  4244. for (i = 0; i < keys.length; ++i) {
  4245. key = keys[i];
  4246. if (key === 'removeListener') continue;
  4247. this.removeAllListeners(key);
  4248. }
  4249. this.removeAllListeners('removeListener');
  4250. this._events = Object.create(null);
  4251. this._eventsCount = 0;
  4252. return this;
  4253. }
  4254. listeners = events[type];
  4255. if (typeof listeners === 'function') {
  4256. this.removeListener(type, listeners);
  4257. } else if (listeners !== undefined) {
  4258. // LIFO order
  4259. for (i = listeners.length - 1; i >= 0; i--) {
  4260. this.removeListener(type, listeners[i]);
  4261. }
  4262. }
  4263. return this;
  4264. };
  4265. function _listeners(target, type, unwrap) {
  4266. var events = target._events;
  4267. if (events === undefined)
  4268. return [];
  4269. var evlistener = events[type];
  4270. if (evlistener === undefined)
  4271. return [];
  4272. if (typeof evlistener === 'function')
  4273. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  4274. return unwrap ?
  4275. unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  4276. }
  4277. EventEmitter.prototype.listeners = function listeners(type) {
  4278. return _listeners(this, type, true);
  4279. };
  4280. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  4281. return _listeners(this, type, false);
  4282. };
  4283. EventEmitter.listenerCount = function(emitter, type) {
  4284. if (typeof emitter.listenerCount === 'function') {
  4285. return emitter.listenerCount(type);
  4286. } else {
  4287. return listenerCount.call(emitter, type);
  4288. }
  4289. };
  4290. EventEmitter.prototype.listenerCount = listenerCount;
  4291. function listenerCount(type) {
  4292. var events = this._events;
  4293. if (events !== undefined) {
  4294. var evlistener = events[type];
  4295. if (typeof evlistener === 'function') {
  4296. return 1;
  4297. } else if (evlistener !== undefined) {
  4298. return evlistener.length;
  4299. }
  4300. }
  4301. return 0;
  4302. }
  4303. EventEmitter.prototype.eventNames = function eventNames() {
  4304. return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
  4305. };
  4306. function arrayClone(arr, n) {
  4307. var copy = new Array(n);
  4308. for (var i = 0; i < n; ++i)
  4309. copy[i] = arr[i];
  4310. return copy;
  4311. }
  4312. function spliceOne(list, index) {
  4313. for (; index + 1 < list.length; index++)
  4314. list[index] = list[index + 1];
  4315. list.pop();
  4316. }
  4317. function unwrapListeners(arr) {
  4318. var ret = new Array(arr.length);
  4319. for (var i = 0; i < ret.length; ++i) {
  4320. ret[i] = arr[i].listener || arr[i];
  4321. }
  4322. return ret;
  4323. }
  4324. /***/ }),
  4325. /* 21 */
  4326. /***/ (function(module, exports, __webpack_require__) {
  4327. "use strict";
  4328. Object.defineProperty(exports, "__esModule", {
  4329. value: true
  4330. });
  4331. 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; }; }(); /**
  4332. *
  4333. * inline demuxer: probe fragments and instantiate
  4334. * appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)
  4335. *
  4336. */
  4337. var _events = __webpack_require__(1);
  4338. var _events2 = _interopRequireDefault(_events);
  4339. var _errors = __webpack_require__(2);
  4340. var _decrypter = __webpack_require__(12);
  4341. var _decrypter2 = _interopRequireDefault(_decrypter);
  4342. var _aacdemuxer = __webpack_require__(45);
  4343. var _aacdemuxer2 = _interopRequireDefault(_aacdemuxer);
  4344. var _mp4demuxer = __webpack_require__(16);
  4345. var _mp4demuxer2 = _interopRequireDefault(_mp4demuxer);
  4346. var _tsdemuxer = __webpack_require__(46);
  4347. var _tsdemuxer2 = _interopRequireDefault(_tsdemuxer);
  4348. var _mp3demuxer = __webpack_require__(49);
  4349. var _mp3demuxer2 = _interopRequireDefault(_mp3demuxer);
  4350. var _mp4Remuxer = __webpack_require__(50);
  4351. var _mp4Remuxer2 = _interopRequireDefault(_mp4Remuxer);
  4352. var _passthroughRemuxer = __webpack_require__(53);
  4353. var _passthroughRemuxer2 = _interopRequireDefault(_passthroughRemuxer);
  4354. var _getSelfScope = __webpack_require__(5);
  4355. var _logger = __webpack_require__(0);
  4356. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  4357. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4358. // see https://stackoverflow.com/a/11237259/589493
  4359. var global = (0, _getSelfScope.getSelfScope)(); // safeguard for code that might run both on worker and main thread
  4360. var now = void 0;
  4361. // performance.now() not available on WebWorker, at least on Safari Desktop
  4362. try {
  4363. now = global.performance.now.bind(global.performance);
  4364. } catch (err) {
  4365. _logger.logger.debug('Unable to use Performance API on this environment');
  4366. now = global.Date.now;
  4367. }
  4368. var DemuxerInline = function () {
  4369. function DemuxerInline(observer, typeSupported, config, vendor) {
  4370. _classCallCheck(this, DemuxerInline);
  4371. this.observer = observer;
  4372. this.typeSupported = typeSupported;
  4373. this.config = config;
  4374. this.vendor = vendor;
  4375. }
  4376. _createClass(DemuxerInline, [{
  4377. key: 'destroy',
  4378. value: function destroy() {
  4379. var demuxer = this.demuxer;
  4380. if (demuxer) {
  4381. demuxer.destroy();
  4382. }
  4383. }
  4384. }, {
  4385. key: 'push',
  4386. value: function push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
  4387. var _this = this;
  4388. if (data.byteLength > 0 && decryptdata != null && decryptdata.key != null && decryptdata.method === 'AES-128') {
  4389. var decrypter = this.decrypter;
  4390. if (decrypter == null) {
  4391. decrypter = this.decrypter = new _decrypter2.default(this.observer, this.config);
  4392. }
  4393. var startTime = now();
  4394. decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) {
  4395. var endTime = now();
  4396. _this.observer.trigger(_events2.default.FRAG_DECRYPTED, { stats: { tstart: startTime, tdecrypt: endTime } });
  4397. _this.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  4398. });
  4399. } else {
  4400. this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  4401. }
  4402. }
  4403. }, {
  4404. key: 'pushDecrypted',
  4405. value: function pushDecrypted(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
  4406. var demuxer = this.demuxer;
  4407. if (!demuxer ||
  4408. // in case of continuity change, or track switch
  4409. // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
  4410. // so let's check that current demuxer is still valid
  4411. (discontinuity || trackSwitch) && !this.probe(data)) {
  4412. var observer = this.observer;
  4413. var typeSupported = this.typeSupported;
  4414. var config = this.config;
  4415. // probing order is TS/AAC/MP3/MP4
  4416. 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 }];
  4417. // probe for content type
  4418. for (var i = 0, len = muxConfig.length; i < len; i++) {
  4419. var mux = muxConfig[i];
  4420. var probe = mux.demux.probe;
  4421. if (probe(data)) {
  4422. var _remuxer = this.remuxer = new mux.remux(observer, config, typeSupported, this.vendor);
  4423. demuxer = new mux.demux(observer, _remuxer, config, typeSupported);
  4424. this.probe = probe;
  4425. break;
  4426. }
  4427. }
  4428. if (!demuxer) {
  4429. 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' });
  4430. return;
  4431. }
  4432. this.demuxer = demuxer;
  4433. }
  4434. var remuxer = this.remuxer;
  4435. if (discontinuity || trackSwitch) {
  4436. demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration);
  4437. remuxer.resetInitSegment();
  4438. }
  4439. if (discontinuity) {
  4440. demuxer.resetTimeStamp(defaultInitPTS);
  4441. remuxer.resetTimeStamp(defaultInitPTS);
  4442. }
  4443. if (typeof demuxer.setDecryptData === 'function') {
  4444. demuxer.setDecryptData(decryptdata);
  4445. }
  4446. demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);
  4447. }
  4448. }]);
  4449. return DemuxerInline;
  4450. }();
  4451. exports.default = DemuxerInline;
  4452. module.exports = exports['default'];
  4453. /***/ }),
  4454. /* 22 */
  4455. /***/ (function(module, exports, __webpack_require__) {
  4456. "use strict";
  4457. Object.defineProperty(exports, "__esModule", {
  4458. value: true
  4459. });
  4460. exports.getAudioConfig = getAudioConfig;
  4461. exports.isHeaderPattern = isHeaderPattern;
  4462. exports.getHeaderLength = getHeaderLength;
  4463. exports.getFullFrameLength = getFullFrameLength;
  4464. exports.isHeader = isHeader;
  4465. exports.probe = probe;
  4466. exports.initTrackConfig = initTrackConfig;
  4467. exports.getFrameDuration = getFrameDuration;
  4468. exports.parseFrameHeader = parseFrameHeader;
  4469. exports.appendFrame = appendFrame;
  4470. var _logger = __webpack_require__(0);
  4471. var _errors = __webpack_require__(2);
  4472. var _events = __webpack_require__(1);
  4473. var _events2 = _interopRequireDefault(_events);
  4474. var _getSelfScope = __webpack_require__(5);
  4475. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  4476. /**
  4477. * ADTS parser helper
  4478. */
  4479. function getAudioConfig(observer, data, offset, audioCodec) {
  4480. var adtsObjectType = void 0,
  4481. // :int
  4482. adtsSampleingIndex = void 0,
  4483. // :int
  4484. adtsExtensionSampleingIndex = void 0,
  4485. // :int
  4486. adtsChanelConfig = void 0,
  4487. // :int
  4488. config = void 0,
  4489. userAgent = navigator.userAgent.toLowerCase(),
  4490. manifestCodec = audioCodec,
  4491. adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  4492. // byte 2
  4493. adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1;
  4494. adtsSampleingIndex = (data[offset + 2] & 0x3C) >>> 2;
  4495. if (adtsSampleingIndex > adtsSampleingRates.length - 1) {
  4496. observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'invalid ADTS sampling index:' + adtsSampleingIndex });
  4497. return;
  4498. }
  4499. adtsChanelConfig = (data[offset + 2] & 0x01) << 2;
  4500. // byte 3
  4501. adtsChanelConfig |= (data[offset + 3] & 0xC0) >>> 6;
  4502. _logger.logger.log('manifest codec:' + audioCodec + ',ADTS data:type:' + adtsObjectType + ',sampleingIndex:' + adtsSampleingIndex + '[' + adtsSampleingRates[adtsSampleingIndex] + 'Hz],channelConfig:' + adtsChanelConfig);
  4503. // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
  4504. if (/firefox/i.test(userAgent)) {
  4505. if (adtsSampleingIndex >= 6) {
  4506. adtsObjectType = 5;
  4507. config = new Array(4);
  4508. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  4509. // there is a factor 2 between frame sample rate and output sample rate
  4510. // multiply frequency by 2 (see table below, equivalent to substract 3)
  4511. adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
  4512. } else {
  4513. adtsObjectType = 2;
  4514. config = new Array(2);
  4515. adtsExtensionSampleingIndex = adtsSampleingIndex;
  4516. }
  4517. // Android : always use AAC
  4518. } else if (userAgent.indexOf('android') !== -1) {
  4519. adtsObjectType = 2;
  4520. config = new Array(2);
  4521. adtsExtensionSampleingIndex = adtsSampleingIndex;
  4522. } else {
  4523. /* for other browsers (Chrome/Vivaldi/Opera ...)
  4524. always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
  4525. */
  4526. adtsObjectType = 5;
  4527. config = new Array(4);
  4528. // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
  4529. if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSampleingIndex >= 6) {
  4530. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  4531. // there is a factor 2 between frame sample rate and output sample rate
  4532. // multiply frequency by 2 (see table below, equivalent to substract 3)
  4533. adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
  4534. } else {
  4535. // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
  4536. // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
  4537. if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSampleingIndex >= 6 && adtsChanelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChanelConfig === 1) {
  4538. adtsObjectType = 2;
  4539. config = new Array(2);
  4540. }
  4541. adtsExtensionSampleingIndex = adtsSampleingIndex;
  4542. }
  4543. }
  4544. /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  4545. ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
  4546. Audio Profile / Audio Object Type
  4547. 0: Null
  4548. 1: AAC Main
  4549. 2: AAC LC (Low Complexity)
  4550. 3: AAC SSR (Scalable Sample Rate)
  4551. 4: AAC LTP (Long Term Prediction)
  4552. 5: SBR (Spectral Band Replication)
  4553. 6: AAC Scalable
  4554. sampling freq
  4555. 0: 96000 Hz
  4556. 1: 88200 Hz
  4557. 2: 64000 Hz
  4558. 3: 48000 Hz
  4559. 4: 44100 Hz
  4560. 5: 32000 Hz
  4561. 6: 24000 Hz
  4562. 7: 22050 Hz
  4563. 8: 16000 Hz
  4564. 9: 12000 Hz
  4565. 10: 11025 Hz
  4566. 11: 8000 Hz
  4567. 12: 7350 Hz
  4568. 13: Reserved
  4569. 14: Reserved
  4570. 15: frequency is written explictly
  4571. Channel Configurations
  4572. These are the channel configurations:
  4573. 0: Defined in AOT Specifc Config
  4574. 1: 1 channel: front-center
  4575. 2: 2 channels: front-left, front-right
  4576. */
  4577. // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  4578. config[0] = adtsObjectType << 3;
  4579. // samplingFrequencyIndex
  4580. config[0] |= (adtsSampleingIndex & 0x0E) >> 1;
  4581. config[1] |= (adtsSampleingIndex & 0x01) << 7;
  4582. // channelConfiguration
  4583. config[1] |= adtsChanelConfig << 3;
  4584. if (adtsObjectType === 5) {
  4585. // adtsExtensionSampleingIndex
  4586. config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1;
  4587. config[2] = (adtsExtensionSampleingIndex & 0x01) << 7;
  4588. // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
  4589. // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
  4590. config[2] |= 2 << 2;
  4591. config[3] = 0;
  4592. }
  4593. return { config: config, samplerate: adtsSampleingRates[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: 'mp4a.40.' + adtsObjectType, manifestCodec: manifestCodec };
  4594. }
  4595. function isHeaderPattern(data, offset) {
  4596. return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
  4597. }
  4598. function getHeaderLength(data, offset) {
  4599. return data[offset + 1] & 0x01 ? 7 : 9;
  4600. }
  4601. function getFullFrameLength(data, offset) {
  4602. return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;
  4603. }
  4604. function isHeader(data, offset) {
  4605. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  4606. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  4607. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  4608. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  4609. return true;
  4610. }
  4611. return false;
  4612. }
  4613. function probe(data, offset) {
  4614. // same as isHeader but we also check that ADTS frame follows last ADTS frame
  4615. // or end of data is reached
  4616. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  4617. // ADTS header Length
  4618. var headerLength = getHeaderLength(data, offset);
  4619. // ADTS frame Length
  4620. var frameLength = headerLength;
  4621. if (offset + 5 < data.length) {
  4622. frameLength = getFullFrameLength(data, offset);
  4623. }
  4624. var newOffset = offset + frameLength;
  4625. if (newOffset === data.length || newOffset + 1 < data.length && isHeaderPattern(data, newOffset)) {
  4626. return true;
  4627. }
  4628. }
  4629. return false;
  4630. }
  4631. function initTrackConfig(track, observer, data, offset, audioCodec) {
  4632. if (!track.samplerate) {
  4633. var config = getAudioConfig(observer, data, offset, audioCodec);
  4634. track.config = config.config;
  4635. track.samplerate = config.samplerate;
  4636. track.channelCount = config.channelCount;
  4637. track.codec = config.codec;
  4638. track.manifestCodec = config.manifestCodec;
  4639. _logger.logger.log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount);
  4640. }
  4641. }
  4642. function getFrameDuration(samplerate) {
  4643. return 1024 * 90000 / samplerate;
  4644. }
  4645. function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {
  4646. var headerLength = void 0,
  4647. frameLength = void 0,
  4648. stamp = void 0;
  4649. var length = data.length;
  4650. // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  4651. headerLength = getHeaderLength(data, offset);
  4652. // retrieve frame size
  4653. frameLength = getFullFrameLength(data, offset);
  4654. frameLength -= headerLength;
  4655. if (frameLength > 0 && offset + headerLength + frameLength <= length) {
  4656. stamp = pts + frameIndex * frameDuration;
  4657. // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
  4658. return { headerLength: headerLength, frameLength: frameLength, stamp: stamp };
  4659. }
  4660. return undefined;
  4661. }
  4662. function appendFrame(track, data, offset, pts, frameIndex) {
  4663. var frameDuration = getFrameDuration(track.samplerate);
  4664. var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);
  4665. if (header) {
  4666. var stamp = header.stamp;
  4667. var headerLength = header.headerLength;
  4668. var frameLength = header.frameLength;
  4669. // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
  4670. var aacSample = {
  4671. unit: data.subarray(offset + headerLength, offset + headerLength + frameLength),
  4672. pts: stamp,
  4673. dts: stamp
  4674. };
  4675. track.samples.push(aacSample);
  4676. track.len += frameLength;
  4677. return { sample: aacSample, length: frameLength + headerLength };
  4678. }
  4679. return undefined;
  4680. }
  4681. /***/ }),
  4682. /* 23 */
  4683. /***/ (function(module, exports, __webpack_require__) {
  4684. "use strict";
  4685. Object.defineProperty(exports, "__esModule", {
  4686. value: true
  4687. });
  4688. /**
  4689. * MPEG parser helper
  4690. */
  4691. var MpegAudio = {
  4692. 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],
  4693. SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000],
  4694. SamplesCoefficients: [
  4695. // MPEG 2.5
  4696. [0, // Reserved
  4697. 72, // Layer3
  4698. 144, // Layer2
  4699. 12 // Layer1
  4700. ],
  4701. // Reserved
  4702. [0, // Reserved
  4703. 0, // Layer3
  4704. 0, // Layer2
  4705. 0 // Layer1
  4706. ],
  4707. // MPEG 2
  4708. [0, // Reserved
  4709. 72, // Layer3
  4710. 144, // Layer2
  4711. 12 // Layer1
  4712. ],
  4713. // MPEG 1
  4714. [0, // Reserved
  4715. 144, // Layer3
  4716. 144, // Layer2
  4717. 12 // Layer1
  4718. ]],
  4719. BytesInSlot: [0, // Reserved
  4720. 1, // Layer3
  4721. 1, // Layer2
  4722. 4 // Layer1
  4723. ],
  4724. appendFrame: function appendFrame(track, data, offset, pts, frameIndex) {
  4725. // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
  4726. if (offset + 24 > data.length) {
  4727. return undefined;
  4728. }
  4729. var header = this.parseHeader(data, offset);
  4730. if (header && offset + header.frameLength <= data.length) {
  4731. var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
  4732. var stamp = pts + frameIndex * frameDuration;
  4733. var sample = { unit: data.subarray(offset, offset + header.frameLength), pts: stamp, dts: stamp };
  4734. track.config = [];
  4735. track.channelCount = header.channelCount;
  4736. track.samplerate = header.sampleRate;
  4737. track.samples.push(sample);
  4738. track.len += header.frameLength;
  4739. return { sample: sample, length: header.frameLength };
  4740. }
  4741. return undefined;
  4742. },
  4743. parseHeader: function parseHeader(data, offset) {
  4744. var headerB = data[offset + 1] >> 3 & 3;
  4745. var headerC = data[offset + 1] >> 1 & 3;
  4746. var headerE = data[offset + 2] >> 4 & 15;
  4747. var headerF = data[offset + 2] >> 2 & 3;
  4748. var headerG = data[offset + 2] >> 1 & 1;
  4749. if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {
  4750. var columnInBitrates = headerB === 3 ? 3 - headerC : headerC === 3 ? 3 : 4;
  4751. var bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;
  4752. var columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;
  4753. var sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];
  4754. var channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
  4755. var sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];
  4756. var bytesInSlot = MpegAudio.BytesInSlot[headerC];
  4757. var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  4758. var frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot;
  4759. return { sampleRate: sampleRate, channelCount: channelCount, frameLength: frameLength, samplesPerFrame: samplesPerFrame };
  4760. }
  4761. return undefined;
  4762. },
  4763. isHeaderPattern: function isHeaderPattern(data, offset) {
  4764. return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
  4765. },
  4766. isHeader: function isHeader(data, offset) {
  4767. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  4768. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  4769. // More info http://www.mp3-tech.org/programmer/frame_header.html
  4770. if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
  4771. return true;
  4772. }
  4773. return false;
  4774. },
  4775. probe: function probe(data, offset) {
  4776. // same as isHeader but we also check that MPEG frame follows last MPEG frame
  4777. // or end of data is reached
  4778. if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
  4779. // MPEG header Length
  4780. var headerLength = 4;
  4781. // MPEG frame Length
  4782. var header = this.parseHeader(data, offset);
  4783. var frameLength = headerLength;
  4784. if (header && header.frameLength) {
  4785. frameLength = header.frameLength;
  4786. }
  4787. var newOffset = offset + frameLength;
  4788. if (newOffset === data.length || newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset)) {
  4789. return true;
  4790. }
  4791. }
  4792. return false;
  4793. }
  4794. };
  4795. exports.default = MpegAudio;
  4796. module.exports = exports["default"];
  4797. /***/ }),
  4798. /* 24 */
  4799. /***/ (function(module, exports, __webpack_require__) {
  4800. "use strict";
  4801. Object.defineProperty(exports, "__esModule", {
  4802. value: true
  4803. });
  4804. exports.Observer = undefined;
  4805. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  4806. var _eventemitter = __webpack_require__(54);
  4807. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4808. 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; }
  4809. 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; }
  4810. /**
  4811. * @class
  4812. *
  4813. * Simple adapter sub-class of Nodejs-like EventEmitter.
  4814. *
  4815. * We simply want to pass along the event-name itself
  4816. * in every call to a handler, which is the purpose of our `trigger` method
  4817. * extending the standard API.
  4818. *
  4819. */
  4820. var Observer = exports.Observer = function (_EventEmitter) {
  4821. _inherits(Observer, _EventEmitter);
  4822. function Observer() {
  4823. _classCallCheck(this, Observer);
  4824. return _possibleConstructorReturn(this, (Observer.__proto__ || Object.getPrototypeOf(Observer)).apply(this, arguments));
  4825. }
  4826. _createClass(Observer, [{
  4827. key: 'trigger',
  4828. /**
  4829. *
  4830. * @param {string} event
  4831. * @param {any} data
  4832. */
  4833. value: function trigger(event) {
  4834. for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4835. data[_key - 1] = arguments[_key];
  4836. }
  4837. this.emit.apply(this, [event, event].concat(data));
  4838. }
  4839. }]);
  4840. return Observer;
  4841. }(_eventemitter.EventEmitter);
  4842. /***/ }),
  4843. /* 25 */
  4844. /***/ (function(module, exports, __webpack_require__) {
  4845. "use strict";
  4846. Object.defineProperty(exports, "__esModule", {
  4847. value: true
  4848. });
  4849. /**
  4850. * TimeRanges to string helper
  4851. */
  4852. var TimeRanges = {
  4853. toString: function toString(r) {
  4854. var log = '',
  4855. len = r.length;
  4856. for (var i = 0; i < len; i++) {
  4857. log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';
  4858. }
  4859. return log;
  4860. }
  4861. };
  4862. exports.default = TimeRanges;
  4863. module.exports = exports['default'];
  4864. /***/ }),
  4865. /* 26 */
  4866. /***/ (function(module, exports, __webpack_require__) {
  4867. "use strict";
  4868. Object.defineProperty(exports, "__esModule", {
  4869. value: true
  4870. });
  4871. exports.findFirstFragWithCC = findFirstFragWithCC;
  4872. exports.findFragWithCC = findFragWithCC;
  4873. exports.shouldAlignOnDiscontinuities = shouldAlignOnDiscontinuities;
  4874. exports.findDiscontinuousReferenceFrag = findDiscontinuousReferenceFrag;
  4875. exports.adjustPts = adjustPts;
  4876. exports.alignStream = alignStream;
  4877. exports.alignDiscontinuities = alignDiscontinuities;
  4878. exports.alignPDT = alignPDT;
  4879. var _binarySearch = __webpack_require__(9);
  4880. var _binarySearch2 = _interopRequireDefault(_binarySearch);
  4881. var _logger = __webpack_require__(0);
  4882. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  4883. function findFirstFragWithCC(fragments, cc) {
  4884. var firstFrag = null;
  4885. for (var i = 0; i < fragments.length; i += 1) {
  4886. var currentFrag = fragments[i];
  4887. if (currentFrag && currentFrag.cc === cc) {
  4888. firstFrag = currentFrag;
  4889. break;
  4890. }
  4891. }
  4892. return firstFrag;
  4893. }
  4894. function findFragWithCC(fragments, CC) {
  4895. return _binarySearch2.default.search(fragments, function (candidate) {
  4896. if (candidate.cc < CC) {
  4897. return 1;
  4898. } else if (candidate.cc > CC) {
  4899. return -1;
  4900. } else {
  4901. return 0;
  4902. }
  4903. });
  4904. }
  4905. function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {
  4906. var shouldAlign = false;
  4907. if (lastLevel && lastLevel.details && details) {
  4908. if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
  4909. shouldAlign = true;
  4910. }
  4911. }
  4912. return shouldAlign;
  4913. }
  4914. // Find the first frag in the previous level which matches the CC of the first frag of the new level
  4915. function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
  4916. var prevFrags = prevDetails.fragments;
  4917. var curFrags = curDetails.fragments;
  4918. if (!curFrags.length || !prevFrags.length) {
  4919. _logger.logger.log('No fragments to align');
  4920. return;
  4921. }
  4922. var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
  4923. if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
  4924. _logger.logger.log('No frag in previous level to align on');
  4925. return;
  4926. }
  4927. return prevStartFrag;
  4928. }
  4929. function adjustPts(sliding, details) {
  4930. details.fragments.forEach(function (frag) {
  4931. if (frag) {
  4932. var start = frag.start + sliding;
  4933. frag.start = frag.startPTS = start;
  4934. frag.endPTS = start + frag.duration;
  4935. }
  4936. });
  4937. details.PTSKnown = true;
  4938. }
  4939. /**
  4940. * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
  4941. * contiguous stream with the last fragments.
  4942. * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
  4943. * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
  4944. * and an extra download.
  4945. * @param lastFrag
  4946. * @param lastLevel
  4947. * @param details
  4948. */
  4949. function alignStream(lastFrag, lastLevel, details) {
  4950. alignDiscontinuities(lastFrag, details, lastLevel);
  4951. if (!details.PTSKnown && lastLevel) {
  4952. // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
  4953. // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
  4954. // discontinuity sequence.
  4955. alignPDT(details, lastLevel.details);
  4956. }
  4957. }
  4958. /**
  4959. * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
  4960. * discontinuity sequence.
  4961. * @param lastLevel - The details of the last loaded level
  4962. * @param details - The details of the new level
  4963. */
  4964. function alignDiscontinuities(lastFrag, details, lastLevel) {
  4965. if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {
  4966. var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);
  4967. if (referenceFrag) {
  4968. _logger.logger.log('Adjusting PTS using last level due to CC increase within current level');
  4969. adjustPts(referenceFrag.start, details);
  4970. }
  4971. }
  4972. }
  4973. /**
  4974. * Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.
  4975. * @param details - The details of the new level
  4976. * @param lastDetails - The details of the last loaded level
  4977. */
  4978. function alignPDT(details, lastDetails) {
  4979. if (lastDetails && lastDetails.fragments.length) {
  4980. if (!details.hasProgramDateTime || !lastDetails.hasProgramDateTime) {
  4981. return;
  4982. }
  4983. // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM
  4984. // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM
  4985. // then we can deduce that playlist B sliding is 1000+8 = 1008s
  4986. var lastPDT = lastDetails.fragments[0].programDateTime;
  4987. var newPDT = details.fragments[0].programDateTime;
  4988. // date diff is in ms. frag.start is in seconds
  4989. var sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;
  4990. if (Number.isFinite(sliding)) {
  4991. _logger.logger.log('adjusting PTS using programDateTime delta, sliding:' + sliding.toFixed(3));
  4992. adjustPts(sliding, details);
  4993. }
  4994. }
  4995. }
  4996. /***/ }),
  4997. /* 27 */
  4998. /***/ (function(module, exports, __webpack_require__) {
  4999. "use strict";
  5000. Object.defineProperty(exports, "__esModule", {
  5001. value: true
  5002. });
  5003. exports.findFragmentByPDT = findFragmentByPDT;
  5004. exports.findFragmentByPTS = findFragmentByPTS;
  5005. exports.fragmentWithinToleranceTest = fragmentWithinToleranceTest;
  5006. exports.pdtWithinToleranceTest = pdtWithinToleranceTest;
  5007. var _binarySearch = __webpack_require__(9);
  5008. var _binarySearch2 = _interopRequireDefault(_binarySearch);
  5009. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5010. /**
  5011. * Returns first fragment whose endPdt value exceeds the given PDT.
  5012. * @param {Array<Fragment>} fragments - The array of candidate fragments
  5013. * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded
  5014. * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  5015. * @returns {*|null} fragment - The best matching fragment
  5016. */
  5017. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  5018. if (!Array.isArray(fragments) || !fragments.length || !Number.isFinite(PDTValue)) {
  5019. return null;
  5020. }
  5021. // if less than start
  5022. if (PDTValue < fragments[0].programDateTime) {
  5023. return null;
  5024. }
  5025. if (PDTValue >= fragments[fragments.length - 1].endProgramDateTime) {
  5026. return null;
  5027. }
  5028. maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
  5029. for (var seg = 0; seg < fragments.length; ++seg) {
  5030. var frag = fragments[seg];
  5031. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  5032. return frag;
  5033. }
  5034. }
  5035. return null;
  5036. }
  5037. /**
  5038. * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
  5039. * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
  5040. * breaking any traps which would cause the same fragment to be continuously selected within a small range.
  5041. * @param {*} fragPrevious - The last frag successfully appended
  5042. * @param {Array<Fragment>} fragments - The array of candidate fragments
  5043. * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within
  5044. * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  5045. * @returns {*} foundFrag - The best matching fragment
  5046. */
  5047. function findFragmentByPTS(fragPrevious, fragments) {
  5048. var bufferEnd = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  5049. var maxFragLookUpTolerance = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  5050. var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : null;
  5051. // Prefer the next fragment if it's within tolerance
  5052. if (fragNext && !fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) {
  5053. return fragNext;
  5054. }
  5055. return _binarySearch2.default.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  5056. }
  5057. /**
  5058. * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
  5059. * @param {*} candidate - The fragment to test
  5060. * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within
  5061. * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
  5062. * @returns {number} - 0 if it matches, 1 if too low, -1 if too high
  5063. */
  5064. function fragmentWithinToleranceTest() {
  5065. var bufferEnd = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  5066. var maxFragLookUpTolerance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  5067. var candidate = arguments[2];
  5068. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  5069. // this is to cope with situations like
  5070. // bufferEnd = 9.991
  5071. // frag[Ø] : [0,10]
  5072. // frag[1] : [10,20]
  5073. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  5074. // frag start frag start+duration
  5075. // |-----------------------------|
  5076. // <---> <--->
  5077. // ...--------><-----------------------------><---------....
  5078. // previous frag matching fragment next frag
  5079. // return -1 return 0 return 1
  5080. // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  5081. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  5082. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  5083. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  5084. return 1;
  5085. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  5086. // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  5087. return -1;
  5088. }
  5089. return 0;
  5090. }
  5091. /**
  5092. * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
  5093. * This function tests the candidate's program date time values, as represented in Unix time
  5094. * @param {*} candidate - The fragment to test
  5095. * @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range
  5096. * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
  5097. * @returns {boolean} True if contiguous, false otherwise
  5098. */
  5099. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  5100. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;
  5101. return candidate.endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  5102. }
  5103. /***/ }),
  5104. /* 28 */
  5105. /***/ (function(module, exports, __webpack_require__) {
  5106. "use strict";
  5107. Object.defineProperty(exports, "__esModule", {
  5108. value: true
  5109. });
  5110. 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; }; }();
  5111. var _eventHandler = __webpack_require__(3);
  5112. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  5113. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5114. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5115. 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; }
  5116. 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; }
  5117. /**
  5118. * Sub-class specialization of EventHandler base class.
  5119. *
  5120. * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
  5121. * scheduled asynchroneously, avoiding recursive calls in the same tick.
  5122. *
  5123. * The task itself is implemented in `doTick`. It can be requested and called for single execution
  5124. * using the `tick` method.
  5125. *
  5126. * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
  5127. * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
  5128. *
  5129. * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
  5130. * and cancelled with `clearNextTick`.
  5131. *
  5132. * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
  5133. *
  5134. * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
  5135. *
  5136. * Further explanations:
  5137. *
  5138. * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
  5139. * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
  5140. *
  5141. * When the task execution (`tick` method) is called in re-entrant way this is detected and
  5142. * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
  5143. * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
  5144. */
  5145. var TaskLoop = function (_EventHandler) {
  5146. _inherits(TaskLoop, _EventHandler);
  5147. function TaskLoop(hls) {
  5148. var _ref;
  5149. _classCallCheck(this, TaskLoop);
  5150. for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  5151. events[_key - 1] = arguments[_key];
  5152. }
  5153. var _this = _possibleConstructorReturn(this, (_ref = TaskLoop.__proto__ || Object.getPrototypeOf(TaskLoop)).call.apply(_ref, [this, hls].concat(events)));
  5154. _this._tickInterval = null;
  5155. _this._tickTimer = null;
  5156. _this._tickCallCount = 0;
  5157. _this._boundTick = _this.tick.bind(_this);
  5158. return _this;
  5159. }
  5160. /**
  5161. * @override
  5162. */
  5163. _createClass(TaskLoop, [{
  5164. key: 'onHandlerDestroying',
  5165. value: function onHandlerDestroying() {
  5166. // clear all timers before unregistering from event bus
  5167. this.clearNextTick();
  5168. this.clearInterval();
  5169. }
  5170. /**
  5171. * @returns {boolean}
  5172. */
  5173. }, {
  5174. key: 'hasInterval',
  5175. value: function hasInterval() {
  5176. return !!this._tickInterval;
  5177. }
  5178. /**
  5179. * @returns {boolean}
  5180. */
  5181. }, {
  5182. key: 'hasNextTick',
  5183. value: function hasNextTick() {
  5184. return !!this._tickTimer;
  5185. }
  5186. /**
  5187. * @param {number} millis Interval time (ms)
  5188. * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)
  5189. */
  5190. }, {
  5191. key: 'setInterval',
  5192. value: function (_setInterval) {
  5193. function setInterval(_x) {
  5194. return _setInterval.apply(this, arguments);
  5195. }
  5196. setInterval.toString = function () {
  5197. return _setInterval.toString();
  5198. };
  5199. return setInterval;
  5200. }(function (millis) {
  5201. if (!this._tickInterval) {
  5202. this._tickInterval = setInterval(this._boundTick, millis);
  5203. return true;
  5204. }
  5205. return false;
  5206. })
  5207. /**
  5208. * @returns {boolean} True when interval was cleared, false when none was set (no effect)
  5209. */
  5210. }, {
  5211. key: 'clearInterval',
  5212. value: function (_clearInterval) {
  5213. function clearInterval() {
  5214. return _clearInterval.apply(this, arguments);
  5215. }
  5216. clearInterval.toString = function () {
  5217. return _clearInterval.toString();
  5218. };
  5219. return clearInterval;
  5220. }(function () {
  5221. if (this._tickInterval) {
  5222. clearInterval(this._tickInterval);
  5223. this._tickInterval = null;
  5224. return true;
  5225. }
  5226. return false;
  5227. })
  5228. /**
  5229. * @returns {boolean} True when timeout was cleared, false when none was set (no effect)
  5230. */
  5231. }, {
  5232. key: 'clearNextTick',
  5233. value: function clearNextTick() {
  5234. if (this._tickTimer) {
  5235. clearTimeout(this._tickTimer);
  5236. this._tickTimer = null;
  5237. return true;
  5238. }
  5239. return false;
  5240. }
  5241. /**
  5242. * Will call the subclass doTick implementation in this main loop tick
  5243. * or in the next one (via setTimeout(,0)) in case it has already been called
  5244. * in this tick (in case this is a re-entrant call).
  5245. */
  5246. }, {
  5247. key: 'tick',
  5248. value: function tick() {
  5249. this._tickCallCount++;
  5250. if (this._tickCallCount === 1) {
  5251. this.doTick();
  5252. // re-entrant call to tick from previous doTick call stack
  5253. // -> schedule a call on the next main loop iteration to process this task processing request
  5254. if (this._tickCallCount > 1) {
  5255. // make sure only one timer exists at any time at max
  5256. this.clearNextTick();
  5257. this._tickTimer = setTimeout(this._boundTick, 0);
  5258. }
  5259. this._tickCallCount = 0;
  5260. }
  5261. }
  5262. /**
  5263. * For subclass to implement task logic
  5264. * @abstract
  5265. */
  5266. }, {
  5267. key: 'doTick',
  5268. value: function doTick() {}
  5269. }]);
  5270. return TaskLoop;
  5271. }(_eventHandler2.default);
  5272. exports.default = TaskLoop;
  5273. module.exports = exports['default'];
  5274. /***/ }),
  5275. /* 29 */
  5276. /***/ (function(module, exports, __webpack_require__) {
  5277. "use strict";
  5278. Object.defineProperty(exports, "__esModule", {
  5279. value: true
  5280. });
  5281. exports.sendAddTrackEvent = sendAddTrackEvent;
  5282. exports.clearCurrentCues = clearCurrentCues;
  5283. function sendAddTrackEvent(track, videoEl) {
  5284. var event = null;
  5285. try {
  5286. event = new window.Event('addtrack');
  5287. } catch (err) {
  5288. // for IE11
  5289. event = document.createEvent('Event');
  5290. event.initEvent('addtrack', false, false);
  5291. }
  5292. event.track = track;
  5293. videoEl.dispatchEvent(event);
  5294. }
  5295. function clearCurrentCues(track) {
  5296. if (track && track.cues) {
  5297. while (track.cues.length > 0) {
  5298. track.removeCue(track.cues[0]);
  5299. }
  5300. }
  5301. }
  5302. /***/ }),
  5303. /* 30 */
  5304. /***/ (function(module, exports, __webpack_require__) {
  5305. "use strict";
  5306. Object.defineProperty(exports, "__esModule", {
  5307. value: true
  5308. });
  5309. exports.fixLineBreaks = undefined;
  5310. var _vttcue = __webpack_require__(71);
  5311. var _vttcue2 = _interopRequireDefault(_vttcue);
  5312. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5313. var StringDecoder = function StringDecoder() {
  5314. return {
  5315. decode: function decode(data) {
  5316. if (!data) {
  5317. return '';
  5318. }
  5319. if (typeof data !== 'string') {
  5320. throw new Error('Error - expected string data.');
  5321. }
  5322. return decodeURIComponent(encodeURIComponent(data));
  5323. }
  5324. };
  5325. }; /*
  5326. * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js#L1716
  5327. */
  5328. function VTTParser() {
  5329. this.window = window;
  5330. this.state = 'INITIAL';
  5331. this.buffer = '';
  5332. this.decoder = new StringDecoder();
  5333. this.regionList = [];
  5334. }
  5335. // Try to parse input as a time stamp.
  5336. function parseTimeStamp(input) {
  5337. function computeSeconds(h, m, s, f) {
  5338. return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
  5339. }
  5340. var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);
  5341. if (!m) {
  5342. return null;
  5343. }
  5344. if (m[3]) {
  5345. // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
  5346. return computeSeconds(m[1], m[2], m[3].replace(':', ''), m[4]);
  5347. } else if (m[1] > 59) {
  5348. // Timestamp takes the form of [hours]:[minutes].[milliseconds]
  5349. // First position is hours as it's over 59.
  5350. return computeSeconds(m[1], m[2], 0, m[4]);
  5351. } else {
  5352. // Timestamp takes the form of [minutes]:[seconds].[milliseconds]
  5353. return computeSeconds(0, m[1], m[2], m[4]);
  5354. }
  5355. }
  5356. // A settings object holds key/value pairs and will ignore anything but the first
  5357. // assignment to a specific key.
  5358. function Settings() {
  5359. this.values = Object.create(null);
  5360. }
  5361. Settings.prototype = {
  5362. // Only accept the first assignment to any key.
  5363. set: function set(k, v) {
  5364. if (!this.get(k) && v !== '') {
  5365. this.values[k] = v;
  5366. }
  5367. },
  5368. // Return the value for a key, or a default value.
  5369. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  5370. // a number of possible default values as properties where 'defaultKey' is
  5371. // the key of the property that will be chosen; otherwise it's assumed to be
  5372. // a single value.
  5373. get: function get(k, dflt, defaultKey) {
  5374. if (defaultKey) {
  5375. return this.has(k) ? this.values[k] : dflt[defaultKey];
  5376. }
  5377. return this.has(k) ? this.values[k] : dflt;
  5378. },
  5379. // Check whether we have a value for a key.
  5380. has: function has(k) {
  5381. return k in this.values;
  5382. },
  5383. // Accept a setting if its one of the given alternatives.
  5384. alt: function alt(k, v, a) {
  5385. for (var n = 0; n < a.length; ++n) {
  5386. if (v === a[n]) {
  5387. this.set(k, v);
  5388. break;
  5389. }
  5390. }
  5391. },
  5392. // Accept a setting if its a valid (signed) integer.
  5393. integer: function integer(k, v) {
  5394. if (/^-?\d+$/.test(v)) {
  5395. // integer
  5396. this.set(k, parseInt(v, 10));
  5397. }
  5398. },
  5399. // Accept a setting if its a valid percentage.
  5400. percent: function percent(k, v) {
  5401. var m = void 0;
  5402. if (m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/)) {
  5403. v = parseFloat(v);
  5404. if (v >= 0 && v <= 100) {
  5405. this.set(k, v);
  5406. return true;
  5407. }
  5408. }
  5409. return false;
  5410. }
  5411. };
  5412. // Helper function to parse input into groups separated by 'groupDelim', and
  5413. // interprete each group as a key/value pair separated by 'keyValueDelim'.
  5414. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  5415. var groups = groupDelim ? input.split(groupDelim) : [input];
  5416. for (var i in groups) {
  5417. if (typeof groups[i] !== 'string') {
  5418. continue;
  5419. }
  5420. var kv = groups[i].split(keyValueDelim);
  5421. if (kv.length !== 2) {
  5422. continue;
  5423. }
  5424. var k = kv[0];
  5425. var v = kv[1];
  5426. callback(k, v);
  5427. }
  5428. }
  5429. var defaults = new _vttcue2.default(0, 0, 0);
  5430. // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244
  5431. // Safari doesn't yet support this change, but FF and Chrome do.
  5432. var center = defaults.align === 'middle' ? 'middle' : 'center';
  5433. function parseCue(input, cue, regionList) {
  5434. // Remember the original input if we need to throw an error.
  5435. var oInput = input;
  5436. // 4.1 WebVTT timestamp
  5437. function consumeTimeStamp() {
  5438. var ts = parseTimeStamp(input);
  5439. if (ts === null) {
  5440. throw new Error('Malformed timestamp: ' + oInput);
  5441. }
  5442. // Remove time stamp from input.
  5443. input = input.replace(/^[^\sa-zA-Z-]+/, '');
  5444. return ts;
  5445. }
  5446. // 4.4.2 WebVTT cue settings
  5447. function consumeCueSettings(input, cue) {
  5448. var settings = new Settings();
  5449. parseOptions(input, function (k, v) {
  5450. switch (k) {
  5451. case 'region':
  5452. // Find the last region we parsed with the same region id.
  5453. for (var i = regionList.length - 1; i >= 0; i--) {
  5454. if (regionList[i].id === v) {
  5455. settings.set(k, regionList[i].region);
  5456. break;
  5457. }
  5458. }
  5459. break;
  5460. case 'vertical':
  5461. settings.alt(k, v, ['rl', 'lr']);
  5462. break;
  5463. case 'line':
  5464. var vals = v.split(','),
  5465. vals0 = vals[0];
  5466. settings.integer(k, vals0);
  5467. if (settings.percent(k, vals0)) {
  5468. settings.set('snapToLines', false);
  5469. }
  5470. settings.alt(k, vals0, ['auto']);
  5471. if (vals.length === 2) {
  5472. settings.alt('lineAlign', vals[1], ['start', center, 'end']);
  5473. }
  5474. break;
  5475. case 'position':
  5476. vals = v.split(',');
  5477. settings.percent(k, vals[0]);
  5478. if (vals.length === 2) {
  5479. settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);
  5480. }
  5481. break;
  5482. case 'size':
  5483. settings.percent(k, v);
  5484. break;
  5485. case 'align':
  5486. settings.alt(k, v, ['start', center, 'end', 'left', 'right']);
  5487. break;
  5488. }
  5489. }, /:/, /\s/);
  5490. // Apply default values for any missing fields.
  5491. cue.region = settings.get('region', null);
  5492. cue.vertical = settings.get('vertical', '');
  5493. var line = settings.get('line', 'auto');
  5494. if (line === 'auto' && defaults.line === -1) {
  5495. // set numeric line number for Safari
  5496. line = -1;
  5497. }
  5498. cue.line = line;
  5499. cue.lineAlign = settings.get('lineAlign', 'start');
  5500. cue.snapToLines = settings.get('snapToLines', true);
  5501. cue.size = settings.get('size', 100);
  5502. cue.align = settings.get('align', center);
  5503. var position = settings.get('position', 'auto');
  5504. if (position === 'auto' && defaults.position === 50) {
  5505. // set numeric position for Safari
  5506. position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;
  5507. }
  5508. cue.position = position;
  5509. }
  5510. function skipWhitespace() {
  5511. input = input.replace(/^\s+/, '');
  5512. }
  5513. // 4.1 WebVTT cue timings.
  5514. skipWhitespace();
  5515. cue.startTime = consumeTimeStamp(); // (1) collect cue start time
  5516. skipWhitespace();
  5517. if (input.substr(0, 3) !== '-->') {
  5518. // (3) next characters must match '-->'
  5519. throw new Error('Malformed time stamp (time stamps must be separated by \'-->\'): ' + oInput);
  5520. }
  5521. input = input.substr(3);
  5522. skipWhitespace();
  5523. cue.endTime = consumeTimeStamp(); // (5) collect cue end time
  5524. // 4.1 WebVTT cue settings list.
  5525. skipWhitespace();
  5526. consumeCueSettings(input, cue);
  5527. }
  5528. function fixLineBreaks(input) {
  5529. return input.replace(/<br(?: \/)?>/gi, '\n');
  5530. }
  5531. VTTParser.prototype = {
  5532. parse: function parse(data) {
  5533. var self = this;
  5534. // If there is no data then we won't decode it, but will just try to parse
  5535. // whatever is in buffer already. This may occur in circumstances, for
  5536. // example when flush() is called.
  5537. if (data) {
  5538. // Try to decode the data that we received.
  5539. self.buffer += self.decoder.decode(data, { stream: true });
  5540. }
  5541. function collectNextLine() {
  5542. var buffer = self.buffer;
  5543. var pos = 0;
  5544. buffer = fixLineBreaks(buffer);
  5545. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  5546. ++pos;
  5547. }
  5548. var line = buffer.substr(0, pos);
  5549. // Advance the buffer early in case we fail below.
  5550. if (buffer[pos] === '\r') {
  5551. ++pos;
  5552. }
  5553. if (buffer[pos] === '\n') {
  5554. ++pos;
  5555. }
  5556. self.buffer = buffer.substr(pos);
  5557. return line;
  5558. }
  5559. // 3.2 WebVTT metadata header syntax
  5560. function parseHeader(input) {
  5561. parseOptions(input, function (k, v) {
  5562. switch (k) {
  5563. case 'Region':
  5564. // 3.3 WebVTT region metadata header syntax
  5565. // console.log('parse region', v);
  5566. // parseRegion(v);
  5567. break;
  5568. }
  5569. }, /:/);
  5570. }
  5571. // 5.1 WebVTT file parsing.
  5572. try {
  5573. var line = void 0;
  5574. if (self.state === 'INITIAL') {
  5575. // We can't start parsing until we have the first line.
  5576. if (!/\r\n|\n/.test(self.buffer)) {
  5577. return this;
  5578. }
  5579. line = collectNextLine();
  5580. // strip of UTF-8 BOM if any
  5581. // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
  5582. var m = line.match(/^()?WEBVTT([ \t].*)?$/);
  5583. if (!m || !m[0]) {
  5584. throw new Error('Malformed WebVTT signature.');
  5585. }
  5586. self.state = 'HEADER';
  5587. }
  5588. var alreadyCollectedLine = false;
  5589. while (self.buffer) {
  5590. // We can't parse a line until we have the full line.
  5591. if (!/\r\n|\n/.test(self.buffer)) {
  5592. return this;
  5593. }
  5594. if (!alreadyCollectedLine) {
  5595. line = collectNextLine();
  5596. } else {
  5597. alreadyCollectedLine = false;
  5598. }
  5599. switch (self.state) {
  5600. case 'HEADER':
  5601. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  5602. if (/:/.test(line)) {
  5603. parseHeader(line);
  5604. } else if (!line) {
  5605. // An empty line terminates the header and starts the body (cues).
  5606. self.state = 'ID';
  5607. }
  5608. continue;
  5609. case 'NOTE':
  5610. // Ignore NOTE blocks.
  5611. if (!line) {
  5612. self.state = 'ID';
  5613. }
  5614. continue;
  5615. case 'ID':
  5616. // Check for the start of NOTE blocks.
  5617. if (/^NOTE($|[ \t])/.test(line)) {
  5618. self.state = 'NOTE';
  5619. break;
  5620. }
  5621. // 19-29 - Allow any number of line terminators, then initialize new cue values.
  5622. if (!line) {
  5623. continue;
  5624. }
  5625. self.cue = new _vttcue2.default(0, 0, '');
  5626. self.state = 'CUE';
  5627. // 30-39 - Check if self line contains an optional identifier or timing data.
  5628. if (line.indexOf('-->') === -1) {
  5629. self.cue.id = line;
  5630. continue;
  5631. }
  5632. // Process line as start of a cue.
  5633. /* falls through */
  5634. case 'CUE':
  5635. // 40 - Collect cue timings and settings.
  5636. try {
  5637. parseCue(line, self.cue, self.regionList);
  5638. } catch (e) {
  5639. // In case of an error ignore rest of the cue.
  5640. self.cue = null;
  5641. self.state = 'BADCUE';
  5642. continue;
  5643. }
  5644. self.state = 'CUETEXT';
  5645. continue;
  5646. case 'CUETEXT':
  5647. var hasSubstring = line.indexOf('-->') !== -1;
  5648. // 34 - If we have an empty line then report the cue.
  5649. // 35 - If we have the special substring '-->' then report the cue,
  5650. // but do not collect the line as we need to process the current
  5651. // one as a new cue.
  5652. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  5653. // We are done parsing self cue.
  5654. if (self.oncue) {
  5655. self.oncue(self.cue);
  5656. }
  5657. self.cue = null;
  5658. self.state = 'ID';
  5659. continue;
  5660. }
  5661. if (self.cue.text) {
  5662. self.cue.text += '\n';
  5663. }
  5664. self.cue.text += line;
  5665. continue;
  5666. case 'BADCUE':
  5667. // BADCUE
  5668. // 54-62 - Collect and discard the remaining cue.
  5669. if (!line) {
  5670. self.state = 'ID';
  5671. }
  5672. continue;
  5673. }
  5674. }
  5675. } catch (e) {
  5676. // If we are currently parsing a cue, report what we have.
  5677. if (self.state === 'CUETEXT' && self.cue && self.oncue) {
  5678. self.oncue(self.cue);
  5679. }
  5680. self.cue = null;
  5681. // Enter BADWEBVTT state if header was not parsed correctly otherwise
  5682. // another exception occurred so enter BADCUE state.
  5683. self.state = self.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';
  5684. }
  5685. return this;
  5686. },
  5687. flush: function flush() {
  5688. var self = this;
  5689. try {
  5690. // Finish decoding the stream.
  5691. self.buffer += self.decoder.decode();
  5692. // Synthesize the end of the current cue or region.
  5693. if (self.cue || self.state === 'HEADER') {
  5694. self.buffer += '\n\n';
  5695. self.parse();
  5696. }
  5697. // If we've flushed, parsed, and we're still on the INITIAL state then
  5698. // that means we don't have enough of the stream to parse the first
  5699. // line.
  5700. if (self.state === 'INITIAL') {
  5701. throw new Error('Malformed WebVTT signature.');
  5702. }
  5703. } catch (e) {
  5704. throw e;
  5705. }
  5706. if (self.onflush) {
  5707. self.onflush();
  5708. }
  5709. return this;
  5710. }
  5711. };
  5712. exports.fixLineBreaks = fixLineBreaks;
  5713. exports.default = VTTParser;
  5714. /***/ }),
  5715. /* 31 */
  5716. /***/ (function(module, exports, __webpack_require__) {
  5717. module.exports = __webpack_require__(32);
  5718. /***/ }),
  5719. /* 32 */
  5720. /***/ (function(module, exports, __webpack_require__) {
  5721. "use strict";
  5722. Object.defineProperty(exports, "__esModule", {
  5723. value: true
  5724. });
  5725. 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; }; }();
  5726. 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); } };
  5727. var _xgplayer = __webpack_require__(33);
  5728. var _xgplayer2 = _interopRequireDefault(_xgplayer);
  5729. var _hls = __webpack_require__(34);
  5730. var _hls2 = _interopRequireDefault(_hls);
  5731. var _utils = __webpack_require__(80);
  5732. var _utils2 = _interopRequireDefault(_utils);
  5733. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5734. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5735. 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; }
  5736. 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; }
  5737. var HlsJsPlayer = function (_Player) {
  5738. _inherits(HlsJsPlayer, _Player);
  5739. function HlsJsPlayer(options) {
  5740. _classCallCheck(this, HlsJsPlayer);
  5741. var _this = _possibleConstructorReturn(this, (HlsJsPlayer.__proto__ || Object.getPrototypeOf(HlsJsPlayer)).call(this, options));
  5742. _this.hlsOpts = options.hlsOpts || {};
  5743. var util = _xgplayer2.default.util;
  5744. var player = _this;
  5745. player.once('complete', function () {
  5746. if (player.config.isLive) {
  5747. util.addClass(player.root, 'xgplayer-is-live');
  5748. if (!util.findDom(player.controls, '.xgplayer-live')) {
  5749. var live = util.createDom('xg-live', '正在直播', {}, 'xgplayer-live');
  5750. player.controls.appendChild(live);
  5751. }
  5752. }
  5753. });
  5754. _this.browser = _utils2.default.getBrowserVersion();
  5755. if (player.config.useHls === undefined) {
  5756. if (_xgplayer2.default.sniffer.device === 'mobile' && navigator.platform !== 'MacIntel' && navigator.platform !== 'Win32' || _this.browser.indexOf('Safari') > -1) {
  5757. return _possibleConstructorReturn(_this);
  5758. }
  5759. } else if (!player.config.useHls) {
  5760. return _possibleConstructorReturn(_this);
  5761. }
  5762. Number.isFinite = Number.isFinite || function (value) {
  5763. return typeof value === "number" && isFinite(value);
  5764. };
  5765. var hls = void 0;
  5766. hls = new _hls2.default(_this.hlsOpts);
  5767. _this.hls = hls;
  5768. Object.defineProperty(player, 'src', {
  5769. get: function get() {
  5770. return player.currentSrc;
  5771. },
  5772. set: function set(url) {
  5773. util.removeClass(player.root, 'xgplayer-is-live');
  5774. var liveDom = document.querySelector('.xgplayer-live');
  5775. if (liveDom) {
  5776. liveDom.parentNode.removeChild(liveDom);
  5777. }
  5778. // player.config.url = url
  5779. var paused = player.paused;
  5780. player.hls.stopLoad();
  5781. player.hls.detachMedia();
  5782. player.hls.destroy();
  5783. player.hls = new _hls2.default(player.hlsOpts);
  5784. player.register(url);
  5785. if (!paused) {
  5786. player.pause();
  5787. player.once('pause', function () {
  5788. player.hls.loadSource(url);
  5789. });
  5790. player.once('canplay', function () {
  5791. player.play().catch(function (err) {});
  5792. });
  5793. } else {
  5794. player.hls.loadSource(url);
  5795. }
  5796. player.hls.attachMedia(player.video);
  5797. player.once('canplay', function () {
  5798. player.currentTime = 0;
  5799. });
  5800. },
  5801. configurable: true
  5802. });
  5803. _this.register(_this.config.url);
  5804. _this.once('complete', function () {
  5805. hls.attachMedia(player.video);
  5806. player.once('canplay', function () {
  5807. player.play().catch(function (err) {});
  5808. });
  5809. });
  5810. _this.once('destroy', function () {
  5811. hls.stopLoad();
  5812. });
  5813. return _this;
  5814. }
  5815. _createClass(HlsJsPlayer, [{
  5816. key: 'register',
  5817. value: function register(url) {
  5818. var hls = this.hls;
  5819. var util = _xgplayer2.default.util;
  5820. var player = this;
  5821. hls.on(_hls2.default.Events.MEDIA_ATTACHED, function () {
  5822. hls.loadSource(url);
  5823. });
  5824. hls.on(_hls2.default.Events.LEVEL_LOADED, function (name, e) {
  5825. if (!hls.inited) {
  5826. hls.inited = true;
  5827. if (e && e.details && e.details.live) {
  5828. util.addClass(player.root, 'xgplayer-is-live');
  5829. if (!util.findDom(player.root, '.xgplayer-live')) {
  5830. var live = util.createDom('xg-live', '正在直播', {}, 'xgplayer-live');
  5831. player.controls.appendChild(live);
  5832. }
  5833. }
  5834. }
  5835. });
  5836. hls.on(_hls2.default.Events.ERROR, function (event, data) {
  5837. player.emit('HLS_ERROR', {
  5838. errorType: data.type,
  5839. errorDetails: data.details,
  5840. errorFatal: data.fatal
  5841. });
  5842. if (data.fatal) {
  5843. switch (data.type) {
  5844. case _hls2.default.ErrorTypes.NETWORK_ERROR:
  5845. hls.startLoad();
  5846. break;
  5847. case _hls2.default.ErrorTypes.MEDIA_ERROR:
  5848. hls.recoverMediaError();
  5849. break;
  5850. default:
  5851. player.emit('error', data);
  5852. }
  5853. }
  5854. });
  5855. this._statistics();
  5856. }
  5857. }, {
  5858. key: '_statistics',
  5859. value: function _statistics() {
  5860. var statsInfo = {
  5861. speed: 0,
  5862. playerType: "HlsPlayer"
  5863. };
  5864. var mediainfo = {
  5865. videoDataRate: 0,
  5866. audioDataRate: 0
  5867. };
  5868. var hls = this.hls;
  5869. var player = this;
  5870. hls.on(_hls2.default.Events.FRAG_LOAD_PROGRESS, function (flag, payload) {
  5871. statsInfo.speed = payload.stats.loaded / 1000;
  5872. });
  5873. hls.on(_hls2.default.Events.FRAG_PARSING_DATA, function (flag, payload) {
  5874. if (payload.type === 'video') {
  5875. mediainfo.fps = parseInt(payload.nb / (payload.endPTS - payload.startPTS));
  5876. }
  5877. });
  5878. hls.on(_hls2.default.Events.FRAG_PARSING_INIT_SEGMENT, function (flag, payload) {
  5879. mediainfo.hasAudio = payload.tracks && payload.tracks.audio ? true : false;
  5880. mediainfo.hasVideo = payload.tracks && payload.tracks.audio ? true : false;
  5881. if (mediainfo.hasAudio) {
  5882. var track = payload.tracks.audio;
  5883. mediainfo.audioChannelCount = track.metadata && track.metadata.channelCount ? track.metadata.channelCount : 0;
  5884. mediainfo.audioCodec = track.codec;
  5885. }
  5886. if (mediainfo.hasVideo) {
  5887. var _track = payload.tracks.video;
  5888. mediainfo.videoCodec = _track.codec;
  5889. mediainfo.width = _track.metadata && _track.metadata.width ? _track.metadata.width : 0;
  5890. mediainfo.height = _track.metadata && _track.metadata.height ? _track.metadata.height : 0;
  5891. }
  5892. mediainfo.duration = payload.frag && payload.frag.duration ? payload.frag.duration : 0;
  5893. mediainfo.level = payload.frag && payload.frag.level ? payload.frag.level : 0;
  5894. if (mediainfo.videoCodec || mediainfo.audioCodec) {
  5895. mediainfo.mimeType = 'video/hls; codecs="' + mediainfo.videoCodec + ';' + mediainfo.audioCodec + '"';
  5896. }
  5897. player.mediainfo = mediainfo;
  5898. player.emit("media_info", mediainfo);
  5899. });
  5900. this._statisticsTimmer = setInterval(function () {
  5901. player.emit("statistics_info", statsInfo);
  5902. statsInfo.speed = 0;
  5903. }, 1000);
  5904. }
  5905. }, {
  5906. key: 'destroy',
  5907. value: function destroy() {
  5908. _get(HlsJsPlayer.prototype.__proto__ || Object.getPrototypeOf(HlsJsPlayer.prototype), 'destroy', this).call(this);
  5909. clearInterval(this._statisticsTimmer);
  5910. }
  5911. }]);
  5912. return HlsJsPlayer;
  5913. }(_xgplayer2.default);
  5914. HlsJsPlayer.isSupported = _hls2.default.isSupported;
  5915. exports.default = HlsJsPlayer;
  5916. module.exports = exports['default'];
  5917. /***/ }),
  5918. /* 33 */
  5919. /***/ (function(module, exports) {
  5920. module.exports = __WEBPACK_EXTERNAL_MODULE__33__;
  5921. /***/ }),
  5922. /* 34 */
  5923. /***/ (function(module, exports, __webpack_require__) {
  5924. "use strict";
  5925. Object.defineProperty(exports, "__esModule", {
  5926. value: true
  5927. });
  5928. 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; }; }();
  5929. var _urlToolkit = __webpack_require__(8);
  5930. var URLToolkit = _interopRequireWildcard(_urlToolkit);
  5931. var _errors = __webpack_require__(2);
  5932. var _playlistLoader = __webpack_require__(15);
  5933. var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
  5934. var _fragmentLoader = __webpack_require__(38);
  5935. var _fragmentLoader2 = _interopRequireDefault(_fragmentLoader);
  5936. var _keyLoader = __webpack_require__(39);
  5937. var _keyLoader2 = _interopRequireDefault(_keyLoader);
  5938. var _fragmentTracker = __webpack_require__(6);
  5939. var _streamController = __webpack_require__(40);
  5940. var _streamController2 = _interopRequireDefault(_streamController);
  5941. var _levelController = __webpack_require__(57);
  5942. var _levelController2 = _interopRequireDefault(_levelController);
  5943. var _id3TrackController = __webpack_require__(58);
  5944. var _id3TrackController2 = _interopRequireDefault(_id3TrackController);
  5945. var _isSupported2 = __webpack_require__(59);
  5946. var _logger = __webpack_require__(0);
  5947. var _config = __webpack_require__(60);
  5948. var _events = __webpack_require__(1);
  5949. var _events2 = _interopRequireDefault(_events);
  5950. var _observer = __webpack_require__(24);
  5951. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5952. 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; } }
  5953. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5954. 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; }
  5955. 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; }
  5956. /**
  5957. * @module Hls
  5958. * @class
  5959. * @constructor
  5960. */
  5961. var Hls = function (_Observer) {
  5962. _inherits(Hls, _Observer);
  5963. _createClass(Hls, null, [{
  5964. key: 'isSupported',
  5965. /**
  5966. * @type {boolean}
  5967. */
  5968. value: function isSupported() {
  5969. return (0, _isSupported2.isSupported)();
  5970. }
  5971. /**
  5972. * @type {HlsEvents}
  5973. */
  5974. }, {
  5975. key: 'version',
  5976. /**
  5977. * @type {string}
  5978. */
  5979. get: function get() {
  5980. return __VERSION__;
  5981. }
  5982. }, {
  5983. key: 'Events',
  5984. get: function get() {
  5985. return _events2.default;
  5986. }
  5987. /**
  5988. * @type {HlsErrorTypes}
  5989. */
  5990. }, {
  5991. key: 'ErrorTypes',
  5992. get: function get() {
  5993. return _errors.ErrorTypes;
  5994. }
  5995. /**
  5996. * @type {HlsErrorDetails}
  5997. */
  5998. }, {
  5999. key: 'ErrorDetails',
  6000. get: function get() {
  6001. return _errors.ErrorDetails;
  6002. }
  6003. /**
  6004. * @type {HlsConfig}
  6005. */
  6006. }, {
  6007. key: 'DefaultConfig',
  6008. get: function get() {
  6009. if (!Hls.defaultConfig) {
  6010. return _config.hlsDefaultConfig;
  6011. }
  6012. return Hls.defaultConfig;
  6013. }
  6014. /**
  6015. * @type {HlsConfig}
  6016. */
  6017. ,
  6018. set: function set(defaultConfig) {
  6019. Hls.defaultConfig = defaultConfig;
  6020. }
  6021. /**
  6022. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  6023. *
  6024. * @constructs Hls
  6025. * @param {HlsConfig} config
  6026. */
  6027. }]);
  6028. function Hls() {
  6029. var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  6030. _classCallCheck(this, Hls);
  6031. var _this = _possibleConstructorReturn(this, (Hls.__proto__ || Object.getPrototypeOf(Hls)).call(this));
  6032. var defaultConfig = Hls.DefaultConfig;
  6033. if ((config.liveSyncDurationCount || config.liveMaxLatencyDurationCount) && (config.liveSyncDuration || config.liveMaxLatencyDuration)) {
  6034. throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');
  6035. }
  6036. for (var prop in defaultConfig) {
  6037. if (prop in config) continue;
  6038. config[prop] = defaultConfig[prop];
  6039. }
  6040. if (config.liveMaxLatencyDurationCount !== undefined && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {
  6041. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');
  6042. }
  6043. if (config.liveMaxLatencyDuration !== undefined && (config.liveMaxLatencyDuration <= config.liveSyncDuration || config.liveSyncDuration === undefined)) {
  6044. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');
  6045. }
  6046. (0, _logger.enableLogs)(config.debug);
  6047. _this.config = config;
  6048. _this._autoLevelCapping = -1;
  6049. // core controllers and network loaders
  6050. /**
  6051. * @member {AbrController} abrController
  6052. */
  6053. var abrController = _this.abrController = new config.abrController(_this);
  6054. var bufferController = new config.bufferController(_this);
  6055. var capLevelController = new config.capLevelController(_this);
  6056. var fpsController = new config.fpsController(_this);
  6057. var playListLoader = new _playlistLoader2.default(_this);
  6058. var fragmentLoader = new _fragmentLoader2.default(_this);
  6059. var keyLoader = new _keyLoader2.default(_this);
  6060. var id3TrackController = new _id3TrackController2.default(_this);
  6061. // network controllers
  6062. /**
  6063. * @member {LevelController} levelController
  6064. */
  6065. var levelController = _this.levelController = new _levelController2.default(_this);
  6066. // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important
  6067. var fragmentTracker = new _fragmentTracker.FragmentTracker(_this);
  6068. /**
  6069. * @member {StreamController} streamController
  6070. */
  6071. var streamController = _this.streamController = new _streamController2.default(_this, fragmentTracker);
  6072. var networkControllers = [levelController, streamController];
  6073. // optional audio stream controller
  6074. /**
  6075. * @var {ICoreComponent | Controller}
  6076. */
  6077. var Controller = config.audioStreamController;
  6078. if (Controller) {
  6079. networkControllers.push(new Controller(_this, fragmentTracker));
  6080. }
  6081. /**
  6082. * @member {INetworkController[]} networkControllers
  6083. */
  6084. _this.networkControllers = networkControllers;
  6085. /**
  6086. * @var {ICoreComponent[]}
  6087. */
  6088. var coreComponents = [playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];
  6089. // optional audio track and subtitle controller
  6090. Controller = config.audioTrackController;
  6091. if (Controller) {
  6092. var audioTrackController = new Controller(_this);
  6093. /**
  6094. * @member {AudioTrackController} audioTrackController
  6095. */
  6096. _this.audioTrackController = audioTrackController;
  6097. coreComponents.push(audioTrackController);
  6098. }
  6099. Controller = config.subtitleTrackController;
  6100. if (Controller) {
  6101. var subtitleTrackController = new Controller(_this);
  6102. /**
  6103. * @member {SubtitleTrackController} subtitleTrackController
  6104. */
  6105. _this.subtitleTrackController = subtitleTrackController;
  6106. networkControllers.push(subtitleTrackController);
  6107. }
  6108. Controller = config.emeController;
  6109. if (Controller) {
  6110. var emeController = new Controller(_this);
  6111. /**
  6112. * @member {EMEController} emeController
  6113. */
  6114. _this.emeController = emeController;
  6115. coreComponents.push(emeController);
  6116. }
  6117. // optional subtitle controllers
  6118. Controller = config.subtitleStreamController;
  6119. if (Controller) {
  6120. networkControllers.push(new Controller(_this, fragmentTracker));
  6121. }
  6122. Controller = config.timelineController;
  6123. if (Controller) {
  6124. coreComponents.push(new Controller(_this));
  6125. }
  6126. /**
  6127. * @member {ICoreComponent[]}
  6128. */
  6129. _this.coreComponents = coreComponents;
  6130. return _this;
  6131. }
  6132. /**
  6133. * Dispose of the instance
  6134. */
  6135. _createClass(Hls, [{
  6136. key: 'destroy',
  6137. value: function destroy() {
  6138. _logger.logger.log('destroy');
  6139. this.trigger(_events2.default.DESTROYING);
  6140. this.detachMedia();
  6141. this.coreComponents.concat(this.networkControllers).forEach(function (component) {
  6142. component.destroy();
  6143. });
  6144. this.url = null;
  6145. this.removeAllListeners();
  6146. this._autoLevelCapping = -1;
  6147. }
  6148. /**
  6149. * Attach a media element
  6150. * @param {HTMLMediaElement} media
  6151. */
  6152. }, {
  6153. key: 'attachMedia',
  6154. value: function attachMedia(media) {
  6155. _logger.logger.log('attachMedia');
  6156. this.media = media;
  6157. this.trigger(_events2.default.MEDIA_ATTACHING, { media: media });
  6158. }
  6159. /**
  6160. * Detach from the media
  6161. */
  6162. }, {
  6163. key: 'detachMedia',
  6164. value: function detachMedia() {
  6165. _logger.logger.log('detachMedia');
  6166. this.trigger(_events2.default.MEDIA_DETACHING);
  6167. this.media = null;
  6168. }
  6169. /**
  6170. * Set the source URL. Can be relative or absolute.
  6171. * @param {string} url
  6172. */
  6173. }, {
  6174. key: 'loadSource',
  6175. value: function loadSource(url) {
  6176. url = URLToolkit.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true });
  6177. _logger.logger.log('loadSource:' + url);
  6178. this.url = url;
  6179. // when attaching to a source URL, trigger a playlist load
  6180. this.trigger(_events2.default.MANIFEST_LOADING, { url: url });
  6181. }
  6182. /**
  6183. * Start loading data from the stream source.
  6184. * Depending on default config, client starts loading automatically when a source is set.
  6185. *
  6186. * @param {number} startPosition Set the start position to stream from
  6187. * @default -1 None (from earliest point)
  6188. */
  6189. }, {
  6190. key: 'startLoad',
  6191. value: function startLoad() {
  6192. var startPosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1;
  6193. _logger.logger.log('startLoad(' + startPosition + ')');
  6194. this.networkControllers.forEach(function (controller) {
  6195. controller.startLoad(startPosition);
  6196. });
  6197. }
  6198. /**
  6199. * Stop loading of any stream data.
  6200. */
  6201. }, {
  6202. key: 'stopLoad',
  6203. value: function stopLoad() {
  6204. _logger.logger.log('stopLoad');
  6205. this.networkControllers.forEach(function (controller) {
  6206. controller.stopLoad();
  6207. });
  6208. }
  6209. /**
  6210. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  6211. */
  6212. }, {
  6213. key: 'swapAudioCodec',
  6214. value: function swapAudioCodec() {
  6215. _logger.logger.log('swapAudioCodec');
  6216. this.streamController.swapAudioCodec();
  6217. }
  6218. /**
  6219. * When the media-element fails, this allows to detach and then re-attach it
  6220. * as one call (convenience method).
  6221. *
  6222. * Automatic recovery of media-errors by this process is configurable.
  6223. */
  6224. }, {
  6225. key: 'recoverMediaError',
  6226. value: function recoverMediaError() {
  6227. _logger.logger.log('recoverMediaError');
  6228. var media = this.media;
  6229. this.detachMedia();
  6230. this.attachMedia(media);
  6231. }
  6232. /**
  6233. * @type {QualityLevel[]}
  6234. */
  6235. }, {
  6236. key: 'levels',
  6237. get: function get() {
  6238. return this.levelController.levels;
  6239. }
  6240. /**
  6241. * Index of quality level currently played
  6242. * @type {number}
  6243. */
  6244. }, {
  6245. key: 'currentLevel',
  6246. get: function get() {
  6247. return this.streamController.currentLevel;
  6248. }
  6249. /**
  6250. * Set quality level index immediately .
  6251. * This will flush the current buffer to replace the quality asap.
  6252. * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.
  6253. * @type {number} -1 for automatic level selection
  6254. */
  6255. ,
  6256. set: function set(newLevel) {
  6257. _logger.logger.log('set currentLevel:' + newLevel);
  6258. this.loadLevel = newLevel;
  6259. this.streamController.immediateLevelSwitch();
  6260. }
  6261. /**
  6262. * Index of next quality level loaded as scheduled by stream controller.
  6263. * @type {number}
  6264. */
  6265. }, {
  6266. key: 'nextLevel',
  6267. get: function get() {
  6268. return this.streamController.nextLevel;
  6269. }
  6270. /**
  6271. * Set quality level index for next loaded data.
  6272. * This will switch the video quality asap, without interrupting playback.
  6273. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  6274. * @type {number} -1 for automatic level selection
  6275. */
  6276. ,
  6277. set: function set(newLevel) {
  6278. _logger.logger.log('set nextLevel:' + newLevel);
  6279. this.levelController.manualLevel = newLevel;
  6280. this.streamController.nextLevelSwitch();
  6281. }
  6282. /**
  6283. * Return the quality level of the currently or last (of none is loaded currently) segment
  6284. * @type {number}
  6285. */
  6286. }, {
  6287. key: 'loadLevel',
  6288. get: function get() {
  6289. return this.levelController.level;
  6290. }
  6291. /**
  6292. * Set quality level index for next loaded data in a conservative way.
  6293. * This will switch the quality without flushing, but interrupt current loading.
  6294. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  6295. * @type {number} newLevel -1 for automatic level selection
  6296. */
  6297. ,
  6298. set: function set(newLevel) {
  6299. _logger.logger.log('set loadLevel:' + newLevel);
  6300. this.levelController.manualLevel = newLevel;
  6301. }
  6302. /**
  6303. * get next quality level loaded
  6304. * @type {number}
  6305. */
  6306. }, {
  6307. key: 'nextLoadLevel',
  6308. get: function get() {
  6309. return this.levelController.nextLoadLevel;
  6310. }
  6311. /**
  6312. * Set quality level of next loaded segment in a fully "non-destructive" way.
  6313. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  6314. * @type {number} level
  6315. */
  6316. ,
  6317. set: function set(level) {
  6318. this.levelController.nextLoadLevel = level;
  6319. }
  6320. /**
  6321. * Return "first level": like a default level, if not set,
  6322. * falls back to index of first level referenced in manifest
  6323. * @type {number}
  6324. */
  6325. }, {
  6326. key: 'firstLevel',
  6327. get: function get() {
  6328. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  6329. }
  6330. /**
  6331. * Sets "first-level", see getter.
  6332. * @type {number}
  6333. */
  6334. ,
  6335. set: function set(newLevel) {
  6336. _logger.logger.log('set firstLevel:' + newLevel);
  6337. this.levelController.firstLevel = newLevel;
  6338. }
  6339. /**
  6340. * Return start level (level of first fragment that will be played back)
  6341. * if not overrided by user, first level appearing in manifest will be used as start level
  6342. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  6343. * (determined from download of first segment)
  6344. * @type {number}
  6345. */
  6346. }, {
  6347. key: 'startLevel',
  6348. get: function get() {
  6349. return this.levelController.startLevel;
  6350. }
  6351. /**
  6352. * set start level (level of first fragment that will be played back)
  6353. * if not overrided by user, first level appearing in manifest will be used as start level
  6354. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  6355. * (determined from download of first segment)
  6356. * @type {number} newLevel
  6357. */
  6358. ,
  6359. set: function set(newLevel) {
  6360. _logger.logger.log('set startLevel:' + newLevel);
  6361. var hls = this;
  6362. // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
  6363. if (newLevel !== -1) {
  6364. newLevel = Math.max(newLevel, hls.minAutoLevel);
  6365. }
  6366. hls.levelController.startLevel = newLevel;
  6367. }
  6368. /**
  6369. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  6370. * @type {number}
  6371. */
  6372. }, {
  6373. key: 'autoLevelCapping',
  6374. get: function get() {
  6375. return this._autoLevelCapping;
  6376. }
  6377. /**
  6378. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  6379. * @type {number}
  6380. */
  6381. ,
  6382. set: function set(newLevel) {
  6383. _logger.logger.log('set autoLevelCapping:' + newLevel);
  6384. this._autoLevelCapping = newLevel;
  6385. }
  6386. /**
  6387. * True when automatic level selection enabled
  6388. * @type {boolean}
  6389. */
  6390. }, {
  6391. key: 'autoLevelEnabled',
  6392. get: function get() {
  6393. return this.levelController.manualLevel === -1;
  6394. }
  6395. /**
  6396. * Level set manually (if any)
  6397. * @type {number}
  6398. */
  6399. }, {
  6400. key: 'manualLevel',
  6401. get: function get() {
  6402. return this.levelController.manualLevel;
  6403. }
  6404. /**
  6405. * min level selectable in auto mode according to config.minAutoBitrate
  6406. * @type {number}
  6407. */
  6408. }, {
  6409. key: 'minAutoLevel',
  6410. get: function get() {
  6411. var hls = this,
  6412. levels = hls.levels,
  6413. minAutoBitrate = hls.config.minAutoBitrate,
  6414. len = levels ? levels.length : 0;
  6415. for (var i = 0; i < len; i++) {
  6416. var levelNextBitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate;
  6417. if (levelNextBitrate > minAutoBitrate) {
  6418. return i;
  6419. }
  6420. }
  6421. return 0;
  6422. }
  6423. /**
  6424. * max level selectable in auto mode according to autoLevelCapping
  6425. * @type {number}
  6426. */
  6427. }, {
  6428. key: 'maxAutoLevel',
  6429. get: function get() {
  6430. var hls = this;
  6431. var levels = hls.levels;
  6432. var autoLevelCapping = hls.autoLevelCapping;
  6433. var maxAutoLevel = void 0;
  6434. if (autoLevelCapping === -1 && levels && levels.length) {
  6435. maxAutoLevel = levels.length - 1;
  6436. } else {
  6437. maxAutoLevel = autoLevelCapping;
  6438. }
  6439. return maxAutoLevel;
  6440. }
  6441. /**
  6442. * next automatically selected quality level
  6443. * @type {number}
  6444. */
  6445. }, {
  6446. key: 'nextAutoLevel',
  6447. get: function get() {
  6448. var hls = this;
  6449. // ensure next auto level is between min and max auto level
  6450. return Math.min(Math.max(hls.abrController.nextAutoLevel, hls.minAutoLevel), hls.maxAutoLevel);
  6451. }
  6452. /**
  6453. * this setter is used to force next auto level.
  6454. * this is useful to force a switch down in auto mode:
  6455. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  6456. * forced value is valid for one fragment. upon succesful frag loading at forced level,
  6457. * this value will be resetted to -1 by ABR controller.
  6458. * @type {number}
  6459. */
  6460. ,
  6461. set: function set(nextLevel) {
  6462. var hls = this;
  6463. hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel);
  6464. }
  6465. /**
  6466. * @type {AudioTrack[]}
  6467. */
  6468. }, {
  6469. key: 'audioTracks',
  6470. get: function get() {
  6471. var audioTrackController = this.audioTrackController;
  6472. return audioTrackController ? audioTrackController.audioTracks : [];
  6473. }
  6474. /**
  6475. * index of the selected audio track (index in audio track lists)
  6476. * @type {number}
  6477. */
  6478. }, {
  6479. key: 'audioTrack',
  6480. get: function get() {
  6481. var audioTrackController = this.audioTrackController;
  6482. return audioTrackController ? audioTrackController.audioTrack : -1;
  6483. }
  6484. /**
  6485. * selects an audio track, based on its index in audio track lists
  6486. * @type {number}
  6487. */
  6488. ,
  6489. set: function set(audioTrackId) {
  6490. var audioTrackController = this.audioTrackController;
  6491. if (audioTrackController) {
  6492. audioTrackController.audioTrack = audioTrackId;
  6493. }
  6494. }
  6495. /**
  6496. * @type {Seconds}
  6497. */
  6498. }, {
  6499. key: 'liveSyncPosition',
  6500. get: function get() {
  6501. return this.streamController.liveSyncPosition;
  6502. }
  6503. /**
  6504. * get alternate subtitle tracks list from playlist
  6505. * @type {SubtitleTrack[]}
  6506. */
  6507. }, {
  6508. key: 'subtitleTracks',
  6509. get: function get() {
  6510. var subtitleTrackController = this.subtitleTrackController;
  6511. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  6512. }
  6513. /**
  6514. * index of the selected subtitle track (index in subtitle track lists)
  6515. * @type {number}
  6516. */
  6517. }, {
  6518. key: 'subtitleTrack',
  6519. get: function get() {
  6520. var subtitleTrackController = this.subtitleTrackController;
  6521. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  6522. }
  6523. /**
  6524. * select an subtitle track, based on its index in subtitle track lists
  6525. * @type{number}
  6526. */
  6527. ,
  6528. set: function set(subtitleTrackId) {
  6529. var subtitleTrackController = this.subtitleTrackController;
  6530. if (subtitleTrackController) {
  6531. subtitleTrackController.subtitleTrack = subtitleTrackId;
  6532. }
  6533. }
  6534. /**
  6535. * @type {boolean}
  6536. */
  6537. }, {
  6538. key: 'subtitleDisplay',
  6539. get: function get() {
  6540. var subtitleTrackController = this.subtitleTrackController;
  6541. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  6542. }
  6543. /**
  6544. * Enable/disable subtitle display rendering
  6545. * @type {boolean}
  6546. */
  6547. ,
  6548. set: function set(value) {
  6549. var subtitleTrackController = this.subtitleTrackController;
  6550. if (subtitleTrackController) {
  6551. subtitleTrackController.subtitleDisplay = value;
  6552. }
  6553. }
  6554. }]);
  6555. return Hls;
  6556. }(_observer.Observer);
  6557. exports.default = Hls;
  6558. module.exports = exports['default'];
  6559. /***/ }),
  6560. /* 35 */
  6561. /***/ (function(module, exports, __webpack_require__) {
  6562. "use strict";
  6563. Object.defineProperty(exports, "__esModule", {
  6564. value: true
  6565. });
  6566. 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; }; }();
  6567. var _urlToolkit = __webpack_require__(8);
  6568. var URLToolkit = _interopRequireWildcard(_urlToolkit);
  6569. var _fragment = __webpack_require__(11);
  6570. var _fragment2 = _interopRequireDefault(_fragment);
  6571. var _level = __webpack_require__(36);
  6572. var _level2 = _interopRequireDefault(_level);
  6573. var _levelKey = __webpack_require__(17);
  6574. var _levelKey2 = _interopRequireDefault(_levelKey);
  6575. var _attrList = __webpack_require__(37);
  6576. var _attrList2 = _interopRequireDefault(_attrList);
  6577. var _logger = __webpack_require__(0);
  6578. var _codecs = __webpack_require__(18);
  6579. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6580. 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; } }
  6581. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6582. /**
  6583. * M3U8 parser
  6584. * @module
  6585. */
  6586. // https://regex101.com is your friend
  6587. var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g;
  6588. var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  6589. var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  6590. /|(?!#)([\S+ ?]+)/.source, // segment URI, group 3 => the URI (note newline is not eaten)
  6591. /|#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)
  6592. /|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec
  6593. /|#.*/.source // All other non-segment oriented tags will match with all groups empty
  6594. ].join(''), 'g');
  6595. 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?/;
  6596. var MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i;
  6597. var M3U8Parser = function () {
  6598. function M3U8Parser() {
  6599. _classCallCheck(this, M3U8Parser);
  6600. }
  6601. _createClass(M3U8Parser, null, [{
  6602. key: 'findGroup',
  6603. value: function findGroup(groups, mediaGroupId) {
  6604. if (!groups) {
  6605. return null;
  6606. }
  6607. var matchingGroup = null;
  6608. for (var i = 0; i < groups.length; i++) {
  6609. var group = groups[i];
  6610. if (group.id === mediaGroupId) {
  6611. matchingGroup = group;
  6612. }
  6613. }
  6614. return matchingGroup;
  6615. }
  6616. }, {
  6617. key: 'convertAVC1ToAVCOTI',
  6618. value: function convertAVC1ToAVCOTI(codec) {
  6619. var result = void 0,
  6620. avcdata = codec.split('.');
  6621. if (avcdata.length > 2) {
  6622. result = avcdata.shift() + '.';
  6623. result += parseInt(avcdata.shift()).toString(16);
  6624. result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
  6625. } else {
  6626. result = codec;
  6627. }
  6628. return result;
  6629. }
  6630. }, {
  6631. key: 'resolve',
  6632. value: function resolve(url, baseUrl) {
  6633. return URLToolkit.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });
  6634. }
  6635. }, {
  6636. key: 'parseMasterPlaylist',
  6637. value: function parseMasterPlaylist(string, baseurl) {
  6638. var levels = [],
  6639. result = void 0;
  6640. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  6641. function setCodecs(codecs, level) {
  6642. ['video', 'audio'].forEach(function (type) {
  6643. var filtered = codecs.filter(function (codec) {
  6644. return (0, _codecs.isCodecType)(codec, type);
  6645. });
  6646. if (filtered.length) {
  6647. var preferred = filtered.filter(function (codec) {
  6648. return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;
  6649. });
  6650. level[type + 'Codec'] = preferred.length > 0 ? preferred[0] : filtered[0];
  6651. // remove from list
  6652. codecs = codecs.filter(function (codec) {
  6653. return filtered.indexOf(codec) === -1;
  6654. });
  6655. }
  6656. });
  6657. level.unknownCodecs = codecs;
  6658. }
  6659. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  6660. var level = {};
  6661. var attrs = level.attrs = new _attrList2.default(result[1]);
  6662. level.url = M3U8Parser.resolve(result[2], baseurl);
  6663. var resolution = attrs.decimalResolution('RESOLUTION');
  6664. if (resolution) {
  6665. level.width = resolution.width;
  6666. level.height = resolution.height;
  6667. }
  6668. level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');
  6669. level.name = attrs.NAME;
  6670. setCodecs([].concat((attrs.CODECS || '').split(/[ ,]+/)), level);
  6671. if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {
  6672. level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);
  6673. }
  6674. levels.push(level);
  6675. }
  6676. return levels;
  6677. }
  6678. }, {
  6679. key: 'parseMasterPlaylistMedia',
  6680. value: function parseMasterPlaylistMedia(string, baseurl, type) {
  6681. var audioGroups = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
  6682. var result = void 0;
  6683. var medias = [];
  6684. var id = 0;
  6685. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  6686. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  6687. var media = {};
  6688. var attrs = new _attrList2.default(result[1]);
  6689. if (attrs.TYPE === type) {
  6690. media.groupId = attrs['GROUP-ID'];
  6691. media.name = attrs.NAME;
  6692. media.type = type;
  6693. media.default = attrs.DEFAULT === 'YES';
  6694. media.autoselect = attrs.AUTOSELECT === 'YES';
  6695. media.forced = attrs.FORCED === 'YES';
  6696. if (attrs.URI) {
  6697. media.url = M3U8Parser.resolve(attrs.URI, baseurl);
  6698. }
  6699. media.lang = attrs.LANGUAGE;
  6700. if (!media.name) {
  6701. media.name = media.lang;
  6702. }
  6703. if (audioGroups.length) {
  6704. var groupCodec = M3U8Parser.findGroup(audioGroups, media.groupId);
  6705. media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec;
  6706. }
  6707. media.id = id++;
  6708. medias.push(media);
  6709. }
  6710. }
  6711. return medias;
  6712. }
  6713. }, {
  6714. key: 'parseLevelPlaylist',
  6715. value: function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) {
  6716. var currentSN = 0;
  6717. var totalduration = 0;
  6718. var level = new _level2.default(baseurl);
  6719. var levelkey = new _levelKey2.default();
  6720. var cc = 0;
  6721. var prevFrag = null;
  6722. var frag = new _fragment2.default();
  6723. var result = void 0;
  6724. var i = void 0;
  6725. var firstPdtIndex = null;
  6726. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  6727. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  6728. var duration = result[1];
  6729. if (duration) {
  6730. // INF
  6731. frag.duration = parseFloat(duration);
  6732. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  6733. var title = (' ' + result[2]).slice(1);
  6734. frag.title = title || null;
  6735. frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
  6736. } else if (result[3]) {
  6737. // url
  6738. if (Number.isFinite(frag.duration)) {
  6739. var sn = currentSN++;
  6740. frag.type = type;
  6741. frag.start = totalduration;
  6742. frag.levelkey = levelkey;
  6743. frag.sn = sn;
  6744. frag.level = id;
  6745. frag.cc = cc;
  6746. frag.urlId = levelUrlId;
  6747. frag.baseurl = baseurl;
  6748. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  6749. frag.relurl = (' ' + result[3]).slice(1);
  6750. assignProgramDateTime(frag, prevFrag);
  6751. level.fragments.push(frag);
  6752. prevFrag = frag;
  6753. totalduration += frag.duration;
  6754. frag = new _fragment2.default();
  6755. }
  6756. } else if (result[4]) {
  6757. // X-BYTERANGE
  6758. frag.rawByteRange = (' ' + result[4]).slice(1);
  6759. if (prevFrag) {
  6760. var lastByteRangeEndOffset = prevFrag.byteRangeEndOffset;
  6761. if (lastByteRangeEndOffset) {
  6762. frag.lastByteRangeEndOffset = lastByteRangeEndOffset;
  6763. }
  6764. }
  6765. } else if (result[5]) {
  6766. // PROGRAM-DATE-TIME
  6767. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  6768. frag.rawProgramDateTime = (' ' + result[5]).slice(1);
  6769. frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
  6770. if (firstPdtIndex === null) {
  6771. firstPdtIndex = level.fragments.length;
  6772. }
  6773. } else {
  6774. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  6775. for (i = 1; i < result.length; i++) {
  6776. if (result[i] !== undefined) {
  6777. break;
  6778. }
  6779. }
  6780. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  6781. var value1 = (' ' + result[i + 1]).slice(1);
  6782. var value2 = (' ' + result[i + 2]).slice(1);
  6783. switch (result[i]) {
  6784. case '#':
  6785. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  6786. break;
  6787. case 'PLAYLIST-TYPE':
  6788. level.type = value1.toUpperCase();
  6789. break;
  6790. case 'MEDIA-SEQUENCE':
  6791. currentSN = level.startSN = parseInt(value1);
  6792. break;
  6793. case 'TARGETDURATION':
  6794. level.targetduration = parseFloat(value1);
  6795. break;
  6796. case 'VERSION':
  6797. level.version = parseInt(value1);
  6798. break;
  6799. case 'EXTM3U':
  6800. break;
  6801. case 'ENDLIST':
  6802. level.live = false;
  6803. break;
  6804. case 'DIS':
  6805. cc++;
  6806. frag.tagList.push(['DIS']);
  6807. break;
  6808. case 'DISCONTINUITY-SEQ':
  6809. cc = parseInt(value1);
  6810. break;
  6811. case 'KEY':
  6812. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4
  6813. var decryptparams = value1;
  6814. var keyAttrs = new _attrList2.default(decryptparams);
  6815. var decryptmethod = keyAttrs.enumeratedString('METHOD'),
  6816. decrypturi = keyAttrs.URI,
  6817. decryptiv = keyAttrs.hexadecimalInteger('IV');
  6818. if (decryptmethod) {
  6819. levelkey = new _levelKey2.default();
  6820. if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0) {
  6821. levelkey.method = decryptmethod;
  6822. // URI to get the key
  6823. levelkey.baseuri = baseurl;
  6824. levelkey.reluri = decrypturi;
  6825. levelkey.key = null;
  6826. // Initialization Vector (IV)
  6827. levelkey.iv = decryptiv;
  6828. }
  6829. }
  6830. break;
  6831. case 'START':
  6832. var startParams = value1;
  6833. var startAttrs = new _attrList2.default(startParams);
  6834. var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
  6835. // TIME-OFFSET can be 0
  6836. if (Number.isFinite(startTimeOffset)) {
  6837. level.startTimeOffset = startTimeOffset;
  6838. }
  6839. break;
  6840. case 'MAP':
  6841. var mapAttrs = new _attrList2.default(value1);
  6842. frag.relurl = mapAttrs.URI;
  6843. frag.rawByteRange = mapAttrs.BYTERANGE;
  6844. frag.baseurl = baseurl;
  6845. frag.level = id;
  6846. frag.type = type;
  6847. frag.sn = 'initSegment';
  6848. level.initSegment = frag;
  6849. frag = new _fragment2.default();
  6850. frag.rawProgramDateTime = level.initSegment.rawProgramDateTime;
  6851. break;
  6852. default:
  6853. _logger.logger.warn('line parsed but not handled: ' + result);
  6854. break;
  6855. }
  6856. }
  6857. }
  6858. frag = prevFrag;
  6859. // logger.log('found ' + level.fragments.length + ' fragments');
  6860. if (frag && !frag.relurl) {
  6861. level.fragments.pop();
  6862. totalduration -= frag.duration;
  6863. }
  6864. level.totalduration = totalduration;
  6865. level.averagetargetduration = totalduration / level.fragments.length;
  6866. level.endSN = currentSN - 1;
  6867. level.startCC = level.fragments[0] ? level.fragments[0].cc : 0;
  6868. level.endCC = cc;
  6869. if (!level.initSegment && level.fragments.length) {
  6870. // this is a bit lurky but HLS really has no other way to tell us
  6871. // if the fragments are TS or MP4, except if we download them :/
  6872. // but this is to be able to handle SIDX.
  6873. if (level.fragments.every(function (frag) {
  6874. return MP4_REGEX_SUFFIX.test(frag.relurl);
  6875. })) {
  6876. _logger.logger.warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');
  6877. frag = new _fragment2.default();
  6878. frag.relurl = level.fragments[0].relurl;
  6879. frag.baseurl = baseurl;
  6880. frag.level = id;
  6881. frag.type = type;
  6882. frag.sn = 'initSegment';
  6883. level.initSegment = frag;
  6884. level.needSidxRanges = true;
  6885. }
  6886. }
  6887. /**
  6888. * Backfill any missing PDT values
  6889. "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
  6890. one or more Media Segment URIs, the client SHOULD extrapolate
  6891. backward from that tag (using EXTINF durations and/or media
  6892. timestamps) to associate dates with those segments."
  6893. * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
  6894. * computed.
  6895. */
  6896. if (firstPdtIndex) {
  6897. backfillProgramDateTimes(level.fragments, firstPdtIndex);
  6898. }
  6899. return level;
  6900. }
  6901. }]);
  6902. return M3U8Parser;
  6903. }();
  6904. exports.default = M3U8Parser;
  6905. function backfillProgramDateTimes(fragments, startIndex) {
  6906. var fragPrev = fragments[startIndex];
  6907. for (var i = startIndex - 1; i >= 0; i--) {
  6908. var frag = fragments[i];
  6909. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
  6910. fragPrev = frag;
  6911. }
  6912. }
  6913. function assignProgramDateTime(frag, prevFrag) {
  6914. if (frag.rawProgramDateTime) {
  6915. frag.programDateTime = Date.parse(frag.rawProgramDateTime);
  6916. } else if (prevFrag && prevFrag.programDateTime) {
  6917. frag.programDateTime = prevFrag.endProgramDateTime;
  6918. }
  6919. if (!Number.isFinite(frag.programDateTime)) {
  6920. frag.programDateTime = null;
  6921. frag.rawProgramDateTime = null;
  6922. }
  6923. }
  6924. module.exports = exports['default'];
  6925. /***/ }),
  6926. /* 36 */
  6927. /***/ (function(module, exports, __webpack_require__) {
  6928. "use strict";
  6929. Object.defineProperty(exports, "__esModule", {
  6930. value: true
  6931. });
  6932. 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; }; }();
  6933. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6934. var Level = function () {
  6935. function Level(baseUrl) {
  6936. _classCallCheck(this, Level);
  6937. // Please keep properties in alphabetical order
  6938. this.endCC = 0;
  6939. this.endSN = 0;
  6940. this.fragments = [];
  6941. this.initSegment = null;
  6942. this.live = true;
  6943. this.needSidxRanges = false;
  6944. this.startCC = 0;
  6945. this.startSN = 0;
  6946. this.startTimeOffset = null;
  6947. this.targetduration = 0;
  6948. this.totalduration = 0;
  6949. this.type = null;
  6950. this.url = baseUrl;
  6951. this.version = null;
  6952. }
  6953. _createClass(Level, [{
  6954. key: "hasProgramDateTime",
  6955. get: function get() {
  6956. return !!(this.fragments[0] && Number.isFinite(this.fragments[0].programDateTime));
  6957. }
  6958. }]);
  6959. return Level;
  6960. }();
  6961. exports.default = Level;
  6962. module.exports = exports["default"];
  6963. /***/ }),
  6964. /* 37 */
  6965. /***/ (function(module, exports, __webpack_require__) {
  6966. "use strict";
  6967. Object.defineProperty(exports, "__esModule", {
  6968. value: true
  6969. });
  6970. 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; }; }();
  6971. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6972. var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; // eslint-disable-line no-useless-escape
  6973. var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape
  6974. // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
  6975. var AttrList = function () {
  6976. function AttrList(attrs) {
  6977. _classCallCheck(this, AttrList);
  6978. if (typeof attrs === 'string') {
  6979. attrs = AttrList.parseAttrList(attrs);
  6980. }
  6981. for (var attr in attrs) {
  6982. if (attrs.hasOwnProperty(attr)) {
  6983. this[attr] = attrs[attr];
  6984. }
  6985. }
  6986. }
  6987. _createClass(AttrList, [{
  6988. key: 'decimalInteger',
  6989. value: function decimalInteger(attrName) {
  6990. var intValue = parseInt(this[attrName], 10);
  6991. if (intValue > Number.MAX_SAFE_INTEGER) {
  6992. return Infinity;
  6993. }
  6994. return intValue;
  6995. }
  6996. }, {
  6997. key: 'hexadecimalInteger',
  6998. value: function hexadecimalInteger(attrName) {
  6999. if (this[attrName]) {
  7000. var stringValue = (this[attrName] || '0x').slice(2);
  7001. stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
  7002. var value = new Uint8Array(stringValue.length / 2);
  7003. for (var i = 0; i < stringValue.length / 2; i++) {
  7004. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  7005. }
  7006. return value;
  7007. } else {
  7008. return null;
  7009. }
  7010. }
  7011. }, {
  7012. key: 'hexadecimalIntegerAsNumber',
  7013. value: function hexadecimalIntegerAsNumber(attrName) {
  7014. var intValue = parseInt(this[attrName], 16);
  7015. if (intValue > Number.MAX_SAFE_INTEGER) {
  7016. return Infinity;
  7017. }
  7018. return intValue;
  7019. }
  7020. }, {
  7021. key: 'decimalFloatingPoint',
  7022. value: function decimalFloatingPoint(attrName) {
  7023. return parseFloat(this[attrName]);
  7024. }
  7025. }, {
  7026. key: 'enumeratedString',
  7027. value: function enumeratedString(attrName) {
  7028. return this[attrName];
  7029. }
  7030. }, {
  7031. key: 'decimalResolution',
  7032. value: function decimalResolution(attrName) {
  7033. var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  7034. if (res === null) {
  7035. return undefined;
  7036. }
  7037. return {
  7038. width: parseInt(res[1], 10),
  7039. height: parseInt(res[2], 10)
  7040. };
  7041. }
  7042. }], [{
  7043. key: 'parseAttrList',
  7044. value: function parseAttrList(input) {
  7045. var match = void 0,
  7046. attrs = {};
  7047. ATTR_LIST_REGEX.lastIndex = 0;
  7048. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  7049. var value = match[2],
  7050. quote = '"';
  7051. if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
  7052. value = value.slice(1, -1);
  7053. }
  7054. attrs[match[1]] = value;
  7055. }
  7056. return attrs;
  7057. }
  7058. }]);
  7059. return AttrList;
  7060. }();
  7061. exports.default = AttrList;
  7062. module.exports = exports['default'];
  7063. /***/ }),
  7064. /* 38 */
  7065. /***/ (function(module, exports, __webpack_require__) {
  7066. "use strict";
  7067. Object.defineProperty(exports, "__esModule", {
  7068. value: true
  7069. });
  7070. 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; }; }();
  7071. 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); } };
  7072. var _events = __webpack_require__(1);
  7073. var _events2 = _interopRequireDefault(_events);
  7074. var _eventHandler = __webpack_require__(3);
  7075. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  7076. var _errors = __webpack_require__(2);
  7077. var _logger = __webpack_require__(0);
  7078. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  7079. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7080. 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; }
  7081. 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; } /*
  7082. * Fragment Loader
  7083. */
  7084. var FragmentLoader = function (_EventHandler) {
  7085. _inherits(FragmentLoader, _EventHandler);
  7086. function FragmentLoader(hls) {
  7087. _classCallCheck(this, FragmentLoader);
  7088. var _this = _possibleConstructorReturn(this, (FragmentLoader.__proto__ || Object.getPrototypeOf(FragmentLoader)).call(this, hls, _events2.default.FRAG_LOADING));
  7089. _this.loaders = {};
  7090. return _this;
  7091. }
  7092. _createClass(FragmentLoader, [{
  7093. key: 'destroy',
  7094. value: function destroy() {
  7095. var loaders = this.loaders;
  7096. for (var loaderName in loaders) {
  7097. var loader = loaders[loaderName];
  7098. if (loader) {
  7099. loader.destroy();
  7100. }
  7101. }
  7102. this.loaders = {};
  7103. _get(FragmentLoader.prototype.__proto__ || Object.getPrototypeOf(FragmentLoader.prototype), 'destroy', this).call(this);
  7104. }
  7105. }, {
  7106. key: 'onFragLoading',
  7107. value: function onFragLoading(data) {
  7108. var frag = data.frag,
  7109. type = frag.type,
  7110. loaders = this.loaders,
  7111. config = this.hls.config,
  7112. FragmentILoader = config.fLoader,
  7113. DefaultILoader = config.loader;
  7114. // reset fragment state
  7115. frag.loaded = 0;
  7116. var loader = loaders[type];
  7117. if (loader) {
  7118. _logger.logger.warn('abort previous fragment loader for type: ' + type);
  7119. loader.abort();
  7120. }
  7121. loader = loaders[type] = frag.loader = config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);
  7122. var loaderContext = void 0,
  7123. loaderConfig = void 0,
  7124. loaderCallbacks = void 0;
  7125. loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false };
  7126. var start = frag.byteRangeStartOffset,
  7127. end = frag.byteRangeEndOffset;
  7128. if (Number.isFinite(start) && Number.isFinite(end)) {
  7129. loaderContext.rangeStart = start;
  7130. loaderContext.rangeEnd = end;
  7131. }
  7132. loaderConfig = {
  7133. timeout: config.fragLoadingTimeOut,
  7134. maxRetry: 0,
  7135. retryDelay: 0,
  7136. maxRetryDelay: config.fragLoadingMaxRetryTimeout
  7137. };
  7138. loaderCallbacks = {
  7139. onSuccess: this.loadsuccess.bind(this),
  7140. onError: this.loaderror.bind(this),
  7141. onTimeout: this.loadtimeout.bind(this),
  7142. onProgress: this.loadprogress.bind(this)
  7143. };
  7144. loader.load(loaderContext, loaderConfig, loaderCallbacks);
  7145. }
  7146. }, {
  7147. key: 'loadsuccess',
  7148. value: function loadsuccess(response, stats, context) {
  7149. var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  7150. var payload = response.data,
  7151. frag = context.frag;
  7152. // detach fragment loader on load success
  7153. frag.loader = undefined;
  7154. this.loaders[frag.type] = undefined;
  7155. this.hls.trigger(_events2.default.FRAG_LOADED, { payload: payload, frag: frag, stats: stats, networkDetails: networkDetails });
  7156. }
  7157. }, {
  7158. key: 'loaderror',
  7159. value: function loaderror(response, context) {
  7160. var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  7161. var frag = context.frag;
  7162. var loader = frag.loader;
  7163. if (loader) {
  7164. loader.abort();
  7165. }
  7166. this.loaders[frag.type] = undefined;
  7167. 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 });
  7168. }
  7169. }, {
  7170. key: 'loadtimeout',
  7171. value: function loadtimeout(stats, context) {
  7172. var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  7173. var frag = context.frag;
  7174. var loader = frag.loader;
  7175. if (loader) {
  7176. loader.abort();
  7177. }
  7178. this.loaders[frag.type] = undefined;
  7179. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag, networkDetails: networkDetails });
  7180. }
  7181. // data will be used for progressive parsing
  7182. }, {
  7183. key: 'loadprogress',
  7184. value: function loadprogress(stats, context, data) {
  7185. var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  7186. // jshint ignore:line
  7187. var frag = context.frag;
  7188. frag.loaded = stats.loaded;
  7189. this.hls.trigger(_events2.default.FRAG_LOAD_PROGRESS, { frag: frag, stats: stats, networkDetails: networkDetails });
  7190. }
  7191. }]);
  7192. return FragmentLoader;
  7193. }(_eventHandler2.default);
  7194. exports.default = FragmentLoader;
  7195. module.exports = exports['default'];
  7196. /***/ }),
  7197. /* 39 */
  7198. /***/ (function(module, exports, __webpack_require__) {
  7199. "use strict";
  7200. Object.defineProperty(exports, "__esModule", {
  7201. value: true
  7202. });
  7203. 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; }; }();
  7204. var _events = __webpack_require__(1);
  7205. var _events2 = _interopRequireDefault(_events);
  7206. var _eventHandler = __webpack_require__(3);
  7207. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  7208. var _errors = __webpack_require__(2);
  7209. var _logger = __webpack_require__(0);
  7210. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  7211. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7212. 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; }
  7213. 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; } /*
  7214. * Decrypt key Loader
  7215. */
  7216. var KeyLoader = function (_EventHandler) {
  7217. _inherits(KeyLoader, _EventHandler);
  7218. function KeyLoader(hls) {
  7219. _classCallCheck(this, KeyLoader);
  7220. var _this = _possibleConstructorReturn(this, (KeyLoader.__proto__ || Object.getPrototypeOf(KeyLoader)).call(this, hls, _events2.default.KEY_LOADING));
  7221. _this.loaders = {};
  7222. _this.decryptkey = null;
  7223. _this.decrypturl = null;
  7224. return _this;
  7225. }
  7226. _createClass(KeyLoader, [{
  7227. key: 'destroy',
  7228. value: function destroy() {
  7229. for (var loaderName in this.loaders) {
  7230. var loader = this.loaders[loaderName];
  7231. if (loader) {
  7232. loader.destroy();
  7233. }
  7234. }
  7235. this.loaders = {};
  7236. _eventHandler2.default.prototype.destroy.call(this);
  7237. }
  7238. }, {
  7239. key: 'onKeyLoading',
  7240. value: function onKeyLoading(data) {
  7241. var frag = data.frag,
  7242. type = frag.type,
  7243. loader = this.loaders[type],
  7244. decryptdata = frag.decryptdata,
  7245. uri = decryptdata.uri;
  7246. // if uri is different from previous one or if decrypt key not retrieved yet
  7247. if (uri !== this.decrypturl || this.decryptkey === null) {
  7248. var config = this.hls.config;
  7249. if (loader) {
  7250. _logger.logger.warn('abort previous key loader for type:' + type);
  7251. loader.abort();
  7252. }
  7253. frag.loader = this.loaders[type] = new config.loader(config);
  7254. this.decrypturl = uri;
  7255. this.decryptkey = null;
  7256. var loaderContext = void 0,
  7257. loaderConfig = void 0,
  7258. loaderCallbacks = void 0;
  7259. loaderContext = { url: uri, frag: frag, responseType: 'arraybuffer' };
  7260. // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
  7261. // key-loader will trigger an error and rely on stream-controller to handle retry logic.
  7262. // this will also align retry logic with fragment-loader
  7263. loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: 0, retryDelay: config.fragLoadingRetryDelay, maxRetryDelay: config.fragLoadingMaxRetryTimeout };
  7264. loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) };
  7265. frag.loader.load(loaderContext, loaderConfig, loaderCallbacks);
  7266. } else if (this.decryptkey) {
  7267. // we already loaded this key, return it
  7268. decryptdata.key = this.decryptkey;
  7269. this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag });
  7270. }
  7271. }
  7272. }, {
  7273. key: 'loadsuccess',
  7274. value: function loadsuccess(response, stats, context) {
  7275. var frag = context.frag;
  7276. this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data);
  7277. // detach fragment loader on load success
  7278. frag.loader = undefined;
  7279. this.loaders[frag.type] = undefined;
  7280. this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag });
  7281. }
  7282. }, {
  7283. key: 'loaderror',
  7284. value: function loaderror(response, context) {
  7285. var frag = context.frag,
  7286. loader = frag.loader;
  7287. if (loader) {
  7288. loader.abort();
  7289. }
  7290. this.loaders[context.type] = undefined;
  7291. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: frag, response: response });
  7292. }
  7293. }, {
  7294. key: 'loadtimeout',
  7295. value: function loadtimeout(stats, context) {
  7296. var frag = context.frag,
  7297. loader = frag.loader;
  7298. if (loader) {
  7299. loader.abort();
  7300. }
  7301. this.loaders[context.type] = undefined;
  7302. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_TIMEOUT, fatal: false, frag: frag });
  7303. }
  7304. }]);
  7305. return KeyLoader;
  7306. }(_eventHandler2.default);
  7307. exports.default = KeyLoader;
  7308. module.exports = exports['default'];
  7309. /***/ }),
  7310. /* 40 */
  7311. /***/ (function(module, exports, __webpack_require__) {
  7312. "use strict";
  7313. Object.defineProperty(exports, "__esModule", {
  7314. value: true
  7315. });
  7316. 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; }; }();
  7317. 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); } };
  7318. var _binarySearch = __webpack_require__(9);
  7319. var _binarySearch2 = _interopRequireDefault(_binarySearch);
  7320. var _bufferHelper = __webpack_require__(4);
  7321. var _demuxer = __webpack_require__(19);
  7322. var _demuxer2 = _interopRequireDefault(_demuxer);
  7323. var _events = __webpack_require__(1);
  7324. var _events2 = _interopRequireDefault(_events);
  7325. var _fragmentTracker = __webpack_require__(6);
  7326. var _fragment = __webpack_require__(11);
  7327. var _fragment2 = _interopRequireDefault(_fragment);
  7328. var _playlistLoader = __webpack_require__(15);
  7329. var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
  7330. var _levelHelper = __webpack_require__(7);
  7331. var LevelHelper = _interopRequireWildcard(_levelHelper);
  7332. var _timeRanges = __webpack_require__(25);
  7333. var _timeRanges2 = _interopRequireDefault(_timeRanges);
  7334. var _errors = __webpack_require__(2);
  7335. var _logger = __webpack_require__(0);
  7336. var _discontinuities = __webpack_require__(26);
  7337. var _fragmentFinders = __webpack_require__(27);
  7338. var _gapController = __webpack_require__(56);
  7339. var _gapController2 = _interopRequireDefault(_gapController);
  7340. var _baseStreamController = __webpack_require__(14);
  7341. var _baseStreamController2 = _interopRequireDefault(_baseStreamController);
  7342. 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; } }
  7343. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  7344. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7345. 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; }
  7346. 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; } /*
  7347. * Stream Controller
  7348. */
  7349. var TICK_INTERVAL = 100; // how often to tick in ms
  7350. var StreamController = function (_BaseStreamController) {
  7351. _inherits(StreamController, _BaseStreamController);
  7352. function StreamController(hls, fragmentTracker) {
  7353. _classCallCheck(this, StreamController);
  7354. 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));
  7355. _this.fragmentTracker = fragmentTracker;
  7356. _this.config = hls.config;
  7357. _this.audioCodecSwap = false;
  7358. _this._state = _baseStreamController.State.STOPPED;
  7359. _this.stallReported = false;
  7360. _this.gapController = null;
  7361. return _this;
  7362. }
  7363. _createClass(StreamController, [{
  7364. key: 'startLoad',
  7365. value: function startLoad(startPosition) {
  7366. if (this.levels) {
  7367. var lastCurrentTime = this.lastCurrentTime,
  7368. hls = this.hls;
  7369. this.stopLoad();
  7370. this.setInterval(TICK_INTERVAL);
  7371. this.level = -1;
  7372. this.fragLoadError = 0;
  7373. if (!this.startFragRequested) {
  7374. // determine load level
  7375. var startLevel = hls.startLevel;
  7376. if (startLevel === -1) {
  7377. // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  7378. startLevel = 0;
  7379. this.bitrateTest = true;
  7380. }
  7381. // set new level to playlist loader : this will trigger start level load
  7382. // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  7383. this.level = hls.nextLoadLevel = startLevel;
  7384. this.loadedmetadata = false;
  7385. }
  7386. // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
  7387. if (lastCurrentTime > 0 && startPosition === -1) {
  7388. _logger.logger.log('override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3));
  7389. startPosition = lastCurrentTime;
  7390. }
  7391. this.state = _baseStreamController.State.IDLE;
  7392. this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
  7393. this.tick();
  7394. } else {
  7395. this.forceStartLoad = true;
  7396. this.state = _baseStreamController.State.STOPPED;
  7397. }
  7398. }
  7399. }, {
  7400. key: 'stopLoad',
  7401. value: function stopLoad() {
  7402. this.forceStartLoad = false;
  7403. _get(StreamController.prototype.__proto__ || Object.getPrototypeOf(StreamController.prototype), 'stopLoad', this).call(this);
  7404. }
  7405. }, {
  7406. key: 'doTick',
  7407. value: function doTick() {
  7408. switch (this.state) {
  7409. case _baseStreamController.State.BUFFER_FLUSHING:
  7410. // in buffer flushing state, reset fragLoadError counter
  7411. this.fragLoadError = 0;
  7412. break;
  7413. case _baseStreamController.State.IDLE:
  7414. this._doTickIdle();
  7415. break;
  7416. case _baseStreamController.State.WAITING_LEVEL:
  7417. var level = this.levels[this.level];
  7418. // check if playlist is already loaded
  7419. if (level && level.details) {
  7420. this.state = _baseStreamController.State.IDLE;
  7421. }
  7422. break;
  7423. case _baseStreamController.State.FRAG_LOADING_WAITING_RETRY:
  7424. var now = window.performance.now();
  7425. var retryDate = this.retryDate;
  7426. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  7427. if (!retryDate || now >= retryDate || this.media && this.media.seeking) {
  7428. _logger.logger.log('mediaController: retryDate reached, switch back to IDLE state');
  7429. this.state = _baseStreamController.State.IDLE;
  7430. }
  7431. break;
  7432. case _baseStreamController.State.ERROR:
  7433. case _baseStreamController.State.STOPPED:
  7434. case _baseStreamController.State.FRAG_LOADING:
  7435. case _baseStreamController.State.PARSING:
  7436. case _baseStreamController.State.PARSED:
  7437. case _baseStreamController.State.ENDED:
  7438. break;
  7439. default:
  7440. break;
  7441. }
  7442. // check buffer
  7443. this._checkBuffer();
  7444. // check/update current fragment
  7445. this._checkFragmentChanged();
  7446. }
  7447. // Ironically the "idle" state is the on we do the most logic in it seems ....
  7448. // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently
  7449. // played segment, or on pause/play/seek instead of naively checking every 100ms?
  7450. }, {
  7451. key: '_doTickIdle',
  7452. value: function _doTickIdle() {
  7453. var hls = this.hls,
  7454. config = hls.config,
  7455. media = this.media;
  7456. // if start level not parsed yet OR
  7457. // if video not attached AND start fragment already requested OR start frag prefetch disable
  7458. // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
  7459. if (this.levelLastLoaded === undefined || !media && (this.startFragRequested || !config.startFragPrefetch)) {
  7460. return;
  7461. }
  7462. // if we have not yet loaded any fragment, start loading from start position
  7463. var pos = void 0;
  7464. if (this.loadedmetadata) {
  7465. pos = media.currentTime;
  7466. } else {
  7467. pos = this.nextLoadPosition;
  7468. }
  7469. // determine next load level
  7470. var level = hls.nextLoadLevel,
  7471. levelInfo = this.levels[level];
  7472. if (!levelInfo) {
  7473. return;
  7474. }
  7475. var levelBitrate = levelInfo.bitrate,
  7476. maxBufLen = void 0;
  7477. // 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
  7478. if (levelBitrate) {
  7479. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  7480. } else {
  7481. maxBufLen = config.maxBufferLength;
  7482. }
  7483. maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);
  7484. // determine next candidate fragment to be loaded, based on current position and end of buffer position
  7485. // ensure up to `config.maxMaxBufferLength` of buffer upfront
  7486. var bufferInfo = _bufferHelper.BufferHelper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, config.maxBufferHole),
  7487. bufferLen = bufferInfo.len;
  7488. // Stay idle if we are still with buffer margins
  7489. if (bufferLen >= maxBufLen) {
  7490. return;
  7491. }
  7492. // if buffer length is less than maxBufLen try to load a new fragment ...
  7493. _logger.logger.trace('buffer length of ' + bufferLen.toFixed(3) + ' is below max of ' + maxBufLen.toFixed(3) + '. checking for more payload ...');
  7494. // set next load level : this will trigger a playlist load if needed
  7495. this.level = hls.nextLoadLevel = level;
  7496. var levelDetails = levelInfo.details;
  7497. // if level info not retrieved yet, switch state and wait for level retrieval
  7498. // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  7499. // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  7500. if (!levelDetails || levelDetails.live && this.levelLastLoaded !== level) {
  7501. this.state = _baseStreamController.State.WAITING_LEVEL;
  7502. return;
  7503. }
  7504. if (this._streamEnded(bufferInfo, levelDetails)) {
  7505. var data = {};
  7506. if (this.altAudio) {
  7507. data.type = 'video';
  7508. }
  7509. this.hls.trigger(_events2.default.BUFFER_EOS, data);
  7510. this.state = _baseStreamController.State.ENDED;
  7511. return;
  7512. }
  7513. // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)
  7514. this._fetchPayloadOrEos(pos, bufferInfo, levelDetails);
  7515. }
  7516. }, {
  7517. key: '_fetchPayloadOrEos',
  7518. value: function _fetchPayloadOrEos(pos, bufferInfo, levelDetails) {
  7519. var fragPrevious = this.fragPrevious,
  7520. level = this.level,
  7521. fragments = levelDetails.fragments,
  7522. fragLen = fragments.length;
  7523. // empty playlist
  7524. if (fragLen === 0) {
  7525. return;
  7526. }
  7527. // find fragment index, contiguous with end of buffer position
  7528. var start = fragments[0].start,
  7529. end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
  7530. bufferEnd = bufferInfo.end,
  7531. frag = void 0;
  7532. if (levelDetails.initSegment && !levelDetails.initSegment.data) {
  7533. frag = levelDetails.initSegment;
  7534. } else {
  7535. // in case of live playlist we need to ensure that requested position is not located before playlist start
  7536. if (levelDetails.live) {
  7537. var initialLiveManifestSize = this.config.initialLiveManifestSize;
  7538. if (fragLen < initialLiveManifestSize) {
  7539. _logger.logger.warn('Can not start playback of a level, reason: not enough fragments ' + fragLen + ' < ' + initialLiveManifestSize);
  7540. return;
  7541. }
  7542. frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen);
  7543. // if it explicitely returns null don't load any fragment and exit function now
  7544. if (frag === null) {
  7545. return;
  7546. }
  7547. } else {
  7548. // VoD playlist: if bufferEnd before start of playlist, load first fragment
  7549. if (bufferEnd < start) {
  7550. frag = fragments[0];
  7551. }
  7552. }
  7553. }
  7554. if (!frag) {
  7555. frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);
  7556. }
  7557. if (frag) {
  7558. if (frag.encrypted) {
  7559. _logger.logger.log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level);
  7560. this._loadKey(frag);
  7561. } else {
  7562. _logger.logger.log('Loading ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level + ', currentTime:' + pos.toFixed(3) + ',bufferEnd:' + bufferEnd.toFixed(3));
  7563. this._loadFragment(frag);
  7564. }
  7565. }
  7566. }
  7567. }, {
  7568. key: '_ensureFragmentAtLivePoint',
  7569. value: function _ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen) {
  7570. var config = this.hls.config,
  7571. media = this.media;
  7572. var frag = void 0;
  7573. // check if requested position is within seekable boundaries :
  7574. // logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);
  7575. var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  7576. if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {
  7577. var liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);
  7578. _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));
  7579. bufferEnd = liveSyncPosition;
  7580. if (media && media.readyState && media.duration > liveSyncPosition) {
  7581. media.currentTime = liveSyncPosition;
  7582. }
  7583. this.nextLoadPosition = liveSyncPosition;
  7584. }
  7585. // if end of buffer greater than live edge, don't load any fragment
  7586. // this could happen if live playlist intermittently slides in the past.
  7587. // level 1 loaded [182580161,182580167]
  7588. // level 1 loaded [182580162,182580169]
  7589. // Loading 182580168 of [182580162 ,182580169],level 1 ..
  7590. // Loading 182580169 of [182580162 ,182580169],level 1 ..
  7591. // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168
  7592. // level 1 loaded [182580164,182580171]
  7593. //
  7594. // don't return null in case media not loaded yet (readystate === 0)
  7595. if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {
  7596. return null;
  7597. }
  7598. if (this.startFragRequested && !levelDetails.PTSKnown) {
  7599. /* we are switching level on live playlist, but we don't have any PTS info for that quality level ...
  7600. try to load frag matching with next SN.
  7601. even if SN are not synchronized between playlists, loading this frag will help us
  7602. compute playlist sliding and find the right one after in case it was not the right consecutive one */
  7603. if (fragPrevious) {
  7604. if (levelDetails.hasProgramDateTime) {
  7605. // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)
  7606. _logger.logger.log('live playlist, switching playlist, load frag with same PDT: ' + fragPrevious.programDateTime);
  7607. frag = (0, _fragmentFinders.findFragmentByPDT)(fragments, fragPrevious.endProgramDateTime, config.maxFragLookUpTolerance);
  7608. } else {
  7609. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  7610. var targetSN = fragPrevious.sn + 1;
  7611. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  7612. var fragNext = fragments[targetSN - levelDetails.startSN];
  7613. if (fragPrevious.cc === fragNext.cc) {
  7614. frag = fragNext;
  7615. _logger.logger.log('live playlist, switching playlist, load frag with next SN: ' + frag.sn);
  7616. }
  7617. }
  7618. // next frag SN not available (or not with same continuity counter)
  7619. // look for a frag sharing the same CC
  7620. if (!frag) {
  7621. frag = _binarySearch2.default.search(fragments, function (frag) {
  7622. return fragPrevious.cc - frag.cc;
  7623. });
  7624. if (frag) {
  7625. _logger.logger.log('live playlist, switching playlist, load frag with same CC: ' + frag.sn);
  7626. }
  7627. }
  7628. }
  7629. }
  7630. if (!frag) {
  7631. /* we have no idea about which fragment should be loaded.
  7632. so let's load mid fragment. it will help computing playlist sliding and find the right one
  7633. */
  7634. frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))];
  7635. _logger.logger.log('live playlist, switching playlist, unknown, load middle frag : ' + frag.sn);
  7636. }
  7637. }
  7638. return frag;
  7639. }
  7640. }, {
  7641. key: '_findFragment',
  7642. value: function _findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails) {
  7643. var config = this.hls.config;
  7644. var frag = void 0;
  7645. if (bufferEnd < end) {
  7646. var lookupTolerance = bufferEnd > end - config.maxFragLookUpTolerance ? 0 : config.maxFragLookUpTolerance;
  7647. // Remove the tolerance if it would put the bufferEnd past the actual end of stream
  7648. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  7649. frag = (0, _fragmentFinders.findFragmentByPTS)(fragPrevious, fragments, bufferEnd, lookupTolerance);
  7650. } else {
  7651. // reach end of playlist
  7652. frag = fragments[fragLen - 1];
  7653. }
  7654. if (frag) {
  7655. var curSNIdx = frag.sn - levelDetails.startSN;
  7656. var sameLevel = fragPrevious && frag.level === fragPrevious.level;
  7657. var prevFrag = fragments[curSNIdx - 1];
  7658. var nextFrag = fragments[curSNIdx + 1];
  7659. // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
  7660. if (fragPrevious && frag.sn === fragPrevious.sn) {
  7661. if (sameLevel && !frag.backtracked) {
  7662. if (frag.sn < levelDetails.endSN) {
  7663. var deltaPTS = fragPrevious.deltaPTS;
  7664. // if there is a significant delta between audio and video, larger than max allowed hole,
  7665. // and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)
  7666. // let's try to load previous fragment again to get last keyframe
  7667. // then we will reload again current fragment (that way we should be able to fill the buffer hole ...)
  7668. if (deltaPTS && deltaPTS > config.maxBufferHole && fragPrevious.dropped && curSNIdx) {
  7669. frag = prevFrag;
  7670. _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');
  7671. } else {
  7672. frag = nextFrag;
  7673. _logger.logger.log('SN just loaded, load next one: ' + frag.sn, frag);
  7674. }
  7675. } else {
  7676. frag = null;
  7677. }
  7678. } else if (frag.backtracked) {
  7679. // Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes
  7680. if (nextFrag && nextFrag.backtracked) {
  7681. _logger.logger.warn('Already backtracked from fragment ' + nextFrag.sn + ', will not backtrack to fragment ' + frag.sn + '. Loading fragment ' + nextFrag.sn);
  7682. frag = nextFrag;
  7683. } else {
  7684. // If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe
  7685. // 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
  7686. _logger.logger.warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');
  7687. frag.dropped = 0;
  7688. if (prevFrag) {
  7689. frag = prevFrag;
  7690. frag.backtracked = true;
  7691. } else if (curSNIdx) {
  7692. // can't backtrack on very first fragment
  7693. frag = null;
  7694. }
  7695. }
  7696. }
  7697. }
  7698. }
  7699. return frag;
  7700. }
  7701. }, {
  7702. key: '_loadKey',
  7703. value: function _loadKey(frag) {
  7704. this.state = _baseStreamController.State.KEY_LOADING;
  7705. this.hls.trigger(_events2.default.KEY_LOADING, { frag: frag });
  7706. }
  7707. }, {
  7708. key: '_loadFragment',
  7709. value: function _loadFragment(frag) {
  7710. // Check if fragment is not loaded
  7711. var fragState = this.fragmentTracker.getState(frag);
  7712. this.fragCurrent = frag;
  7713. this.startFragRequested = true;
  7714. // Don't update nextLoadPosition for fragments which are not buffered
  7715. if (Number.isFinite(frag.sn) && !frag.bitrateTest) {
  7716. this.nextLoadPosition = frag.start + frag.duration;
  7717. }
  7718. // Allow backtracked fragments to load
  7719. if (frag.backtracked || fragState === _fragmentTracker.FragmentState.NOT_LOADED || fragState === _fragmentTracker.FragmentState.PARTIAL) {
  7720. frag.autoLevel = this.hls.autoLevelEnabled;
  7721. frag.bitrateTest = this.bitrateTest;
  7722. this.hls.trigger(_events2.default.FRAG_LOADING, { frag: frag });
  7723. // lazy demuxer init, as this could take some time ... do it during frag loading
  7724. if (!this.demuxer) {
  7725. this.demuxer = new _demuxer2.default(this.hls, 'main');
  7726. }
  7727. this.state = _baseStreamController.State.FRAG_LOADING;
  7728. } else if (fragState === _fragmentTracker.FragmentState.APPENDING) {
  7729. // Lower the buffer size and try again
  7730. if (this._reduceMaxBufferLength(frag.duration)) {
  7731. this.fragmentTracker.removeFragment(frag);
  7732. }
  7733. }
  7734. }
  7735. }, {
  7736. key: 'getBufferedFrag',
  7737. value: function getBufferedFrag(position) {
  7738. return this.fragmentTracker.getBufferedFrag(position, _playlistLoader2.default.LevelType.MAIN);
  7739. }
  7740. }, {
  7741. key: 'followingBufferedFrag',
  7742. value: function followingBufferedFrag(frag) {
  7743. if (frag) {
  7744. // try to get range of next fragment (500ms after this range)
  7745. return this.getBufferedFrag(frag.endPTS + 0.5);
  7746. }
  7747. return null;
  7748. }
  7749. }, {
  7750. key: '_checkFragmentChanged',
  7751. value: function _checkFragmentChanged() {
  7752. var fragPlayingCurrent = void 0,
  7753. currentTime = void 0,
  7754. video = this.media;
  7755. if (video && video.readyState && video.seeking === false) {
  7756. currentTime = video.currentTime;
  7757. /* if video element is in seeked state, currentTime can only increase.
  7758. (assuming that playback rate is positive ...)
  7759. As sometimes currentTime jumps back to zero after a
  7760. media decode error, check this, to avoid seeking back to
  7761. wrong position after a media decode error
  7762. */
  7763. if (currentTime > this.lastCurrentTime) {
  7764. this.lastCurrentTime = currentTime;
  7765. }
  7766. if (_bufferHelper.BufferHelper.isBuffered(video, currentTime)) {
  7767. fragPlayingCurrent = this.getBufferedFrag(currentTime);
  7768. } else if (_bufferHelper.BufferHelper.isBuffered(video, currentTime + 0.1)) {
  7769. /* ensure that FRAG_CHANGED event is triggered at startup,
  7770. when first video frame is displayed and playback is paused.
  7771. add a tolerance of 100ms, in case current position is not buffered,
  7772. check if current pos+100ms is buffered and use that buffer range
  7773. for FRAG_CHANGED event reporting */
  7774. fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1);
  7775. }
  7776. if (fragPlayingCurrent) {
  7777. var fragPlaying = fragPlayingCurrent;
  7778. if (fragPlaying !== this.fragPlaying) {
  7779. this.hls.trigger(_events2.default.FRAG_CHANGED, { frag: fragPlaying });
  7780. var fragPlayingLevel = fragPlaying.level;
  7781. if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {
  7782. this.hls.trigger(_events2.default.LEVEL_SWITCHED, { level: fragPlayingLevel });
  7783. }
  7784. this.fragPlaying = fragPlaying;
  7785. }
  7786. }
  7787. }
  7788. }
  7789. /*
  7790. on immediate level switch :
  7791. - pause playback if playing
  7792. - cancel any pending load request
  7793. - and trigger a buffer flush
  7794. */
  7795. }, {
  7796. key: 'immediateLevelSwitch',
  7797. value: function immediateLevelSwitch() {
  7798. _logger.logger.log('immediateLevelSwitch');
  7799. if (!this.immediateSwitch) {
  7800. this.immediateSwitch = true;
  7801. var media = this.media,
  7802. previouslyPaused = void 0;
  7803. if (media) {
  7804. previouslyPaused = media.paused;
  7805. media.pause();
  7806. } else {
  7807. // don't restart playback after instant level switch in case media not attached
  7808. previouslyPaused = true;
  7809. }
  7810. this.previouslyPaused = previouslyPaused;
  7811. }
  7812. var fragCurrent = this.fragCurrent;
  7813. if (fragCurrent && fragCurrent.loader) {
  7814. fragCurrent.loader.abort();
  7815. }
  7816. this.fragCurrent = null;
  7817. // flush everything
  7818. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  7819. }
  7820. /**
  7821. * on immediate level switch end, after new fragment has been buffered:
  7822. * - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)
  7823. * - resume the playback if needed
  7824. */
  7825. }, {
  7826. key: 'immediateLevelSwitchEnd',
  7827. value: function immediateLevelSwitchEnd() {
  7828. var media = this.media;
  7829. if (media && media.buffered.length) {
  7830. this.immediateSwitch = false;
  7831. if (_bufferHelper.BufferHelper.isBuffered(media, media.currentTime)) {
  7832. // only nudge if currentTime is buffered
  7833. media.currentTime -= 0.0001;
  7834. }
  7835. if (!this.previouslyPaused) {
  7836. media.play();
  7837. }
  7838. }
  7839. }
  7840. /**
  7841. * try to switch ASAP without breaking video playback:
  7842. * in order to ensure smooth but quick level switching,
  7843. * we need to find the next flushable buffer range
  7844. * we should take into account new segment fetch time
  7845. */
  7846. }, {
  7847. key: 'nextLevelSwitch',
  7848. value: function nextLevelSwitch() {
  7849. var media = this.media;
  7850. // ensure that media is defined and that metadata are available (to retrieve currentTime)
  7851. if (media && media.readyState) {
  7852. var fetchdelay = void 0,
  7853. fragPlayingCurrent = void 0,
  7854. nextBufferedFrag = void 0;
  7855. fragPlayingCurrent = this.getBufferedFrag(media.currentTime);
  7856. if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) {
  7857. // flush buffer preceding current fragment (flush until current fragment start offset)
  7858. // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  7859. this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1);
  7860. }
  7861. if (!media.paused) {
  7862. // add a safety delay of 1s
  7863. var nextLevelId = this.hls.nextLoadLevel,
  7864. nextLevel = this.levels[nextLevelId],
  7865. fragLastKbps = this.fragLastKbps;
  7866. if (fragLastKbps && this.fragCurrent) {
  7867. fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;
  7868. } else {
  7869. fetchdelay = 0;
  7870. }
  7871. } else {
  7872. fetchdelay = 0;
  7873. }
  7874. // logger.log('fetchdelay:'+fetchdelay);
  7875. // find buffer range that will be reached once new fragment will be fetched
  7876. nextBufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  7877. if (nextBufferedFrag) {
  7878. // we can flush buffer range following this one without stalling playback
  7879. nextBufferedFrag = this.followingBufferedFrag(nextBufferedFrag);
  7880. if (nextBufferedFrag) {
  7881. // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  7882. var fragCurrent = this.fragCurrent;
  7883. if (fragCurrent && fragCurrent.loader) {
  7884. fragCurrent.loader.abort();
  7885. }
  7886. this.fragCurrent = null;
  7887. // start flush position is the start PTS of next buffered frag.
  7888. // we use frag.naxStartPTS which is max(audio startPTS, video startPTS).
  7889. // in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment
  7890. this.flushMainBuffer(nextBufferedFrag.maxStartPTS, Number.POSITIVE_INFINITY);
  7891. }
  7892. }
  7893. }
  7894. }
  7895. }, {
  7896. key: 'flushMainBuffer',
  7897. value: function flushMainBuffer(startOffset, endOffset) {
  7898. this.state = _baseStreamController.State.BUFFER_FLUSHING;
  7899. var flushScope = { startOffset: startOffset, endOffset: endOffset };
  7900. // if alternate audio tracks are used, only flush video, otherwise flush everything
  7901. if (this.altAudio) {
  7902. flushScope.type = 'video';
  7903. }
  7904. this.hls.trigger(_events2.default.BUFFER_FLUSHING, flushScope);
  7905. }
  7906. }, {
  7907. key: 'onMediaAttached',
  7908. value: function onMediaAttached(data) {
  7909. var media = this.media = this.mediaBuffer = data.media;
  7910. this.onvseeking = this.onMediaSeeking.bind(this);
  7911. this.onvseeked = this.onMediaSeeked.bind(this);
  7912. this.onvended = this.onMediaEnded.bind(this);
  7913. media.addEventListener('seeking', this.onvseeking);
  7914. media.addEventListener('seeked', this.onvseeked);
  7915. media.addEventListener('ended', this.onvended);
  7916. var config = this.config;
  7917. if (this.levels && config.autoStartLoad) {
  7918. this.hls.startLoad(config.startPosition);
  7919. }
  7920. this.gapController = new _gapController2.default(config, media, this.fragmentTracker, this.hls);
  7921. }
  7922. }, {
  7923. key: 'onMediaDetaching',
  7924. value: function onMediaDetaching() {
  7925. var media = this.media;
  7926. if (media && media.ended) {
  7927. _logger.logger.log('MSE detaching and video ended, reset startPosition');
  7928. this.startPosition = this.lastCurrentTime = 0;
  7929. }
  7930. // reset fragment backtracked flag
  7931. var levels = this.levels;
  7932. if (levels) {
  7933. levels.forEach(function (level) {
  7934. if (level.details) {
  7935. level.details.fragments.forEach(function (fragment) {
  7936. fragment.backtracked = undefined;
  7937. });
  7938. }
  7939. });
  7940. }
  7941. // remove video listeners
  7942. if (media) {
  7943. media.removeEventListener('seeking', this.onvseeking);
  7944. media.removeEventListener('seeked', this.onvseeked);
  7945. media.removeEventListener('ended', this.onvended);
  7946. this.onvseeking = this.onvseeked = this.onvended = null;
  7947. }
  7948. this.media = this.mediaBuffer = null;
  7949. this.loadedmetadata = false;
  7950. this.stopLoad();
  7951. }
  7952. }, {
  7953. key: 'onMediaSeeked',
  7954. value: function onMediaSeeked() {
  7955. var media = this.media,
  7956. currentTime = media ? media.currentTime : undefined;
  7957. if (Number.isFinite(currentTime)) {
  7958. _logger.logger.log('media seeked to ' + currentTime.toFixed(3));
  7959. }
  7960. // tick to speed up FRAGMENT_PLAYING triggering
  7961. this.tick();
  7962. }
  7963. }, {
  7964. key: 'onManifestLoading',
  7965. value: function onManifestLoading() {
  7966. // reset buffer on manifest loading
  7967. _logger.logger.log('trigger BUFFER_RESET');
  7968. this.hls.trigger(_events2.default.BUFFER_RESET);
  7969. this.fragmentTracker.removeAllFragments();
  7970. this.stalled = false;
  7971. this.startPosition = this.lastCurrentTime = 0;
  7972. }
  7973. }, {
  7974. key: 'onManifestParsed',
  7975. value: function onManifestParsed(data) {
  7976. var aac = false,
  7977. heaac = false,
  7978. codec = void 0;
  7979. data.levels.forEach(function (level) {
  7980. // detect if we have different kind of audio codecs used amongst playlists
  7981. codec = level.audioCodec;
  7982. if (codec) {
  7983. if (codec.indexOf('mp4a.40.2') !== -1) {
  7984. aac = true;
  7985. }
  7986. if (codec.indexOf('mp4a.40.5') !== -1) {
  7987. heaac = true;
  7988. }
  7989. }
  7990. });
  7991. this.audioCodecSwitch = aac && heaac;
  7992. if (this.audioCodecSwitch) {
  7993. _logger.logger.log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  7994. }
  7995. this.levels = data.levels;
  7996. this.startFragRequested = false;
  7997. var config = this.config;
  7998. if (config.autoStartLoad || this.forceStartLoad) {
  7999. this.hls.startLoad(config.startPosition);
  8000. }
  8001. }
  8002. }, {
  8003. key: 'onLevelLoaded',
  8004. value: function onLevelLoaded(data) {
  8005. var newDetails = data.details;
  8006. var newLevelId = data.level;
  8007. var lastLevel = this.levels[this.levelLastLoaded];
  8008. var curLevel = this.levels[newLevelId];
  8009. var duration = newDetails.totalduration;
  8010. var sliding = 0;
  8011. _logger.logger.log('level ' + newLevelId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration);
  8012. if (newDetails.live) {
  8013. var curDetails = curLevel.details;
  8014. if (curDetails && newDetails.fragments.length > 0) {
  8015. // we already have details for that level, merge them
  8016. LevelHelper.mergeDetails(curDetails, newDetails);
  8017. sliding = newDetails.fragments[0].start;
  8018. this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
  8019. if (newDetails.PTSKnown && Number.isFinite(sliding)) {
  8020. _logger.logger.log('live playlist sliding:' + sliding.toFixed(3));
  8021. } else {
  8022. _logger.logger.log('live playlist - outdated PTS, unknown sliding');
  8023. (0, _discontinuities.alignStream)(this.fragPrevious, lastLevel, newDetails);
  8024. }
  8025. } else {
  8026. _logger.logger.log('live playlist - first load, unknown sliding');
  8027. newDetails.PTSKnown = false;
  8028. (0, _discontinuities.alignStream)(this.fragPrevious, lastLevel, newDetails);
  8029. }
  8030. } else {
  8031. newDetails.PTSKnown = false;
  8032. }
  8033. // override level info
  8034. curLevel.details = newDetails;
  8035. this.levelLastLoaded = newLevelId;
  8036. this.hls.trigger(_events2.default.LEVEL_UPDATED, { details: newDetails, level: newLevelId });
  8037. if (this.startFragRequested === false) {
  8038. // compute start position if set to -1. use it straight away if value is defined
  8039. if (this.startPosition === -1 || this.lastCurrentTime === -1) {
  8040. // first, check if start time offset has been set in playlist, if yes, use this value
  8041. var startTimeOffset = newDetails.startTimeOffset;
  8042. if (Number.isFinite(startTimeOffset)) {
  8043. if (startTimeOffset < 0) {
  8044. _logger.logger.log('negative start time offset ' + startTimeOffset + ', count from end of last fragment');
  8045. startTimeOffset = sliding + duration + startTimeOffset;
  8046. }
  8047. _logger.logger.log('start time offset found in playlist, adjust startPosition to ' + startTimeOffset);
  8048. this.startPosition = startTimeOffset;
  8049. } else {
  8050. // if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)
  8051. if (newDetails.live) {
  8052. this.startPosition = this.computeLivePosition(sliding, newDetails);
  8053. _logger.logger.log('configure startPosition to ' + this.startPosition);
  8054. } else {
  8055. this.startPosition = 0;
  8056. }
  8057. }
  8058. this.lastCurrentTime = this.startPosition;
  8059. }
  8060. this.nextLoadPosition = this.startPosition;
  8061. }
  8062. // only switch batck to IDLE state if we were waiting for level to start downloading a new fragment
  8063. if (this.state === _baseStreamController.State.WAITING_LEVEL) {
  8064. this.state = _baseStreamController.State.IDLE;
  8065. }
  8066. // trigger handler right now
  8067. this.tick();
  8068. }
  8069. }, {
  8070. key: 'onKeyLoaded',
  8071. value: function onKeyLoaded() {
  8072. if (this.state === _baseStreamController.State.KEY_LOADING) {
  8073. this.state = _baseStreamController.State.IDLE;
  8074. this.tick();
  8075. }
  8076. }
  8077. }, {
  8078. key: 'onFragLoaded',
  8079. value: function onFragLoaded(data) {
  8080. var fragCurrent = this.fragCurrent,
  8081. hls = this.hls,
  8082. levels = this.levels,
  8083. media = this.media;
  8084. var fragLoaded = data.frag;
  8085. if (this.state === _baseStreamController.State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'main' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
  8086. var stats = data.stats;
  8087. var currentLevel = levels[fragCurrent.level];
  8088. var details = currentLevel.details;
  8089. // reset frag bitrate test in any case after frag loaded event
  8090. // if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0
  8091. // then this means that we should be able to load a fragment at a higher quality level
  8092. this.bitrateTest = false;
  8093. this.stats = stats;
  8094. _logger.logger.log('Loaded ' + fragCurrent.sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + fragCurrent.level);
  8095. if (fragLoaded.bitrateTest && hls.nextLoadLevel) {
  8096. // switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo
  8097. this.state = _baseStreamController.State.IDLE;
  8098. this.startFragRequested = false;
  8099. stats.tparsed = stats.tbuffered = window.performance.now();
  8100. hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
  8101. this.tick();
  8102. } else if (fragLoaded.sn === 'initSegment') {
  8103. this.state = _baseStreamController.State.IDLE;
  8104. stats.tparsed = stats.tbuffered = window.performance.now();
  8105. details.initSegment.data = data.payload;
  8106. hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
  8107. this.tick();
  8108. } else {
  8109. _logger.logger.log('Parsing ' + fragCurrent.sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + fragCurrent.level + ', cc ' + fragCurrent.cc);
  8110. this.state = _baseStreamController.State.PARSING;
  8111. this.pendingBuffering = true;
  8112. this.appended = false;
  8113. // Bitrate test frags are not usually buffered so the fragment tracker ignores them. If Hls.js decides to buffer
  8114. // it (and therefore ends up at this line), then the fragment tracker needs to be manually informed.
  8115. if (fragLoaded.bitrateTest) {
  8116. fragLoaded.bitrateTest = false;
  8117. this.fragmentTracker.onFragLoaded({
  8118. frag: fragLoaded
  8119. });
  8120. }
  8121. // 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)
  8122. var accurateTimeOffset = !(media && media.seeking) && (details.PTSKnown || !details.live);
  8123. var initSegmentData = details.initSegment ? details.initSegment.data : [];
  8124. var audioCodec = this._getAudioCodec(currentLevel);
  8125. // transmux the MPEG-TS data to ISO-BMFF segments
  8126. var demuxer = this.demuxer = this.demuxer || new _demuxer2.default(this.hls, 'main');
  8127. demuxer.push(data.payload, initSegmentData, audioCodec, currentLevel.videoCodec, fragCurrent, details.totalduration, accurateTimeOffset);
  8128. }
  8129. }
  8130. this.fragLoadError = 0;
  8131. }
  8132. }, {
  8133. key: 'onFragParsingInitSegment',
  8134. value: function onFragParsingInitSegment(data) {
  8135. var fragCurrent = this.fragCurrent;
  8136. var fragNew = data.frag;
  8137. if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === _baseStreamController.State.PARSING) {
  8138. var tracks = data.tracks,
  8139. trackName = void 0,
  8140. track = void 0;
  8141. // if audio track is expected to come from audio stream controller, discard any coming from main
  8142. if (tracks.audio && this.altAudio) {
  8143. delete tracks.audio;
  8144. }
  8145. // include levelCodec in audio and video tracks
  8146. track = tracks.audio;
  8147. if (track) {
  8148. var audioCodec = this.levels[this.level].audioCodec,
  8149. ua = navigator.userAgent.toLowerCase();
  8150. if (audioCodec && this.audioCodecSwap) {
  8151. _logger.logger.log('swapping playlist audio codec');
  8152. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  8153. audioCodec = 'mp4a.40.2';
  8154. } else {
  8155. audioCodec = 'mp4a.40.5';
  8156. }
  8157. }
  8158. // in case AAC and HE-AAC audio codecs are signalled in manifest
  8159. // force HE-AAC , as it seems that most browsers prefers that way,
  8160. // except for mono streams OR on FF
  8161. // these conditions might need to be reviewed ...
  8162. if (this.audioCodecSwitch) {
  8163. // don't force HE-AAC if mono stream
  8164. if (track.metadata.channelCount !== 1 &&
  8165. // don't force HE-AAC if firefox
  8166. ua.indexOf('firefox') === -1) {
  8167. audioCodec = 'mp4a.40.5';
  8168. }
  8169. }
  8170. // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  8171. if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') {
  8172. // Exclude mpeg audio
  8173. audioCodec = 'mp4a.40.2';
  8174. _logger.logger.log('Android: force audio codec to ' + audioCodec);
  8175. }
  8176. track.levelCodec = audioCodec;
  8177. track.id = data.id;
  8178. }
  8179. track = tracks.video;
  8180. if (track) {
  8181. track.levelCodec = this.levels[this.level].videoCodec;
  8182. track.id = data.id;
  8183. }
  8184. this.hls.trigger(_events2.default.BUFFER_CODECS, tracks);
  8185. // loop through tracks that are going to be provided to bufferController
  8186. for (trackName in tracks) {
  8187. track = tracks[trackName];
  8188. _logger.logger.log('main track:' + trackName + ',container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']');
  8189. var initSegment = track.initSegment;
  8190. if (initSegment) {
  8191. this.appended = true;
  8192. // arm pending Buffering flag before appending a segment
  8193. this.pendingBuffering = true;
  8194. this.hls.trigger(_events2.default.BUFFER_APPENDING, { type: trackName, data: initSegment, parent: 'main', content: 'initSegment' });
  8195. }
  8196. }
  8197. // trigger handler right now
  8198. this.tick();
  8199. }
  8200. }
  8201. }, {
  8202. key: 'onFragParsingData',
  8203. value: function onFragParsingData(data) {
  8204. var _this2 = this;
  8205. var fragCurrent = this.fragCurrent;
  8206. var fragNew = data.frag;
  8207. 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
  8208. this.state === _baseStreamController.State.PARSING) {
  8209. var level = this.levels[this.level],
  8210. frag = fragCurrent;
  8211. if (!Number.isFinite(data.endPTS)) {
  8212. data.endPTS = data.startPTS + fragCurrent.duration;
  8213. data.endDTS = data.startDTS + fragCurrent.duration;
  8214. }
  8215. if (data.hasAudio === true) {
  8216. frag.addElementaryStream(_fragment2.default.ElementaryStreamTypes.AUDIO);
  8217. }
  8218. if (data.hasVideo === true) {
  8219. frag.addElementaryStream(_fragment2.default.ElementaryStreamTypes.VIDEO);
  8220. }
  8221. _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));
  8222. // Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments)
  8223. if (data.type === 'video') {
  8224. frag.dropped = data.dropped;
  8225. if (frag.dropped) {
  8226. if (!frag.backtracked) {
  8227. var levelDetails = level.details;
  8228. if (levelDetails && frag.sn === levelDetails.startSN) {
  8229. _logger.logger.warn('missing video frame(s) on first frag, appending with gap', frag.sn);
  8230. } else {
  8231. _logger.logger.warn('missing video frame(s), backtracking fragment', frag.sn);
  8232. // Return back to the IDLE state without appending to buffer
  8233. // Causes findFragments to backtrack a segment and find the keyframe
  8234. // Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment
  8235. this.fragmentTracker.removeFragment(frag);
  8236. frag.backtracked = true;
  8237. this.nextLoadPosition = data.startPTS;
  8238. this.state = _baseStreamController.State.IDLE;
  8239. this.fragPrevious = frag;
  8240. this.tick();
  8241. return;
  8242. }
  8243. } else {
  8244. _logger.logger.warn('Already backtracked on this fragment, appending with the gap', frag.sn);
  8245. }
  8246. } else {
  8247. // Only reset the backtracked flag if we've loaded the frag without any dropped frames
  8248. frag.backtracked = false;
  8249. }
  8250. }
  8251. var drift = LevelHelper.updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS),
  8252. hls = this.hls;
  8253. hls.trigger(_events2.default.LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS });
  8254. // has remuxer dropped video frames located before first keyframe ?
  8255. [data.data1, data.data2].forEach(function (buffer) {
  8256. // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
  8257. // in that case it is useless to append following segments
  8258. if (buffer && buffer.length && _this2.state === _baseStreamController.State.PARSING) {
  8259. _this2.appended = true;
  8260. // arm pending Buffering flag before appending a segment
  8261. _this2.pendingBuffering = true;
  8262. hls.trigger(_events2.default.BUFFER_APPENDING, { type: data.type, data: buffer, parent: 'main', content: 'data' });
  8263. }
  8264. });
  8265. // trigger handler right now
  8266. this.tick();
  8267. }
  8268. }
  8269. }, {
  8270. key: 'onFragParsed',
  8271. value: function onFragParsed(data) {
  8272. var fragCurrent = this.fragCurrent;
  8273. var fragNew = data.frag;
  8274. if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === _baseStreamController.State.PARSING) {
  8275. this.stats.tparsed = window.performance.now();
  8276. this.state = _baseStreamController.State.PARSED;
  8277. this._checkAppendedParsed();
  8278. }
  8279. }
  8280. }, {
  8281. key: 'onAudioTrackSwitching',
  8282. value: function onAudioTrackSwitching(data) {
  8283. // if any URL found on new audio track, it is an alternate audio track
  8284. var altAudio = !!data.url,
  8285. trackId = data.id;
  8286. // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
  8287. // don't do anything if we switch to alt audio: audio stream controller is handling it.
  8288. // we will just have to change buffer scheduling on audioTrackSwitched
  8289. if (!altAudio) {
  8290. if (this.mediaBuffer !== this.media) {
  8291. _logger.logger.log('switching on main audio, use media.buffered to schedule main fragment loading');
  8292. this.mediaBuffer = this.media;
  8293. var fragCurrent = this.fragCurrent;
  8294. // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
  8295. if (fragCurrent.loader) {
  8296. _logger.logger.log('switching to main audio track, cancel main fragment load');
  8297. fragCurrent.loader.abort();
  8298. }
  8299. this.fragCurrent = null;
  8300. this.fragPrevious = null;
  8301. // destroy demuxer to force init segment generation (following audio switch)
  8302. if (this.demuxer) {
  8303. this.demuxer.destroy();
  8304. this.demuxer = null;
  8305. }
  8306. // switch to IDLE state to load new fragment
  8307. this.state = _baseStreamController.State.IDLE;
  8308. }
  8309. var hls = this.hls;
  8310. // switching to main audio, flush all audio and trigger track switched
  8311. hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
  8312. hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: trackId });
  8313. this.altAudio = false;
  8314. }
  8315. }
  8316. }, {
  8317. key: 'onAudioTrackSwitched',
  8318. value: function onAudioTrackSwitched(data) {
  8319. var trackId = data.id,
  8320. altAudio = !!this.hls.audioTracks[trackId].url;
  8321. if (altAudio) {
  8322. var videoBuffer = this.videoBuffer;
  8323. // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
  8324. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  8325. _logger.logger.log('switching on alternate audio, use video.buffered to schedule main fragment loading');
  8326. this.mediaBuffer = videoBuffer;
  8327. }
  8328. }
  8329. this.altAudio = altAudio;
  8330. this.tick();
  8331. }
  8332. }, {
  8333. key: 'onBufferCreated',
  8334. value: function onBufferCreated(data) {
  8335. var tracks = data.tracks,
  8336. mediaTrack = void 0,
  8337. name = void 0,
  8338. alternate = false;
  8339. for (var type in tracks) {
  8340. var track = tracks[type];
  8341. if (track.id === 'main') {
  8342. name = type;
  8343. mediaTrack = track;
  8344. // keep video source buffer reference
  8345. if (type === 'video') {
  8346. this.videoBuffer = tracks[type].buffer;
  8347. }
  8348. } else {
  8349. alternate = true;
  8350. }
  8351. }
  8352. if (alternate && mediaTrack) {
  8353. _logger.logger.log('alternate track found, use ' + name + '.buffered to schedule main fragment loading');
  8354. this.mediaBuffer = mediaTrack.buffer;
  8355. } else {
  8356. this.mediaBuffer = this.media;
  8357. }
  8358. }
  8359. }, {
  8360. key: 'onBufferAppended',
  8361. value: function onBufferAppended(data) {
  8362. if (data.parent === 'main') {
  8363. var state = this.state;
  8364. if (state === _baseStreamController.State.PARSING || state === _baseStreamController.State.PARSED) {
  8365. // check if all buffers have been appended
  8366. this.pendingBuffering = data.pending > 0;
  8367. this._checkAppendedParsed();
  8368. }
  8369. }
  8370. }
  8371. }, {
  8372. key: '_checkAppendedParsed',
  8373. value: function _checkAppendedParsed() {
  8374. // trigger handler right now
  8375. if (this.state === _baseStreamController.State.PARSED && (!this.appended || !this.pendingBuffering)) {
  8376. var frag = this.fragCurrent;
  8377. if (frag) {
  8378. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  8379. _logger.logger.log('main buffered : ' + _timeRanges2.default.toString(media.buffered));
  8380. this.fragPrevious = frag;
  8381. var stats = this.stats;
  8382. stats.tbuffered = window.performance.now();
  8383. // we should get rid of this.fragLastKbps
  8384. this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));
  8385. this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' });
  8386. this.state = _baseStreamController.State.IDLE;
  8387. }
  8388. this.tick();
  8389. }
  8390. }
  8391. }, {
  8392. key: 'onError',
  8393. value: function onError(data) {
  8394. var frag = data.frag || this.fragCurrent;
  8395. // don't handle frag error not related to main fragment
  8396. if (frag && frag.type !== 'main') {
  8397. return;
  8398. }
  8399. // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  8400. var mediaBuffered = !!this.media && _bufferHelper.BufferHelper.isBuffered(this.media, this.media.currentTime) && _bufferHelper.BufferHelper.isBuffered(this.media, this.media.currentTime + 0.5);
  8401. switch (data.details) {
  8402. case _errors.ErrorDetails.FRAG_LOAD_ERROR:
  8403. case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
  8404. case _errors.ErrorDetails.KEY_LOAD_ERROR:
  8405. case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
  8406. if (!data.fatal) {
  8407. // keep retrying until the limit will be reached
  8408. if (this.fragLoadError + 1 <= this.config.fragLoadingMaxRetry) {
  8409. // exponential backoff capped to config.fragLoadingMaxRetryTimeout
  8410. var delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);
  8411. _logger.logger.warn('mediaController: frag loading failed, retry in ' + delay + ' ms');
  8412. this.retryDate = window.performance.now() + delay;
  8413. // retry loading state
  8414. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  8415. // in that case, reset startFragRequested flag
  8416. if (!this.loadedmetadata) {
  8417. this.startFragRequested = false;
  8418. this.nextLoadPosition = this.startPosition;
  8419. }
  8420. this.fragLoadError++;
  8421. this.state = _baseStreamController.State.FRAG_LOADING_WAITING_RETRY;
  8422. } else {
  8423. _logger.logger.error('mediaController: ' + data.details + ' reaches max retry, redispatch as fatal ...');
  8424. // switch error to fatal
  8425. data.fatal = true;
  8426. this.state = _baseStreamController.State.ERROR;
  8427. }
  8428. }
  8429. break;
  8430. case _errors.ErrorDetails.LEVEL_LOAD_ERROR:
  8431. case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT:
  8432. if (this.state !== _baseStreamController.State.ERROR) {
  8433. if (data.fatal) {
  8434. // if fatal error, stop processing
  8435. this.state = _baseStreamController.State.ERROR;
  8436. _logger.logger.warn('streamController: ' + data.details + ',switch to ' + this.state + ' state ...');
  8437. } else {
  8438. // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE
  8439. if (!data.levelRetry && this.state === _baseStreamController.State.WAITING_LEVEL) {
  8440. this.state = _baseStreamController.State.IDLE;
  8441. }
  8442. }
  8443. }
  8444. break;
  8445. case _errors.ErrorDetails.BUFFER_FULL_ERROR:
  8446. // if in appending state
  8447. if (data.parent === 'main' && (this.state === _baseStreamController.State.PARSING || this.state === _baseStreamController.State.PARSED)) {
  8448. // reduce max buf len if current position is buffered
  8449. if (mediaBuffered) {
  8450. this._reduceMaxBufferLength(this.config.maxBufferLength);
  8451. this.state = _baseStreamController.State.IDLE;
  8452. } else {
  8453. // current position is not buffered, but browser is still complaining about buffer full error
  8454. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  8455. // in that case flush the whole buffer to recover
  8456. _logger.logger.warn('buffer full error also media.currentTime is not buffered, flush everything');
  8457. this.fragCurrent = null;
  8458. // flush everything
  8459. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  8460. }
  8461. }
  8462. break;
  8463. default:
  8464. break;
  8465. }
  8466. }
  8467. }, {
  8468. key: '_reduceMaxBufferLength',
  8469. value: function _reduceMaxBufferLength(minLength) {
  8470. var config = this.config;
  8471. if (config.maxMaxBufferLength >= minLength) {
  8472. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  8473. config.maxMaxBufferLength /= 2;
  8474. _logger.logger.warn('main:reduce max buffer length to ' + config.maxMaxBufferLength + 's');
  8475. return true;
  8476. }
  8477. return false;
  8478. }
  8479. /**
  8480. * Checks the health of the buffer and attempts to resolve playback stalls.
  8481. * @private
  8482. */
  8483. }, {
  8484. key: '_checkBuffer',
  8485. value: function _checkBuffer() {
  8486. var media = this.media;
  8487. if (!media || media.readyState === 0) {
  8488. // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0)
  8489. return;
  8490. }
  8491. var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;
  8492. var buffered = mediaBuffer.buffered;
  8493. if (!this.loadedmetadata && buffered.length) {
  8494. this.loadedmetadata = true;
  8495. this._seekToStartPos();
  8496. } else if (this.immediateSwitch) {
  8497. this.immediateLevelSwitchEnd();
  8498. } else {
  8499. this.gapController.poll(this.lastCurrentTime, buffered);
  8500. }
  8501. }
  8502. }, {
  8503. key: 'onFragLoadEmergencyAborted',
  8504. value: function onFragLoadEmergencyAborted() {
  8505. this.state = _baseStreamController.State.IDLE;
  8506. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  8507. // in that case, reset startFragRequested flag
  8508. if (!this.loadedmetadata) {
  8509. this.startFragRequested = false;
  8510. this.nextLoadPosition = this.startPosition;
  8511. }
  8512. this.tick();
  8513. }
  8514. }, {
  8515. key: 'onBufferFlushed',
  8516. value: function onBufferFlushed() {
  8517. /* after successful buffer flushing, filter flushed fragments from bufferedFrags
  8518. use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)
  8519. */
  8520. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  8521. if (media) {
  8522. // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams
  8523. this.fragmentTracker.detectEvictedFragments(_fragment2.default.ElementaryStreamTypes.VIDEO, media.buffered);
  8524. }
  8525. // move to IDLE once flush complete. this should trigger new fragment loading
  8526. this.state = _baseStreamController.State.IDLE;
  8527. // reset reference to frag
  8528. this.fragPrevious = null;
  8529. }
  8530. }, {
  8531. key: 'swapAudioCodec',
  8532. value: function swapAudioCodec() {
  8533. this.audioCodecSwap = !this.audioCodecSwap;
  8534. }
  8535. }, {
  8536. key: 'computeLivePosition',
  8537. value: function computeLivePosition(sliding, levelDetails) {
  8538. var targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration;
  8539. return sliding + Math.max(0, levelDetails.totalduration - targetLatency);
  8540. }
  8541. /**
  8542. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  8543. * @private
  8544. */
  8545. }, {
  8546. key: '_seekToStartPos',
  8547. value: function _seekToStartPos() {
  8548. var media = this.media;
  8549. var currentTime = media.currentTime;
  8550. // only adjust currentTime if different from startPosition or if startPosition not buffered
  8551. // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
  8552. var startPosition = media.seeking ? currentTime : this.startPosition;
  8553. // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered
  8554. if (currentTime !== startPosition) {
  8555. // if startPosition not buffered, let's seek to buffered.start(0)
  8556. _logger.logger.log('target start position not buffered, seek to buffered.start(0) ' + startPosition + ' from current time ' + currentTime + ' ');
  8557. media.currentTime = startPosition;
  8558. }
  8559. }
  8560. }, {
  8561. key: '_getAudioCodec',
  8562. value: function _getAudioCodec(currentLevel) {
  8563. var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  8564. if (this.audioCodecSwap) {
  8565. _logger.logger.log('swapping playlist audio codec');
  8566. if (audioCodec) {
  8567. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  8568. audioCodec = 'mp4a.40.2';
  8569. } else {
  8570. audioCodec = 'mp4a.40.5';
  8571. }
  8572. }
  8573. }
  8574. return audioCodec;
  8575. }
  8576. }, {
  8577. key: 'state',
  8578. set: function set(nextState) {
  8579. if (this.state !== nextState) {
  8580. var previousState = this.state;
  8581. this._state = nextState;
  8582. _logger.logger.log('main stream:' + previousState + '->' + nextState);
  8583. this.hls.trigger(_events2.default.STREAM_STATE_TRANSITION, { previousState: previousState, nextState: nextState });
  8584. }
  8585. },
  8586. get: function get() {
  8587. return this._state;
  8588. }
  8589. }, {
  8590. key: 'currentLevel',
  8591. get: function get() {
  8592. var media = this.media;
  8593. if (media) {
  8594. var frag = this.getBufferedFrag(media.currentTime);
  8595. if (frag) {
  8596. return frag.level;
  8597. }
  8598. }
  8599. return -1;
  8600. }
  8601. }, {
  8602. key: 'nextBufferedFrag',
  8603. get: function get() {
  8604. var media = this.media;
  8605. if (media) {
  8606. // first get end range of current fragment
  8607. return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime));
  8608. } else {
  8609. return null;
  8610. }
  8611. }
  8612. }, {
  8613. key: 'nextLevel',
  8614. get: function get() {
  8615. var frag = this.nextBufferedFrag;
  8616. if (frag) {
  8617. return frag.level;
  8618. } else {
  8619. return -1;
  8620. }
  8621. }
  8622. }, {
  8623. key: 'liveSyncPosition',
  8624. get: function get() {
  8625. return this._liveSyncPosition;
  8626. },
  8627. set: function set(value) {
  8628. this._liveSyncPosition = value;
  8629. }
  8630. }]);
  8631. return StreamController;
  8632. }(_baseStreamController2.default);
  8633. exports.default = StreamController;
  8634. module.exports = exports['default'];
  8635. /***/ }),
  8636. /* 41 */
  8637. /***/ (function(module, exports, __webpack_require__) {
  8638. function webpackBootstrapFunc (modules) {
  8639. /******/ // The module cache
  8640. /******/ var installedModules = {};
  8641. /******/ // The require function
  8642. /******/ function __webpack_require__(moduleId) {
  8643. /******/ // Check if module is in cache
  8644. /******/ if(installedModules[moduleId])
  8645. /******/ return installedModules[moduleId].exports;
  8646. /******/ // Create a new module (and put it into the cache)
  8647. /******/ var module = installedModules[moduleId] = {
  8648. /******/ i: moduleId,
  8649. /******/ l: false,
  8650. /******/ exports: {}
  8651. /******/ };
  8652. /******/ // Execute the module function
  8653. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  8654. /******/ // Flag the module as loaded
  8655. /******/ module.l = true;
  8656. /******/ // Return the exports of the module
  8657. /******/ return module.exports;
  8658. /******/ }
  8659. /******/ // expose the modules object (__webpack_modules__)
  8660. /******/ __webpack_require__.m = modules;
  8661. /******/ // expose the module cache
  8662. /******/ __webpack_require__.c = installedModules;
  8663. /******/ // identity function for calling harmony imports with the correct context
  8664. /******/ __webpack_require__.i = function(value) { return value; };
  8665. /******/ // define getter function for harmony exports
  8666. /******/ __webpack_require__.d = function(exports, name, getter) {
  8667. /******/ if(!__webpack_require__.o(exports, name)) {
  8668. /******/ Object.defineProperty(exports, name, {
  8669. /******/ configurable: false,
  8670. /******/ enumerable: true,
  8671. /******/ get: getter
  8672. /******/ });
  8673. /******/ }
  8674. /******/ };
  8675. /******/ // define __esModule on exports
  8676. /******/ __webpack_require__.r = function(exports) {
  8677. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  8678. /******/ };
  8679. /******/ // getDefaultExport function for compatibility with non-harmony modules
  8680. /******/ __webpack_require__.n = function(module) {
  8681. /******/ var getter = module && module.__esModule ?
  8682. /******/ function getDefault() { return module['default']; } :
  8683. /******/ function getModuleExports() { return module; };
  8684. /******/ __webpack_require__.d(getter, 'a', getter);
  8685. /******/ return getter;
  8686. /******/ };
  8687. /******/ // Object.prototype.hasOwnProperty.call
  8688. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  8689. /******/ // __webpack_public_path__
  8690. /******/ __webpack_require__.p = "/";
  8691. /******/ // on error function for async loading
  8692. /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };
  8693. var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE)
  8694. return f.default || f // try to call default if defined to also support babel esmodule exports
  8695. }
  8696. var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+'
  8697. var dependencyRegExp = '\\(\\s*(\/\\*.*?\\*\/)?\\s*.*?(' + moduleNameReqExp + ').*?\\)' // additional chars when output.pathinfo is true
  8698. // http://stackoverflow.com/a/2593661/130442
  8699. function quoteRegExp (str) {
  8700. return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&')
  8701. }
  8702. function isNumeric(n) {
  8703. return !isNaN(1 * n); // 1 * n converts integers, integers as string ("123"), 1e3 and "1e3" to integers and strings to NaN
  8704. }
  8705. function getModuleDependencies (sources, module, queueName) {
  8706. var retval = {}
  8707. retval[queueName] = []
  8708. var fnString = module.toString()
  8709. var wrapperSignature = fnString.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/)
  8710. if (!wrapperSignature) return retval
  8711. var webpackRequireName = wrapperSignature[1]
  8712. // main bundle deps
  8713. var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')
  8714. var match
  8715. while ((match = re.exec(fnString))) {
  8716. if (match[3] === 'dll-reference') continue
  8717. retval[queueName].push(match[3])
  8718. }
  8719. // dll deps
  8720. re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g')
  8721. while ((match = re.exec(fnString))) {
  8722. if (!sources[match[2]]) {
  8723. retval[queueName].push(match[1])
  8724. sources[match[2]] = __webpack_require__(match[1]).m
  8725. }
  8726. retval[match[2]] = retval[match[2]] || []
  8727. retval[match[2]].push(match[4])
  8728. }
  8729. // convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3
  8730. var keys = Object.keys(retval);
  8731. for (var i = 0; i < keys.length; i++) {
  8732. for (var j = 0; j < retval[keys[i]].length; j++) {
  8733. if (isNumeric(retval[keys[i]][j])) {
  8734. retval[keys[i]][j] = 1 * retval[keys[i]][j];
  8735. }
  8736. }
  8737. }
  8738. return retval
  8739. }
  8740. function hasValuesInQueues (queues) {
  8741. var keys = Object.keys(queues)
  8742. return keys.reduce(function (hasValues, key) {
  8743. return hasValues || queues[key].length > 0
  8744. }, false)
  8745. }
  8746. function getRequiredModules (sources, moduleId) {
  8747. var modulesQueue = {
  8748. main: [moduleId]
  8749. }
  8750. var requiredModules = {
  8751. main: []
  8752. }
  8753. var seenModules = {
  8754. main: {}
  8755. }
  8756. while (hasValuesInQueues(modulesQueue)) {
  8757. var queues = Object.keys(modulesQueue)
  8758. for (var i = 0; i < queues.length; i++) {
  8759. var queueName = queues[i]
  8760. var queue = modulesQueue[queueName]
  8761. var moduleToCheck = queue.pop()
  8762. seenModules[queueName] = seenModules[queueName] || {}
  8763. if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue
  8764. seenModules[queueName][moduleToCheck] = true
  8765. requiredModules[queueName] = requiredModules[queueName] || []
  8766. requiredModules[queueName].push(moduleToCheck)
  8767. var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)
  8768. var newModulesKeys = Object.keys(newModules)
  8769. for (var j = 0; j < newModulesKeys.length; j++) {
  8770. modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []
  8771. modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])
  8772. }
  8773. }
  8774. }
  8775. return requiredModules
  8776. }
  8777. module.exports = function (moduleId, options) {
  8778. options = options || {}
  8779. var sources = {
  8780. main: __webpack_require__.m
  8781. }
  8782. var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId)
  8783. var src = ''
  8784. Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {
  8785. var entryModule = 0
  8786. while (requiredModules[module][entryModule]) {
  8787. entryModule++
  8788. }
  8789. requiredModules[module].push(entryModule)
  8790. sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'
  8791. 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'
  8792. })
  8793. 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);'
  8794. var blob = new window.Blob([src], { type: 'text/javascript' })
  8795. if (options.bare) { return blob }
  8796. var URL = window.URL || window.webkitURL || window.mozURL || window.msURL
  8797. var workerUrl = URL.createObjectURL(blob)
  8798. var worker = new window.Worker(workerUrl)
  8799. worker.objectURL = workerUrl
  8800. return worker
  8801. }
  8802. /***/ }),
  8803. /* 42 */
  8804. /***/ (function(module, exports, __webpack_require__) {
  8805. "use strict";
  8806. Object.defineProperty(exports, "__esModule", {
  8807. value: true
  8808. });
  8809. 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; }; }();
  8810. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8811. var AESCrypto = function () {
  8812. function AESCrypto(subtle, iv) {
  8813. _classCallCheck(this, AESCrypto);
  8814. this.subtle = subtle;
  8815. this.aesIV = iv;
  8816. }
  8817. _createClass(AESCrypto, [{
  8818. key: 'decrypt',
  8819. value: function decrypt(data, key) {
  8820. return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data);
  8821. }
  8822. }]);
  8823. return AESCrypto;
  8824. }();
  8825. exports.default = AESCrypto;
  8826. module.exports = exports['default'];
  8827. /***/ }),
  8828. /* 43 */
  8829. /***/ (function(module, exports, __webpack_require__) {
  8830. "use strict";
  8831. Object.defineProperty(exports, "__esModule", {
  8832. value: true
  8833. });
  8834. 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; }; }();
  8835. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8836. var FastAESKey = function () {
  8837. function FastAESKey(subtle, key) {
  8838. _classCallCheck(this, FastAESKey);
  8839. this.subtle = subtle;
  8840. this.key = key;
  8841. }
  8842. _createClass(FastAESKey, [{
  8843. key: 'expandKey',
  8844. value: function expandKey() {
  8845. return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']);
  8846. }
  8847. }]);
  8848. return FastAESKey;
  8849. }();
  8850. exports.default = FastAESKey;
  8851. module.exports = exports['default'];
  8852. /***/ }),
  8853. /* 44 */
  8854. /***/ (function(module, exports, __webpack_require__) {
  8855. "use strict";
  8856. Object.defineProperty(exports, "__esModule", {
  8857. value: true
  8858. });
  8859. 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; }; }();
  8860. exports.removePadding = removePadding;
  8861. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8862. // PKCS7
  8863. function removePadding(buffer) {
  8864. var outputBytes = buffer.byteLength;
  8865. var paddingBytes = outputBytes && new DataView(buffer).getUint8(outputBytes - 1);
  8866. if (paddingBytes) {
  8867. return buffer.slice(0, outputBytes - paddingBytes);
  8868. } else {
  8869. return buffer;
  8870. }
  8871. }
  8872. var AESDecryptor = function () {
  8873. function AESDecryptor() {
  8874. _classCallCheck(this, AESDecryptor);
  8875. // Static after running initTable
  8876. this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  8877. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  8878. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  8879. this.sBox = new Uint32Array(256);
  8880. this.invSBox = new Uint32Array(256);
  8881. // Changes during runtime
  8882. this.key = new Uint32Array(0);
  8883. this.initTable();
  8884. }
  8885. // Using view.getUint32() also swaps the byte order.
  8886. _createClass(AESDecryptor, [{
  8887. key: 'uint8ArrayToUint32Array_',
  8888. value: function uint8ArrayToUint32Array_(arrayBuffer) {
  8889. var view = new DataView(arrayBuffer);
  8890. var newArray = new Uint32Array(4);
  8891. for (var i = 0; i < 4; i++) {
  8892. newArray[i] = view.getUint32(i * 4);
  8893. }
  8894. return newArray;
  8895. }
  8896. }, {
  8897. key: 'initTable',
  8898. value: function initTable() {
  8899. var sBox = this.sBox;
  8900. var invSBox = this.invSBox;
  8901. var subMix = this.subMix;
  8902. var subMix0 = subMix[0];
  8903. var subMix1 = subMix[1];
  8904. var subMix2 = subMix[2];
  8905. var subMix3 = subMix[3];
  8906. var invSubMix = this.invSubMix;
  8907. var invSubMix0 = invSubMix[0];
  8908. var invSubMix1 = invSubMix[1];
  8909. var invSubMix2 = invSubMix[2];
  8910. var invSubMix3 = invSubMix[3];
  8911. var d = new Uint32Array(256);
  8912. var x = 0;
  8913. var xi = 0;
  8914. var i = 0;
  8915. for (i = 0; i < 256; i++) {
  8916. if (i < 128) {
  8917. d[i] = i << 1;
  8918. } else {
  8919. d[i] = i << 1 ^ 0x11b;
  8920. }
  8921. }
  8922. for (i = 0; i < 256; i++) {
  8923. var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  8924. sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
  8925. sBox[x] = sx;
  8926. invSBox[sx] = x;
  8927. // Compute multiplication
  8928. var x2 = d[x];
  8929. var x4 = d[x2];
  8930. var x8 = d[x4];
  8931. // Compute sub/invSub bytes, mix columns tables
  8932. var t = d[sx] * 0x101 ^ sx * 0x1010100;
  8933. subMix0[x] = t << 24 | t >>> 8;
  8934. subMix1[x] = t << 16 | t >>> 16;
  8935. subMix2[x] = t << 8 | t >>> 24;
  8936. subMix3[x] = t;
  8937. // Compute inv sub bytes, inv mix columns tables
  8938. t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  8939. invSubMix0[sx] = t << 24 | t >>> 8;
  8940. invSubMix1[sx] = t << 16 | t >>> 16;
  8941. invSubMix2[sx] = t << 8 | t >>> 24;
  8942. invSubMix3[sx] = t;
  8943. // Compute next counter
  8944. if (!x) {
  8945. x = xi = 1;
  8946. } else {
  8947. x = x2 ^ d[d[d[x8 ^ x2]]];
  8948. xi ^= d[d[xi]];
  8949. }
  8950. }
  8951. }
  8952. }, {
  8953. key: 'expandKey',
  8954. value: function expandKey(keyBuffer) {
  8955. // convert keyBuffer to Uint32Array
  8956. var key = this.uint8ArrayToUint32Array_(keyBuffer);
  8957. var sameKey = true;
  8958. var offset = 0;
  8959. while (offset < key.length && sameKey) {
  8960. sameKey = key[offset] === this.key[offset];
  8961. offset++;
  8962. }
  8963. if (sameKey) {
  8964. return;
  8965. }
  8966. this.key = key;
  8967. var keySize = this.keySize = key.length;
  8968. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  8969. throw new Error('Invalid aes key size=' + keySize);
  8970. }
  8971. var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  8972. var ksRow = void 0;
  8973. var invKsRow = void 0;
  8974. var keySchedule = this.keySchedule = new Uint32Array(ksRows);
  8975. var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  8976. var sbox = this.sBox;
  8977. var rcon = this.rcon;
  8978. var invSubMix = this.invSubMix;
  8979. var invSubMix0 = invSubMix[0];
  8980. var invSubMix1 = invSubMix[1];
  8981. var invSubMix2 = invSubMix[2];
  8982. var invSubMix3 = invSubMix[3];
  8983. var prev = void 0;
  8984. var t = void 0;
  8985. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  8986. if (ksRow < keySize) {
  8987. prev = keySchedule[ksRow] = key[ksRow];
  8988. continue;
  8989. }
  8990. t = prev;
  8991. if (ksRow % keySize === 0) {
  8992. // Rot word
  8993. t = t << 8 | t >>> 24;
  8994. // Sub word
  8995. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  8996. // Mix Rcon
  8997. t ^= rcon[ksRow / keySize | 0] << 24;
  8998. } else if (keySize > 6 && ksRow % keySize === 4) {
  8999. // Sub word
  9000. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  9001. }
  9002. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  9003. }
  9004. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  9005. ksRow = ksRows - invKsRow;
  9006. if (invKsRow & 3) {
  9007. t = keySchedule[ksRow];
  9008. } else {
  9009. t = keySchedule[ksRow - 4];
  9010. }
  9011. if (invKsRow < 4 || ksRow <= 4) {
  9012. invKeySchedule[invKsRow] = t;
  9013. } else {
  9014. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
  9015. }
  9016. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  9017. }
  9018. }
  9019. // Adding this as a method greatly improves performance.
  9020. }, {
  9021. key: 'networkToHostOrderSwap',
  9022. value: function networkToHostOrderSwap(word) {
  9023. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  9024. }
  9025. }, {
  9026. key: 'decrypt',
  9027. value: function decrypt(inputArrayBuffer, offset, aesIV, removePKCS7Padding) {
  9028. var nRounds = this.keySize + 6;
  9029. var invKeySchedule = this.invKeySchedule;
  9030. var invSBOX = this.invSBox;
  9031. var invSubMix = this.invSubMix;
  9032. var invSubMix0 = invSubMix[0];
  9033. var invSubMix1 = invSubMix[1];
  9034. var invSubMix2 = invSubMix[2];
  9035. var invSubMix3 = invSubMix[3];
  9036. var initVector = this.uint8ArrayToUint32Array_(aesIV);
  9037. var initVector0 = initVector[0];
  9038. var initVector1 = initVector[1];
  9039. var initVector2 = initVector[2];
  9040. var initVector3 = initVector[3];
  9041. var inputInt32 = new Int32Array(inputArrayBuffer);
  9042. var outputInt32 = new Int32Array(inputInt32.length);
  9043. var t0 = void 0,
  9044. t1 = void 0,
  9045. t2 = void 0,
  9046. t3 = void 0;
  9047. var s0 = void 0,
  9048. s1 = void 0,
  9049. s2 = void 0,
  9050. s3 = void 0;
  9051. var inputWords0 = void 0,
  9052. inputWords1 = void 0,
  9053. inputWords2 = void 0,
  9054. inputWords3 = void 0;
  9055. var ksRow = void 0,
  9056. i = void 0;
  9057. var swapWord = this.networkToHostOrderSwap;
  9058. while (offset < inputInt32.length) {
  9059. inputWords0 = swapWord(inputInt32[offset]);
  9060. inputWords1 = swapWord(inputInt32[offset + 1]);
  9061. inputWords2 = swapWord(inputInt32[offset + 2]);
  9062. inputWords3 = swapWord(inputInt32[offset + 3]);
  9063. s0 = inputWords0 ^ invKeySchedule[0];
  9064. s1 = inputWords3 ^ invKeySchedule[1];
  9065. s2 = inputWords2 ^ invKeySchedule[2];
  9066. s3 = inputWords1 ^ invKeySchedule[3];
  9067. ksRow = 4;
  9068. // Iterate through the rounds of decryption
  9069. for (i = 1; i < nRounds; i++) {
  9070. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
  9071. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  9072. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  9073. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  9074. // Update state
  9075. s0 = t0;
  9076. s1 = t1;
  9077. s2 = t2;
  9078. s3 = t3;
  9079. ksRow = ksRow + 4;
  9080. }
  9081. // Shift rows, sub bytes, add round key
  9082. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
  9083. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  9084. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  9085. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  9086. ksRow = ksRow + 3;
  9087. // Write
  9088. outputInt32[offset] = swapWord(t0 ^ initVector0);
  9089. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  9090. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  9091. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  9092. // reset initVector to last 4 unsigned int
  9093. initVector0 = inputWords0;
  9094. initVector1 = inputWords1;
  9095. initVector2 = inputWords2;
  9096. initVector3 = inputWords3;
  9097. offset = offset + 4;
  9098. }
  9099. return removePKCS7Padding ? removePadding(outputInt32.buffer) : outputInt32.buffer;
  9100. }
  9101. }, {
  9102. key: 'destroy',
  9103. value: function destroy() {
  9104. this.key = undefined;
  9105. this.keySize = undefined;
  9106. this.ksRows = undefined;
  9107. this.sBox = undefined;
  9108. this.invSBox = undefined;
  9109. this.subMix = undefined;
  9110. this.invSubMix = undefined;
  9111. this.keySchedule = undefined;
  9112. this.invKeySchedule = undefined;
  9113. this.rcon = undefined;
  9114. }
  9115. }]);
  9116. return AESDecryptor;
  9117. }();
  9118. exports.default = AESDecryptor;
  9119. /***/ }),
  9120. /* 45 */
  9121. /***/ (function(module, exports, __webpack_require__) {
  9122. "use strict";
  9123. Object.defineProperty(exports, "__esModule", {
  9124. value: true
  9125. });
  9126. 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; }; }(); /**
  9127. * AAC demuxer
  9128. */
  9129. var _adts = __webpack_require__(22);
  9130. var ADTS = _interopRequireWildcard(_adts);
  9131. var _logger = __webpack_require__(0);
  9132. var _id = __webpack_require__(10);
  9133. var _id2 = _interopRequireDefault(_id);
  9134. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9135. 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; } }
  9136. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9137. var AACDemuxer = function () {
  9138. function AACDemuxer(observer, remuxer, config) {
  9139. _classCallCheck(this, AACDemuxer);
  9140. this.observer = observer;
  9141. this.config = config;
  9142. this.remuxer = remuxer;
  9143. }
  9144. _createClass(AACDemuxer, [{
  9145. key: 'resetInitSegment',
  9146. value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  9147. this._audioTrack = { container: 'audio/adts', type: 'audio', id: 0, sequenceNumber: 0, isAAC: true, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };
  9148. }
  9149. }, {
  9150. key: 'resetTimeStamp',
  9151. value: function resetTimeStamp() {}
  9152. }, {
  9153. key: 'append',
  9154. // feed incoming data to the front of the parsing pipeline
  9155. value: function append(data, timeOffset, contiguous, accurateTimeOffset) {
  9156. var track = this._audioTrack;
  9157. var id3Data = _id2.default.getID3Data(data, 0) || [];
  9158. var timestamp = _id2.default.getTimeStamp(id3Data);
  9159. var pts = Number.isFinite(timestamp) ? timestamp * 90 : timeOffset * 90000;
  9160. var frameIndex = 0;
  9161. var stamp = pts;
  9162. var length = data.length;
  9163. var offset = id3Data.length;
  9164. var id3Samples = [{ pts: stamp, dts: stamp, data: id3Data }];
  9165. while (offset < length - 1) {
  9166. if (ADTS.isHeader(data, offset) && offset + 5 < length) {
  9167. ADTS.initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  9168. var frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);
  9169. if (frame) {
  9170. offset += frame.length;
  9171. stamp = frame.sample.pts;
  9172. frameIndex++;
  9173. } else {
  9174. _logger.logger.log('Unable to parse AAC frame');
  9175. break;
  9176. }
  9177. } else if (_id2.default.isHeader(data, offset)) {
  9178. id3Data = _id2.default.getID3Data(data, offset);
  9179. id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });
  9180. offset += id3Data.length;
  9181. } else {
  9182. // nothing found, keep looking
  9183. offset++;
  9184. }
  9185. }
  9186. this.remuxer.remux(track, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset);
  9187. }
  9188. }, {
  9189. key: 'destroy',
  9190. value: function destroy() {}
  9191. }], [{
  9192. key: 'probe',
  9193. value: function probe(data) {
  9194. if (!data) {
  9195. return false;
  9196. }
  9197. // Check for the ADTS sync word
  9198. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  9199. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  9200. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  9201. var id3Data = _id2.default.getID3Data(data, 0) || [];
  9202. var offset = id3Data.length;
  9203. for (var length = data.length; offset < length; offset++) {
  9204. if (ADTS.probe(data, offset)) {
  9205. _logger.logger.log('ADTS sync word found !');
  9206. return true;
  9207. }
  9208. }
  9209. return false;
  9210. }
  9211. }]);
  9212. return AACDemuxer;
  9213. }();
  9214. exports.default = AACDemuxer;
  9215. module.exports = exports['default'];
  9216. /***/ }),
  9217. /* 46 */
  9218. /***/ (function(module, exports, __webpack_require__) {
  9219. "use strict";
  9220. Object.defineProperty(exports, "__esModule", {
  9221. value: true
  9222. });
  9223. 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; }; }(); /**
  9224. * highly optimized TS demuxer:
  9225. * parse PAT, PMT
  9226. * extract PES packet from audio and video PIDs
  9227. * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet
  9228. * trigger the remuxer upon parsing completion
  9229. * 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.
  9230. * it also controls the remuxing process :
  9231. * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.
  9232. */
  9233. // import Hex from '../utils/hex';
  9234. var _adts = __webpack_require__(22);
  9235. var ADTS = _interopRequireWildcard(_adts);
  9236. var _mpegaudio = __webpack_require__(23);
  9237. var _mpegaudio2 = _interopRequireDefault(_mpegaudio);
  9238. var _events = __webpack_require__(1);
  9239. var _events2 = _interopRequireDefault(_events);
  9240. var _expGolomb = __webpack_require__(47);
  9241. var _expGolomb2 = _interopRequireDefault(_expGolomb);
  9242. var _sampleAes = __webpack_require__(48);
  9243. var _sampleAes2 = _interopRequireDefault(_sampleAes);
  9244. var _logger = __webpack_require__(0);
  9245. var _errors = __webpack_require__(2);
  9246. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9247. 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; } }
  9248. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9249. // We are using fixed track IDs for driving the MP4 remuxer
  9250. // instead of following the TS PIDs.
  9251. // There is no reason not to do this and some browsers/SourceBuffer-demuxers
  9252. // may not like if there are TrackID "switches"
  9253. // See https://github.com/video-dev/hls.js/issues/1331
  9254. // Here we are mapping our internal track types to constant MP4 track IDs
  9255. // With MSE currently one can only have one track of each, and we are muxing
  9256. // whatever video/audio rendition in them.
  9257. var RemuxerTrackIdConfig = {
  9258. video: 1,
  9259. audio: 2,
  9260. id3: 3,
  9261. text: 4
  9262. };
  9263. var TSDemuxer = function () {
  9264. function TSDemuxer(observer, remuxer, config, typeSupported) {
  9265. _classCallCheck(this, TSDemuxer);
  9266. this.observer = observer;
  9267. this.config = config;
  9268. this.typeSupported = typeSupported;
  9269. this.remuxer = remuxer;
  9270. this.sampleAes = null;
  9271. }
  9272. _createClass(TSDemuxer, [{
  9273. key: 'setDecryptData',
  9274. value: function setDecryptData(decryptdata) {
  9275. if (decryptdata != null && decryptdata.key != null && decryptdata.method === 'SAMPLE-AES') {
  9276. this.sampleAes = new _sampleAes2.default(this.observer, this.config, decryptdata, this.discardEPB);
  9277. } else {
  9278. this.sampleAes = null;
  9279. }
  9280. }
  9281. }, {
  9282. key: 'resetInitSegment',
  9283. /**
  9284. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  9285. * Resets all internal track instances of the demuxer.
  9286. *
  9287. * @override Implements generic demuxing/remuxing interface (see DemuxerInline)
  9288. * @param {object} initSegment
  9289. * @param {string} audioCodec
  9290. * @param {string} videoCodec
  9291. * @param {number} duration (in TS timescale = 90kHz)
  9292. */
  9293. value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  9294. this.pmtParsed = false;
  9295. this._pmtId = -1;
  9296. this._avcTrack = TSDemuxer.createTrack('video', duration);
  9297. this._audioTrack = TSDemuxer.createTrack('audio', duration);
  9298. this._id3Track = TSDemuxer.createTrack('id3', duration);
  9299. this._txtTrack = TSDemuxer.createTrack('text', duration);
  9300. // flush any partial content
  9301. this.aacOverFlow = null;
  9302. this.aacLastPTS = null;
  9303. this.avcSample = null;
  9304. this.audioCodec = audioCodec;
  9305. this.videoCodec = videoCodec;
  9306. this._duration = duration;
  9307. }
  9308. /**
  9309. *
  9310. * @override
  9311. */
  9312. }, {
  9313. key: 'resetTimeStamp',
  9314. value: function resetTimeStamp() {}
  9315. // feed incoming data to the front of the parsing pipeline
  9316. }, {
  9317. key: 'append',
  9318. value: function append(data, timeOffset, contiguous, accurateTimeOffset) {
  9319. var start = void 0,
  9320. len = data.length,
  9321. stt = void 0,
  9322. pid = void 0,
  9323. atf = void 0,
  9324. offset = void 0,
  9325. pes = void 0,
  9326. unknownPIDs = false;
  9327. this.contiguous = contiguous;
  9328. var pmtParsed = this.pmtParsed,
  9329. avcTrack = this._avcTrack,
  9330. audioTrack = this._audioTrack,
  9331. id3Track = this._id3Track,
  9332. avcId = avcTrack.pid,
  9333. audioId = audioTrack.pid,
  9334. id3Id = id3Track.pid,
  9335. pmtId = this._pmtId,
  9336. avcData = avcTrack.pesData,
  9337. audioData = audioTrack.pesData,
  9338. id3Data = id3Track.pesData,
  9339. parsePAT = this._parsePAT,
  9340. parsePMT = this._parsePMT,
  9341. parsePES = this._parsePES,
  9342. parseAVCPES = this._parseAVCPES.bind(this),
  9343. parseAACPES = this._parseAACPES.bind(this),
  9344. parseMPEGPES = this._parseMPEGPES.bind(this),
  9345. parseID3PES = this._parseID3PES.bind(this);
  9346. var syncOffset = TSDemuxer._syncOffset(data);
  9347. // don't parse last TS packet if incomplete
  9348. len -= (len + syncOffset) % 188;
  9349. // loop through TS packets
  9350. for (start = syncOffset; start < len; start += 188) {
  9351. if (data[start] === 0x47) {
  9352. stt = !!(data[start + 1] & 0x40);
  9353. // pid is a 13-bit field starting at the last bit of TS[1]
  9354. pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
  9355. atf = (data[start + 3] & 0x30) >> 4;
  9356. // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
  9357. if (atf > 1) {
  9358. offset = start + 5 + data[start + 4];
  9359. // continue if there is only adaptation field
  9360. if (offset === start + 188) {
  9361. continue;
  9362. }
  9363. } else {
  9364. offset = start + 4;
  9365. }
  9366. switch (pid) {
  9367. case avcId:
  9368. if (stt) {
  9369. if (avcData && (pes = parsePES(avcData)) && pes.pts !== undefined) {
  9370. parseAVCPES(pes, false);
  9371. }
  9372. avcData = { data: [], size: 0 };
  9373. }
  9374. if (avcData) {
  9375. avcData.data.push(data.subarray(offset, start + 188));
  9376. avcData.size += start + 188 - offset;
  9377. }
  9378. break;
  9379. case audioId:
  9380. if (stt) {
  9381. if (audioData && (pes = parsePES(audioData)) && pes.pts !== undefined) {
  9382. if (audioTrack.isAAC) {
  9383. parseAACPES(pes);
  9384. } else {
  9385. parseMPEGPES(pes);
  9386. }
  9387. }
  9388. audioData = { data: [], size: 0 };
  9389. }
  9390. if (audioData) {
  9391. audioData.data.push(data.subarray(offset, start + 188));
  9392. audioData.size += start + 188 - offset;
  9393. }
  9394. break;
  9395. case id3Id:
  9396. if (stt) {
  9397. if (id3Data && (pes = parsePES(id3Data)) && pes.pts !== undefined) {
  9398. parseID3PES(pes);
  9399. }
  9400. id3Data = { data: [], size: 0 };
  9401. }
  9402. if (id3Data) {
  9403. id3Data.data.push(data.subarray(offset, start + 188));
  9404. id3Data.size += start + 188 - offset;
  9405. }
  9406. break;
  9407. case 0:
  9408. if (stt) {
  9409. offset += data[offset] + 1;
  9410. }
  9411. pmtId = this._pmtId = parsePAT(data, offset);
  9412. break;
  9413. case pmtId:
  9414. if (stt) {
  9415. offset += data[offset] + 1;
  9416. }
  9417. var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, this.sampleAes != null);
  9418. // only update track id if track PID found while parsing PMT
  9419. // this is to avoid resetting the PID to -1 in case
  9420. // track PID transiently disappears from the stream
  9421. // this could happen in case of transient missing audio samples for example
  9422. // NOTE this is only the PID of the track as found in TS,
  9423. // but we are not using this for MP4 track IDs.
  9424. avcId = parsedPIDs.avc;
  9425. if (avcId > 0) {
  9426. avcTrack.pid = avcId;
  9427. }
  9428. audioId = parsedPIDs.audio;
  9429. if (audioId > 0) {
  9430. audioTrack.pid = audioId;
  9431. audioTrack.isAAC = parsedPIDs.isAAC;
  9432. }
  9433. id3Id = parsedPIDs.id3;
  9434. if (id3Id > 0) {
  9435. id3Track.pid = id3Id;
  9436. }
  9437. if (unknownPIDs && !pmtParsed) {
  9438. _logger.logger.log('reparse from beginning');
  9439. unknownPIDs = false;
  9440. // we set it to -188, the += 188 in the for loop will reset start to 0
  9441. start = syncOffset - 188;
  9442. }
  9443. pmtParsed = this.pmtParsed = true;
  9444. break;
  9445. case 17:
  9446. case 0x1fff:
  9447. break;
  9448. default:
  9449. unknownPIDs = true;
  9450. break;
  9451. }
  9452. } else {
  9453. 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' });
  9454. }
  9455. }
  9456. // try to parse last PES packets
  9457. if (avcData && (pes = parsePES(avcData)) && pes.pts !== undefined) {
  9458. parseAVCPES(pes, true);
  9459. avcTrack.pesData = null;
  9460. } else {
  9461. // either avcData null or PES truncated, keep it for next frag parsing
  9462. avcTrack.pesData = avcData;
  9463. }
  9464. if (audioData && (pes = parsePES(audioData)) && pes.pts !== undefined) {
  9465. if (audioTrack.isAAC) {
  9466. parseAACPES(pes);
  9467. } else {
  9468. parseMPEGPES(pes);
  9469. }
  9470. audioTrack.pesData = null;
  9471. } else {
  9472. if (audioData && audioData.size) {
  9473. _logger.logger.log('last AAC PES packet truncated,might overlap between fragments');
  9474. }
  9475. // either audioData null or PES truncated, keep it for next frag parsing
  9476. audioTrack.pesData = audioData;
  9477. }
  9478. if (id3Data && (pes = parsePES(id3Data)) && pes.pts !== undefined) {
  9479. parseID3PES(pes);
  9480. id3Track.pesData = null;
  9481. } else {
  9482. // either id3Data null or PES truncated, keep it for next frag parsing
  9483. id3Track.pesData = id3Data;
  9484. }
  9485. if (this.sampleAes == null) {
  9486. this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
  9487. } else {
  9488. this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
  9489. }
  9490. }
  9491. }, {
  9492. key: 'decryptAndRemux',
  9493. value: function decryptAndRemux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  9494. if (audioTrack.samples && audioTrack.isAAC) {
  9495. var localthis = this;
  9496. this.sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
  9497. localthis.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  9498. });
  9499. } else {
  9500. this.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  9501. }
  9502. }
  9503. }, {
  9504. key: 'decryptAndRemuxAvc',
  9505. value: function decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  9506. if (videoTrack.samples) {
  9507. var localthis = this;
  9508. this.sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
  9509. localthis.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  9510. });
  9511. } else {
  9512. this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  9513. }
  9514. }
  9515. }, {
  9516. key: 'destroy',
  9517. value: function destroy() {
  9518. this._initPTS = this._initDTS = undefined;
  9519. this._duration = 0;
  9520. }
  9521. }, {
  9522. key: '_parsePAT',
  9523. value: function _parsePAT(data, offset) {
  9524. // skip the PSI header and parse the first PMT entry
  9525. return (data[offset + 10] & 0x1F) << 8 | data[offset + 11];
  9526. // logger.log('PMT PID:' + this._pmtId);
  9527. }
  9528. }, {
  9529. key: '_parsePMT',
  9530. value: function _parsePMT(data, offset, mpegSupported, isSampleAes) {
  9531. var sectionLength = void 0,
  9532. tableEnd = void 0,
  9533. programInfoLength = void 0,
  9534. pid = void 0,
  9535. result = { audio: -1, avc: -1, id3: -1, isAAC: true };
  9536. sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
  9537. tableEnd = offset + 3 + sectionLength - 4;
  9538. // to determine where the table is, we have to figure out how
  9539. // long the program info descriptors are
  9540. programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
  9541. // advance the offset to the first entry in the mapping table
  9542. offset += 12 + programInfoLength;
  9543. while (offset < tableEnd) {
  9544. pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];
  9545. switch (data[offset]) {
  9546. case 0xcf:
  9547. // SAMPLE-AES AAC
  9548. if (!isSampleAes) {
  9549. _logger.logger.log('unkown stream type:' + data[offset]);
  9550. break;
  9551. }
  9552. /* falls through */
  9553. // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
  9554. case 0x0f:
  9555. // logger.log('AAC PID:' + pid);
  9556. if (result.audio === -1) {
  9557. result.audio = pid;
  9558. }
  9559. break;
  9560. // Packetized metadata (ID3)
  9561. case 0x15:
  9562. // logger.log('ID3 PID:' + pid);
  9563. if (result.id3 === -1) {
  9564. result.id3 = pid;
  9565. }
  9566. break;
  9567. case 0xdb:
  9568. // SAMPLE-AES AVC
  9569. if (!isSampleAes) {
  9570. _logger.logger.log('unkown stream type:' + data[offset]);
  9571. break;
  9572. }
  9573. /* falls through */
  9574. // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
  9575. case 0x1b:
  9576. // logger.log('AVC PID:' + pid);
  9577. if (result.avc === -1) {
  9578. result.avc = pid;
  9579. }
  9580. break;
  9581. // ISO/IEC 11172-3 (MPEG-1 audio)
  9582. // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
  9583. case 0x03:
  9584. case 0x04:
  9585. // logger.log('MPEG PID:' + pid);
  9586. if (!mpegSupported) {
  9587. _logger.logger.log('MPEG audio found, not supported in this browser for now');
  9588. } else if (result.audio === -1) {
  9589. result.audio = pid;
  9590. result.isAAC = false;
  9591. }
  9592. break;
  9593. case 0x24:
  9594. _logger.logger.warn('HEVC stream type found, not supported for now');
  9595. break;
  9596. default:
  9597. _logger.logger.log('unkown stream type:' + data[offset]);
  9598. break;
  9599. }
  9600. // move to the next table entry
  9601. // skip past the elementary stream descriptors, if present
  9602. offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;
  9603. }
  9604. return result;
  9605. }
  9606. }, {
  9607. key: '_parsePES',
  9608. value: function _parsePES(stream) {
  9609. var i = 0,
  9610. frag = void 0,
  9611. pesFlags = void 0,
  9612. pesPrefix = void 0,
  9613. pesLen = void 0,
  9614. pesHdrLen = void 0,
  9615. pesData = void 0,
  9616. pesPts = void 0,
  9617. pesDts = void 0,
  9618. payloadStartOffset = void 0,
  9619. data = stream.data;
  9620. // safety check
  9621. if (!stream || stream.size === 0) {
  9622. return null;
  9623. }
  9624. // we might need up to 19 bytes to read PES header
  9625. // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
  9626. // usually only one merge is needed (and this is rare ...)
  9627. while (data[0].length < 19 && data.length > 1) {
  9628. var newData = new Uint8Array(data[0].length + data[1].length);
  9629. newData.set(data[0]);
  9630. newData.set(data[1], data[0].length);
  9631. data[0] = newData;
  9632. data.splice(1, 1);
  9633. }
  9634. // retrieve PTS/DTS from first fragment
  9635. frag = data[0];
  9636. pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  9637. if (pesPrefix === 1) {
  9638. pesLen = (frag[4] << 8) + frag[5];
  9639. // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
  9640. // minus 6 : PES header size
  9641. if (pesLen && pesLen > stream.size - 6) {
  9642. return null;
  9643. }
  9644. pesFlags = frag[7];
  9645. if (pesFlags & 0xC0) {
  9646. /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  9647. as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
  9648. as Bitwise operators treat their operands as a sequence of 32 bits */
  9649. pesPts = (frag[9] & 0x0E) * 536870912 + // 1 << 29
  9650. (frag[10] & 0xFF) * 4194304 + // 1 << 22
  9651. (frag[11] & 0xFE) * 16384 + // 1 << 14
  9652. (frag[12] & 0xFF) * 128 + // 1 << 7
  9653. (frag[13] & 0xFE) / 2;
  9654. // check if greater than 2^32 -1
  9655. if (pesPts > 4294967295) {
  9656. // decrement 2^33
  9657. pesPts -= 8589934592;
  9658. }
  9659. if (pesFlags & 0x40) {
  9660. pesDts = (frag[14] & 0x0E) * 536870912 + // 1 << 29
  9661. (frag[15] & 0xFF) * 4194304 + // 1 << 22
  9662. (frag[16] & 0xFE) * 16384 + // 1 << 14
  9663. (frag[17] & 0xFF) * 128 + // 1 << 7
  9664. (frag[18] & 0xFE) / 2;
  9665. // check if greater than 2^32 -1
  9666. if (pesDts > 4294967295) {
  9667. // decrement 2^33
  9668. pesDts -= 8589934592;
  9669. }
  9670. if (pesPts - pesDts > 60 * 90000) {
  9671. _logger.logger.warn(Math.round((pesPts - pesDts) / 90000) + 's delta between PTS and DTS, align them');
  9672. pesPts = pesDts;
  9673. }
  9674. } else {
  9675. pesDts = pesPts;
  9676. }
  9677. }
  9678. pesHdrLen = frag[8];
  9679. // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
  9680. payloadStartOffset = pesHdrLen + 9;
  9681. stream.size -= payloadStartOffset;
  9682. // reassemble PES packet
  9683. pesData = new Uint8Array(stream.size);
  9684. for (var j = 0, dataLen = data.length; j < dataLen; j++) {
  9685. frag = data[j];
  9686. var len = frag.byteLength;
  9687. if (payloadStartOffset) {
  9688. if (payloadStartOffset > len) {
  9689. // trim full frag if PES header bigger than frag
  9690. payloadStartOffset -= len;
  9691. continue;
  9692. } else {
  9693. // trim partial frag if PES header smaller than frag
  9694. frag = frag.subarray(payloadStartOffset);
  9695. len -= payloadStartOffset;
  9696. payloadStartOffset = 0;
  9697. }
  9698. }
  9699. pesData.set(frag, i);
  9700. i += len;
  9701. }
  9702. if (pesLen) {
  9703. // payload size : remove PES header + PES extension
  9704. pesLen -= pesHdrLen + 3;
  9705. }
  9706. return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen };
  9707. } else {
  9708. return null;
  9709. }
  9710. }
  9711. }, {
  9712. key: 'pushAccesUnit',
  9713. value: function pushAccesUnit(avcSample, avcTrack) {
  9714. if (avcSample.units.length && avcSample.frame) {
  9715. var samples = avcTrack.samples;
  9716. var nbSamples = samples.length;
  9717. // only push AVC sample if starting with a keyframe is not mandatory OR
  9718. // if keyframe already found in this fragment OR
  9719. // keyframe found in last fragment (track.sps) AND
  9720. // samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous
  9721. if (!this.config.forceKeyFrameOnDiscontinuity || avcSample.key === true || avcTrack.sps && (nbSamples || this.contiguous)) {
  9722. avcSample.id = nbSamples;
  9723. samples.push(avcSample);
  9724. } else {
  9725. // dropped samples, track it
  9726. avcTrack.dropped++;
  9727. }
  9728. }
  9729. if (avcSample.debug.length) {
  9730. _logger.logger.log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);
  9731. }
  9732. }
  9733. }, {
  9734. key: '_parseAVCPES',
  9735. value: function _parseAVCPES(pes, last) {
  9736. var _this = this;
  9737. // logger.log('parse new PES');
  9738. var track = this._avcTrack,
  9739. units = this._parseAVCNALu(pes.data),
  9740. debug = false,
  9741. expGolombDecoder = void 0,
  9742. avcSample = this.avcSample,
  9743. push = void 0,
  9744. spsfound = false,
  9745. i = void 0,
  9746. pushAccesUnit = this.pushAccesUnit.bind(this),
  9747. createAVCSample = function createAVCSample(key, pts, dts, debug) {
  9748. return { key: key, pts: pts, dts: dts, units: [], debug: debug };
  9749. };
  9750. // free pes.data to save up some memory
  9751. pes.data = null;
  9752. // if new NAL units found and last sample still there, let's push ...
  9753. // this helps parsing streams with missing AUD (only do this if AUD never found)
  9754. if (avcSample && units.length && !track.audFound) {
  9755. pushAccesUnit(avcSample, track);
  9756. avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');
  9757. }
  9758. units.forEach(function (unit) {
  9759. switch (unit.type) {
  9760. // NDR
  9761. case 1:
  9762. push = true;
  9763. if (!avcSample) {
  9764. avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
  9765. }
  9766. if (debug) {
  9767. avcSample.debug += 'NDR ';
  9768. }
  9769. avcSample.frame = true;
  9770. var data = unit.data;
  9771. // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
  9772. if (spsfound && data.length > 4) {
  9773. // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
  9774. var sliceType = new _expGolomb2.default(data).readSliceType();
  9775. // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
  9776. // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
  9777. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
  9778. // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
  9779. // if (sliceType === 2 || sliceType === 7) {
  9780. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  9781. avcSample.key = true;
  9782. }
  9783. }
  9784. break;
  9785. // IDR
  9786. case 5:
  9787. push = true;
  9788. // handle PES not starting with AUD
  9789. if (!avcSample) {
  9790. avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
  9791. }
  9792. if (debug) {
  9793. avcSample.debug += 'IDR ';
  9794. }
  9795. avcSample.key = true;
  9796. avcSample.frame = true;
  9797. break;
  9798. // SEI
  9799. case 6:
  9800. push = true;
  9801. if (debug && avcSample) {
  9802. avcSample.debug += 'SEI ';
  9803. }
  9804. expGolombDecoder = new _expGolomb2.default(_this.discardEPB(unit.data));
  9805. // skip frameType
  9806. expGolombDecoder.readUByte();
  9807. var payloadType = 0;
  9808. var payloadSize = 0;
  9809. var endOfCaptions = false;
  9810. var b = 0;
  9811. while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {
  9812. payloadType = 0;
  9813. do {
  9814. b = expGolombDecoder.readUByte();
  9815. payloadType += b;
  9816. } while (b === 0xFF);
  9817. // Parse payload size.
  9818. payloadSize = 0;
  9819. do {
  9820. b = expGolombDecoder.readUByte();
  9821. payloadSize += b;
  9822. } while (b === 0xFF);
  9823. // TODO: there can be more than one payload in an SEI packet...
  9824. // TODO: need to read type and size in a while loop to get them all
  9825. if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {
  9826. endOfCaptions = true;
  9827. var countryCode = expGolombDecoder.readUByte();
  9828. if (countryCode === 181) {
  9829. var providerCode = expGolombDecoder.readUShort();
  9830. if (providerCode === 49) {
  9831. var userStructure = expGolombDecoder.readUInt();
  9832. if (userStructure === 0x47413934) {
  9833. var userDataType = expGolombDecoder.readUByte();
  9834. // Raw CEA-608 bytes wrapped in CEA-708 packet
  9835. if (userDataType === 3) {
  9836. var firstByte = expGolombDecoder.readUByte();
  9837. var secondByte = expGolombDecoder.readUByte();
  9838. var totalCCs = 31 & firstByte;
  9839. var byteArray = [firstByte, secondByte];
  9840. for (i = 0; i < totalCCs; i++) {
  9841. // 3 bytes per CC
  9842. byteArray.push(expGolombDecoder.readUByte());
  9843. byteArray.push(expGolombDecoder.readUByte());
  9844. byteArray.push(expGolombDecoder.readUByte());
  9845. }
  9846. _this._insertSampleInOrder(_this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray });
  9847. }
  9848. }
  9849. }
  9850. }
  9851. } else if (payloadSize < expGolombDecoder.bytesAvailable) {
  9852. for (i = 0; i < payloadSize; i++) {
  9853. expGolombDecoder.readUByte();
  9854. }
  9855. }
  9856. }
  9857. break;
  9858. // SPS
  9859. case 7:
  9860. push = true;
  9861. spsfound = true;
  9862. if (debug && avcSample) {
  9863. avcSample.debug += 'SPS ';
  9864. }
  9865. if (!track.sps) {
  9866. expGolombDecoder = new _expGolomb2.default(unit.data);
  9867. var config = expGolombDecoder.readSPS();
  9868. track.width = config.width;
  9869. track.height = config.height;
  9870. track.pixelRatio = config.pixelRatio;
  9871. track.sps = [unit.data];
  9872. track.duration = _this._duration;
  9873. var codecarray = unit.data.subarray(1, 4);
  9874. var codecstring = 'avc1.';
  9875. for (i = 0; i < 3; i++) {
  9876. var h = codecarray[i].toString(16);
  9877. if (h.length < 2) {
  9878. h = '0' + h;
  9879. }
  9880. codecstring += h;
  9881. }
  9882. track.codec = codecstring;
  9883. }
  9884. break;
  9885. // PPS
  9886. case 8:
  9887. push = true;
  9888. if (debug && avcSample) {
  9889. avcSample.debug += 'PPS ';
  9890. }
  9891. if (!track.pps) {
  9892. track.pps = [unit.data];
  9893. }
  9894. break;
  9895. // AUD
  9896. case 9:
  9897. push = false;
  9898. track.audFound = true;
  9899. if (avcSample) {
  9900. pushAccesUnit(avcSample, track);
  9901. }
  9902. avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');
  9903. break;
  9904. // Filler Data
  9905. case 12:
  9906. push = false;
  9907. break;
  9908. default:
  9909. push = false;
  9910. if (avcSample) {
  9911. avcSample.debug += 'unknown NAL ' + unit.type + ' ';
  9912. }
  9913. break;
  9914. }
  9915. if (avcSample && push) {
  9916. var _units = avcSample.units;
  9917. _units.push(unit);
  9918. }
  9919. });
  9920. // if last PES packet, push samples
  9921. if (last && avcSample) {
  9922. pushAccesUnit(avcSample, track);
  9923. this.avcSample = null;
  9924. }
  9925. }
  9926. }, {
  9927. key: '_insertSampleInOrder',
  9928. value: function _insertSampleInOrder(arr, data) {
  9929. var len = arr.length;
  9930. if (len > 0) {
  9931. if (data.pts >= arr[len - 1].pts) {
  9932. arr.push(data);
  9933. } else {
  9934. for (var pos = len - 1; pos >= 0; pos--) {
  9935. if (data.pts < arr[pos].pts) {
  9936. arr.splice(pos, 0, data);
  9937. break;
  9938. }
  9939. }
  9940. }
  9941. } else {
  9942. arr.push(data);
  9943. }
  9944. }
  9945. }, {
  9946. key: '_getLastNalUnit',
  9947. value: function _getLastNalUnit() {
  9948. var avcSample = this.avcSample,
  9949. lastUnit = void 0;
  9950. // try to fallback to previous sample if current one is empty
  9951. if (!avcSample || avcSample.units.length === 0) {
  9952. var track = this._avcTrack,
  9953. samples = track.samples;
  9954. avcSample = samples[samples.length - 1];
  9955. }
  9956. if (avcSample) {
  9957. var units = avcSample.units;
  9958. lastUnit = units[units.length - 1];
  9959. }
  9960. return lastUnit;
  9961. }
  9962. }, {
  9963. key: '_parseAVCNALu',
  9964. value: function _parseAVCNALu(array) {
  9965. var i = 0,
  9966. len = array.byteLength,
  9967. value = void 0,
  9968. overflow = void 0,
  9969. track = this._avcTrack,
  9970. state = track.naluState || 0,
  9971. lastState = state;
  9972. var units = [],
  9973. unit = void 0,
  9974. unitType = void 0,
  9975. lastUnitStart = -1,
  9976. lastUnitType = void 0;
  9977. // logger.log('PES:' + Hex.hexDump(array));
  9978. if (state === -1) {
  9979. // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
  9980. lastUnitStart = 0;
  9981. // NALu type is value read from offset 0
  9982. lastUnitType = array[0] & 0x1f;
  9983. state = 0;
  9984. i = 1;
  9985. }
  9986. while (i < len) {
  9987. value = array[i++];
  9988. // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
  9989. if (!state) {
  9990. state = value ? 0 : 1;
  9991. continue;
  9992. }
  9993. if (state === 1) {
  9994. state = value ? 0 : 2;
  9995. continue;
  9996. }
  9997. // here we have state either equal to 2 or 3
  9998. if (!value) {
  9999. state = 3;
  10000. } else if (value === 1) {
  10001. if (lastUnitStart >= 0) {
  10002. unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType };
  10003. // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  10004. units.push(unit);
  10005. } else {
  10006. // lastUnitStart is undefined => this is the first start code found in this PES packet
  10007. // first check if start code delimiter is overlapping between 2 PES packets,
  10008. // ie it started in last packet (lastState not zero)
  10009. // and ended at the beginning of this PES packet (i <= 4 - lastState)
  10010. var lastUnit = this._getLastNalUnit();
  10011. if (lastUnit) {
  10012. if (lastState && i <= 4 - lastState) {
  10013. // start delimiter overlapping between PES packets
  10014. // strip start delimiter bytes from the end of last NAL unit
  10015. // check if lastUnit had a state different from zero
  10016. if (lastUnit.state) {
  10017. // strip last bytes
  10018. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  10019. }
  10020. }
  10021. // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
  10022. overflow = i - state - 1;
  10023. if (overflow > 0) {
  10024. // logger.log('first NALU found with overflow:' + overflow);
  10025. var tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
  10026. tmp.set(lastUnit.data, 0);
  10027. tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
  10028. lastUnit.data = tmp;
  10029. }
  10030. }
  10031. }
  10032. // check if we can read unit type
  10033. if (i < len) {
  10034. unitType = array[i] & 0x1f;
  10035. // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
  10036. lastUnitStart = i;
  10037. lastUnitType = unitType;
  10038. state = 0;
  10039. } else {
  10040. // not enough byte to read unit type. let's read it on next PES parsing
  10041. state = -1;
  10042. }
  10043. } else {
  10044. state = 0;
  10045. }
  10046. }
  10047. if (lastUnitStart >= 0 && state >= 0) {
  10048. unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType, state: state };
  10049. units.push(unit);
  10050. // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
  10051. }
  10052. // no NALu found
  10053. if (units.length === 0) {
  10054. // append pes.data to previous NAL unit
  10055. var _lastUnit = this._getLastNalUnit();
  10056. if (_lastUnit) {
  10057. var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength);
  10058. _tmp.set(_lastUnit.data, 0);
  10059. _tmp.set(array, _lastUnit.data.byteLength);
  10060. _lastUnit.data = _tmp;
  10061. }
  10062. }
  10063. track.naluState = state;
  10064. return units;
  10065. }
  10066. /**
  10067. * remove Emulation Prevention bytes from a RBSP
  10068. */
  10069. }, {
  10070. key: 'discardEPB',
  10071. value: function discardEPB(data) {
  10072. var length = data.byteLength,
  10073. EPBPositions = [],
  10074. i = 1,
  10075. newLength = void 0,
  10076. newData = void 0;
  10077. // Find all `Emulation Prevention Bytes`
  10078. while (i < length - 2) {
  10079. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  10080. EPBPositions.push(i + 2);
  10081. i += 2;
  10082. } else {
  10083. i++;
  10084. }
  10085. }
  10086. // If no Emulation Prevention Bytes were found just return the original
  10087. // array
  10088. if (EPBPositions.length === 0) {
  10089. return data;
  10090. }
  10091. // Create a new array to hold the NAL unit data
  10092. newLength = length - EPBPositions.length;
  10093. newData = new Uint8Array(newLength);
  10094. var sourceIndex = 0;
  10095. for (i = 0; i < newLength; sourceIndex++, i++) {
  10096. if (sourceIndex === EPBPositions[0]) {
  10097. // Skip this byte
  10098. sourceIndex++;
  10099. // Remove this position index
  10100. EPBPositions.shift();
  10101. }
  10102. newData[i] = data[sourceIndex];
  10103. }
  10104. return newData;
  10105. }
  10106. }, {
  10107. key: '_parseAACPES',
  10108. value: function _parseAACPES(pes) {
  10109. var track = this._audioTrack,
  10110. data = pes.data,
  10111. pts = pes.pts,
  10112. startOffset = 0,
  10113. aacOverFlow = this.aacOverFlow,
  10114. aacLastPTS = this.aacLastPTS,
  10115. frameDuration = void 0,
  10116. frameIndex = void 0,
  10117. offset = void 0,
  10118. stamp = void 0,
  10119. len = void 0;
  10120. if (aacOverFlow) {
  10121. var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);
  10122. tmp.set(aacOverFlow, 0);
  10123. tmp.set(data, aacOverFlow.byteLength);
  10124. // logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);
  10125. data = tmp;
  10126. }
  10127. // look for ADTS header (0xFFFx)
  10128. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  10129. if (ADTS.isHeader(data, offset)) {
  10130. break;
  10131. }
  10132. }
  10133. // if ADTS header does not start straight from the beginning of the PES payload, raise an error
  10134. if (offset) {
  10135. var reason = void 0,
  10136. fatal = void 0;
  10137. if (offset < len - 1) {
  10138. reason = 'AAC PES did not start with ADTS header,offset:' + offset;
  10139. fatal = false;
  10140. } else {
  10141. reason = 'no ADTS header found in AAC PES';
  10142. fatal = true;
  10143. }
  10144. _logger.logger.warn('parsing error:' + reason);
  10145. this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: fatal, reason: reason });
  10146. if (fatal) {
  10147. return;
  10148. }
  10149. }
  10150. ADTS.initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  10151. frameIndex = 0;
  10152. frameDuration = ADTS.getFrameDuration(track.samplerate);
  10153. // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
  10154. // first sample PTS should be equal to last sample PTS + frameDuration
  10155. if (aacOverFlow && aacLastPTS) {
  10156. var newPTS = aacLastPTS + frameDuration;
  10157. if (Math.abs(newPTS - pts) > 1) {
  10158. _logger.logger.log('AAC: align PTS for overlapping frames by ' + Math.round((newPTS - pts) / 90));
  10159. pts = newPTS;
  10160. }
  10161. }
  10162. // scan for aac samples
  10163. while (offset < len) {
  10164. if (ADTS.isHeader(data, offset) && offset + 5 < len) {
  10165. var frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);
  10166. if (frame) {
  10167. // logger.log(`${Math.round(frame.sample.pts)} : AAC`);
  10168. offset += frame.length;
  10169. stamp = frame.sample.pts;
  10170. frameIndex++;
  10171. } else {
  10172. // logger.log('Unable to parse AAC frame');
  10173. break;
  10174. }
  10175. } else {
  10176. // nothing found, keep looking
  10177. offset++;
  10178. }
  10179. }
  10180. if (offset < len) {
  10181. aacOverFlow = data.subarray(offset, len);
  10182. // logger.log(`AAC: overflow detected:${len-offset}`);
  10183. } else {
  10184. aacOverFlow = null;
  10185. }
  10186. this.aacOverFlow = aacOverFlow;
  10187. this.aacLastPTS = stamp;
  10188. }
  10189. }, {
  10190. key: '_parseMPEGPES',
  10191. value: function _parseMPEGPES(pes) {
  10192. var data = pes.data;
  10193. var length = data.length;
  10194. var frameIndex = 0;
  10195. var offset = 0;
  10196. var pts = pes.pts;
  10197. while (offset < length) {
  10198. if (_mpegaudio2.default.isHeader(data, offset)) {
  10199. var frame = _mpegaudio2.default.appendFrame(this._audioTrack, data, offset, pts, frameIndex);
  10200. if (frame) {
  10201. offset += frame.length;
  10202. frameIndex++;
  10203. } else {
  10204. // logger.log('Unable to parse Mpeg audio frame');
  10205. break;
  10206. }
  10207. } else {
  10208. // nothing found, keep looking
  10209. offset++;
  10210. }
  10211. }
  10212. }
  10213. }, {
  10214. key: '_parseID3PES',
  10215. value: function _parseID3PES(pes) {
  10216. this._id3Track.samples.push(pes);
  10217. }
  10218. }], [{
  10219. key: 'probe',
  10220. value: function probe(data) {
  10221. var syncOffset = TSDemuxer._syncOffset(data);
  10222. if (syncOffset < 0) {
  10223. return false;
  10224. } else {
  10225. if (syncOffset) {
  10226. _logger.logger.warn('MPEG2-TS detected but first sync word found @ offset ' + syncOffset + ', junk ahead ?');
  10227. }
  10228. return true;
  10229. }
  10230. }
  10231. }, {
  10232. key: '_syncOffset',
  10233. value: function _syncOffset(data) {
  10234. // scan 1000 first bytes
  10235. var scanwindow = Math.min(1000, data.length - 3 * 188);
  10236. var i = 0;
  10237. while (i < scanwindow) {
  10238. // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
  10239. if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {
  10240. return i;
  10241. } else {
  10242. i++;
  10243. }
  10244. }
  10245. return -1;
  10246. }
  10247. /**
  10248. * Creates a track model internal to demuxer used to drive remuxing input
  10249. *
  10250. * @param {string} type 'audio' | 'video' | 'id3' | 'text'
  10251. * @param {number} duration
  10252. * @return {object} TSDemuxer's internal track model
  10253. */
  10254. }, {
  10255. key: 'createTrack',
  10256. value: function createTrack(type, duration) {
  10257. return {
  10258. container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
  10259. type: type,
  10260. id: RemuxerTrackIdConfig[type],
  10261. pid: -1,
  10262. inputTimeScale: 90000,
  10263. sequenceNumber: 0,
  10264. samples: [],
  10265. len: 0,
  10266. dropped: type === 'video' ? 0 : undefined,
  10267. isAAC: type === 'audio' ? true : undefined,
  10268. duration: type === 'audio' ? duration : undefined
  10269. };
  10270. }
  10271. }]);
  10272. return TSDemuxer;
  10273. }();
  10274. exports.default = TSDemuxer;
  10275. module.exports = exports['default'];
  10276. /***/ }),
  10277. /* 47 */
  10278. /***/ (function(module, exports, __webpack_require__) {
  10279. "use strict";
  10280. Object.defineProperty(exports, "__esModule", {
  10281. value: true
  10282. });
  10283. 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; }; }(); /**
  10284. * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
  10285. */
  10286. var _logger = __webpack_require__(0);
  10287. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10288. var ExpGolomb = function () {
  10289. function ExpGolomb(data) {
  10290. _classCallCheck(this, ExpGolomb);
  10291. this.data = data;
  10292. // the number of bytes left to examine in this.data
  10293. this.bytesAvailable = data.byteLength;
  10294. // the current word being examined
  10295. this.word = 0; // :uint
  10296. // the number of bits left to examine in the current word
  10297. this.bitsAvailable = 0; // :uint
  10298. }
  10299. // ():void
  10300. _createClass(ExpGolomb, [{
  10301. key: 'loadWord',
  10302. value: function loadWord() {
  10303. var data = this.data,
  10304. bytesAvailable = this.bytesAvailable,
  10305. position = data.byteLength - bytesAvailable,
  10306. workingBytes = new Uint8Array(4),
  10307. availableBytes = Math.min(4, bytesAvailable);
  10308. if (availableBytes === 0) {
  10309. throw new Error('no bytes available');
  10310. }
  10311. workingBytes.set(data.subarray(position, position + availableBytes));
  10312. this.word = new DataView(workingBytes.buffer).getUint32(0);
  10313. // track the amount of this.data that has been processed
  10314. this.bitsAvailable = availableBytes * 8;
  10315. this.bytesAvailable -= availableBytes;
  10316. }
  10317. // (count:int):void
  10318. }, {
  10319. key: 'skipBits',
  10320. value: function skipBits(count) {
  10321. var skipBytes = void 0; // :int
  10322. if (this.bitsAvailable > count) {
  10323. this.word <<= count;
  10324. this.bitsAvailable -= count;
  10325. } else {
  10326. count -= this.bitsAvailable;
  10327. skipBytes = count >> 3;
  10328. count -= skipBytes >> 3;
  10329. this.bytesAvailable -= skipBytes;
  10330. this.loadWord();
  10331. this.word <<= count;
  10332. this.bitsAvailable -= count;
  10333. }
  10334. }
  10335. // (size:int):uint
  10336. }, {
  10337. key: 'readBits',
  10338. value: function readBits(size) {
  10339. var bits = Math.min(this.bitsAvailable, size),
  10340. // :uint
  10341. valu = this.word >>> 32 - bits; // :uint
  10342. if (size > 32) {
  10343. _logger.logger.error('Cannot read more than 32 bits at a time');
  10344. }
  10345. this.bitsAvailable -= bits;
  10346. if (this.bitsAvailable > 0) {
  10347. this.word <<= bits;
  10348. } else if (this.bytesAvailable > 0) {
  10349. this.loadWord();
  10350. }
  10351. bits = size - bits;
  10352. if (bits > 0 && this.bitsAvailable) {
  10353. return valu << bits | this.readBits(bits);
  10354. } else {
  10355. return valu;
  10356. }
  10357. }
  10358. // ():uint
  10359. }, {
  10360. key: 'skipLZ',
  10361. value: function skipLZ() {
  10362. var leadingZeroCount = void 0; // :uint
  10363. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  10364. if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
  10365. // the first bit of working word is 1
  10366. this.word <<= leadingZeroCount;
  10367. this.bitsAvailable -= leadingZeroCount;
  10368. return leadingZeroCount;
  10369. }
  10370. }
  10371. // we exhausted word and still have not found a 1
  10372. this.loadWord();
  10373. return leadingZeroCount + this.skipLZ();
  10374. }
  10375. // ():void
  10376. }, {
  10377. key: 'skipUEG',
  10378. value: function skipUEG() {
  10379. this.skipBits(1 + this.skipLZ());
  10380. }
  10381. // ():void
  10382. }, {
  10383. key: 'skipEG',
  10384. value: function skipEG() {
  10385. this.skipBits(1 + this.skipLZ());
  10386. }
  10387. // ():uint
  10388. }, {
  10389. key: 'readUEG',
  10390. value: function readUEG() {
  10391. var clz = this.skipLZ(); // :uint
  10392. return this.readBits(clz + 1) - 1;
  10393. }
  10394. // ():int
  10395. }, {
  10396. key: 'readEG',
  10397. value: function readEG() {
  10398. var valu = this.readUEG(); // :int
  10399. if (0x01 & valu) {
  10400. // the number is odd if the low order bit is set
  10401. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  10402. } else {
  10403. return -1 * (valu >>> 1); // divide by two then make it negative
  10404. }
  10405. }
  10406. // Some convenience functions
  10407. // :Boolean
  10408. }, {
  10409. key: 'readBoolean',
  10410. value: function readBoolean() {
  10411. return this.readBits(1) === 1;
  10412. }
  10413. // ():int
  10414. }, {
  10415. key: 'readUByte',
  10416. value: function readUByte() {
  10417. return this.readBits(8);
  10418. }
  10419. // ():int
  10420. }, {
  10421. key: 'readUShort',
  10422. value: function readUShort() {
  10423. return this.readBits(16);
  10424. }
  10425. // ():int
  10426. }, {
  10427. key: 'readUInt',
  10428. value: function readUInt() {
  10429. return this.readBits(32);
  10430. }
  10431. /**
  10432. * Advance the ExpGolomb decoder past a scaling list. The scaling
  10433. * list is optionally transmitted as part of a sequence parameter
  10434. * set and is not relevant to transmuxing.
  10435. * @param count {number} the number of entries in this scaling list
  10436. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  10437. */
  10438. }, {
  10439. key: 'skipScalingList',
  10440. value: function skipScalingList(count) {
  10441. var lastScale = 8,
  10442. nextScale = 8,
  10443. j = void 0,
  10444. deltaScale = void 0;
  10445. for (j = 0; j < count; j++) {
  10446. if (nextScale !== 0) {
  10447. deltaScale = this.readEG();
  10448. nextScale = (lastScale + deltaScale + 256) % 256;
  10449. }
  10450. lastScale = nextScale === 0 ? lastScale : nextScale;
  10451. }
  10452. }
  10453. /**
  10454. * Read a sequence parameter set and return some interesting video
  10455. * properties. A sequence parameter set is the H264 metadata that
  10456. * describes the properties of upcoming video frames.
  10457. * @param data {Uint8Array} the bytes of a sequence parameter set
  10458. * @return {object} an object with configuration parsed from the
  10459. * sequence parameter set, including the dimensions of the
  10460. * associated video frames.
  10461. */
  10462. }, {
  10463. key: 'readSPS',
  10464. value: function readSPS() {
  10465. var frameCropLeftOffset = 0,
  10466. frameCropRightOffset = 0,
  10467. frameCropTopOffset = 0,
  10468. frameCropBottomOffset = 0,
  10469. profileIdc = void 0,
  10470. profileCompat = void 0,
  10471. levelIdc = void 0,
  10472. numRefFramesInPicOrderCntCycle = void 0,
  10473. picWidthInMbsMinus1 = void 0,
  10474. picHeightInMapUnitsMinus1 = void 0,
  10475. frameMbsOnlyFlag = void 0,
  10476. scalingListCount = void 0,
  10477. i = void 0,
  10478. readUByte = this.readUByte.bind(this),
  10479. readBits = this.readBits.bind(this),
  10480. readUEG = this.readUEG.bind(this),
  10481. readBoolean = this.readBoolean.bind(this),
  10482. skipBits = this.skipBits.bind(this),
  10483. skipEG = this.skipEG.bind(this),
  10484. skipUEG = this.skipUEG.bind(this),
  10485. skipScalingList = this.skipScalingList.bind(this);
  10486. readUByte();
  10487. profileIdc = readUByte(); // profile_idc
  10488. profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5)
  10489. skipBits(3); // reserved_zero_3bits u(3),
  10490. levelIdc = readUByte(); // level_idc u(8)
  10491. skipUEG(); // seq_parameter_set_id
  10492. // some profiles have more optional data we don't need
  10493. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  10494. var chromaFormatIdc = readUEG();
  10495. if (chromaFormatIdc === 3) {
  10496. skipBits(1);
  10497. } // separate_colour_plane_flag
  10498. skipUEG(); // bit_depth_luma_minus8
  10499. skipUEG(); // bit_depth_chroma_minus8
  10500. skipBits(1); // qpprime_y_zero_transform_bypass_flag
  10501. if (readBoolean()) {
  10502. // seq_scaling_matrix_present_flag
  10503. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  10504. for (i = 0; i < scalingListCount; i++) {
  10505. if (readBoolean()) {
  10506. // seq_scaling_list_present_flag[ i ]
  10507. if (i < 6) {
  10508. skipScalingList(16);
  10509. } else {
  10510. skipScalingList(64);
  10511. }
  10512. }
  10513. }
  10514. }
  10515. }
  10516. skipUEG(); // log2_max_frame_num_minus4
  10517. var picOrderCntType = readUEG();
  10518. if (picOrderCntType === 0) {
  10519. readUEG(); // log2_max_pic_order_cnt_lsb_minus4
  10520. } else if (picOrderCntType === 1) {
  10521. skipBits(1); // delta_pic_order_always_zero_flag
  10522. skipEG(); // offset_for_non_ref_pic
  10523. skipEG(); // offset_for_top_to_bottom_field
  10524. numRefFramesInPicOrderCntCycle = readUEG();
  10525. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  10526. skipEG();
  10527. } // offset_for_ref_frame[ i ]
  10528. }
  10529. skipUEG(); // max_num_ref_frames
  10530. skipBits(1); // gaps_in_frame_num_value_allowed_flag
  10531. picWidthInMbsMinus1 = readUEG();
  10532. picHeightInMapUnitsMinus1 = readUEG();
  10533. frameMbsOnlyFlag = readBits(1);
  10534. if (frameMbsOnlyFlag === 0) {
  10535. skipBits(1);
  10536. } // mb_adaptive_frame_field_flag
  10537. skipBits(1); // direct_8x8_inference_flag
  10538. if (readBoolean()) {
  10539. // frame_cropping_flag
  10540. frameCropLeftOffset = readUEG();
  10541. frameCropRightOffset = readUEG();
  10542. frameCropTopOffset = readUEG();
  10543. frameCropBottomOffset = readUEG();
  10544. }
  10545. var pixelRatio = [1, 1];
  10546. if (readBoolean()) {
  10547. // vui_parameters_present_flag
  10548. if (readBoolean()) {
  10549. // aspect_ratio_info_present_flag
  10550. var aspectRatioIdc = readUByte();
  10551. switch (aspectRatioIdc) {
  10552. case 1:
  10553. pixelRatio = [1, 1];break;
  10554. case 2:
  10555. pixelRatio = [12, 11];break;
  10556. case 3:
  10557. pixelRatio = [10, 11];break;
  10558. case 4:
  10559. pixelRatio = [16, 11];break;
  10560. case 5:
  10561. pixelRatio = [40, 33];break;
  10562. case 6:
  10563. pixelRatio = [24, 11];break;
  10564. case 7:
  10565. pixelRatio = [20, 11];break;
  10566. case 8:
  10567. pixelRatio = [32, 11];break;
  10568. case 9:
  10569. pixelRatio = [80, 33];break;
  10570. case 10:
  10571. pixelRatio = [18, 11];break;
  10572. case 11:
  10573. pixelRatio = [15, 11];break;
  10574. case 12:
  10575. pixelRatio = [64, 33];break;
  10576. case 13:
  10577. pixelRatio = [160, 99];break;
  10578. case 14:
  10579. pixelRatio = [4, 3];break;
  10580. case 15:
  10581. pixelRatio = [3, 2];break;
  10582. case 16:
  10583. pixelRatio = [2, 1];break;
  10584. case 255:
  10585. {
  10586. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  10587. break;
  10588. }
  10589. }
  10590. }
  10591. }
  10592. return {
  10593. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  10594. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  10595. pixelRatio: pixelRatio
  10596. };
  10597. }
  10598. }, {
  10599. key: 'readSliceType',
  10600. value: function readSliceType() {
  10601. // skip NALu type
  10602. this.readUByte();
  10603. // discard first_mb_in_slice
  10604. this.readUEG();
  10605. // return slice_type
  10606. return this.readUEG();
  10607. }
  10608. }]);
  10609. return ExpGolomb;
  10610. }();
  10611. exports.default = ExpGolomb;
  10612. module.exports = exports['default'];
  10613. /***/ }),
  10614. /* 48 */
  10615. /***/ (function(module, exports, __webpack_require__) {
  10616. "use strict";
  10617. Object.defineProperty(exports, "__esModule", {
  10618. value: true
  10619. });
  10620. 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; }; }(); /**
  10621. * SAMPLE-AES decrypter
  10622. */
  10623. var _decrypter = __webpack_require__(12);
  10624. var _decrypter2 = _interopRequireDefault(_decrypter);
  10625. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  10626. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10627. var SampleAesDecrypter = function () {
  10628. function SampleAesDecrypter(observer, config, decryptdata, discardEPB) {
  10629. _classCallCheck(this, SampleAesDecrypter);
  10630. this.decryptdata = decryptdata;
  10631. this.discardEPB = discardEPB;
  10632. this.decrypter = new _decrypter2.default(observer, config, { removePKCS7Padding: false });
  10633. }
  10634. _createClass(SampleAesDecrypter, [{
  10635. key: 'decryptBuffer',
  10636. value: function decryptBuffer(encryptedData, callback) {
  10637. this.decrypter.decrypt(encryptedData, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, callback);
  10638. }
  10639. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  10640. }, {
  10641. key: 'decryptAacSample',
  10642. value: function decryptAacSample(samples, sampleIndex, callback, sync) {
  10643. var curUnit = samples[sampleIndex].unit;
  10644. var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  10645. var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  10646. var localthis = this;
  10647. this.decryptBuffer(encryptedBuffer, function (decryptedData) {
  10648. decryptedData = new Uint8Array(decryptedData);
  10649. curUnit.set(decryptedData, 16);
  10650. if (!sync) {
  10651. localthis.decryptAacSamples(samples, sampleIndex + 1, callback);
  10652. }
  10653. });
  10654. }
  10655. }, {
  10656. key: 'decryptAacSamples',
  10657. value: function decryptAacSamples(samples, sampleIndex, callback) {
  10658. for (;; sampleIndex++) {
  10659. if (sampleIndex >= samples.length) {
  10660. callback();
  10661. return;
  10662. }
  10663. if (samples[sampleIndex].unit.length < 32) {
  10664. continue;
  10665. }
  10666. var sync = this.decrypter.isSync();
  10667. this.decryptAacSample(samples, sampleIndex, callback, sync);
  10668. if (!sync) {
  10669. return;
  10670. }
  10671. }
  10672. }
  10673. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  10674. }, {
  10675. key: 'getAvcEncryptedData',
  10676. value: function getAvcEncryptedData(decodedData) {
  10677. var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  10678. var encryptedData = new Int8Array(encryptedDataLen);
  10679. var outputPos = 0;
  10680. for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {
  10681. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  10682. }
  10683. return encryptedData;
  10684. }
  10685. }, {
  10686. key: 'getAvcDecryptedUnit',
  10687. value: function getAvcDecryptedUnit(decodedData, decryptedData) {
  10688. decryptedData = new Uint8Array(decryptedData);
  10689. var inputPos = 0;
  10690. for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {
  10691. decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos);
  10692. }
  10693. return decodedData;
  10694. }
  10695. }, {
  10696. key: 'decryptAvcSample',
  10697. value: function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {
  10698. var decodedData = this.discardEPB(curUnit.data);
  10699. var encryptedData = this.getAvcEncryptedData(decodedData);
  10700. var localthis = this;
  10701. this.decryptBuffer(encryptedData.buffer, function (decryptedData) {
  10702. curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedData);
  10703. if (!sync) {
  10704. localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  10705. }
  10706. });
  10707. }
  10708. }, {
  10709. key: 'decryptAvcSamples',
  10710. value: function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  10711. for (;; sampleIndex++, unitIndex = 0) {
  10712. if (sampleIndex >= samples.length) {
  10713. callback();
  10714. return;
  10715. }
  10716. var curUnits = samples[sampleIndex].units;
  10717. for (;; unitIndex++) {
  10718. if (unitIndex >= curUnits.length) {
  10719. break;
  10720. }
  10721. var curUnit = curUnits[unitIndex];
  10722. if (curUnit.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  10723. continue;
  10724. }
  10725. var sync = this.decrypter.isSync();
  10726. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);
  10727. if (!sync) {
  10728. return;
  10729. }
  10730. }
  10731. }
  10732. }
  10733. }]);
  10734. return SampleAesDecrypter;
  10735. }();
  10736. exports.default = SampleAesDecrypter;
  10737. module.exports = exports['default'];
  10738. /***/ }),
  10739. /* 49 */
  10740. /***/ (function(module, exports, __webpack_require__) {
  10741. "use strict";
  10742. Object.defineProperty(exports, "__esModule", {
  10743. value: true
  10744. });
  10745. 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; }; }(); /**
  10746. * MP3 demuxer
  10747. */
  10748. var _id = __webpack_require__(10);
  10749. var _id2 = _interopRequireDefault(_id);
  10750. var _logger = __webpack_require__(0);
  10751. var _mpegaudio = __webpack_require__(23);
  10752. var _mpegaudio2 = _interopRequireDefault(_mpegaudio);
  10753. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  10754. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10755. var MP3Demuxer = function () {
  10756. function MP3Demuxer(observer, remuxer, config) {
  10757. _classCallCheck(this, MP3Demuxer);
  10758. this.observer = observer;
  10759. this.config = config;
  10760. this.remuxer = remuxer;
  10761. }
  10762. _createClass(MP3Demuxer, [{
  10763. key: 'resetInitSegment',
  10764. value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  10765. this._audioTrack = { container: 'audio/mpeg', type: 'audio', id: -1, sequenceNumber: 0, isAAC: false, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };
  10766. }
  10767. }, {
  10768. key: 'resetTimeStamp',
  10769. value: function resetTimeStamp() {}
  10770. }, {
  10771. key: 'append',
  10772. // feed incoming data to the front of the parsing pipeline
  10773. value: function append(data, timeOffset, contiguous, accurateTimeOffset) {
  10774. var id3Data = _id2.default.getID3Data(data, 0);
  10775. var timestamp = _id2.default.getTimeStamp(id3Data);
  10776. var pts = timestamp ? 90 * timestamp : timeOffset * 90000;
  10777. var offset = id3Data.length;
  10778. var length = data.length;
  10779. var frameIndex = 0,
  10780. stamp = 0;
  10781. var track = this._audioTrack;
  10782. var id3Samples = [{ pts: pts, dts: pts, data: id3Data }];
  10783. while (offset < length) {
  10784. if (_mpegaudio2.default.isHeader(data, offset)) {
  10785. var frame = _mpegaudio2.default.appendFrame(track, data, offset, pts, frameIndex);
  10786. if (frame) {
  10787. offset += frame.length;
  10788. stamp = frame.sample.pts;
  10789. frameIndex++;
  10790. } else {
  10791. // logger.log('Unable to parse Mpeg audio frame');
  10792. break;
  10793. }
  10794. } else if (_id2.default.isHeader(data, offset)) {
  10795. id3Data = _id2.default.getID3Data(data, offset);
  10796. id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });
  10797. offset += id3Data.length;
  10798. } else {
  10799. // nothing found, keep looking
  10800. offset++;
  10801. }
  10802. }
  10803. this.remuxer.remux(track, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset);
  10804. }
  10805. }, {
  10806. key: 'destroy',
  10807. value: function destroy() {}
  10808. }], [{
  10809. key: 'probe',
  10810. value: function probe(data) {
  10811. // check if data contains ID3 timestamp and MPEG sync word
  10812. var offset = void 0,
  10813. length = void 0;
  10814. var id3Data = _id2.default.getID3Data(data, 0);
  10815. if (id3Data && _id2.default.getTimeStamp(id3Data) !== undefined) {
  10816. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  10817. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  10818. // More info http://www.mp3-tech.org/programmer/frame_header.html
  10819. for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) {
  10820. if (_mpegaudio2.default.probe(data, offset)) {
  10821. _logger.logger.log('MPEG Audio sync word found !');
  10822. return true;
  10823. }
  10824. }
  10825. }
  10826. return false;
  10827. }
  10828. }]);
  10829. return MP3Demuxer;
  10830. }();
  10831. exports.default = MP3Demuxer;
  10832. module.exports = exports['default'];
  10833. /***/ }),
  10834. /* 50 */
  10835. /***/ (function(module, exports, __webpack_require__) {
  10836. "use strict";
  10837. Object.defineProperty(exports, "__esModule", {
  10838. value: true
  10839. });
  10840. 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; }; }(); /**
  10841. * fMP4 remuxer
  10842. */
  10843. var _aacHelper = __webpack_require__(51);
  10844. var _aacHelper2 = _interopRequireDefault(_aacHelper);
  10845. var _mp4Generator = __webpack_require__(52);
  10846. var _mp4Generator2 = _interopRequireDefault(_mp4Generator);
  10847. var _events = __webpack_require__(1);
  10848. var _events2 = _interopRequireDefault(_events);
  10849. var _errors = __webpack_require__(2);
  10850. var _logger = __webpack_require__(0);
  10851. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  10852. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10853. // 10 seconds
  10854. var MAX_SILENT_FRAME_DURATION = 10 * 1000;
  10855. var MP4Remuxer = function () {
  10856. function MP4Remuxer(observer, config, typeSupported, vendor) {
  10857. _classCallCheck(this, MP4Remuxer);
  10858. this.observer = observer;
  10859. this.config = config;
  10860. this.typeSupported = typeSupported;
  10861. var userAgent = navigator.userAgent;
  10862. this.isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS');
  10863. this.ISGenerated = false;
  10864. }
  10865. _createClass(MP4Remuxer, [{
  10866. key: 'destroy',
  10867. value: function destroy() {}
  10868. }, {
  10869. key: 'resetTimeStamp',
  10870. value: function resetTimeStamp(defaultTimeStamp) {
  10871. this._initPTS = this._initDTS = defaultTimeStamp;
  10872. }
  10873. }, {
  10874. key: 'resetInitSegment',
  10875. value: function resetInitSegment() {
  10876. this.ISGenerated = false;
  10877. }
  10878. }, {
  10879. key: 'remux',
  10880. value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  10881. // generate Init Segment if needed
  10882. if (!this.ISGenerated) {
  10883. this.generateIS(audioTrack, videoTrack, timeOffset);
  10884. }
  10885. if (this.ISGenerated) {
  10886. var nbAudioSamples = audioTrack.samples.length;
  10887. var nbVideoSamples = videoTrack.samples.length;
  10888. var audioTimeOffset = timeOffset;
  10889. var videoTimeOffset = timeOffset;
  10890. if (nbAudioSamples && nbVideoSamples) {
  10891. // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
  10892. // if first audio DTS is not aligned with first video DTS then we need to take that into account
  10893. // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
  10894. // drift between audio and video streams
  10895. var audiovideoDeltaDts = (audioTrack.samples[0].pts - videoTrack.samples[0].pts) / videoTrack.inputTimeScale;
  10896. audioTimeOffset += Math.max(0, audiovideoDeltaDts);
  10897. videoTimeOffset += Math.max(0, -audiovideoDeltaDts);
  10898. }
  10899. // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is
  10900. // calculated in remuxAudio.
  10901. // logger.log('nb AAC samples:' + audioTrack.samples.length);
  10902. if (nbAudioSamples) {
  10903. // if initSegment was generated without video samples, regenerate it again
  10904. if (!audioTrack.timescale) {
  10905. _logger.logger.warn('regenerate InitSegment as audio detected');
  10906. this.generateIS(audioTrack, videoTrack, timeOffset);
  10907. }
  10908. var audioData = this.remuxAudio(audioTrack, audioTimeOffset, contiguous, accurateTimeOffset);
  10909. // logger.log('nb AVC samples:' + videoTrack.samples.length);
  10910. if (nbVideoSamples) {
  10911. var audioTrackLength = void 0;
  10912. if (audioData) {
  10913. audioTrackLength = audioData.endPTS - audioData.startPTS;
  10914. }
  10915. // if initSegment was generated without video samples, regenerate it again
  10916. if (!videoTrack.timescale) {
  10917. _logger.logger.warn('regenerate InitSegment as video detected');
  10918. this.generateIS(audioTrack, videoTrack, timeOffset);
  10919. }
  10920. this.remuxVideo(videoTrack, videoTimeOffset, contiguous, audioTrackLength, accurateTimeOffset);
  10921. }
  10922. } else {
  10923. // logger.log('nb AVC samples:' + videoTrack.samples.length);
  10924. if (nbVideoSamples) {
  10925. var videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, accurateTimeOffset);
  10926. if (videoData && audioTrack.codec) {
  10927. this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);
  10928. }
  10929. }
  10930. }
  10931. }
  10932. // logger.log('nb ID3 samples:' + audioTrack.samples.length);
  10933. if (id3Track.samples.length) {
  10934. this.remuxID3(id3Track, timeOffset);
  10935. }
  10936. // logger.log('nb ID3 samples:' + audioTrack.samples.length);
  10937. if (textTrack.samples.length) {
  10938. this.remuxText(textTrack, timeOffset);
  10939. }
  10940. // notify end of parsing
  10941. this.observer.trigger(_events2.default.FRAG_PARSED);
  10942. }
  10943. }, {
  10944. key: 'generateIS',
  10945. value: function generateIS(audioTrack, videoTrack, timeOffset) {
  10946. var observer = this.observer,
  10947. audioSamples = audioTrack.samples,
  10948. videoSamples = videoTrack.samples,
  10949. typeSupported = this.typeSupported,
  10950. container = 'audio/mp4',
  10951. tracks = {},
  10952. data = { tracks: tracks },
  10953. computePTSDTS = this._initPTS === undefined,
  10954. initPTS = void 0,
  10955. initDTS = void 0;
  10956. if (computePTSDTS) {
  10957. initPTS = initDTS = Infinity;
  10958. }
  10959. if (audioTrack.config && audioSamples.length) {
  10960. // let's use audio sampling rate as MP4 time scale.
  10961. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
  10962. // using audio sampling rate here helps having an integer MP4 frame duration
  10963. // this avoids potential rounding issue and AV sync issue
  10964. audioTrack.timescale = audioTrack.samplerate;
  10965. _logger.logger.log('audio sampling rate : ' + audioTrack.samplerate);
  10966. if (!audioTrack.isAAC) {
  10967. if (typeSupported.mpeg) {
  10968. // Chrome and Safari
  10969. container = 'audio/mpeg';
  10970. audioTrack.codec = '';
  10971. } else if (typeSupported.mp3) {
  10972. // Firefox
  10973. audioTrack.codec = 'mp3';
  10974. }
  10975. }
  10976. tracks.audio = {
  10977. container: container,
  10978. codec: audioTrack.codec,
  10979. initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : _mp4Generator2.default.initSegment([audioTrack]),
  10980. metadata: {
  10981. channelCount: audioTrack.channelCount
  10982. }
  10983. };
  10984. if (computePTSDTS) {
  10985. // remember first PTS of this demuxing context. for audio, PTS = DTS
  10986. initPTS = initDTS = audioSamples[0].pts - audioTrack.inputTimeScale * timeOffset;
  10987. }
  10988. }
  10989. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  10990. // let's use input time scale as MP4 video timescale
  10991. // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
  10992. var inputTimeScale = videoTrack.inputTimeScale;
  10993. videoTrack.timescale = inputTimeScale;
  10994. tracks.video = {
  10995. container: 'video/mp4',
  10996. codec: videoTrack.codec,
  10997. initSegment: _mp4Generator2.default.initSegment([videoTrack]),
  10998. metadata: {
  10999. width: videoTrack.width,
  11000. height: videoTrack.height
  11001. }
  11002. };
  11003. if (computePTSDTS) {
  11004. initPTS = Math.min(initPTS, videoSamples[0].pts - inputTimeScale * timeOffset);
  11005. initDTS = Math.min(initDTS, videoSamples[0].dts - inputTimeScale * timeOffset);
  11006. this.observer.trigger(_events2.default.INIT_PTS_FOUND, { initPTS: initPTS });
  11007. }
  11008. }
  11009. if (Object.keys(tracks).length) {
  11010. observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, data);
  11011. this.ISGenerated = true;
  11012. if (computePTSDTS) {
  11013. this._initPTS = initPTS;
  11014. this._initDTS = initDTS;
  11015. }
  11016. } else {
  11017. observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' });
  11018. }
  11019. }
  11020. }, {
  11021. key: 'remuxVideo',
  11022. value: function remuxVideo(track, timeOffset, contiguous, audioTrackLength, accurateTimeOffset) {
  11023. var offset = 8;
  11024. var mp4SampleDuration = void 0;
  11025. var mdat = void 0;
  11026. var moof = void 0;
  11027. var firstPTS = void 0;
  11028. var firstDTS = void 0;
  11029. var lastPTS = void 0;
  11030. var lastDTS = void 0;
  11031. var timeScale = track.timescale;
  11032. var inputSamples = track.samples;
  11033. var outputSamples = [];
  11034. var nbSamples = inputSamples.length;
  11035. var ptsNormalize = this._PTSNormalize;
  11036. var initPTS = this._initPTS;
  11037. // if parsed fragment is contiguous with last one, let's use last DTS value as reference
  11038. var nextAvcDts = this.nextAvcDts;
  11039. var isSafari = this.isSafari;
  11040. if (nbSamples === 0) {
  11041. return;
  11042. }
  11043. // Safari does not like overlapping DTS on consecutive fragments. let's use nextAvcDts to overcome this if fragments are consecutive
  11044. if (isSafari) {
  11045. // also consider consecutive fragments as being contiguous (even if a level switch occurs),
  11046. // for sake of clarity:
  11047. // consecutive fragments are frags with
  11048. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  11049. // - less than 200 ms PTS gaps (timeScale/5)
  11050. contiguous |= inputSamples.length && nextAvcDts && (accurateTimeOffset && Math.abs(timeOffset - nextAvcDts / timeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAvcDts - initPTS) < timeScale / 5);
  11051. }
  11052. if (!contiguous) {
  11053. // if not contiguous, let's use target timeOffset
  11054. nextAvcDts = timeOffset * timeScale;
  11055. }
  11056. // PTS is coded on 33bits, and can loop from -2^32 to 2^32
  11057. // ptsNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
  11058. inputSamples.forEach(function (sample) {
  11059. sample.pts = ptsNormalize(sample.pts - initPTS, nextAvcDts);
  11060. sample.dts = ptsNormalize(sample.dts - initPTS, nextAvcDts);
  11061. });
  11062. // sort video samples by DTS then PTS then demux id order
  11063. inputSamples.sort(function (a, b) {
  11064. var deltadts = a.dts - b.dts;
  11065. var deltapts = a.pts - b.pts;
  11066. return deltadts || deltapts || a.id - b.id;
  11067. });
  11068. // handle broken streams with PTS < DTS, tolerance up 200ms (18000 in 90kHz timescale)
  11069. var PTSDTSshift = inputSamples.reduce(function (prev, curr) {
  11070. return Math.max(Math.min(prev, curr.pts - curr.dts), -18000);
  11071. }, 0);
  11072. if (PTSDTSshift < 0) {
  11073. _logger.logger.warn('PTS < DTS detected in video samples, shifting DTS by ' + Math.round(PTSDTSshift / 90) + ' ms to overcome this issue');
  11074. for (var i = 0; i < inputSamples.length; i++) {
  11075. inputSamples[i].dts += PTSDTSshift;
  11076. }
  11077. }
  11078. // compute first DTS and last DTS, normalize them against reference value
  11079. var sample = inputSamples[0];
  11080. firstDTS = Math.max(sample.dts, 0);
  11081. firstPTS = Math.max(sample.pts, 0);
  11082. // check timestamp continuity accross consecutive fragments (this is to remove inter-fragment gap/hole)
  11083. var delta = Math.round((firstDTS - nextAvcDts) / 90);
  11084. // if fragment are contiguous, detect hole/overlapping between fragments
  11085. if (contiguous) {
  11086. if (delta) {
  11087. if (delta > 1) {
  11088. _logger.logger.log('AVC:' + delta + ' ms hole between fragments detected,filling it');
  11089. } else if (delta < -1) {
  11090. _logger.logger.log('AVC:' + -delta + ' ms overlapping between fragments detected');
  11091. }
  11092. // remove hole/gap : set DTS to next expected DTS
  11093. firstDTS = nextAvcDts;
  11094. inputSamples[0].dts = firstDTS;
  11095. // offset PTS as well, ensure that PTS is smaller or equal than new DTS
  11096. firstPTS = Math.max(firstPTS - delta, nextAvcDts);
  11097. inputSamples[0].pts = firstPTS;
  11098. _logger.logger.log('Video/PTS/DTS adjusted: ' + Math.round(firstPTS / 90) + '/' + Math.round(firstDTS / 90) + ',delta:' + delta + ' ms');
  11099. }
  11100. }
  11101. // compute lastPTS/lastDTS
  11102. sample = inputSamples[inputSamples.length - 1];
  11103. lastDTS = Math.max(sample.dts, 0);
  11104. lastPTS = Math.max(sample.pts, 0, lastDTS);
  11105. // on Safari let's signal the same sample duration for all samples
  11106. // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
  11107. // set this constant duration as being the avg delta between consecutive DTS.
  11108. if (isSafari) {
  11109. mp4SampleDuration = Math.round((lastDTS - firstDTS) / (inputSamples.length - 1));
  11110. }
  11111. var nbNalu = 0,
  11112. naluLen = 0;
  11113. for (var _i = 0; _i < nbSamples; _i++) {
  11114. // compute total/avc sample length and nb of NAL units
  11115. var _sample = inputSamples[_i],
  11116. units = _sample.units,
  11117. nbUnits = units.length,
  11118. sampleLen = 0;
  11119. for (var j = 0; j < nbUnits; j++) {
  11120. sampleLen += units[j].data.length;
  11121. }
  11122. naluLen += sampleLen;
  11123. nbNalu += nbUnits;
  11124. _sample.length = sampleLen;
  11125. // normalize PTS/DTS
  11126. if (isSafari) {
  11127. // sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples
  11128. _sample.dts = firstDTS + _i * mp4SampleDuration;
  11129. } else {
  11130. // ensure sample monotonic DTS
  11131. _sample.dts = Math.max(_sample.dts, firstDTS);
  11132. }
  11133. // ensure that computed value is greater or equal than sample DTS
  11134. _sample.pts = Math.max(_sample.pts, _sample.dts);
  11135. }
  11136. /* concatenate the video data and construct the mdat in place
  11137. (need 8 more bytes to fill length and mpdat type) */
  11138. var mdatSize = naluLen + 4 * nbNalu + 8;
  11139. try {
  11140. mdat = new Uint8Array(mdatSize);
  11141. } catch (err) {
  11142. 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 });
  11143. return;
  11144. }
  11145. var view = new DataView(mdat.buffer);
  11146. view.setUint32(0, mdatSize);
  11147. mdat.set(_mp4Generator2.default.types.mdat, 4);
  11148. for (var _i2 = 0; _i2 < nbSamples; _i2++) {
  11149. var avcSample = inputSamples[_i2],
  11150. avcSampleUnits = avcSample.units,
  11151. mp4SampleLength = 0,
  11152. compositionTimeOffset = void 0;
  11153. // convert NALU bitstream to MP4 format (prepend NALU with size field)
  11154. for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) {
  11155. var unit = avcSampleUnits[_j],
  11156. unitData = unit.data,
  11157. unitDataLen = unit.data.byteLength;
  11158. view.setUint32(offset, unitDataLen);
  11159. offset += 4;
  11160. mdat.set(unitData, offset);
  11161. offset += unitDataLen;
  11162. mp4SampleLength += 4 + unitDataLen;
  11163. }
  11164. if (!isSafari) {
  11165. // expected sample duration is the Decoding Timestamp diff of consecutive samples
  11166. if (_i2 < nbSamples - 1) {
  11167. mp4SampleDuration = inputSamples[_i2 + 1].dts - avcSample.dts;
  11168. } else {
  11169. var config = this.config,
  11170. lastFrameDuration = avcSample.dts - inputSamples[_i2 > 0 ? _i2 - 1 : _i2].dts;
  11171. if (config.stretchShortVideoTrack) {
  11172. // In some cases, a segment's audio track duration may exceed the video track duration.
  11173. // Since we've already remuxed audio, and we know how long the audio track is, we look to
  11174. // see if the delta to the next segment is longer than maxBufferHole.
  11175. // If so, playback would potentially get stuck, so we artificially inflate
  11176. // the duration of the last frame to minimize any potential gap between segments.
  11177. var maxBufferHole = config.maxBufferHole,
  11178. gapTolerance = Math.floor(maxBufferHole * timeScale),
  11179. deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;
  11180. if (deltaToFrameEnd > gapTolerance) {
  11181. // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
  11182. // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
  11183. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  11184. if (mp4SampleDuration < 0) {
  11185. mp4SampleDuration = lastFrameDuration;
  11186. }
  11187. _logger.logger.log('It is approximately ' + deltaToFrameEnd / 90 + ' ms to the next segment; using duration ' + mp4SampleDuration / 90 + ' ms for the last video frame.');
  11188. } else {
  11189. mp4SampleDuration = lastFrameDuration;
  11190. }
  11191. } else {
  11192. mp4SampleDuration = lastFrameDuration;
  11193. }
  11194. }
  11195. compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);
  11196. } else {
  11197. compositionTimeOffset = Math.max(0, mp4SampleDuration * Math.round((avcSample.pts - avcSample.dts) / mp4SampleDuration));
  11198. }
  11199. // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');
  11200. // console.log(`avcSample.dts: ${avcSample.dts / 90}, avcSample.pts: ${avcSample.pts / 90}, mp4SampleDuration: ${mp4SampleDuration / 90}`, avcSample)
  11201. outputSamples.push({
  11202. size: mp4SampleLength,
  11203. // constant duration
  11204. duration: mp4SampleDuration,
  11205. cts: compositionTimeOffset,
  11206. flags: {
  11207. isLeading: 0,
  11208. isDependedOn: 0,
  11209. hasRedundancy: 0,
  11210. degradPrio: 0,
  11211. dependsOn: avcSample.key ? 2 : 1,
  11212. isNonSync: avcSample.key ? 0 : 1
  11213. }
  11214. });
  11215. }
  11216. // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
  11217. this.nextAvcDts = lastDTS + mp4SampleDuration;
  11218. var dropped = track.dropped;
  11219. track.len = 0;
  11220. track.nbNalu = 0;
  11221. track.dropped = 0;
  11222. if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
  11223. var flags = outputSamples[0].flags;
  11224. // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue
  11225. // https://code.google.com/p/chromium/issues/detail?id=229412
  11226. flags.dependsOn = 2;
  11227. flags.isNonSync = 0;
  11228. }
  11229. track.samples = outputSamples;
  11230. moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstDTS, track);
  11231. track.samples = [];
  11232. var data = {
  11233. data1: moof,
  11234. data2: mdat,
  11235. startPTS: firstPTS / timeScale,
  11236. endPTS: (lastPTS + mp4SampleDuration) / timeScale,
  11237. startDTS: firstDTS / timeScale,
  11238. endDTS: this.nextAvcDts / timeScale,
  11239. type: 'video',
  11240. hasAudio: false,
  11241. hasVideo: true,
  11242. nb: outputSamples.length,
  11243. dropped: dropped
  11244. };
  11245. this.observer.trigger(_events2.default.FRAG_PARSING_DATA, data);
  11246. return data;
  11247. }
  11248. }, {
  11249. key: 'remuxAudio',
  11250. value: function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset) {
  11251. var inputTimeScale = track.inputTimeScale;
  11252. var mp4timeScale = track.timescale;
  11253. var scaleFactor = inputTimeScale / mp4timeScale;
  11254. var mp4SampleDuration = track.isAAC ? 1024 : 1152;
  11255. var inputSampleDuration = mp4SampleDuration * scaleFactor;
  11256. var ptsNormalize = this._PTSNormalize;
  11257. var initPTS = this._initPTS;
  11258. var rawMPEG = !track.isAAC && this.typeSupported.mpeg;
  11259. var offset = void 0,
  11260. mp4Sample = void 0,
  11261. fillFrame = void 0,
  11262. mdat = void 0,
  11263. moof = void 0,
  11264. firstPTS = void 0,
  11265. lastPTS = void 0,
  11266. inputSamples = track.samples,
  11267. outputSamples = [],
  11268. nextAudioPts = this.nextAudioPts;
  11269. // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
  11270. // for sake of clarity:
  11271. // consecutive fragments are frags with
  11272. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  11273. // - less than 20 audio frames distance
  11274. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  11275. // this helps ensuring audio continuity
  11276. // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
  11277. contiguous |= inputSamples.length && nextAudioPts && (accurateTimeOffset && Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAudioPts - initPTS) < 20 * inputSampleDuration);
  11278. // compute normalized PTS
  11279. inputSamples.forEach(function (sample) {
  11280. sample.pts = sample.dts = ptsNormalize(sample.pts - initPTS, timeOffset * inputTimeScale);
  11281. });
  11282. // filter out sample with negative PTS that are not playable anyway
  11283. // if we don't remove these negative samples, they will shift all audio samples forward.
  11284. // leading to audio overlap between current / next fragment
  11285. inputSamples = inputSamples.filter(function (sample) {
  11286. return sample.pts >= 0;
  11287. });
  11288. // in case all samples have negative PTS, and have been filtered out, return now
  11289. if (inputSamples.length === 0) {
  11290. return;
  11291. }
  11292. if (!contiguous) {
  11293. if (!accurateTimeOffset) {
  11294. // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
  11295. nextAudioPts = inputSamples[0].pts;
  11296. } else {
  11297. // if timeOffset is accurate, let's use it as predicted next audio PTS
  11298. nextAudioPts = timeOffset * inputTimeScale;
  11299. }
  11300. }
  11301. // If the audio track is missing samples, the frames seem to get "left-shifted" within the
  11302. // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
  11303. // In an effort to prevent this from happening, we inject frames here where there are gaps.
  11304. // When possible, we inject a silent frame; when that's not possible, we duplicate the last
  11305. // frame.
  11306. if (track.isAAC) {
  11307. var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  11308. for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length;) {
  11309. // First, let's see how far off this frame is from where we expect it to be
  11310. var sample = inputSamples[i],
  11311. delta;
  11312. var pts = sample.pts;
  11313. delta = pts - nextPts;
  11314. var duration = Math.abs(1000 * delta / inputTimeScale);
  11315. // If we're overlapping by more than a duration, drop this sample
  11316. if (delta <= -maxAudioFramesDrift * inputSampleDuration) {
  11317. _logger.logger.warn('Dropping 1 audio frame @ ' + (nextPts / inputTimeScale).toFixed(3) + 's due to ' + Math.round(duration) + ' ms overlap.');
  11318. inputSamples.splice(i, 1);
  11319. track.len -= sample.unit.length;
  11320. // Don't touch nextPtsNorm or i
  11321. } // eslint-disable-line brace-style
  11322. // Insert missing frames if:
  11323. // 1: We're more than maxAudioFramesDrift frame away
  11324. // 2: Not more than MAX_SILENT_FRAME_DURATION away
  11325. // 3: currentTime (aka nextPtsNorm) is not 0
  11326. else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && nextPts) {
  11327. var missing = Math.round(delta / inputSampleDuration);
  11328. _logger.logger.warn('Injecting ' + missing + ' audio frame @ ' + (nextPts / inputTimeScale).toFixed(3) + 's due to ' + Math.round(1000 * delta / inputTimeScale) + ' ms gap.');
  11329. for (var j = 0; j < missing; j++) {
  11330. var newStamp = Math.max(nextPts, 0);
  11331. fillFrame = _aacHelper2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  11332. if (!fillFrame) {
  11333. _logger.logger.log('Unable to get silent frame for given audio codec; duplicating last frame instead.');
  11334. fillFrame = sample.unit.subarray();
  11335. }
  11336. inputSamples.splice(i, 0, { unit: fillFrame, pts: newStamp, dts: newStamp });
  11337. track.len += fillFrame.length;
  11338. nextPts += inputSampleDuration;
  11339. i++;
  11340. }
  11341. // Adjust sample to next expected pts
  11342. sample.pts = sample.dts = nextPts;
  11343. nextPts += inputSampleDuration;
  11344. i++;
  11345. } else {
  11346. // Otherwise, just adjust pts
  11347. if (Math.abs(delta) > 0.1 * inputSampleDuration) {
  11348. // logger.log(`Invalid frame delta ${Math.round(delta + inputSampleDuration)} at PTS ${Math.round(pts / 90)} (should be ${Math.round(inputSampleDuration)}).`);
  11349. }
  11350. sample.pts = sample.dts = nextPts;
  11351. nextPts += inputSampleDuration;
  11352. i++;
  11353. }
  11354. }
  11355. }
  11356. for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
  11357. var audioSample = inputSamples[_j2];
  11358. var unit = audioSample.unit;
  11359. var _pts = audioSample.pts;
  11360. // logger.log(`Audio/PTS:${Math.round(pts/90)}`);
  11361. // if not first sample
  11362. if (lastPTS !== undefined) {
  11363. mp4Sample.duration = Math.round((_pts - lastPTS) / scaleFactor);
  11364. } else {
  11365. var _delta = Math.round(1000 * (_pts - nextAudioPts) / inputTimeScale),
  11366. numMissingFrames = 0;
  11367. // if fragment are contiguous, detect hole/overlapping between fragments
  11368. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  11369. if (contiguous && track.isAAC) {
  11370. // log delta
  11371. if (_delta) {
  11372. if (_delta > 0 && _delta < MAX_SILENT_FRAME_DURATION) {
  11373. numMissingFrames = Math.round((_pts - nextAudioPts) / inputSampleDuration);
  11374. _logger.logger.log(_delta + ' ms hole between AAC samples detected,filling it');
  11375. if (numMissingFrames > 0) {
  11376. fillFrame = _aacHelper2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  11377. if (!fillFrame) {
  11378. fillFrame = unit.subarray();
  11379. }
  11380. track.len += numMissingFrames * fillFrame.length;
  11381. }
  11382. // if we have frame overlap, overlapping for more than half a frame duraion
  11383. } else if (_delta < -12) {
  11384. // drop overlapping audio frames... browser will deal with it
  11385. _logger.logger.log('drop overlapping AAC sample, expected/parsed/delta:' + (nextAudioPts / inputTimeScale).toFixed(3) + 's/' + (_pts / inputTimeScale).toFixed(3) + 's/' + -_delta + 'ms');
  11386. track.len -= unit.byteLength;
  11387. continue;
  11388. }
  11389. // set PTS/DTS to expected PTS/DTS
  11390. _pts = nextAudioPts;
  11391. }
  11392. }
  11393. // remember first PTS of our audioSamples
  11394. firstPTS = _pts;
  11395. if (track.len > 0) {
  11396. /* concatenate the audio data and construct the mdat in place
  11397. (need 8 more bytes to fill length and mdat type) */
  11398. var mdatSize = rawMPEG ? track.len : track.len + 8;
  11399. offset = rawMPEG ? 0 : 8;
  11400. try {
  11401. mdat = new Uint8Array(mdatSize);
  11402. } catch (err) {
  11403. 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 });
  11404. return;
  11405. }
  11406. if (!rawMPEG) {
  11407. var view = new DataView(mdat.buffer);
  11408. view.setUint32(0, mdatSize);
  11409. mdat.set(_mp4Generator2.default.types.mdat, 4);
  11410. }
  11411. } else {
  11412. // no audio samples
  11413. return;
  11414. }
  11415. for (var _i3 = 0; _i3 < numMissingFrames; _i3++) {
  11416. fillFrame = _aacHelper2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  11417. if (!fillFrame) {
  11418. _logger.logger.log('Unable to get silent frame for given audio codec; duplicating this frame instead.');
  11419. fillFrame = unit.subarray();
  11420. }
  11421. mdat.set(fillFrame, offset);
  11422. offset += fillFrame.byteLength;
  11423. mp4Sample = {
  11424. size: fillFrame.byteLength,
  11425. cts: 0,
  11426. duration: 1024,
  11427. flags: {
  11428. isLeading: 0,
  11429. isDependedOn: 0,
  11430. hasRedundancy: 0,
  11431. degradPrio: 0,
  11432. dependsOn: 1
  11433. }
  11434. };
  11435. outputSamples.push(mp4Sample);
  11436. }
  11437. }
  11438. mdat.set(unit, offset);
  11439. var unitLen = unit.byteLength;
  11440. offset += unitLen;
  11441. // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${audioSample.pts}/${audioSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(audioSample.pts/4294967296).toFixed(3)}');
  11442. mp4Sample = {
  11443. size: unitLen,
  11444. cts: 0,
  11445. duration: 0,
  11446. flags: {
  11447. isLeading: 0,
  11448. isDependedOn: 0,
  11449. hasRedundancy: 0,
  11450. degradPrio: 0,
  11451. dependsOn: 1
  11452. }
  11453. };
  11454. outputSamples.push(mp4Sample);
  11455. lastPTS = _pts;
  11456. }
  11457. var lastSampleDuration = 0;
  11458. var nbSamples = outputSamples.length;
  11459. // set last sample duration as being identical to previous sample
  11460. if (nbSamples >= 2) {
  11461. lastSampleDuration = outputSamples[nbSamples - 2].duration;
  11462. mp4Sample.duration = lastSampleDuration;
  11463. }
  11464. if (nbSamples) {
  11465. // next audio sample PTS should be equal to last sample PTS + duration
  11466. this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSampleDuration;
  11467. // logger.log('Audio/PTS/PTSend:' + audioSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));
  11468. track.len = 0;
  11469. track.samples = outputSamples;
  11470. if (rawMPEG) {
  11471. moof = new Uint8Array();
  11472. } else {
  11473. moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstPTS / scaleFactor, track);
  11474. }
  11475. track.samples = [];
  11476. var start = firstPTS / inputTimeScale;
  11477. var end = nextAudioPts / inputTimeScale;
  11478. var audioData = {
  11479. data1: moof,
  11480. data2: mdat,
  11481. startPTS: start,
  11482. endPTS: end,
  11483. startDTS: start,
  11484. endDTS: end,
  11485. type: 'audio',
  11486. hasAudio: true,
  11487. hasVideo: false,
  11488. nb: nbSamples
  11489. };
  11490. this.observer.trigger(_events2.default.FRAG_PARSING_DATA, audioData);
  11491. return audioData;
  11492. }
  11493. return null;
  11494. }
  11495. }, {
  11496. key: 'remuxEmptyAudio',
  11497. value: function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
  11498. var inputTimeScale = track.inputTimeScale,
  11499. mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale,
  11500. scaleFactor = inputTimeScale / mp4timeScale,
  11501. nextAudioPts = this.nextAudioPts,
  11502. // sync with video's timestamp
  11503. startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS,
  11504. endDTS = videoData.endDTS * inputTimeScale + this._initDTS,
  11505. // one sample's duration value
  11506. sampleDuration = 1024,
  11507. frameDuration = scaleFactor * sampleDuration,
  11508. // samples count of this segment's duration
  11509. nbSamples = Math.ceil((endDTS - startDTS) / frameDuration),
  11510. // silent frame
  11511. silentFrame = _aacHelper2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  11512. _logger.logger.warn('remux empty Audio');
  11513. // Can't remux if we can't generate a silent frame...
  11514. if (!silentFrame) {
  11515. _logger.logger.trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');
  11516. return;
  11517. }
  11518. var samples = [];
  11519. for (var i = 0; i < nbSamples; i++) {
  11520. var stamp = startDTS + i * frameDuration;
  11521. samples.push({ unit: silentFrame, pts: stamp, dts: stamp });
  11522. track.len += silentFrame.length;
  11523. }
  11524. track.samples = samples;
  11525. this.remuxAudio(track, timeOffset, contiguous);
  11526. }
  11527. }, {
  11528. key: 'remuxID3',
  11529. value: function remuxID3(track) {
  11530. var length = track.samples.length,
  11531. sample = void 0;
  11532. var inputTimeScale = track.inputTimeScale;
  11533. var initPTS = this._initPTS;
  11534. var initDTS = this._initDTS;
  11535. // consume samples
  11536. if (length) {
  11537. for (var index = 0; index < length; index++) {
  11538. sample = track.samples[index];
  11539. // setting id3 pts, dts to relative time
  11540. // using this._initPTS and this._initDTS to calculate relative time
  11541. sample.pts = (sample.pts - initPTS) / inputTimeScale;
  11542. sample.dts = (sample.dts - initDTS) / inputTimeScale;
  11543. }
  11544. this.observer.trigger(_events2.default.FRAG_PARSING_METADATA, {
  11545. samples: track.samples
  11546. });
  11547. }
  11548. track.samples = [];
  11549. }
  11550. }, {
  11551. key: 'remuxText',
  11552. value: function remuxText(track) {
  11553. track.samples.sort(function (a, b) {
  11554. return a.pts - b.pts;
  11555. });
  11556. var length = track.samples.length,
  11557. sample = void 0;
  11558. var inputTimeScale = track.inputTimeScale;
  11559. var initPTS = this._initPTS;
  11560. // consume samples
  11561. if (length) {
  11562. for (var index = 0; index < length; index++) {
  11563. sample = track.samples[index];
  11564. // setting text pts, dts to relative time
  11565. // using this._initPTS and this._initDTS to calculate relative time
  11566. sample.pts = (sample.pts - initPTS) / inputTimeScale;
  11567. }
  11568. this.observer.trigger(_events2.default.FRAG_PARSING_USERDATA, {
  11569. samples: track.samples
  11570. });
  11571. }
  11572. track.samples = [];
  11573. }
  11574. }, {
  11575. key: '_PTSNormalize',
  11576. value: function _PTSNormalize(value, reference) {
  11577. var offset = void 0;
  11578. if (reference === undefined) {
  11579. return value;
  11580. }
  11581. if (reference < value) {
  11582. // - 2^33
  11583. offset = -8589934592;
  11584. } else {
  11585. // + 2^33
  11586. offset = 8589934592;
  11587. }
  11588. /* PTS is 33bit (from 0 to 2^33 -1)
  11589. if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
  11590. PTS looping occured. fill the gap */
  11591. while (Math.abs(value - reference) > 4294967296) {
  11592. value += offset;
  11593. }
  11594. return value;
  11595. }
  11596. }]);
  11597. return MP4Remuxer;
  11598. }();
  11599. exports.default = MP4Remuxer;
  11600. module.exports = exports['default'];
  11601. /***/ }),
  11602. /* 51 */
  11603. /***/ (function(module, exports, __webpack_require__) {
  11604. "use strict";
  11605. Object.defineProperty(exports, "__esModule", {
  11606. value: true
  11607. });
  11608. 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; }; }();
  11609. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  11610. /**
  11611. * AAC helper
  11612. */
  11613. var AAC = function () {
  11614. function AAC() {
  11615. _classCallCheck(this, AAC);
  11616. }
  11617. _createClass(AAC, null, [{
  11618. key: 'getSilentFrame',
  11619. value: function getSilentFrame(codec, channelCount) {
  11620. switch (codec) {
  11621. case 'mp4a.40.2':
  11622. if (channelCount === 1) {
  11623. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  11624. } else if (channelCount === 2) {
  11625. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  11626. } else if (channelCount === 3) {
  11627. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  11628. } else if (channelCount === 4) {
  11629. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  11630. } else if (channelCount === 5) {
  11631. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  11632. } else if (channelCount === 6) {
  11633. 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]);
  11634. }
  11635. break;
  11636. // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
  11637. default:
  11638. if (channelCount === 1) {
  11639. // 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
  11640. 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]);
  11641. } else if (channelCount === 2) {
  11642. // 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
  11643. 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]);
  11644. } else if (channelCount === 3) {
  11645. // 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
  11646. 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]);
  11647. }
  11648. break;
  11649. }
  11650. return null;
  11651. }
  11652. }]);
  11653. return AAC;
  11654. }();
  11655. exports.default = AAC;
  11656. module.exports = exports['default'];
  11657. /***/ }),
  11658. /* 52 */
  11659. /***/ (function(module, exports, __webpack_require__) {
  11660. "use strict";
  11661. Object.defineProperty(exports, "__esModule", {
  11662. value: true
  11663. });
  11664. 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; }; }();
  11665. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  11666. /**
  11667. * Generate MP4 Box
  11668. */
  11669. var UINT32_MAX = Math.pow(2, 32) - 1;
  11670. var MP4 = function () {
  11671. function MP4() {
  11672. _classCallCheck(this, MP4);
  11673. }
  11674. _createClass(MP4, null, [{
  11675. key: 'init',
  11676. value: function init() {
  11677. MP4.types = {
  11678. avc1: [], // codingname
  11679. avcC: [],
  11680. btrt: [],
  11681. dinf: [],
  11682. dref: [],
  11683. esds: [],
  11684. ftyp: [],
  11685. hdlr: [],
  11686. mdat: [],
  11687. mdhd: [],
  11688. mdia: [],
  11689. mfhd: [],
  11690. minf: [],
  11691. moof: [],
  11692. moov: [],
  11693. mp4a: [],
  11694. '.mp3': [],
  11695. mvex: [],
  11696. mvhd: [],
  11697. pasp: [],
  11698. sdtp: [],
  11699. stbl: [],
  11700. stco: [],
  11701. stsc: [],
  11702. stsd: [],
  11703. stsz: [],
  11704. stts: [],
  11705. tfdt: [],
  11706. tfhd: [],
  11707. traf: [],
  11708. trak: [],
  11709. trun: [],
  11710. trex: [],
  11711. tkhd: [],
  11712. vmhd: [],
  11713. smhd: []
  11714. };
  11715. var i = void 0;
  11716. for (i in MP4.types) {
  11717. if (MP4.types.hasOwnProperty(i)) {
  11718. MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  11719. }
  11720. }
  11721. var videoHdlr = new Uint8Array([0x00, // version 0
  11722. 0x00, 0x00, 0x00, // flags
  11723. 0x00, 0x00, 0x00, 0x00, // pre_defined
  11724. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  11725. 0x00, 0x00, 0x00, 0x00, // reserved
  11726. 0x00, 0x00, 0x00, 0x00, // reserved
  11727. 0x00, 0x00, 0x00, 0x00, // reserved
  11728. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  11729. ]);
  11730. var audioHdlr = new Uint8Array([0x00, // version 0
  11731. 0x00, 0x00, 0x00, // flags
  11732. 0x00, 0x00, 0x00, 0x00, // pre_defined
  11733. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  11734. 0x00, 0x00, 0x00, 0x00, // reserved
  11735. 0x00, 0x00, 0x00, 0x00, // reserved
  11736. 0x00, 0x00, 0x00, 0x00, // reserved
  11737. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  11738. ]);
  11739. MP4.HDLR_TYPES = {
  11740. 'video': videoHdlr,
  11741. 'audio': audioHdlr
  11742. };
  11743. var dref = new Uint8Array([0x00, // version 0
  11744. 0x00, 0x00, 0x00, // flags
  11745. 0x00, 0x00, 0x00, 0x01, // entry_count
  11746. 0x00, 0x00, 0x00, 0x0c, // entry_size
  11747. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  11748. 0x00, // version 0
  11749. 0x00, 0x00, 0x01 // entry_flags
  11750. ]);
  11751. var stco = new Uint8Array([0x00, // version
  11752. 0x00, 0x00, 0x00, // flags
  11753. 0x00, 0x00, 0x00, 0x00 // entry_count
  11754. ]);
  11755. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  11756. MP4.STSZ = new Uint8Array([0x00, // version
  11757. 0x00, 0x00, 0x00, // flags
  11758. 0x00, 0x00, 0x00, 0x00, // sample_size
  11759. 0x00, 0x00, 0x00, 0x00 // sample_count
  11760. ]);
  11761. MP4.VMHD = new Uint8Array([0x00, // version
  11762. 0x00, 0x00, 0x01, // flags
  11763. 0x00, 0x00, // graphicsmode
  11764. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  11765. ]);
  11766. MP4.SMHD = new Uint8Array([0x00, // version
  11767. 0x00, 0x00, 0x00, // flags
  11768. 0x00, 0x00, // balance
  11769. 0x00, 0x00 // reserved
  11770. ]);
  11771. MP4.STSD = new Uint8Array([0x00, // version 0
  11772. 0x00, 0x00, 0x00, // flags
  11773. 0x00, 0x00, 0x00, 0x01]); // entry_count
  11774. var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
  11775. var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
  11776. var minorVersion = new Uint8Array([0, 0, 0, 1]);
  11777. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  11778. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  11779. }
  11780. }, {
  11781. key: 'box',
  11782. value: function box(type) {
  11783. var payload = Array.prototype.slice.call(arguments, 1),
  11784. size = 8,
  11785. i = payload.length,
  11786. len = i,
  11787. result = void 0;
  11788. // calculate the total size we need to allocate
  11789. while (i--) {
  11790. size += payload[i].byteLength;
  11791. }
  11792. result = new Uint8Array(size);
  11793. result[0] = size >> 24 & 0xff;
  11794. result[1] = size >> 16 & 0xff;
  11795. result[2] = size >> 8 & 0xff;
  11796. result[3] = size & 0xff;
  11797. result.set(type, 4);
  11798. // copy the payload into the result
  11799. for (i = 0, size = 8; i < len; i++) {
  11800. // copy payload[i] array @ offset size
  11801. result.set(payload[i], size);
  11802. size += payload[i].byteLength;
  11803. }
  11804. return result;
  11805. }
  11806. }, {
  11807. key: 'hdlr',
  11808. value: function hdlr(type) {
  11809. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  11810. }
  11811. }, {
  11812. key: 'mdat',
  11813. value: function mdat(data) {
  11814. return MP4.box(MP4.types.mdat, data);
  11815. }
  11816. }, {
  11817. key: 'mdhd',
  11818. value: function mdhd(timescale, duration) {
  11819. duration *= timescale;
  11820. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  11821. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  11822. return MP4.box(MP4.types.mdhd, new Uint8Array([0x01, // version 1
  11823. 0x00, 0x00, 0x00, // flags
  11824. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
  11825. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
  11826. timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
  11827. 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)
  11828. 0x00, 0x00]));
  11829. }
  11830. }, {
  11831. key: 'mdia',
  11832. value: function mdia(track) {
  11833. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
  11834. }
  11835. }, {
  11836. key: 'mfhd',
  11837. value: function mfhd(sequenceNumber) {
  11838. return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
  11839. sequenceNumber >> 24, sequenceNumber >> 16 & 0xFF, sequenceNumber >> 8 & 0xFF, sequenceNumber & 0xFF // sequence_number
  11840. ]));
  11841. }
  11842. }, {
  11843. key: 'minf',
  11844. value: function minf(track) {
  11845. if (track.type === 'audio') {
  11846. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  11847. } else {
  11848. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  11849. }
  11850. }
  11851. }, {
  11852. key: 'moof',
  11853. value: function moof(sn, baseMediaDecodeTime, track) {
  11854. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  11855. }
  11856. /**
  11857. * @param tracks... (optional) {array} the tracks associated with this movie
  11858. */
  11859. }, {
  11860. key: 'moov',
  11861. value: function moov(tracks) {
  11862. var i = tracks.length,
  11863. boxes = [];
  11864. while (i--) {
  11865. boxes[i] = MP4.trak(tracks[i]);
  11866. }
  11867. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
  11868. }
  11869. }, {
  11870. key: 'mvex',
  11871. value: function mvex(tracks) {
  11872. var i = tracks.length,
  11873. boxes = [];
  11874. while (i--) {
  11875. boxes[i] = MP4.trex(tracks[i]);
  11876. }
  11877. return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
  11878. }
  11879. }, {
  11880. key: 'mvhd',
  11881. value: function mvhd(timescale, duration) {
  11882. duration *= timescale;
  11883. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  11884. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  11885. var bytes = new Uint8Array([0x01, // version 1
  11886. 0x00, 0x00, 0x00, // flags
  11887. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
  11888. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
  11889. timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
  11890. 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
  11891. 0x01, 0x00, // 1.0 volume
  11892. 0x00, 0x00, // reserved
  11893. 0x00, 0x00, 0x00, 0x00, // reserved
  11894. 0x00, 0x00, 0x00, 0x00, // reserved
  11895. 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
  11896. 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
  11897. 0xff, 0xff, 0xff, 0xff // next_track_ID
  11898. ]);
  11899. return MP4.box(MP4.types.mvhd, bytes);
  11900. }
  11901. }, {
  11902. key: 'sdtp',
  11903. value: function sdtp(track) {
  11904. var samples = track.samples || [],
  11905. bytes = new Uint8Array(4 + samples.length),
  11906. flags = void 0,
  11907. i = void 0;
  11908. // leave the full box header (4 bytes) all zero
  11909. // write the sample table
  11910. for (i = 0; i < samples.length; i++) {
  11911. flags = samples[i].flags;
  11912. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  11913. }
  11914. return MP4.box(MP4.types.sdtp, bytes);
  11915. }
  11916. }, {
  11917. key: 'stbl',
  11918. value: function stbl(track) {
  11919. 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));
  11920. }
  11921. }, {
  11922. key: 'avc1',
  11923. value: function avc1(track) {
  11924. var sps = [],
  11925. pps = [],
  11926. i = void 0,
  11927. data = void 0,
  11928. len = void 0;
  11929. // assemble the SPSs
  11930. for (i = 0; i < track.sps.length; i++) {
  11931. data = track.sps[i];
  11932. len = data.byteLength;
  11933. sps.push(len >>> 8 & 0xFF);
  11934. sps.push(len & 0xFF);
  11935. // SPS
  11936. sps = sps.concat(Array.prototype.slice.call(data));
  11937. }
  11938. // assemble the PPSs
  11939. for (i = 0; i < track.pps.length; i++) {
  11940. data = track.pps[i];
  11941. len = data.byteLength;
  11942. pps.push(len >>> 8 & 0xFF);
  11943. pps.push(len & 0xFF);
  11944. pps = pps.concat(Array.prototype.slice.call(data));
  11945. }
  11946. var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version
  11947. sps[3], // profile
  11948. sps[4], // profile compat
  11949. sps[5], // level
  11950. 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes
  11951. 0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
  11952. ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
  11953. ]).concat(pps))),
  11954. // "PPS"
  11955. width = track.width,
  11956. height = track.height,
  11957. hSpacing = track.pixelRatio[0],
  11958. vSpacing = track.pixelRatio[1];
  11959. return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved
  11960. 0x00, 0x00, 0x00, // reserved
  11961. 0x00, 0x01, // data_reference_index
  11962. 0x00, 0x00, // pre_defined
  11963. 0x00, 0x00, // reserved
  11964. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  11965. width >> 8 & 0xFF, width & 0xff, // width
  11966. height >> 8 & 0xFF, height & 0xff, // height
  11967. 0x00, 0x48, 0x00, 0x00, // horizresolution
  11968. 0x00, 0x48, 0x00, 0x00, // vertresolution
  11969. 0x00, 0x00, 0x00, 0x00, // reserved
  11970. 0x00, 0x01, // frame_count
  11971. 0x12, 0x64, 0x61, 0x69, 0x6C, // dailymotion/hls.js
  11972. 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
  11973. 0x00, 0x18, // depth = 24
  11974. 0x11, 0x11]), // pre_defined = -1
  11975. avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  11976. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  11977. 0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate
  11978. MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24, // hSpacing
  11979. hSpacing >> 16 & 0xFF, hSpacing >> 8 & 0xFF, hSpacing & 0xFF, vSpacing >> 24, // vSpacing
  11980. vSpacing >> 16 & 0xFF, vSpacing >> 8 & 0xFF, vSpacing & 0xFF])));
  11981. }
  11982. }, {
  11983. key: 'esds',
  11984. value: function esds(track) {
  11985. var configlen = track.config.length;
  11986. return new Uint8Array([0x00, // version 0
  11987. 0x00, 0x00, 0x00, // flags
  11988. 0x03, // descriptor_type
  11989. 0x17 + configlen, // length
  11990. 0x00, 0x01, // es_id
  11991. 0x00, // stream_priority
  11992. 0x04, // descriptor_type
  11993. 0x0f + configlen, // length
  11994. 0x40, // codec : mpeg4_audio
  11995. 0x15, // stream_type
  11996. 0x00, 0x00, 0x00, // buffer_size
  11997. 0x00, 0x00, 0x00, 0x00, // maxBitrate
  11998. 0x00, 0x00, 0x00, 0x00, // avgBitrate
  11999. 0x05 // descriptor_type
  12000. ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
  12001. }
  12002. }, {
  12003. key: 'mp4a',
  12004. value: function mp4a(track) {
  12005. var samplerate = track.samplerate;
  12006. return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved
  12007. 0x00, 0x00, 0x00, // reserved
  12008. 0x00, 0x01, // data_reference_index
  12009. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  12010. 0x00, track.channelCount, // channelcount
  12011. 0x00, 0x10, // sampleSize:16bits
  12012. 0x00, 0x00, 0x00, 0x00, // reserved2
  12013. samplerate >> 8 & 0xFF, samplerate & 0xff, //
  12014. 0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
  12015. }
  12016. }, {
  12017. key: 'mp3',
  12018. value: function mp3(track) {
  12019. var samplerate = track.samplerate;
  12020. return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved
  12021. 0x00, 0x00, 0x00, // reserved
  12022. 0x00, 0x01, // data_reference_index
  12023. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  12024. 0x00, track.channelCount, // channelcount
  12025. 0x00, 0x10, // sampleSize:16bits
  12026. 0x00, 0x00, 0x00, 0x00, // reserved2
  12027. samplerate >> 8 & 0xFF, samplerate & 0xff, //
  12028. 0x00, 0x00]));
  12029. }
  12030. }, {
  12031. key: 'stsd',
  12032. value: function stsd(track) {
  12033. if (track.type === 'audio') {
  12034. if (!track.isAAC && track.codec === 'mp3') {
  12035. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  12036. }
  12037. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  12038. } else {
  12039. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  12040. }
  12041. }
  12042. }, {
  12043. key: 'tkhd',
  12044. value: function tkhd(track) {
  12045. var id = track.id,
  12046. duration = track.duration * track.timescale,
  12047. width = track.width,
  12048. height = track.height,
  12049. upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)),
  12050. lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  12051. return MP4.box(MP4.types.tkhd, new Uint8Array([0x01, // version 1
  12052. 0x00, 0x00, 0x07, // flags
  12053. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
  12054. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
  12055. id >> 24 & 0xFF, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID
  12056. 0x00, 0x00, 0x00, 0x00, // reserved
  12057. 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
  12058. 0x00, 0x00, // layer
  12059. 0x00, 0x00, // alternate_group
  12060. 0x00, 0x00, // non-audio track volume
  12061. 0x00, 0x00, // reserved
  12062. 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
  12063. width >> 8 & 0xFF, width & 0xFF, 0x00, 0x00, // width
  12064. height >> 8 & 0xFF, height & 0xFF, 0x00, 0x00 // height
  12065. ]));
  12066. }
  12067. }, {
  12068. key: 'traf',
  12069. value: function traf(track, baseMediaDecodeTime) {
  12070. var sampleDependencyTable = MP4.sdtp(track),
  12071. id = track.id,
  12072. upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)),
  12073. lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  12074. return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0
  12075. 0x00, 0x00, 0x00, // flags
  12076. id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF]) // track_ID
  12077. ), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1
  12078. 0x00, 0x00, 0x00, // flags
  12079. 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
  12080. 20 + // tfdt
  12081. 8 + // traf header
  12082. 16 + // mfhd
  12083. 8 + // moof header
  12084. 8), // mdat header
  12085. sampleDependencyTable);
  12086. }
  12087. /**
  12088. * Generate a track box.
  12089. * @param track {object} a track definition
  12090. * @return {Uint8Array} the track box
  12091. */
  12092. }, {
  12093. key: 'trak',
  12094. value: function trak(track) {
  12095. track.duration = track.duration || 0xffffffff;
  12096. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  12097. }
  12098. }, {
  12099. key: 'trex',
  12100. value: function trex(track) {
  12101. var id = track.id;
  12102. return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0
  12103. 0x00, 0x00, 0x00, // flags
  12104. id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF, // track_ID
  12105. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  12106. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  12107. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  12108. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  12109. ]));
  12110. }
  12111. }, {
  12112. key: 'trun',
  12113. value: function trun(track, offset) {
  12114. var samples = track.samples || [],
  12115. len = samples.length,
  12116. arraylen = 12 + 16 * len,
  12117. array = new Uint8Array(arraylen),
  12118. i = void 0,
  12119. sample = void 0,
  12120. duration = void 0,
  12121. size = void 0,
  12122. flags = void 0,
  12123. cts = void 0;
  12124. offset += 8 + arraylen;
  12125. array.set([0x00, // version 0
  12126. 0x00, 0x0f, 0x01, // flags
  12127. len >>> 24 & 0xFF, len >>> 16 & 0xFF, len >>> 8 & 0xFF, len & 0xFF, // sample_count
  12128. offset >>> 24 & 0xFF, offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF // data_offset
  12129. ], 0);
  12130. for (i = 0; i < len; i++) {
  12131. sample = samples[i];
  12132. duration = sample.duration;
  12133. size = sample.size;
  12134. flags = sample.flags;
  12135. cts = sample.cts;
  12136. array.set([duration >>> 24 & 0xFF, duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, // sample_duration
  12137. size >>> 24 & 0xFF, size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, // sample_size
  12138. 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
  12139. cts >>> 24 & 0xFF, cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF // sample_composition_time_offset
  12140. ], 12 + 16 * i);
  12141. }
  12142. return MP4.box(MP4.types.trun, array);
  12143. }
  12144. }, {
  12145. key: 'initSegment',
  12146. value: function initSegment(tracks) {
  12147. if (!MP4.types) {
  12148. MP4.init();
  12149. }
  12150. var movie = MP4.moov(tracks),
  12151. result = void 0;
  12152. result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
  12153. result.set(MP4.FTYP);
  12154. result.set(movie, MP4.FTYP.byteLength);
  12155. return result;
  12156. }
  12157. }]);
  12158. return MP4;
  12159. }();
  12160. exports.default = MP4;
  12161. module.exports = exports['default'];
  12162. /***/ }),
  12163. /* 53 */
  12164. /***/ (function(module, exports, __webpack_require__) {
  12165. "use strict";
  12166. Object.defineProperty(exports, "__esModule", {
  12167. value: true
  12168. });
  12169. 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; }; }(); /**
  12170. * passthrough remuxer
  12171. */
  12172. var _events = __webpack_require__(1);
  12173. var _events2 = _interopRequireDefault(_events);
  12174. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12175. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  12176. var PassThroughRemuxer = function () {
  12177. function PassThroughRemuxer(observer) {
  12178. _classCallCheck(this, PassThroughRemuxer);
  12179. this.observer = observer;
  12180. }
  12181. _createClass(PassThroughRemuxer, [{
  12182. key: 'destroy',
  12183. value: function destroy() {}
  12184. }, {
  12185. key: 'resetTimeStamp',
  12186. value: function resetTimeStamp() {}
  12187. }, {
  12188. key: 'resetInitSegment',
  12189. value: function resetInitSegment() {}
  12190. }, {
  12191. key: 'remux',
  12192. value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset, rawData) {
  12193. var observer = this.observer;
  12194. var streamType = '';
  12195. if (audioTrack) {
  12196. streamType += 'audio';
  12197. }
  12198. if (videoTrack) {
  12199. streamType += 'video';
  12200. }
  12201. observer.trigger(_events2.default.FRAG_PARSING_DATA, {
  12202. data1: rawData,
  12203. startPTS: timeOffset,
  12204. startDTS: timeOffset,
  12205. type: streamType,
  12206. hasAudio: !!audioTrack,
  12207. hasVideo: !!videoTrack,
  12208. nb: 1,
  12209. dropped: 0
  12210. });
  12211. // notify end of parsing
  12212. observer.trigger(_events2.default.FRAG_PARSED);
  12213. }
  12214. }]);
  12215. return PassThroughRemuxer;
  12216. }();
  12217. exports.default = PassThroughRemuxer;
  12218. module.exports = exports['default'];
  12219. /***/ }),
  12220. /* 54 */
  12221. /***/ (function(module, exports, __webpack_require__) {
  12222. "use strict";
  12223. var has = Object.prototype.hasOwnProperty
  12224. , prefix = '~';
  12225. /**
  12226. * Constructor to create a storage for our `EE` objects.
  12227. * An `Events` instance is a plain object whose properties are event names.
  12228. *
  12229. * @constructor
  12230. * @private
  12231. */
  12232. function Events() {}
  12233. //
  12234. // We try to not inherit from `Object.prototype`. In some engines creating an
  12235. // instance in this way is faster than calling `Object.create(null)` directly.
  12236. // If `Object.create(null)` is not supported we prefix the event names with a
  12237. // character to make sure that the built-in object properties are not
  12238. // overridden or used as an attack vector.
  12239. //
  12240. if (Object.create) {
  12241. Events.prototype = Object.create(null);
  12242. //
  12243. // This hack is needed because the `__proto__` property is still inherited in
  12244. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  12245. //
  12246. if (!new Events().__proto__) prefix = false;
  12247. }
  12248. /**
  12249. * Representation of a single event listener.
  12250. *
  12251. * @param {Function} fn The listener function.
  12252. * @param {*} context The context to invoke the listener with.
  12253. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  12254. * @constructor
  12255. * @private
  12256. */
  12257. function EE(fn, context, once) {
  12258. this.fn = fn;
  12259. this.context = context;
  12260. this.once = once || false;
  12261. }
  12262. /**
  12263. * Add a listener for a given event.
  12264. *
  12265. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  12266. * @param {(String|Symbol)} event The event name.
  12267. * @param {Function} fn The listener function.
  12268. * @param {*} context The context to invoke the listener with.
  12269. * @param {Boolean} once Specify if the listener is a one-time listener.
  12270. * @returns {EventEmitter}
  12271. * @private
  12272. */
  12273. function addListener(emitter, event, fn, context, once) {
  12274. if (typeof fn !== 'function') {
  12275. throw new TypeError('The listener must be a function');
  12276. }
  12277. var listener = new EE(fn, context || emitter, once)
  12278. , evt = prefix ? prefix + event : event;
  12279. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  12280. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  12281. else emitter._events[evt] = [emitter._events[evt], listener];
  12282. return emitter;
  12283. }
  12284. /**
  12285. * Clear event by name.
  12286. *
  12287. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  12288. * @param {(String|Symbol)} evt The Event name.
  12289. * @private
  12290. */
  12291. function clearEvent(emitter, evt) {
  12292. if (--emitter._eventsCount === 0) emitter._events = new Events();
  12293. else delete emitter._events[evt];
  12294. }
  12295. /**
  12296. * Minimal `EventEmitter` interface that is molded against the Node.js
  12297. * `EventEmitter` interface.
  12298. *
  12299. * @constructor
  12300. * @public
  12301. */
  12302. function EventEmitter() {
  12303. this._events = new Events();
  12304. this._eventsCount = 0;
  12305. }
  12306. /**
  12307. * Return an array listing the events for which the emitter has registered
  12308. * listeners.
  12309. *
  12310. * @returns {Array}
  12311. * @public
  12312. */
  12313. EventEmitter.prototype.eventNames = function eventNames() {
  12314. var names = []
  12315. , events
  12316. , name;
  12317. if (this._eventsCount === 0) return names;
  12318. for (name in (events = this._events)) {
  12319. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  12320. }
  12321. if (Object.getOwnPropertySymbols) {
  12322. return names.concat(Object.getOwnPropertySymbols(events));
  12323. }
  12324. return names;
  12325. };
  12326. /**
  12327. * Return the listeners registered for a given event.
  12328. *
  12329. * @param {(String|Symbol)} event The event name.
  12330. * @returns {Array} The registered listeners.
  12331. * @public
  12332. */
  12333. EventEmitter.prototype.listeners = function listeners(event) {
  12334. var evt = prefix ? prefix + event : event
  12335. , handlers = this._events[evt];
  12336. if (!handlers) return [];
  12337. if (handlers.fn) return [handlers.fn];
  12338. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  12339. ee[i] = handlers[i].fn;
  12340. }
  12341. return ee;
  12342. };
  12343. /**
  12344. * Return the number of listeners listening to a given event.
  12345. *
  12346. * @param {(String|Symbol)} event The event name.
  12347. * @returns {Number} The number of listeners.
  12348. * @public
  12349. */
  12350. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  12351. var evt = prefix ? prefix + event : event
  12352. , listeners = this._events[evt];
  12353. if (!listeners) return 0;
  12354. if (listeners.fn) return 1;
  12355. return listeners.length;
  12356. };
  12357. /**
  12358. * Calls each of the listeners registered for a given event.
  12359. *
  12360. * @param {(String|Symbol)} event The event name.
  12361. * @returns {Boolean} `true` if the event had listeners, else `false`.
  12362. * @public
  12363. */
  12364. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  12365. var evt = prefix ? prefix + event : event;
  12366. if (!this._events[evt]) return false;
  12367. var listeners = this._events[evt]
  12368. , len = arguments.length
  12369. , args
  12370. , i;
  12371. if (listeners.fn) {
  12372. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  12373. switch (len) {
  12374. case 1: return listeners.fn.call(listeners.context), true;
  12375. case 2: return listeners.fn.call(listeners.context, a1), true;
  12376. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  12377. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  12378. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  12379. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  12380. }
  12381. for (i = 1, args = new Array(len -1); i < len; i++) {
  12382. args[i - 1] = arguments[i];
  12383. }
  12384. listeners.fn.apply(listeners.context, args);
  12385. } else {
  12386. var length = listeners.length
  12387. , j;
  12388. for (i = 0; i < length; i++) {
  12389. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  12390. switch (len) {
  12391. case 1: listeners[i].fn.call(listeners[i].context); break;
  12392. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  12393. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  12394. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  12395. default:
  12396. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  12397. args[j - 1] = arguments[j];
  12398. }
  12399. listeners[i].fn.apply(listeners[i].context, args);
  12400. }
  12401. }
  12402. }
  12403. return true;
  12404. };
  12405. /**
  12406. * Add a listener for a given event.
  12407. *
  12408. * @param {(String|Symbol)} event The event name.
  12409. * @param {Function} fn The listener function.
  12410. * @param {*} [context=this] The context to invoke the listener with.
  12411. * @returns {EventEmitter} `this`.
  12412. * @public
  12413. */
  12414. EventEmitter.prototype.on = function on(event, fn, context) {
  12415. return addListener(this, event, fn, context, false);
  12416. };
  12417. /**
  12418. * Add a one-time listener for a given event.
  12419. *
  12420. * @param {(String|Symbol)} event The event name.
  12421. * @param {Function} fn The listener function.
  12422. * @param {*} [context=this] The context to invoke the listener with.
  12423. * @returns {EventEmitter} `this`.
  12424. * @public
  12425. */
  12426. EventEmitter.prototype.once = function once(event, fn, context) {
  12427. return addListener(this, event, fn, context, true);
  12428. };
  12429. /**
  12430. * Remove the listeners of a given event.
  12431. *
  12432. * @param {(String|Symbol)} event The event name.
  12433. * @param {Function} fn Only remove the listeners that match this function.
  12434. * @param {*} context Only remove the listeners that have this context.
  12435. * @param {Boolean} once Only remove one-time listeners.
  12436. * @returns {EventEmitter} `this`.
  12437. * @public
  12438. */
  12439. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  12440. var evt = prefix ? prefix + event : event;
  12441. if (!this._events[evt]) return this;
  12442. if (!fn) {
  12443. clearEvent(this, evt);
  12444. return this;
  12445. }
  12446. var listeners = this._events[evt];
  12447. if (listeners.fn) {
  12448. if (
  12449. listeners.fn === fn &&
  12450. (!once || listeners.once) &&
  12451. (!context || listeners.context === context)
  12452. ) {
  12453. clearEvent(this, evt);
  12454. }
  12455. } else {
  12456. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  12457. if (
  12458. listeners[i].fn !== fn ||
  12459. (once && !listeners[i].once) ||
  12460. (context && listeners[i].context !== context)
  12461. ) {
  12462. events.push(listeners[i]);
  12463. }
  12464. }
  12465. //
  12466. // Reset the array, or remove it completely if we have no more listeners.
  12467. //
  12468. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  12469. else clearEvent(this, evt);
  12470. }
  12471. return this;
  12472. };
  12473. /**
  12474. * Remove all listeners, or those of the specified event.
  12475. *
  12476. * @param {(String|Symbol)} [event] The event name.
  12477. * @returns {EventEmitter} `this`.
  12478. * @public
  12479. */
  12480. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  12481. var evt;
  12482. if (event) {
  12483. evt = prefix ? prefix + event : event;
  12484. if (this._events[evt]) clearEvent(this, evt);
  12485. } else {
  12486. this._events = new Events();
  12487. this._eventsCount = 0;
  12488. }
  12489. return this;
  12490. };
  12491. //
  12492. // Alias methods names because people roll like that.
  12493. //
  12494. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  12495. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  12496. //
  12497. // Expose the prefix.
  12498. //
  12499. EventEmitter.prefixed = prefix;
  12500. //
  12501. // Allow `EventEmitter` to be imported as module namespace.
  12502. //
  12503. EventEmitter.EventEmitter = EventEmitter;
  12504. //
  12505. // Expose the module.
  12506. //
  12507. if (true) {
  12508. module.exports = EventEmitter;
  12509. }
  12510. /***/ }),
  12511. /* 55 */
  12512. /***/ (function(module, exports, __webpack_require__) {
  12513. "use strict";
  12514. Object.defineProperty(exports, "__esModule", {
  12515. value: true
  12516. });
  12517. var _demuxerInline = __webpack_require__(21);
  12518. var _demuxerInline2 = _interopRequireDefault(_demuxerInline);
  12519. var _events = __webpack_require__(1);
  12520. var _events2 = _interopRequireDefault(_events);
  12521. var _logger = __webpack_require__(0);
  12522. var _events3 = __webpack_require__(20);
  12523. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12524. /* demuxer web worker.
  12525. * - listen to worker message, and trigger DemuxerInline upon reception of Fragments.
  12526. * - 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.
  12527. */
  12528. var DemuxerWorker = function DemuxerWorker(self) {
  12529. // observer setup
  12530. var observer = new _events3.EventEmitter();
  12531. observer.trigger = function trigger(event) {
  12532. for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12533. data[_key - 1] = arguments[_key];
  12534. }
  12535. observer.emit.apply(observer, [event, event].concat(data));
  12536. };
  12537. observer.off = function off(event) {
  12538. for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  12539. data[_key2 - 1] = arguments[_key2];
  12540. }
  12541. observer.removeListener.apply(observer, [event].concat(data));
  12542. };
  12543. var forwardMessage = function forwardMessage(ev, data) {
  12544. self.postMessage({ event: ev, data: data });
  12545. };
  12546. self.addEventListener('message', function (ev) {
  12547. var data = ev.data;
  12548. // console.log('demuxer cmd:' + data.cmd);
  12549. switch (data.cmd) {
  12550. case 'init':
  12551. var config = JSON.parse(data.config);
  12552. self.demuxer = new _demuxerInline2.default(observer, data.typeSupported, config, data.vendor);
  12553. (0, _logger.enableLogs)(config.debug);
  12554. // signal end of worker init
  12555. forwardMessage('init', null);
  12556. break;
  12557. case 'demux':
  12558. 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);
  12559. break;
  12560. default:
  12561. break;
  12562. }
  12563. });
  12564. // forward events to main thread
  12565. observer.on(_events2.default.FRAG_DECRYPTED, forwardMessage);
  12566. observer.on(_events2.default.FRAG_PARSING_INIT_SEGMENT, forwardMessage);
  12567. observer.on(_events2.default.FRAG_PARSED, forwardMessage);
  12568. observer.on(_events2.default.ERROR, forwardMessage);
  12569. observer.on(_events2.default.FRAG_PARSING_METADATA, forwardMessage);
  12570. observer.on(_events2.default.FRAG_PARSING_USERDATA, forwardMessage);
  12571. observer.on(_events2.default.INIT_PTS_FOUND, forwardMessage);
  12572. // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy)
  12573. observer.on(_events2.default.FRAG_PARSING_DATA, function (ev, data) {
  12574. var transferable = [];
  12575. var message = { event: ev, data: data };
  12576. if (data.data1) {
  12577. message.data1 = data.data1.buffer;
  12578. transferable.push(data.data1.buffer);
  12579. delete data.data1;
  12580. }
  12581. if (data.data2) {
  12582. message.data2 = data.data2.buffer;
  12583. transferable.push(data.data2.buffer);
  12584. delete data.data2;
  12585. }
  12586. self.postMessage(message, transferable);
  12587. });
  12588. };
  12589. exports.default = DemuxerWorker;
  12590. module.exports = exports['default'];
  12591. /***/ }),
  12592. /* 56 */
  12593. /***/ (function(module, exports, __webpack_require__) {
  12594. "use strict";
  12595. Object.defineProperty(exports, "__esModule", {
  12596. value: true
  12597. });
  12598. 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; }; }();
  12599. var _bufferHelper = __webpack_require__(4);
  12600. var _errors = __webpack_require__(2);
  12601. var _events = __webpack_require__(1);
  12602. var _events2 = _interopRequireDefault(_events);
  12603. var _logger = __webpack_require__(0);
  12604. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12605. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  12606. var stallDebounceInterval = 1000;
  12607. var jumpThreshold = 0.5; // tolerance needed as some browsers stalls playback before reaching buffered range end
  12608. var GapController = function () {
  12609. function GapController(config, media, fragmentTracker, hls) {
  12610. _classCallCheck(this, GapController);
  12611. this.config = config;
  12612. this.media = media;
  12613. this.fragmentTracker = fragmentTracker;
  12614. this.hls = hls;
  12615. this.stallReported = false;
  12616. }
  12617. /**
  12618. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  12619. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  12620. * @param lastCurrentTime
  12621. * @param buffered
  12622. */
  12623. _createClass(GapController, [{
  12624. key: 'poll',
  12625. value: function poll(lastCurrentTime, buffered) {
  12626. var config = this.config,
  12627. media = this.media;
  12628. var currentTime = media.currentTime;
  12629. var tnow = window.performance.now();
  12630. if (currentTime !== lastCurrentTime) {
  12631. // The playhead is now moving, but was previously stalled
  12632. if (this.stallReported) {
  12633. _logger.logger.warn('playback not stuck anymore @' + currentTime + ', after ' + Math.round(tnow - this.stalled) + 'ms');
  12634. this.stallReported = false;
  12635. }
  12636. this.stalled = null;
  12637. this.nudgeRetry = 0;
  12638. return;
  12639. }
  12640. if (media.ended || !media.buffered.length || media.readyState > 2) {
  12641. return;
  12642. }
  12643. if (media.seeking && _bufferHelper.BufferHelper.isBuffered(media, currentTime)) {
  12644. return;
  12645. }
  12646. // The playhead isn't moving but it should be
  12647. // Allow some slack time to for small stalls to resolve themselves
  12648. var stalledDuration = tnow - this.stalled;
  12649. var bufferInfo = _bufferHelper.BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  12650. if (!this.stalled) {
  12651. this.stalled = tnow;
  12652. return;
  12653. } else if (stalledDuration >= stallDebounceInterval) {
  12654. // Report stalling after trying to fix
  12655. this._reportStall(bufferInfo.len);
  12656. }
  12657. this._tryFixBufferStall(bufferInfo, stalledDuration);
  12658. }
  12659. /**
  12660. * Detects and attempts to fix known buffer stalling issues.
  12661. * @param bufferInfo - The properties of the current buffer.
  12662. * @param stalledDuration - The amount of time Hls.js has been stalling for.
  12663. * @private
  12664. */
  12665. }, {
  12666. key: '_tryFixBufferStall',
  12667. value: function _tryFixBufferStall(bufferInfo, stalledDuration) {
  12668. var config = this.config,
  12669. fragmentTracker = this.fragmentTracker,
  12670. media = this.media;
  12671. var currentTime = media.currentTime;
  12672. var partial = fragmentTracker.getPartialFragment(currentTime);
  12673. if (partial) {
  12674. // Try to skip over the buffer hole caused by a partial fragment
  12675. // This method isn't limited by the size of the gap between buffered ranges
  12676. this._trySkipBufferHole(partial);
  12677. }
  12678. if (bufferInfo.len > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {
  12679. // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
  12680. // We only try to jump the hole if it's under the configured size
  12681. // Reset stalled so to rearm watchdog timer
  12682. this.stalled = null;
  12683. this._tryNudgeBuffer();
  12684. }
  12685. }
  12686. /**
  12687. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  12688. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  12689. * @private
  12690. */
  12691. }, {
  12692. key: '_reportStall',
  12693. value: function _reportStall(bufferLen) {
  12694. var hls = this.hls,
  12695. media = this.media,
  12696. stallReported = this.stallReported;
  12697. if (!stallReported) {
  12698. // Report stalled error once
  12699. this.stallReported = true;
  12700. _logger.logger.warn('Playback stalling at @' + media.currentTime + ' due to low buffer');
  12701. hls.trigger(_events2.default.ERROR, {
  12702. type: _errors.ErrorTypes.MEDIA_ERROR,
  12703. details: _errors.ErrorDetails.BUFFER_STALLED_ERROR,
  12704. fatal: false,
  12705. buffer: bufferLen
  12706. });
  12707. }
  12708. }
  12709. /**
  12710. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  12711. * @param partial - The partial fragment found at the current time (where playback is stalling).
  12712. * @private
  12713. */
  12714. }, {
  12715. key: '_trySkipBufferHole',
  12716. value: function _trySkipBufferHole(partial) {
  12717. var hls = this.hls,
  12718. media = this.media;
  12719. var currentTime = media.currentTime;
  12720. var lastEndTime = 0;
  12721. // Check if currentTime is between unbuffered regions of partial fragments
  12722. for (var i = 0; i < media.buffered.length; i++) {
  12723. var startTime = media.buffered.start(i);
  12724. if (currentTime >= lastEndTime && currentTime < startTime) {
  12725. media.currentTime = Math.max(startTime, media.currentTime + 0.1);
  12726. _logger.logger.warn('skipping hole, adjusting currentTime from ' + currentTime + ' to ' + media.currentTime);
  12727. this.stalled = null;
  12728. hls.trigger(_events2.default.ERROR, {
  12729. type: _errors.ErrorTypes.MEDIA_ERROR,
  12730. details: _errors.ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  12731. fatal: false,
  12732. reason: 'fragment loaded with buffer holes, seeking from ' + currentTime + ' to ' + media.currentTime,
  12733. frag: partial
  12734. });
  12735. return;
  12736. }
  12737. lastEndTime = media.buffered.end(i);
  12738. }
  12739. }
  12740. /**
  12741. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  12742. * @private
  12743. */
  12744. }, {
  12745. key: '_tryNudgeBuffer',
  12746. value: function _tryNudgeBuffer() {
  12747. var config = this.config,
  12748. hls = this.hls,
  12749. media = this.media;
  12750. var currentTime = media.currentTime;
  12751. var nudgeRetry = (this.nudgeRetry || 0) + 1;
  12752. this.nudgeRetry = nudgeRetry;
  12753. if (nudgeRetry < config.nudgeMaxRetry) {
  12754. var targetTime = currentTime + nudgeRetry * config.nudgeOffset;
  12755. _logger.logger.log('adjust currentTime from ' + currentTime + ' to ' + targetTime);
  12756. // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
  12757. media.currentTime = targetTime;
  12758. hls.trigger(_events2.default.ERROR, {
  12759. type: _errors.ErrorTypes.MEDIA_ERROR,
  12760. details: _errors.ErrorDetails.BUFFER_NUDGE_ON_STALL,
  12761. fatal: false
  12762. });
  12763. } else {
  12764. _logger.logger.error('still stuck in high buffer @' + currentTime + ' after ' + config.nudgeMaxRetry + ', raise fatal error');
  12765. hls.trigger(_events2.default.ERROR, {
  12766. type: _errors.ErrorTypes.MEDIA_ERROR,
  12767. details: _errors.ErrorDetails.BUFFER_STALLED_ERROR,
  12768. fatal: true
  12769. });
  12770. }
  12771. }
  12772. }]);
  12773. return GapController;
  12774. }();
  12775. exports.default = GapController;
  12776. module.exports = exports['default'];
  12777. /***/ }),
  12778. /* 57 */
  12779. /***/ (function(module, exports, __webpack_require__) {
  12780. "use strict";
  12781. Object.defineProperty(exports, "__esModule", {
  12782. value: true
  12783. });
  12784. 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; };
  12785. 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; }; }();
  12786. var _events = __webpack_require__(1);
  12787. var _events2 = _interopRequireDefault(_events);
  12788. var _eventHandler = __webpack_require__(3);
  12789. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  12790. var _logger = __webpack_require__(0);
  12791. var _errors = __webpack_require__(2);
  12792. var _codecs = __webpack_require__(18);
  12793. var _levelHelper = __webpack_require__(7);
  12794. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12795. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  12796. 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; }
  12797. 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; } /*
  12798. * Level Controller
  12799. */
  12800. var _window = window,
  12801. performance = _window.performance;
  12802. var chromeOrFirefox = void 0;
  12803. var LevelController = function (_EventHandler) {
  12804. _inherits(LevelController, _EventHandler);
  12805. function LevelController(hls) {
  12806. _classCallCheck(this, LevelController);
  12807. 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));
  12808. _this.canload = false;
  12809. _this.currentLevelIndex = null;
  12810. _this.manualLevelIndex = -1;
  12811. _this.timer = null;
  12812. chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());
  12813. return _this;
  12814. }
  12815. _createClass(LevelController, [{
  12816. key: 'onHandlerDestroying',
  12817. value: function onHandlerDestroying() {
  12818. this.clearTimer();
  12819. this.manualLevelIndex = -1;
  12820. }
  12821. }, {
  12822. key: 'clearTimer',
  12823. value: function clearTimer() {
  12824. if (this.timer !== null) {
  12825. clearTimeout(this.timer);
  12826. this.timer = null;
  12827. }
  12828. }
  12829. }, {
  12830. key: 'startLoad',
  12831. value: function startLoad() {
  12832. var levels = this._levels;
  12833. this.canload = true;
  12834. this.levelRetryCount = 0;
  12835. // clean up live level details to force reload them, and reset load errors
  12836. if (levels) {
  12837. levels.forEach(function (level) {
  12838. level.loadError = 0;
  12839. var levelDetails = level.details;
  12840. if (levelDetails && levelDetails.live) {
  12841. level.details = undefined;
  12842. }
  12843. });
  12844. }
  12845. // speed up live playlist refresh if timer exists
  12846. if (this.timer !== null) {
  12847. this.loadLevel();
  12848. }
  12849. }
  12850. }, {
  12851. key: 'stopLoad',
  12852. value: function stopLoad() {
  12853. this.canload = false;
  12854. }
  12855. }, {
  12856. key: 'onManifestLoaded',
  12857. value: function onManifestLoaded(data) {
  12858. var levels = [];
  12859. var audioTracks = [];
  12860. var bitrateStart = void 0;
  12861. var levelSet = {};
  12862. var levelFromSet = null;
  12863. var videoCodecFound = false;
  12864. var audioCodecFound = false;
  12865. // regroup redundant levels together
  12866. data.levels.forEach(function (level) {
  12867. var attributes = level.attrs;
  12868. level.loadError = 0;
  12869. level.fragmentError = false;
  12870. videoCodecFound = videoCodecFound || !!level.videoCodec;
  12871. audioCodecFound = audioCodecFound || !!level.audioCodec;
  12872. // erase audio codec info if browser does not support mp4a.40.34.
  12873. // demuxer will autodetect codec and fallback to mpeg/audio
  12874. if (chromeOrFirefox && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {
  12875. level.audioCodec = undefined;
  12876. }
  12877. levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here
  12878. if (!levelFromSet) {
  12879. level.url = [level.url];
  12880. level.urlId = 0;
  12881. levelSet[level.bitrate] = level;
  12882. levels.push(level);
  12883. } else {
  12884. levelFromSet.url.push(level.url);
  12885. }
  12886. if (attributes) {
  12887. if (attributes.AUDIO) {
  12888. audioCodecFound = true;
  12889. (0, _levelHelper.addGroupId)(levelFromSet || level, 'audio', attributes.AUDIO);
  12890. }
  12891. if (attributes.SUBTITLES) {
  12892. (0, _levelHelper.addGroupId)(levelFromSet || level, 'text', attributes.SUBTITLES);
  12893. }
  12894. }
  12895. });
  12896. // remove audio-only level if we also have levels with audio+video codecs signalled
  12897. if (videoCodecFound && audioCodecFound) {
  12898. levels = levels.filter(function (_ref) {
  12899. var videoCodec = _ref.videoCodec;
  12900. return !!videoCodec;
  12901. });
  12902. }
  12903. // only keep levels with supported audio/video codecs
  12904. levels = levels.filter(function (_ref2) {
  12905. var audioCodec = _ref2.audioCodec,
  12906. videoCodec = _ref2.videoCodec;
  12907. return (!audioCodec || (0, _codecs.isCodecSupportedInMp4)(audioCodec, 'audio')) && (!videoCodec || (0, _codecs.isCodecSupportedInMp4)(videoCodec, 'video'));
  12908. });
  12909. if (data.audioTracks) {
  12910. audioTracks = data.audioTracks.filter(function (track) {
  12911. return !track.audioCodec || (0, _codecs.isCodecSupportedInMp4)(track.audioCodec, 'audio');
  12912. });
  12913. // Reassign id's after filtering since they're used as array indices
  12914. audioTracks.forEach(function (track, index) {
  12915. track.id = index;
  12916. });
  12917. }
  12918. if (levels.length > 0) {
  12919. // start bitrate is the first bitrate of the manifest
  12920. bitrateStart = levels[0].bitrate;
  12921. // sort level on bitrate
  12922. levels.sort(function (a, b) {
  12923. return a.bitrate - b.bitrate;
  12924. });
  12925. this._levels = levels;
  12926. // find index of first level in sorted levels
  12927. for (var i = 0; i < levels.length; i++) {
  12928. if (levels[i].bitrate === bitrateStart) {
  12929. this._firstLevel = i;
  12930. _logger.logger.log('manifest loaded,' + levels.length + ' level(s) found, first bitrate:' + bitrateStart);
  12931. break;
  12932. }
  12933. }
  12934. // Audio is only alternate if manifest include a URI along with the audio group tag
  12935. this.hls.trigger(_events2.default.MANIFEST_PARSED, {
  12936. levels: levels,
  12937. audioTracks: audioTracks,
  12938. firstLevel: this._firstLevel,
  12939. stats: data.stats,
  12940. audio: audioCodecFound,
  12941. video: videoCodecFound,
  12942. altAudio: audioTracks.some(function (t) {
  12943. return !!t.url;
  12944. })
  12945. });
  12946. } else {
  12947. this.hls.trigger(_events2.default.ERROR, {
  12948. type: _errors.ErrorTypes.MEDIA_ERROR,
  12949. details: _errors.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  12950. fatal: true,
  12951. url: this.hls.url,
  12952. reason: 'no level with compatible codecs found in manifest'
  12953. });
  12954. }
  12955. }
  12956. }, {
  12957. key: 'setLevelInternal',
  12958. value: function setLevelInternal(newLevel) {
  12959. var levels = this._levels;
  12960. var hls = this.hls;
  12961. // check if level idx is valid
  12962. if (newLevel >= 0 && newLevel < levels.length) {
  12963. // stopping live reloading timer if any
  12964. this.clearTimer();
  12965. if (this.currentLevelIndex !== newLevel) {
  12966. _logger.logger.log('switching to level ' + newLevel);
  12967. this.currentLevelIndex = newLevel;
  12968. var levelProperties = levels[newLevel];
  12969. levelProperties.level = newLevel;
  12970. hls.trigger(_events2.default.LEVEL_SWITCHING, levelProperties);
  12971. }
  12972. var level = levels[newLevel];
  12973. var levelDetails = level.details;
  12974. // check if we need to load playlist for this level
  12975. if (!levelDetails || levelDetails.live) {
  12976. // level not retrieved yet, or live playlist we need to (re)load it
  12977. var urlId = level.urlId;
  12978. hls.trigger(_events2.default.LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId });
  12979. }
  12980. } else {
  12981. // invalid level id given, trigger error
  12982. hls.trigger(_events2.default.ERROR, {
  12983. type: _errors.ErrorTypes.OTHER_ERROR,
  12984. details: _errors.ErrorDetails.LEVEL_SWITCH_ERROR,
  12985. level: newLevel,
  12986. fatal: false,
  12987. reason: 'invalid level idx'
  12988. });
  12989. }
  12990. }
  12991. }, {
  12992. key: 'onError',
  12993. value: function onError(data) {
  12994. if (data.fatal) {
  12995. if (data.type === _errors.ErrorTypes.NETWORK_ERROR) {
  12996. this.clearTimer();
  12997. }
  12998. return;
  12999. }
  13000. var levelError = false,
  13001. fragmentError = false;
  13002. var levelIndex = void 0;
  13003. // try to recover not fatal errors
  13004. switch (data.details) {
  13005. case _errors.ErrorDetails.FRAG_LOAD_ERROR:
  13006. case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
  13007. case _errors.ErrorDetails.KEY_LOAD_ERROR:
  13008. case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
  13009. levelIndex = data.frag.level;
  13010. fragmentError = true;
  13011. break;
  13012. case _errors.ErrorDetails.LEVEL_LOAD_ERROR:
  13013. case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT:
  13014. levelIndex = data.context.level;
  13015. levelError = true;
  13016. break;
  13017. case _errors.ErrorDetails.REMUX_ALLOC_ERROR:
  13018. levelIndex = data.level;
  13019. levelError = true;
  13020. break;
  13021. }
  13022. if (levelIndex !== undefined) {
  13023. this.recoverLevel(data, levelIndex, levelError, fragmentError);
  13024. }
  13025. }
  13026. /**
  13027. * Switch to a redundant stream if any available.
  13028. * If redundant stream is not available, emergency switch down if ABR mode is enabled.
  13029. *
  13030. * @param {Object} errorEvent
  13031. * @param {Number} levelIndex current level index
  13032. * @param {Boolean} levelError
  13033. * @param {Boolean} fragmentError
  13034. */
  13035. // FIXME Find a better abstraction where fragment/level retry management is well decoupled
  13036. }, {
  13037. key: 'recoverLevel',
  13038. value: function recoverLevel(errorEvent, levelIndex, levelError, fragmentError) {
  13039. var _this2 = this;
  13040. var config = this.hls.config;
  13041. var errorDetails = errorEvent.details;
  13042. var level = this._levels[levelIndex];
  13043. var redundantLevels = void 0,
  13044. delay = void 0,
  13045. nextLevel = void 0;
  13046. level.loadError++;
  13047. level.fragmentError = fragmentError;
  13048. if (levelError) {
  13049. if (this.levelRetryCount + 1 <= config.levelLoadingMaxRetry) {
  13050. // exponential backoff capped to max retry timeout
  13051. delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);
  13052. // Schedule level reload
  13053. this.timer = setTimeout(function () {
  13054. return _this2.loadLevel();
  13055. }, delay);
  13056. // boolean used to inform stream controller not to switch back to IDLE on non fatal error
  13057. errorEvent.levelRetry = true;
  13058. this.levelRetryCount++;
  13059. _logger.logger.warn('level controller, ' + errorDetails + ', retry in ' + delay + ' ms, current retry count is ' + this.levelRetryCount);
  13060. } else {
  13061. _logger.logger.error('level controller, cannot recover from ' + errorDetails + ' error');
  13062. this.currentLevelIndex = null;
  13063. // stopping live reloading timer if any
  13064. this.clearTimer();
  13065. // switch error to fatal
  13066. errorEvent.fatal = true;
  13067. return;
  13068. }
  13069. }
  13070. // Try any redundant streams if available for both errors: level and fragment
  13071. // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down
  13072. if (levelError || fragmentError) {
  13073. redundantLevels = level.url.length;
  13074. if (redundantLevels > 1 && level.loadError < redundantLevels) {
  13075. level.urlId = (level.urlId + 1) % redundantLevels;
  13076. level.details = undefined;
  13077. _logger.logger.warn('level controller, ' + errorDetails + ' for level ' + levelIndex + ': switching to redundant URL-id ' + level.urlId);
  13078. // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
  13079. // console.log('New video quality level audio group id:', level.attrs.AUDIO);
  13080. } else {
  13081. // Search for available level
  13082. if (this.manualLevelIndex === -1) {
  13083. // When lowest level has been reached, let's start hunt from the top
  13084. nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1;
  13085. _logger.logger.warn('level controller, ' + errorDetails + ': switch to ' + nextLevel);
  13086. this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;
  13087. } else if (fragmentError) {
  13088. // Allow fragment retry as long as configuration allows.
  13089. // reset this._level so that another call to set level() will trigger again a frag load
  13090. _logger.logger.warn('level controller, ' + errorDetails + ': reload a fragment');
  13091. this.currentLevelIndex = null;
  13092. }
  13093. }
  13094. }
  13095. }
  13096. // reset errors on the successful load of a fragment
  13097. }, {
  13098. key: 'onFragLoaded',
  13099. value: function onFragLoaded(_ref3) {
  13100. var frag = _ref3.frag;
  13101. if (frag !== undefined && frag.type === 'main') {
  13102. var level = this._levels[frag.level];
  13103. if (level !== undefined) {
  13104. level.fragmentError = false;
  13105. level.loadError = 0;
  13106. this.levelRetryCount = 0;
  13107. }
  13108. }
  13109. }
  13110. }, {
  13111. key: 'onLevelLoaded',
  13112. value: function onLevelLoaded(data) {
  13113. var _this3 = this;
  13114. var level = data.level,
  13115. details = data.details;
  13116. // only process level loaded events matching with expected level
  13117. if (level !== this.currentLevelIndex) {
  13118. return;
  13119. }
  13120. var curLevel = this._levels[level];
  13121. // reset level load error counter on successful level loaded only if there is no issues with fragments
  13122. if (!curLevel.fragmentError) {
  13123. curLevel.loadError = 0;
  13124. this.levelRetryCount = 0;
  13125. }
  13126. // if current playlist is a live playlist, arm a timer to reload it
  13127. if (details.live) {
  13128. var reloadInterval = (0, _levelHelper.computeReloadInterval)(curLevel.details, details, data.stats.trequest);
  13129. _logger.logger.log('live playlist, reload in ' + Math.round(reloadInterval) + ' ms');
  13130. this.timer = setTimeout(function () {
  13131. return _this3.loadLevel();
  13132. }, reloadInterval);
  13133. } else {
  13134. this.clearTimer();
  13135. }
  13136. }
  13137. }, {
  13138. key: 'onAudioTrackSwitched',
  13139. value: function onAudioTrackSwitched(data) {
  13140. var audioGroupId = this.hls.audioTracks[data.id].groupId;
  13141. var currentLevel = this.hls.levels[this.currentLevelIndex];
  13142. if (!currentLevel) {
  13143. return;
  13144. }
  13145. if (currentLevel.audioGroupIds) {
  13146. var urlId = -1;
  13147. for (var i = 0; i < currentLevel.audioGroupIds.length; i++) {
  13148. if (currentLevel.audioGroupIds[i] === audioGroupId) {
  13149. urlId = i;
  13150. break;
  13151. }
  13152. }
  13153. if (urlId !== currentLevel.urlId) {
  13154. currentLevel.urlId = urlId;
  13155. this.startLoad();
  13156. }
  13157. }
  13158. }
  13159. }, {
  13160. key: 'loadLevel',
  13161. value: function loadLevel() {
  13162. _logger.logger.debug('call to loadLevel');
  13163. if (this.currentLevelIndex !== null && this.canload) {
  13164. var levelObject = this._levels[this.currentLevelIndex];
  13165. if ((typeof levelObject === 'undefined' ? 'undefined' : _typeof(levelObject)) === 'object' && levelObject.url.length > 0) {
  13166. var level = this.currentLevelIndex;
  13167. var id = levelObject.urlId;
  13168. var url = levelObject.url[id];
  13169. _logger.logger.log('Attempt loading level index ' + level + ' with URL-id ' + id);
  13170. // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
  13171. // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
  13172. this.hls.trigger(_events2.default.LEVEL_LOADING, { url: url, level: level, id: id });
  13173. }
  13174. }
  13175. }
  13176. }, {
  13177. key: 'levels',
  13178. get: function get() {
  13179. return this._levels;
  13180. }
  13181. }, {
  13182. key: 'level',
  13183. get: function get() {
  13184. return this.currentLevelIndex;
  13185. },
  13186. set: function set(newLevel) {
  13187. var levels = this._levels;
  13188. if (levels) {
  13189. newLevel = Math.min(newLevel, levels.length - 1);
  13190. if (this.currentLevelIndex !== newLevel || !levels[newLevel].details) {
  13191. this.setLevelInternal(newLevel);
  13192. }
  13193. }
  13194. }
  13195. }, {
  13196. key: 'manualLevel',
  13197. get: function get() {
  13198. return this.manualLevelIndex;
  13199. },
  13200. set: function set(newLevel) {
  13201. this.manualLevelIndex = newLevel;
  13202. if (this._startLevel === undefined) {
  13203. this._startLevel = newLevel;
  13204. }
  13205. if (newLevel !== -1) {
  13206. this.level = newLevel;
  13207. }
  13208. }
  13209. }, {
  13210. key: 'firstLevel',
  13211. get: function get() {
  13212. return this._firstLevel;
  13213. },
  13214. set: function set(newLevel) {
  13215. this._firstLevel = newLevel;
  13216. }
  13217. }, {
  13218. key: 'startLevel',
  13219. get: function get() {
  13220. // hls.startLevel takes precedence over config.startLevel
  13221. // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)
  13222. if (this._startLevel === undefined) {
  13223. var configStartLevel = this.hls.config.startLevel;
  13224. if (configStartLevel !== undefined) {
  13225. return configStartLevel;
  13226. } else {
  13227. return this._firstLevel;
  13228. }
  13229. } else {
  13230. return this._startLevel;
  13231. }
  13232. },
  13233. set: function set(newLevel) {
  13234. this._startLevel = newLevel;
  13235. }
  13236. }, {
  13237. key: 'nextLoadLevel',
  13238. get: function get() {
  13239. if (this.manualLevelIndex !== -1) {
  13240. return this.manualLevelIndex;
  13241. } else {
  13242. return this.hls.nextAutoLevel;
  13243. }
  13244. },
  13245. set: function set(nextLevel) {
  13246. this.level = nextLevel;
  13247. if (this.manualLevelIndex === -1) {
  13248. this.hls.nextAutoLevel = nextLevel;
  13249. }
  13250. }
  13251. }]);
  13252. return LevelController;
  13253. }(_eventHandler2.default);
  13254. exports.default = LevelController;
  13255. module.exports = exports['default'];
  13256. /***/ }),
  13257. /* 58 */
  13258. /***/ (function(module, exports, __webpack_require__) {
  13259. "use strict";
  13260. Object.defineProperty(exports, "__esModule", {
  13261. value: true
  13262. });
  13263. 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; }; }();
  13264. var _events = __webpack_require__(1);
  13265. var _events2 = _interopRequireDefault(_events);
  13266. var _eventHandler = __webpack_require__(3);
  13267. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  13268. var _id = __webpack_require__(10);
  13269. var _id2 = _interopRequireDefault(_id);
  13270. var _texttrackUtils = __webpack_require__(29);
  13271. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13272. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13273. 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; }
  13274. 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; } /*
  13275. * id3 metadata track controller
  13276. */
  13277. var ID3TrackController = function (_EventHandler) {
  13278. _inherits(ID3TrackController, _EventHandler);
  13279. function ID3TrackController(hls) {
  13280. _classCallCheck(this, ID3TrackController);
  13281. 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));
  13282. _this.id3Track = undefined;
  13283. _this.media = undefined;
  13284. return _this;
  13285. }
  13286. _createClass(ID3TrackController, [{
  13287. key: 'destroy',
  13288. value: function destroy() {
  13289. _eventHandler2.default.prototype.destroy.call(this);
  13290. }
  13291. // Add ID3 metatadata text track.
  13292. }, {
  13293. key: 'onMediaAttached',
  13294. value: function onMediaAttached(data) {
  13295. this.media = data.media;
  13296. if (!this.media) {}
  13297. }
  13298. }, {
  13299. key: 'onMediaDetaching',
  13300. value: function onMediaDetaching() {
  13301. (0, _texttrackUtils.clearCurrentCues)(this.id3Track);
  13302. this.id3Track = undefined;
  13303. this.media = undefined;
  13304. }
  13305. }, {
  13306. key: 'getID3Track',
  13307. value: function getID3Track(textTracks) {
  13308. for (var i = 0; i < textTracks.length; i++) {
  13309. var textTrack = textTracks[i];
  13310. if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
  13311. // send 'addtrack' when reusing the textTrack for metadata,
  13312. // same as what we do for captions
  13313. (0, _texttrackUtils.sendAddTrackEvent)(textTrack, this.media);
  13314. return textTrack;
  13315. }
  13316. }
  13317. return this.media.addTextTrack('metadata', 'id3');
  13318. }
  13319. }, {
  13320. key: 'onFragParsingMetadata',
  13321. value: function onFragParsingMetadata(data) {
  13322. var fragment = data.frag;
  13323. var samples = data.samples;
  13324. // create track dynamically
  13325. if (!this.id3Track) {
  13326. this.id3Track = this.getID3Track(this.media.textTracks);
  13327. this.id3Track.mode = 'hidden';
  13328. }
  13329. // Attempt to recreate Safari functionality by creating
  13330. // WebKitDataCue objects when available and store the decoded
  13331. // ID3 data in the value property of the cue
  13332. var Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;
  13333. for (var i = 0; i < samples.length; i++) {
  13334. var frames = _id2.default.getID3Frames(samples[i].data);
  13335. if (frames) {
  13336. var startTime = samples[i].pts;
  13337. var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.endPTS;
  13338. // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
  13339. if (startTime === endTime) {
  13340. endTime += 0.0001;
  13341. }
  13342. for (var j = 0; j < frames.length; j++) {
  13343. var frame = frames[j];
  13344. // Safari doesn't put the timestamp frame in the TextTrack
  13345. if (!_id2.default.isTimeStampFrame(frame)) {
  13346. var cue = new Cue(startTime, endTime, '');
  13347. cue.value = frame;
  13348. this.id3Track.addCue(cue);
  13349. }
  13350. }
  13351. }
  13352. }
  13353. }
  13354. }]);
  13355. return ID3TrackController;
  13356. }(_eventHandler2.default);
  13357. exports.default = ID3TrackController;
  13358. module.exports = exports['default'];
  13359. /***/ }),
  13360. /* 59 */
  13361. /***/ (function(module, exports, __webpack_require__) {
  13362. "use strict";
  13363. Object.defineProperty(exports, "__esModule", {
  13364. value: true
  13365. });
  13366. exports.isSupported = isSupported;
  13367. var _mediasourceHelper = __webpack_require__(13);
  13368. function isSupported() {
  13369. var mediaSource = (0, _mediasourceHelper.getMediaSource)();
  13370. var sourceBuffer = window.SourceBuffer || window.WebKitSourceBuffer;
  13371. var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
  13372. // if SourceBuffer is exposed ensure its API is valid
  13373. // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
  13374. var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
  13375. return !!isTypeSupported && !!sourceBufferValidAPI;
  13376. }
  13377. /***/ }),
  13378. /* 60 */
  13379. /***/ (function(module, exports, __webpack_require__) {
  13380. "use strict";
  13381. Object.defineProperty(exports, "__esModule", {
  13382. value: true
  13383. });
  13384. exports.hlsDefaultConfig = undefined;
  13385. var _abrController = __webpack_require__(61);
  13386. var _abrController2 = _interopRequireDefault(_abrController);
  13387. var _bufferController = __webpack_require__(64);
  13388. var _bufferController2 = _interopRequireDefault(_bufferController);
  13389. var _capLevelController = __webpack_require__(65);
  13390. var _capLevelController2 = _interopRequireDefault(_capLevelController);
  13391. var _fpsController = __webpack_require__(66);
  13392. var _fpsController2 = _interopRequireDefault(_fpsController);
  13393. var _xhrLoader = __webpack_require__(67);
  13394. var _xhrLoader2 = _interopRequireDefault(_xhrLoader);
  13395. var _audioTrackController = __webpack_require__(68);
  13396. var _audioTrackController2 = _interopRequireDefault(_audioTrackController);
  13397. var _audioStreamController = __webpack_require__(69);
  13398. var _audioStreamController2 = _interopRequireDefault(_audioStreamController);
  13399. var _cues = __webpack_require__(70);
  13400. var Cues = _interopRequireWildcard(_cues);
  13401. var _timelineController = __webpack_require__(72);
  13402. var _timelineController2 = _interopRequireDefault(_timelineController);
  13403. var _subtitleTrackController = __webpack_require__(76);
  13404. var _subtitleTrackController2 = _interopRequireDefault(_subtitleTrackController);
  13405. var _subtitleStreamController = __webpack_require__(77);
  13406. var _emeController = __webpack_require__(78);
  13407. var _emeController2 = _interopRequireDefault(_emeController);
  13408. var _mediakeysHelper = __webpack_require__(79);
  13409. 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; } }
  13410. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13411. // import FetchLoader from './utils/fetch-loader';
  13412. var hlsDefaultConfig = exports.hlsDefaultConfig = {
  13413. autoStartLoad: true, // used by stream-controller
  13414. startPosition: -1, // used by stream-controller
  13415. defaultAudioCodec: undefined, // used by stream-controller
  13416. debug: false, // used by logger
  13417. capLevelOnFPSDrop: false, // used by fps-controller
  13418. capLevelToPlayerSize: false, // used by cap-level-controller
  13419. initialLiveManifestSize: 1, // used by stream-controller
  13420. maxBufferLength: 30, // used by stream-controller
  13421. maxBufferSize: 60 * 1000 * 1000, // used by stream-controller
  13422. maxBufferHole: 0.5, // used by stream-controller
  13423. lowBufferWatchdogPeriod: 0.5, // used by stream-controller
  13424. highBufferWatchdogPeriod: 3, // used by stream-controller
  13425. nudgeOffset: 0.1, // used by stream-controller
  13426. nudgeMaxRetry: 3, // used by stream-controller
  13427. maxFragLookUpTolerance: 0.25, // used by stream-controller
  13428. liveSyncDurationCount: 3, // used by stream-controller
  13429. liveMaxLatencyDurationCount: Infinity, // used by stream-controller
  13430. liveSyncDuration: undefined, // used by stream-controller
  13431. liveMaxLatencyDuration: undefined, // used by stream-controller
  13432. liveDurationInfinity: false, // used by buffer-controller
  13433. liveBackBufferLength: Infinity, // used by buffer-controller
  13434. maxMaxBufferLength: 600, // used by stream-controller
  13435. enableWorker: true, // used by demuxer
  13436. enableSoftwareAES: true, // used by decrypter
  13437. manifestLoadingTimeOut: 10000, // used by playlist-loader
  13438. manifestLoadingMaxRetry: 1, // used by playlist-loader
  13439. manifestLoadingRetryDelay: 1000, // used by playlist-loader
  13440. manifestLoadingMaxRetryTimeout: 64000, // used by playlist-loader
  13441. startLevel: undefined, // used by level-controller
  13442. levelLoadingTimeOut: 10000, // used by playlist-loader
  13443. levelLoadingMaxRetry: 4, // used by playlist-loader
  13444. levelLoadingRetryDelay: 1000, // used by playlist-loader
  13445. levelLoadingMaxRetryTimeout: 64000, // used by playlist-loader
  13446. fragLoadingTimeOut: 20000, // used by fragment-loader
  13447. fragLoadingMaxRetry: 6, // used by fragment-loader
  13448. fragLoadingRetryDelay: 1000, // used by fragment-loader
  13449. fragLoadingMaxRetryTimeout: 64000, // used by fragment-loader
  13450. startFragPrefetch: false, // used by stream-controller
  13451. fpsDroppedMonitoringPeriod: 5000, // used by fps-controller
  13452. fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller
  13453. appendErrorMaxRetry: 3, // used by buffer-controller
  13454. loader: _xhrLoader2.default,
  13455. // loader: FetchLoader,
  13456. fLoader: undefined, // used by fragment-loader
  13457. pLoader: undefined, // used by playlist-loader
  13458. xhrSetup: undefined, // used by xhr-loader
  13459. licenseXhrSetup: undefined, // used by eme-controller
  13460. // fetchSetup: undefined,
  13461. abrController: _abrController2.default,
  13462. bufferController: _bufferController2.default,
  13463. capLevelController: _capLevelController2.default,
  13464. fpsController: _fpsController2.default,
  13465. stretchShortVideoTrack: false, // used by mp4-remuxer
  13466. maxAudioFramesDrift: 1, // used by mp4-remuxer
  13467. forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer
  13468. abrEwmaFastLive: 3, // used by abr-controller
  13469. abrEwmaSlowLive: 9, // used by abr-controller
  13470. abrEwmaFastVoD: 3, // used by abr-controller
  13471. abrEwmaSlowVoD: 9, // used by abr-controller
  13472. abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller
  13473. abrBandWidthFactor: 0.95, // used by abr-controller
  13474. abrBandWidthUpFactor: 0.7, // used by abr-controller
  13475. abrMaxWithRealBitrate: false, // used by abr-controller
  13476. maxStarvationDelay: 4, // used by abr-controller
  13477. maxLoadingDelay: 4, // used by abr-controller
  13478. minAutoBitrate: 0, // used by hls
  13479. emeEnabled: false, // used by eme-controller
  13480. widevineLicenseUrl: undefined, // used by eme-controller
  13481. requestMediaKeySystemAccessFunc: _mediakeysHelper.requestMediaKeySystemAccess // used by eme-controller
  13482. }; /**
  13483. * HLS config
  13484. */
  13485. hlsDefaultConfig.subtitleStreamController = _subtitleStreamController.SubtitleStreamController;
  13486. hlsDefaultConfig.subtitleTrackController = _subtitleTrackController2.default;
  13487. hlsDefaultConfig.timelineController = _timelineController2.default;
  13488. hlsDefaultConfig.cueHandler = Cues; // used by timeline-controller
  13489. hlsDefaultConfig.enableCEA708Captions = true; // used by timeline-controller
  13490. hlsDefaultConfig.enableWebVTT = true; // used by timeline-controller
  13491. hlsDefaultConfig.captionsTextTrack1Label = 'English'; // used by timeline-controller
  13492. hlsDefaultConfig.captionsTextTrack1LanguageCode = 'en'; // used by timeline-controller
  13493. hlsDefaultConfig.captionsTextTrack2Label = 'Spanish'; // used by timeline-controller
  13494. hlsDefaultConfig.captionsTextTrack2LanguageCode = 'es'; // used by timeline-controller
  13495. hlsDefaultConfig.audioStreamController = _audioStreamController2.default;
  13496. hlsDefaultConfig.audioTrackController = _audioTrackController2.default;
  13497. hlsDefaultConfig.emeController = _emeController2.default;
  13498. /***/ }),
  13499. /* 61 */
  13500. /***/ (function(module, exports, __webpack_require__) {
  13501. "use strict";
  13502. Object.defineProperty(exports, "__esModule", {
  13503. value: true
  13504. });
  13505. 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; }; }();
  13506. var _events = __webpack_require__(1);
  13507. var _events2 = _interopRequireDefault(_events);
  13508. var _eventHandler = __webpack_require__(3);
  13509. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  13510. var _bufferHelper = __webpack_require__(4);
  13511. var _errors = __webpack_require__(2);
  13512. var _logger = __webpack_require__(0);
  13513. var _ewmaBandwidthEstimator = __webpack_require__(62);
  13514. var _ewmaBandwidthEstimator2 = _interopRequireDefault(_ewmaBandwidthEstimator);
  13515. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13516. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13517. 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; }
  13518. 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; } /*
  13519. * simple ABR Controller
  13520. * - compute next level based on last fragment bw heuristics
  13521. * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling
  13522. */
  13523. var _window = window,
  13524. performance = _window.performance;
  13525. var AbrController = function (_EventHandler) {
  13526. _inherits(AbrController, _EventHandler);
  13527. function AbrController(hls) {
  13528. _classCallCheck(this, AbrController);
  13529. 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));
  13530. _this.lastLoadedFragLevel = 0;
  13531. _this._nextAutoLevel = -1;
  13532. _this.hls = hls;
  13533. _this.timer = null;
  13534. _this._bwEstimator = null;
  13535. _this.onCheck = _this._abandonRulesCheck.bind(_this);
  13536. return _this;
  13537. }
  13538. _createClass(AbrController, [{
  13539. key: 'destroy',
  13540. value: function destroy() {
  13541. this.clearTimer();
  13542. _eventHandler2.default.prototype.destroy.call(this);
  13543. }
  13544. }, {
  13545. key: 'onFragLoading',
  13546. value: function onFragLoading(data) {
  13547. var frag = data.frag;
  13548. if (frag.type === 'main') {
  13549. if (!this.timer) {
  13550. this.fragCurrent = frag;
  13551. this.timer = setInterval(this.onCheck, 100);
  13552. }
  13553. // lazy init of BwEstimator, rationale is that we use different params for Live/VoD
  13554. // so we need to wait for stream manifest / playlist type to instantiate it.
  13555. if (!this._bwEstimator) {
  13556. var hls = this.hls;
  13557. var config = hls.config;
  13558. var level = frag.level;
  13559. var isLive = hls.levels[level].details.live;
  13560. var ewmaFast = void 0,
  13561. ewmaSlow = void 0;
  13562. if (isLive) {
  13563. ewmaFast = config.abrEwmaFastLive;
  13564. ewmaSlow = config.abrEwmaSlowLive;
  13565. } else {
  13566. ewmaFast = config.abrEwmaFastVoD;
  13567. ewmaSlow = config.abrEwmaSlowVoD;
  13568. }
  13569. this._bwEstimator = new _ewmaBandwidthEstimator2.default(hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate);
  13570. }
  13571. }
  13572. }
  13573. }, {
  13574. key: '_abandonRulesCheck',
  13575. value: function _abandonRulesCheck() {
  13576. /*
  13577. monitor fragment retrieval time...
  13578. we compute expected time of arrival of the complete fragment.
  13579. we compare it to expected time of buffer starvation
  13580. */
  13581. var hls = this.hls;
  13582. var video = hls.media;
  13583. var frag = this.fragCurrent;
  13584. if (!frag) {
  13585. return;
  13586. }
  13587. var loader = frag.loader;
  13588. var minAutoLevel = hls.minAutoLevel;
  13589. // if loader has been destroyed or loading has been aborted, stop timer and return
  13590. if (!loader || loader.stats && loader.stats.aborted) {
  13591. _logger.logger.warn('frag loader destroy or aborted, disarm abandonRules');
  13592. this.clearTimer();
  13593. // reset forced auto level value so that next level will be selected
  13594. this._nextAutoLevel = -1;
  13595. return;
  13596. }
  13597. var stats = loader.stats;
  13598. /* only monitor frag retrieval time if
  13599. (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) */
  13600. if (video && stats && (!video.paused && video.playbackRate !== 0 || !video.readyState) && frag.autoLevel && frag.level) {
  13601. var requestDelay = performance.now() - stats.trequest,
  13602. playbackRate = Math.abs(video.playbackRate);
  13603. // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate
  13604. if (requestDelay > 500 * frag.duration / playbackRate) {
  13605. var levels = hls.levels,
  13606. loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay),
  13607. // byte/s; at least 1 byte/s to avoid division by zero
  13608. // compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size
  13609. level = levels[frag.level],
  13610. levelBitrate = level.realBitrate ? Math.max(level.realBitrate, level.bitrate) : level.bitrate,
  13611. expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8)),
  13612. pos = video.currentTime,
  13613. fragLoadedDelay = (expectedLen - stats.loaded) / loadRate,
  13614. bufferStarvationDelay = (_bufferHelper.BufferHelper.bufferInfo(video, pos, hls.config.maxBufferHole).end - pos) / playbackRate;
  13615. // consider emergency switch down only if we have less than 2 frag buffered AND
  13616. // time to finish loading current fragment is bigger than buffer starvation delay
  13617. // ie if we risk buffer starvation if bw does not increase quickly
  13618. if (bufferStarvationDelay < 2 * frag.duration / playbackRate && fragLoadedDelay > bufferStarvationDelay) {
  13619. var fragLevelNextLoadedDelay = void 0,
  13620. nextLoadLevel = void 0;
  13621. // lets iterate through lower level and try to find the biggest one that could avoid rebuffering
  13622. // we start from current level - 1 and we step down , until we find a matching level
  13623. for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  13624. // compute time to load next fragment at lower level
  13625. // 0.8 : consider only 80% of current bw to be conservative
  13626. // 8 = bits per byte (bps/Bps)
  13627. var levelNextBitrate = levels[nextLoadLevel].realBitrate ? Math.max(levels[nextLoadLevel].realBitrate, levels[nextLoadLevel].bitrate) : levels[nextLoadLevel].bitrate;
  13628. fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate);
  13629. if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
  13630. // we found a lower level that be rebuffering free with current estimated bw !
  13631. break;
  13632. }
  13633. }
  13634. // only emergency switch down if it takes less time to load new fragment at lowest level instead
  13635. // of finishing loading current one ...
  13636. if (fragLevelNextLoadedDelay < fragLoadedDelay) {
  13637. _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));
  13638. // force next load level in auto mode
  13639. hls.nextLoadLevel = nextLoadLevel;
  13640. // update bw estimate for this fragment before cancelling load (this will help reducing the bw)
  13641. this._bwEstimator.sample(requestDelay, stats.loaded);
  13642. // abort fragment loading
  13643. loader.abort();
  13644. // stop abandon rules timer
  13645. this.clearTimer();
  13646. hls.trigger(_events2.default.FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag, stats: stats });
  13647. }
  13648. }
  13649. }
  13650. }
  13651. }
  13652. }, {
  13653. key: 'onFragLoaded',
  13654. value: function onFragLoaded(data) {
  13655. var frag = data.frag;
  13656. if (frag.type === 'main' && Number.isFinite(frag.sn)) {
  13657. // stop monitoring bw once frag loaded
  13658. this.clearTimer();
  13659. // store level id after successful fragment load
  13660. this.lastLoadedFragLevel = frag.level;
  13661. // reset forced auto level value so that next level will be selected
  13662. this._nextAutoLevel = -1;
  13663. // compute level average bitrate
  13664. if (this.hls.config.abrMaxWithRealBitrate) {
  13665. var level = this.hls.levels[frag.level];
  13666. var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;
  13667. var loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration;
  13668. level.loaded = { bytes: loadedBytes, duration: loadedDuration };
  13669. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  13670. }
  13671. // if fragment has been loaded to perform a bitrate test,
  13672. if (data.frag.bitrateTest) {
  13673. var stats = data.stats;
  13674. stats.tparsed = stats.tbuffered = stats.tload;
  13675. this.onFragBuffered(data);
  13676. }
  13677. }
  13678. }
  13679. }, {
  13680. key: 'onFragBuffered',
  13681. value: function onFragBuffered(data) {
  13682. var stats = data.stats;
  13683. var frag = data.frag;
  13684. // only update stats on first frag buffering
  13685. // if same frag is loaded multiple times, it might be in browser cache, and loaded quickly
  13686. // and leading to wrong bw estimation
  13687. // on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED)
  13688. if (stats.aborted !== true && frag.type === 'main' && Number.isFinite(frag.sn) && (!frag.bitrateTest || stats.tload === stats.tbuffered)) {
  13689. // use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached
  13690. // 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
  13691. // as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation
  13692. var fragLoadingProcessingMs = stats.tparsed - stats.trequest;
  13693. _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)));
  13694. this._bwEstimator.sample(fragLoadingProcessingMs, stats.loaded);
  13695. stats.bwEstimate = this._bwEstimator.getEstimate();
  13696. // if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration
  13697. if (frag.bitrateTest) {
  13698. this.bitrateTestDelay = fragLoadingProcessingMs / 1000;
  13699. } else {
  13700. this.bitrateTestDelay = 0;
  13701. }
  13702. }
  13703. }
  13704. }, {
  13705. key: 'onError',
  13706. value: function onError(data) {
  13707. // stop timer in case of frag loading error
  13708. switch (data.details) {
  13709. case _errors.ErrorDetails.FRAG_LOAD_ERROR:
  13710. case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
  13711. this.clearTimer();
  13712. break;
  13713. default:
  13714. break;
  13715. }
  13716. }
  13717. }, {
  13718. key: 'clearTimer',
  13719. value: function clearTimer() {
  13720. clearInterval(this.timer);
  13721. this.timer = null;
  13722. }
  13723. // return next auto level
  13724. }, {
  13725. key: '_findBestLevel',
  13726. value: function _findBestLevel(currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) {
  13727. for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
  13728. var levelInfo = levels[i];
  13729. if (!levelInfo) {
  13730. continue;
  13731. }
  13732. var levelDetails = levelInfo.details,
  13733. avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration,
  13734. live = levelDetails ? levelDetails.live : false,
  13735. adjustedbw = void 0;
  13736. // follow algorithm captured from stagefright :
  13737. // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
  13738. // Pick the highest bandwidth stream below or equal to estimated bandwidth.
  13739. // consider only 80% of the available bandwidth, but if we are switching up,
  13740. // be even more conservative (70%) to avoid overestimating and immediately
  13741. // switching back.
  13742. if (i <= currentLevel) {
  13743. adjustedbw = bwFactor * currentBw;
  13744. } else {
  13745. adjustedbw = bwUpFactor * currentBw;
  13746. }
  13747. var bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate,
  13748. fetchDuration = bitrate * avgDuration / adjustedbw;
  13749. _logger.logger.trace('level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: ' + i + '/' + Math.round(adjustedbw) + '/' + bitrate + '/' + avgDuration + '/' + maxFetchDuration + '/' + fetchDuration);
  13750. // if adjusted bw is greater than level bitrate AND
  13751. if (adjustedbw > bitrate && (
  13752. // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  13753. // 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 ...
  13754. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that _findBestLevel will return -1
  13755. !fetchDuration || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) {
  13756. // as we are looping from highest to lowest, this will return the best achievable quality level
  13757. return i;
  13758. }
  13759. }
  13760. // not enough time budget even with quality level 0 ... rebuffering might happen
  13761. return -1;
  13762. }
  13763. }, {
  13764. key: 'nextAutoLevel',
  13765. get: function get() {
  13766. var forcedAutoLevel = this._nextAutoLevel;
  13767. var bwEstimator = this._bwEstimator;
  13768. // in case next auto level has been forced, and bw not available or not reliable, return forced value
  13769. if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {
  13770. return forcedAutoLevel;
  13771. }
  13772. // compute next level using ABR logic
  13773. var nextABRAutoLevel = this._nextABRAutoLevel;
  13774. // if forced auto level has been defined, use it to cap ABR computed quality level
  13775. if (forcedAutoLevel !== -1) {
  13776. nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);
  13777. }
  13778. return nextABRAutoLevel;
  13779. },
  13780. set: function set(nextLevel) {
  13781. this._nextAutoLevel = nextLevel;
  13782. }
  13783. }, {
  13784. key: '_nextABRAutoLevel',
  13785. get: function get() {
  13786. var hls = this.hls,
  13787. maxAutoLevel = hls.maxAutoLevel,
  13788. levels = hls.levels,
  13789. config = hls.config,
  13790. minAutoLevel = hls.minAutoLevel;
  13791. var video = hls.media,
  13792. currentLevel = this.lastLoadedFragLevel,
  13793. currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0,
  13794. pos = video ? video.currentTime : 0,
  13795. // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as
  13796. // if we're playing back at the normal rate.
  13797. playbackRate = video && video.playbackRate !== 0 ? Math.abs(video.playbackRate) : 1.0,
  13798. avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate,
  13799. // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
  13800. bufferStarvationDelay = (_bufferHelper.BufferHelper.bufferInfo(video, pos, config.maxBufferHole).end - pos) / playbackRate;
  13801. // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
  13802. var bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor, levels);
  13803. if (bestLevel >= 0) {
  13804. return bestLevel;
  13805. } else {
  13806. _logger.logger.trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering');
  13807. // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering
  13808. // if no matching level found, logic will return 0
  13809. var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay,
  13810. bwFactor = config.abrBandWidthFactor,
  13811. bwUpFactor = config.abrBandWidthUpFactor;
  13812. if (bufferStarvationDelay === 0) {
  13813. // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
  13814. var bitrateTestDelay = this.bitrateTestDelay;
  13815. if (bitrateTestDelay) {
  13816. // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
  13817. // max video loading delay used in automatic start level selection :
  13818. // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
  13819. // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
  13820. // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
  13821. var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  13822. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  13823. _logger.logger.trace('bitrate test took ' + Math.round(1000 * bitrateTestDelay) + 'ms, set first fragment max fetchDuration to ' + Math.round(1000 * maxStarvationDelay) + ' ms');
  13824. // don't use conservative factor on bitrate test
  13825. bwFactor = bwUpFactor = 1;
  13826. }
  13827. }
  13828. bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor, levels);
  13829. return Math.max(bestLevel, 0);
  13830. }
  13831. }
  13832. }]);
  13833. return AbrController;
  13834. }(_eventHandler2.default);
  13835. exports.default = AbrController;
  13836. module.exports = exports['default'];
  13837. /***/ }),
  13838. /* 62 */
  13839. /***/ (function(module, exports, __webpack_require__) {
  13840. "use strict";
  13841. Object.defineProperty(exports, "__esModule", {
  13842. value: true
  13843. });
  13844. 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; }; }(); /*
  13845. * EWMA Bandwidth Estimator
  13846. * - heavily inspired from shaka-player
  13847. * Tracks bandwidth samples and estimates available bandwidth.
  13848. * Based on the minimum of two exponentially-weighted moving averages with
  13849. * different half-lives.
  13850. */
  13851. var _ewma = __webpack_require__(63);
  13852. var _ewma2 = _interopRequireDefault(_ewma);
  13853. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13854. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13855. var EwmaBandWidthEstimator = function () {
  13856. function EwmaBandWidthEstimator(hls, slow, fast, defaultEstimate) {
  13857. _classCallCheck(this, EwmaBandWidthEstimator);
  13858. this.hls = hls;
  13859. this.defaultEstimate_ = defaultEstimate;
  13860. this.minWeight_ = 0.001;
  13861. this.minDelayMs_ = 50;
  13862. this.slow_ = new _ewma2.default(slow);
  13863. this.fast_ = new _ewma2.default(fast);
  13864. }
  13865. _createClass(EwmaBandWidthEstimator, [{
  13866. key: 'sample',
  13867. value: function sample(durationMs, numBytes) {
  13868. durationMs = Math.max(durationMs, this.minDelayMs_);
  13869. var bandwidth = 8000 * numBytes / durationMs,
  13870. // console.log('instant bw:'+ Math.round(bandwidth));
  13871. // we weight sample using loading duration....
  13872. weight = durationMs / 1000;
  13873. this.fast_.sample(weight, bandwidth);
  13874. this.slow_.sample(weight, bandwidth);
  13875. }
  13876. }, {
  13877. key: 'canEstimate',
  13878. value: function canEstimate() {
  13879. var fast = this.fast_;
  13880. return fast && fast.getTotalWeight() >= this.minWeight_;
  13881. }
  13882. }, {
  13883. key: 'getEstimate',
  13884. value: function getEstimate() {
  13885. if (this.canEstimate()) {
  13886. // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
  13887. // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
  13888. // Take the minimum of these two estimates. This should have the effect of
  13889. // adapting down quickly, but up more slowly.
  13890. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  13891. } else {
  13892. return this.defaultEstimate_;
  13893. }
  13894. }
  13895. }, {
  13896. key: 'destroy',
  13897. value: function destroy() {}
  13898. }]);
  13899. return EwmaBandWidthEstimator;
  13900. }();
  13901. exports.default = EwmaBandWidthEstimator;
  13902. module.exports = exports['default'];
  13903. /***/ }),
  13904. /* 63 */
  13905. /***/ (function(module, exports, __webpack_require__) {
  13906. "use strict";
  13907. Object.defineProperty(exports, "__esModule", {
  13908. value: true
  13909. });
  13910. 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; }; }();
  13911. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13912. /*
  13913. * compute an Exponential Weighted moving average
  13914. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  13915. * - heavily inspired from shaka-player
  13916. */
  13917. var EWMA = function () {
  13918. // About half of the estimated value will be from the last |halfLife| samples by weight.
  13919. function EWMA(halfLife) {
  13920. _classCallCheck(this, EWMA);
  13921. // Larger values of alpha expire historical data more slowly.
  13922. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  13923. this.estimate_ = 0;
  13924. this.totalWeight_ = 0;
  13925. }
  13926. _createClass(EWMA, [{
  13927. key: "sample",
  13928. value: function sample(weight, value) {
  13929. var adjAlpha = Math.pow(this.alpha_, weight);
  13930. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  13931. this.totalWeight_ += weight;
  13932. }
  13933. }, {
  13934. key: "getTotalWeight",
  13935. value: function getTotalWeight() {
  13936. return this.totalWeight_;
  13937. }
  13938. }, {
  13939. key: "getEstimate",
  13940. value: function getEstimate() {
  13941. if (this.alpha_) {
  13942. var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  13943. return this.estimate_ / zeroFactor;
  13944. } else {
  13945. return this.estimate_;
  13946. }
  13947. }
  13948. }]);
  13949. return EWMA;
  13950. }();
  13951. exports.default = EWMA;
  13952. module.exports = exports["default"];
  13953. /***/ }),
  13954. /* 64 */
  13955. /***/ (function(module, exports, __webpack_require__) {
  13956. "use strict";
  13957. Object.defineProperty(exports, "__esModule", {
  13958. value: true
  13959. });
  13960. 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; }; }();
  13961. var _events = __webpack_require__(1);
  13962. var _events2 = _interopRequireDefault(_events);
  13963. var _eventHandler = __webpack_require__(3);
  13964. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  13965. var _logger = __webpack_require__(0);
  13966. var _errors = __webpack_require__(2);
  13967. var _mediasourceHelper = __webpack_require__(13);
  13968. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13969. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13970. 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; }
  13971. 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; } /*
  13972. * Buffer Controller
  13973. */
  13974. var MediaSource = (0, _mediasourceHelper.getMediaSource)();
  13975. var BufferController = function (_EventHandler) {
  13976. _inherits(BufferController, _EventHandler);
  13977. function BufferController(hls) {
  13978. _classCallCheck(this, BufferController);
  13979. // the value that we have set mediasource.duration to
  13980. // (the actual duration may be tweaked slighly by the browser)
  13981. 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));
  13982. _this._msDuration = null;
  13983. // the value that we want to set mediaSource.duration to
  13984. _this._levelDuration = null;
  13985. // the target duration of the current media playlist
  13986. _this._levelTargetDuration = 10;
  13987. // current stream state: true - for live broadcast, false - for VoD content
  13988. _this._live = null;
  13989. // cache the self generated object url to detect hijack of video tag
  13990. _this._objectUrl = null;
  13991. // The number of BUFFER_CODEC events received before any sourceBuffers are created
  13992. _this.bufferCodecEventsExpected = 0;
  13993. // Source Buffer listeners
  13994. _this.onsbue = _this.onSBUpdateEnd.bind(_this);
  13995. _this.onsbe = _this.onSBUpdateError.bind(_this);
  13996. _this.pendingTracks = {};
  13997. _this.tracks = {};
  13998. return _this;
  13999. }
  14000. _createClass(BufferController, [{
  14001. key: 'destroy',
  14002. value: function destroy() {
  14003. _eventHandler2.default.prototype.destroy.call(this);
  14004. }
  14005. }, {
  14006. key: 'onLevelPtsUpdated',
  14007. value: function onLevelPtsUpdated(data) {
  14008. var type = data.type;
  14009. var audioTrack = this.tracks.audio;
  14010. // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
  14011. // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
  14012. // 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
  14013. // `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend`
  14014. // event if SB is in updating state.
  14015. // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
  14016. if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') {
  14017. // Chrome audio mp3 track
  14018. var audioBuffer = this.sourceBuffer.audio;
  14019. var delta = Math.abs(audioBuffer.timestampOffset - data.start);
  14020. // adjust timestamp offset if time delta is greater than 100ms
  14021. if (delta > 0.1) {
  14022. var updating = audioBuffer.updating;
  14023. try {
  14024. audioBuffer.abort();
  14025. } catch (err) {
  14026. _logger.logger.warn('can not abort audio buffer: ' + err);
  14027. }
  14028. if (!updating) {
  14029. _logger.logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.start);
  14030. audioBuffer.timestampOffset = data.start;
  14031. } else {
  14032. this.audioTimestampOffset = data.start;
  14033. }
  14034. }
  14035. }
  14036. }
  14037. }, {
  14038. key: 'onManifestParsed',
  14039. value: function onManifestParsed(data) {
  14040. // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
  14041. // sourcebuffers will be created all at once when the expected nb of tracks will be reached
  14042. // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
  14043. // it will contain the expected nb of source buffers, no need to compute it
  14044. this.bufferCodecEventsExpected = data.altAudio ? 2 : 1;
  14045. _logger.logger.log(this.bufferCodecEventsExpected + ' bufferCodec event(s) expected');
  14046. }
  14047. }, {
  14048. key: 'onMediaAttaching',
  14049. value: function onMediaAttaching(data) {
  14050. var media = this.media = data.media;
  14051. if (media) {
  14052. // setup the media source
  14053. var ms = this.mediaSource = new MediaSource();
  14054. // Media Source listeners
  14055. this.onmso = this.onMediaSourceOpen.bind(this);
  14056. this.onmse = this.onMediaSourceEnded.bind(this);
  14057. this.onmsc = this.onMediaSourceClose.bind(this);
  14058. ms.addEventListener('sourceopen', this.onmso);
  14059. ms.addEventListener('sourceended', this.onmse);
  14060. ms.addEventListener('sourceclose', this.onmsc);
  14061. // link video and media Source
  14062. media.src = window.URL.createObjectURL(ms);
  14063. // cache the locally generated object url
  14064. this._objectUrl = media.src;
  14065. }
  14066. }
  14067. }, {
  14068. key: 'onMediaDetaching',
  14069. value: function onMediaDetaching() {
  14070. _logger.logger.log('media source detaching');
  14071. var ms = this.mediaSource;
  14072. if (ms) {
  14073. if (ms.readyState === 'open') {
  14074. try {
  14075. // endOfStream could trigger exception if any sourcebuffer is in updating state
  14076. // we don't really care about checking sourcebuffer state here,
  14077. // as we are anyway detaching the MediaSource
  14078. // let's just avoid this exception to propagate
  14079. ms.endOfStream();
  14080. } catch (err) {
  14081. _logger.logger.warn('onMediaDetaching:' + err.message + ' while calling endOfStream');
  14082. }
  14083. }
  14084. ms.removeEventListener('sourceopen', this.onmso);
  14085. ms.removeEventListener('sourceended', this.onmse);
  14086. ms.removeEventListener('sourceclose', this.onmsc);
  14087. // Detach properly the MediaSource from the HTMLMediaElement as
  14088. // suggested in https://github.com/w3c/media-source/issues/53.
  14089. if (this.media) {
  14090. window.URL.revokeObjectURL(this._objectUrl);
  14091. // clean up video tag src only if it's our own url. some external libraries might
  14092. // hijack the video tag and change its 'src' without destroying the Hls instance first
  14093. if (this.media.src === this._objectUrl) {
  14094. this.media.removeAttribute('src');
  14095. this.media.load();
  14096. } else {
  14097. _logger.logger.warn('media.src was changed by a third party - skip cleanup');
  14098. }
  14099. }
  14100. this.mediaSource = null;
  14101. this.media = null;
  14102. this._objectUrl = null;
  14103. this.pendingTracks = {};
  14104. this.tracks = {};
  14105. this.sourceBuffer = {};
  14106. this.flushRange = [];
  14107. this.segments = [];
  14108. this.appended = 0;
  14109. }
  14110. this.onmso = this.onmse = this.onmsc = null;
  14111. this.hls.trigger(_events2.default.MEDIA_DETACHED);
  14112. }
  14113. }, {
  14114. key: 'onMediaSourceOpen',
  14115. value: function onMediaSourceOpen() {
  14116. _logger.logger.log('media source opened');
  14117. this.hls.trigger(_events2.default.MEDIA_ATTACHED, { media: this.media });
  14118. var mediaSource = this.mediaSource;
  14119. if (mediaSource) {
  14120. // once received, don't listen anymore to sourceopen event
  14121. mediaSource.removeEventListener('sourceopen', this.onmso);
  14122. }
  14123. this.checkPendingTracks();
  14124. }
  14125. }, {
  14126. key: 'checkPendingTracks',
  14127. value: function checkPendingTracks() {
  14128. var bufferCodecEventsExpected = this.bufferCodecEventsExpected,
  14129. pendingTracks = this.pendingTracks;
  14130. // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
  14131. // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
  14132. // data has been appended to existing ones.
  14133. // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
  14134. var pendingTracksCount = Object.keys(pendingTracks).length;
  14135. if (pendingTracksCount && !bufferCodecEventsExpected || pendingTracksCount === 2) {
  14136. // ok, let's create them now !
  14137. this.createSourceBuffers(pendingTracks);
  14138. this.pendingTracks = {};
  14139. // append any pending segments now !
  14140. this.doAppending();
  14141. }
  14142. }
  14143. }, {
  14144. key: 'onMediaSourceClose',
  14145. value: function onMediaSourceClose() {
  14146. _logger.logger.log('media source closed');
  14147. }
  14148. }, {
  14149. key: 'onMediaSourceEnded',
  14150. value: function onMediaSourceEnded() {
  14151. _logger.logger.log('media source ended');
  14152. }
  14153. }, {
  14154. key: 'onSBUpdateEnd',
  14155. value: function onSBUpdateEnd() {
  14156. // update timestampOffset
  14157. if (this.audioTimestampOffset) {
  14158. var audioBuffer = this.sourceBuffer.audio;
  14159. _logger.logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + this.audioTimestampOffset);
  14160. audioBuffer.timestampOffset = this.audioTimestampOffset;
  14161. delete this.audioTimestampOffset;
  14162. }
  14163. if (this._needsFlush) {
  14164. this.doFlush();
  14165. }
  14166. if (this._needsEos) {
  14167. this.checkEos();
  14168. }
  14169. this.appending = false;
  14170. var parent = this.parent;
  14171. // count nb of pending segments waiting for appending on this sourcebuffer
  14172. var pending = this.segments.reduce(function (counter, segment) {
  14173. return segment.parent === parent ? counter + 1 : counter;
  14174. }, 0);
  14175. // this.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments
  14176. var timeRanges = {};
  14177. var sourceBuffer = this.sourceBuffer;
  14178. for (var streamType in sourceBuffer) {
  14179. timeRanges[streamType] = sourceBuffer[streamType].buffered;
  14180. }
  14181. // 寻找可播放的起始点。如果没有自动播放,需要手动Seek
  14182. if (this._paused === false && timeRanges["video"] && timeRanges["video"].length > 0 && timeRanges["audio"] && timeRanges["audio"].length > 0) {
  14183. if (timeRanges["video"].end(0) - timeRanges["video"].start(0) > 1 && timeRanges["audio"].end(0) - timeRanges["audio"].start(0) > 1) {
  14184. // Seek to the point that can play;
  14185. var startTime = Math.max(timeRanges["video"].start(0), timeRanges["audio"].start(0));
  14186. this.media.currentTime = startTime;
  14187. this.media.play();
  14188. delete this["_paused"];
  14189. } else {
  14190. // Try to seek more
  14191. var endTime = Math.max(timeRanges["video"].end(0), timeRanges["audio"].end(0));
  14192. this.media.currentTime = endTime;
  14193. this.media.play();
  14194. }
  14195. }
  14196. this.hls.trigger(_events2.default.BUFFER_APPENDED, { parent: parent, pending: pending, timeRanges: timeRanges });
  14197. // don't append in flushing mode
  14198. if (!this._needsFlush) {
  14199. this.doAppending();
  14200. }
  14201. this.updateMediaElementDuration();
  14202. // appending goes first
  14203. if (pending === 0) {
  14204. this.flushLiveBackBuffer();
  14205. }
  14206. }
  14207. }, {
  14208. key: 'onSBUpdateError',
  14209. value: function onSBUpdateError(event) {
  14210. _logger.logger.error('sourceBuffer error:', event);
  14211. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  14212. // this error might not always be fatal (it is fatal if decode error is set, in that case
  14213. // it will be followed by a mediaElement error ...)
  14214. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false });
  14215. // we don't need to do more than that, as accordin to the spec, updateend will be fired just after
  14216. }
  14217. }, {
  14218. key: 'onBufferReset',
  14219. value: function onBufferReset() {
  14220. var sourceBuffer = this.sourceBuffer;
  14221. for (var type in sourceBuffer) {
  14222. var sb = sourceBuffer[type];
  14223. try {
  14224. this.mediaSource.removeSourceBuffer(sb);
  14225. sb.removeEventListener('updateend', this.onsbue);
  14226. sb.removeEventListener('error', this.onsbe);
  14227. } catch (err) {}
  14228. }
  14229. this.sourceBuffer = {};
  14230. this.flushRange = [];
  14231. this.segments = [];
  14232. this.appended = 0;
  14233. }
  14234. }, {
  14235. key: 'onBufferCodecs',
  14236. value: function onBufferCodecs(tracks) {
  14237. var _this2 = this;
  14238. // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
  14239. // if sourcebuffers already created, do nothing ...
  14240. /** 需要放过tracks, 有新的track需要重新加buffer 使得画面到达时,可以播放画面
  14241. if (Object.keys(this.sourceBuffer).length) {
  14242. return;
  14243. }*/
  14244. Object.keys(tracks).forEach(function (trackName) {
  14245. _this2.pendingTracks[trackName] = tracks[trackName];
  14246. });
  14247. var mediaSource = this.mediaSource;
  14248. this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
  14249. if (mediaSource && mediaSource.readyState === 'open') {
  14250. this.checkPendingTracks();
  14251. }
  14252. }
  14253. }, {
  14254. key: 'createSourceBuffers',
  14255. value: function createSourceBuffers(tracks) {
  14256. var sourceBuffer = this.sourceBuffer,
  14257. mediaSource = this.mediaSource;
  14258. for (var trackName in tracks) {
  14259. if (!sourceBuffer[trackName]) {
  14260. var track = tracks[trackName];
  14261. // use levelCodec as first priority
  14262. var codec = track.levelCodec || track.codec;
  14263. var mimeType = track.container + ';codecs=' + codec;
  14264. _logger.logger.log('creating sourceBuffer(' + mimeType + ')');
  14265. try {
  14266. var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
  14267. sb.addEventListener('updateend', this.onsbue);
  14268. sb.addEventListener('error', this.onsbe);
  14269. this.tracks[trackName] = { codec: codec, container: track.container };
  14270. track.buffer = sb;
  14271. } catch (err) {
  14272. if (err.code == 22) {
  14273. _logger.logger.log("Found new track, try to rebuild");
  14274. this._paused = false;
  14275. // setup the media source
  14276. var ms = this.mediaSource = new MediaSource();
  14277. // Media Source listeners
  14278. this.onmso = this.onMediaSourceOpen.bind(this);
  14279. this.onmse = this.onMediaSourceEnded.bind(this);
  14280. this.onmsc = this.onMediaSourceClose.bind(this);
  14281. for (var i = 0; i < Object.keys(this.tracks).length; i++) {
  14282. var _track = this.tracks[Object.keys(this.tracks)[i]];
  14283. this.pendingTracks[Object.keys(this.tracks)[i]] = _track;
  14284. }
  14285. this.tracks = {};
  14286. this.sourceBuffer = {};
  14287. ms.addEventListener('sourceopen', this.onmso);
  14288. ms.addEventListener('sourceended', this.onmse);
  14289. ms.addEventListener('sourceclose', this.onmsc);
  14290. // link video and media Source
  14291. this.media.src = window.URL.createObjectURL(ms);
  14292. // cache the locally generated object url
  14293. this._objectUrl = media.src;
  14294. } else {
  14295. _logger.logger.error('error while trying to add sourceBuffer:' + err.message);
  14296. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType });
  14297. }
  14298. }
  14299. }
  14300. }
  14301. this.hls.trigger(_events2.default.BUFFER_CREATED, { tracks: tracks });
  14302. }
  14303. }, {
  14304. key: 'onBufferAppending',
  14305. value: function onBufferAppending(data) {
  14306. if (!this._needsFlush) {
  14307. if (!this.segments) {
  14308. this.segments = [data];
  14309. } else {
  14310. this.segments.push(data);
  14311. }
  14312. this.doAppending();
  14313. }
  14314. }
  14315. }, {
  14316. key: 'onBufferAppendFail',
  14317. value: function onBufferAppendFail(data) {
  14318. _logger.logger.error('sourceBuffer error:', data.event);
  14319. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  14320. // this error might not always be fatal (it is fatal if decode error is set, in that case
  14321. // it will be followed by a mediaElement error ...)
  14322. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false });
  14323. }
  14324. // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
  14325. }, {
  14326. key: 'onBufferEos',
  14327. value: function onBufferEos(data) {
  14328. var sb = this.sourceBuffer;
  14329. var dataType = data.type;
  14330. for (var type in sb) {
  14331. if (!dataType || type === dataType) {
  14332. if (!sb[type].ended) {
  14333. sb[type].ended = true;
  14334. _logger.logger.log(type + ' sourceBuffer now EOS');
  14335. }
  14336. }
  14337. }
  14338. this.checkEos();
  14339. }
  14340. // if all source buffers are marked as ended, signal endOfStream() to MediaSource.
  14341. }, {
  14342. key: 'checkEos',
  14343. value: function checkEos() {
  14344. var sb = this.sourceBuffer,
  14345. mediaSource = this.mediaSource;
  14346. if (!mediaSource || mediaSource.readyState !== 'open') {
  14347. this._needsEos = false;
  14348. return;
  14349. }
  14350. for (var type in sb) {
  14351. var sbobj = sb[type];
  14352. if (!sbobj.ended) {
  14353. return;
  14354. }
  14355. if (sbobj.updating) {
  14356. this._needsEos = true;
  14357. return;
  14358. }
  14359. }
  14360. _logger.logger.log('all media data are available, signal endOfStream() to MediaSource and stop loading fragment');
  14361. // Notify the media element that it now has all of the media data
  14362. try {
  14363. mediaSource.endOfStream();
  14364. } catch (e) {
  14365. _logger.logger.warn('exception while calling mediaSource.endOfStream()');
  14366. }
  14367. this._needsEos = false;
  14368. }
  14369. }, {
  14370. key: 'onBufferFlushing',
  14371. value: function onBufferFlushing(data) {
  14372. this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });
  14373. // attempt flush immediately
  14374. this.flushBufferCounter = 0;
  14375. this.doFlush();
  14376. }
  14377. }, {
  14378. key: 'flushLiveBackBuffer',
  14379. value: function flushLiveBackBuffer() {
  14380. // clear back buffer for live only
  14381. if (!this._live) {
  14382. return;
  14383. }
  14384. var liveBackBufferLength = this.hls.config.liveBackBufferLength;
  14385. if (!isFinite(liveBackBufferLength) || liveBackBufferLength < 0) {
  14386. return;
  14387. }
  14388. var currentTime = this.media.currentTime;
  14389. var sourceBuffer = this.sourceBuffer;
  14390. var bufferTypes = Object.keys(sourceBuffer);
  14391. var targetBackBufferPosition = currentTime - Math.max(liveBackBufferLength, this._levelTargetDuration);
  14392. for (var index = bufferTypes.length - 1; index >= 0; index--) {
  14393. var bufferType = bufferTypes[index],
  14394. buffered = sourceBuffer[bufferType].buffered;
  14395. // when target buffer start exceeds actual buffer start
  14396. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  14397. // remove buffer up until current time minus minimum back buffer length (removing buffer too close to current
  14398. // time will lead to playback freezing)
  14399. // credits for level target duration - https://github.com/videojs/http-streaming/blob/3132933b6aa99ddefab29c10447624efd6fd6e52/src/segment-loader.js#L91
  14400. this.removeBufferRange(bufferType, sourceBuffer[bufferType], 0, targetBackBufferPosition);
  14401. }
  14402. }
  14403. }
  14404. }, {
  14405. key: 'onLevelUpdated',
  14406. value: function onLevelUpdated(_ref) {
  14407. var details = _ref.details;
  14408. if (details.fragments.length > 0) {
  14409. this._levelDuration = details.totalduration + details.fragments[0].start;
  14410. this._levelTargetDuration = details.averagetargetduration || details.targetduration || 10;
  14411. this._live = details.live;
  14412. this.updateMediaElementDuration();
  14413. }
  14414. }
  14415. /**
  14416. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  14417. * 'liveDurationInfinity` is set to `true`
  14418. * More details: https://github.com/video-dev/hls.js/issues/355
  14419. */
  14420. }, {
  14421. key: 'updateMediaElementDuration',
  14422. value: function updateMediaElementDuration() {
  14423. var config = this.hls.config;
  14424. var duration = void 0;
  14425. if (this._levelDuration === null || !this.media || !this.mediaSource || !this.sourceBuffer || this.media.readyState === 0 || this.mediaSource.readyState !== 'open') {
  14426. return;
  14427. }
  14428. for (var type in this.sourceBuffer) {
  14429. if (this.sourceBuffer[type].updating === true) {
  14430. // can't set duration whilst a buffer is updating
  14431. return;
  14432. }
  14433. }
  14434. duration = this.media.duration;
  14435. // initialise to the value that the media source is reporting
  14436. if (this._msDuration === null) {
  14437. this._msDuration = this.mediaSource.duration;
  14438. }
  14439. if (this._live === true && config.liveDurationInfinity === true) {
  14440. // Override duration to Infinity
  14441. _logger.logger.log('Media Source duration is set to Infinity');
  14442. this._msDuration = this.mediaSource.duration = Infinity;
  14443. } else if (this._levelDuration > this._msDuration && this._levelDuration > duration || !Number.isFinite(duration)) {
  14444. // levelDuration was the last value we set.
  14445. // not using mediaSource.duration as the browser may tweak this value
  14446. // only update Media Source duration if its value increase, this is to avoid
  14447. // flushing already buffered portion when switching between quality level
  14448. _logger.logger.log('Updating Media Source duration to ' + this._levelDuration.toFixed(3));
  14449. this._msDuration = this.mediaSource.duration = this._levelDuration;
  14450. }
  14451. }
  14452. }, {
  14453. key: 'doFlush',
  14454. value: function doFlush() {
  14455. // loop through all buffer ranges to flush
  14456. while (this.flushRange.length) {
  14457. var range = this.flushRange[0];
  14458. // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer
  14459. if (this.flushBuffer(range.start, range.end, range.type)) {
  14460. // range flushed, remove from flush array
  14461. this.flushRange.shift();
  14462. this.flushBufferCounter = 0;
  14463. } else {
  14464. this._needsFlush = true;
  14465. // avoid looping, wait for SB update end to retrigger a flush
  14466. return;
  14467. }
  14468. }
  14469. if (this.flushRange.length === 0) {
  14470. // everything flushed
  14471. this._needsFlush = false;
  14472. // let's recompute this.appended, which is used to avoid flush looping
  14473. var appended = 0;
  14474. var sourceBuffer = this.sourceBuffer;
  14475. try {
  14476. for (var type in sourceBuffer) {
  14477. appended += sourceBuffer[type].buffered.length;
  14478. }
  14479. } catch (error) {
  14480. // error could be thrown while accessing buffered, in case sourcebuffer has already been removed from MediaSource
  14481. // this is harmess at this stage, catch this to avoid reporting an internal exception
  14482. _logger.logger.error('error while accessing sourceBuffer.buffered');
  14483. }
  14484. this.appended = appended;
  14485. this.hls.trigger(_events2.default.BUFFER_FLUSHED);
  14486. }
  14487. }
  14488. }, {
  14489. key: 'doAppending',
  14490. value: function doAppending() {
  14491. var hls = this.hls,
  14492. segments = this.segments,
  14493. sourceBuffer = this.sourceBuffer;
  14494. if (Object.keys(sourceBuffer).length) {
  14495. if (this.media.error) {
  14496. this.segments = [];
  14497. _logger.logger.error('trying to append although a media error occured, flush segment and abort');
  14498. return;
  14499. }
  14500. if (this.appending) {
  14501. // logger.log(`sb appending in progress`);
  14502. return;
  14503. }
  14504. if (segments && segments.length) {
  14505. var segment = segments.shift();
  14506. try {
  14507. var type = segment.type,
  14508. sb = sourceBuffer[type];
  14509. if (sb) {
  14510. if (!sb.updating) {
  14511. // reset sourceBuffer ended flag before appending segment
  14512. sb.ended = false;
  14513. // logger.log(`appending ${segment.content} ${type} SB, size:${segment.data.length}, ${segment.parent}`);
  14514. this.parent = segment.parent;
  14515. // console.log('append buffer ', segment)
  14516. sb.appendBuffer(segment.data);
  14517. this.appendError = 0;
  14518. this.appended++;
  14519. this.appending = true;
  14520. } else {
  14521. segments.unshift(segment);
  14522. }
  14523. } else {
  14524. // in case we don't have any source buffer matching with this segment type,
  14525. // it means that Mediasource fails to create sourcebuffer
  14526. // discard this segment, and trigger update end
  14527. this.onSBUpdateEnd();
  14528. }
  14529. } catch (err) {
  14530. // in case any error occured while appending, put back segment in segments table
  14531. _logger.logger.error('error while trying to append buffer:' + err.message);
  14532. segments.unshift(segment);
  14533. var event = { type: _errors.ErrorTypes.MEDIA_ERROR, parent: segment.parent };
  14534. if (err.code !== 22) {
  14535. if (this.appendError) {
  14536. this.appendError++;
  14537. } else {
  14538. this.appendError = 1;
  14539. }
  14540. event.details = _errors.ErrorDetails.BUFFER_APPEND_ERROR;
  14541. /* with UHD content, we could get loop of quota exceeded error until
  14542. browser is able to evict some data from sourcebuffer. retrying help recovering this
  14543. */
  14544. if (this.appendError > hls.config.appendErrorMaxRetry) {
  14545. _logger.logger.log('fail ' + hls.config.appendErrorMaxRetry + ' times to append segment in sourceBuffer');
  14546. this.segments = [];
  14547. event.fatal = true;
  14548. hls.trigger(_events2.default.ERROR, event);
  14549. } else {
  14550. event.fatal = false;
  14551. hls.trigger(_events2.default.ERROR, event);
  14552. }
  14553. } else {
  14554. // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
  14555. // let's stop appending any segments, and report BUFFER_FULL_ERROR error
  14556. this.segments = [];
  14557. event.details = _errors.ErrorDetails.BUFFER_FULL_ERROR;
  14558. event.fatal = false;
  14559. hls.trigger(_events2.default.ERROR, event);
  14560. }
  14561. }
  14562. }
  14563. }
  14564. }
  14565. /*
  14566. flush specified buffered range,
  14567. return true once range has been flushed.
  14568. as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end
  14569. */
  14570. }, {
  14571. key: 'flushBuffer',
  14572. value: function flushBuffer(startOffset, endOffset, typeIn) {
  14573. var sb = void 0;
  14574. var sourceBuffer = this.sourceBuffer;
  14575. if (Object.keys(sourceBuffer).length) {
  14576. _logger.logger.log('flushBuffer,pos/start/end: ' + this.media.currentTime.toFixed(3) + '/' + startOffset + '/' + endOffset);
  14577. // safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments
  14578. if (this.flushBufferCounter < this.appended) {
  14579. for (var type in sourceBuffer) {
  14580. // check if sourcebuffer type is defined (typeIn): if yes, let's only flush this one
  14581. // if no, let's flush all sourcebuffers
  14582. if (typeIn && type !== typeIn) {
  14583. continue;
  14584. }
  14585. sb = sourceBuffer[type];
  14586. // we are going to flush buffer, mark source buffer as 'not ended'
  14587. sb.ended = false;
  14588. if (!sb.updating) {
  14589. if (this.removeBufferRange(type, sb, startOffset, endOffset)) {
  14590. this.flushBufferCounter++;
  14591. return false;
  14592. }
  14593. } else {
  14594. _logger.logger.warn('cannot flush, sb updating in progress');
  14595. return false;
  14596. }
  14597. }
  14598. } else {
  14599. _logger.logger.warn('abort flushing too many retries');
  14600. }
  14601. _logger.logger.log('buffer flushed');
  14602. }
  14603. // everything flushed !
  14604. return true;
  14605. }
  14606. /**
  14607. * Removes first buffered range from provided source buffer that lies within given start and end offsets.
  14608. *
  14609. * @param type Type of the source buffer, logging purposes only.
  14610. * @param sb Target SourceBuffer instance.
  14611. * @param startOffset
  14612. * @param endOffset
  14613. *
  14614. * @returns {boolean} True when source buffer remove requested.
  14615. */
  14616. }, {
  14617. key: 'removeBufferRange',
  14618. value: function removeBufferRange(type, sb, startOffset, endOffset) {
  14619. try {
  14620. for (var i = 0; i < sb.buffered.length; i++) {
  14621. var bufStart = sb.buffered.start(i);
  14622. var bufEnd = sb.buffered.end(i);
  14623. var removeStart = Math.max(bufStart, startOffset);
  14624. var removeEnd = Math.min(bufEnd, endOffset);
  14625. /* sometimes sourcebuffer.remove() does not flush
  14626. the exact expected time range.
  14627. to avoid rounding issues/infinite loop,
  14628. only flush buffer range of length greater than 500ms.
  14629. */
  14630. if (Math.min(removeEnd, bufEnd) - removeStart > 0.5) {
  14631. _logger.logger.log('sb remove ' + type + ' [' + removeStart + ',' + removeEnd + '], of [' + bufStart + ',' + bufEnd + '], pos:' + this.media.currentTime);
  14632. sb.remove(removeStart, removeEnd);
  14633. return true;
  14634. }
  14635. }
  14636. } catch (error) {
  14637. _logger.logger.warn('removeBufferRange failed', error);
  14638. }
  14639. return false;
  14640. }
  14641. }]);
  14642. return BufferController;
  14643. }(_eventHandler2.default);
  14644. exports.default = BufferController;
  14645. module.exports = exports['default'];
  14646. /***/ }),
  14647. /* 65 */
  14648. /***/ (function(module, exports, __webpack_require__) {
  14649. "use strict";
  14650. Object.defineProperty(exports, "__esModule", {
  14651. value: true
  14652. });
  14653. 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; }; }();
  14654. var _events = __webpack_require__(1);
  14655. var _events2 = _interopRequireDefault(_events);
  14656. var _eventHandler = __webpack_require__(3);
  14657. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  14658. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  14659. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  14660. 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; }
  14661. 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; } /*
  14662. * cap stream level to media size dimension controller
  14663. */
  14664. var CapLevelController = function (_EventHandler) {
  14665. _inherits(CapLevelController, _EventHandler);
  14666. function CapLevelController(hls) {
  14667. _classCallCheck(this, CapLevelController);
  14668. 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));
  14669. _this.autoLevelCapping = Number.POSITIVE_INFINITY;
  14670. _this.firstLevel = null;
  14671. _this.levels = [];
  14672. _this.media = null;
  14673. _this.restrictedLevels = [];
  14674. _this.timer = null;
  14675. return _this;
  14676. }
  14677. _createClass(CapLevelController, [{
  14678. key: 'destroy',
  14679. value: function destroy() {
  14680. if (this.hls.config.capLevelToPlayerSize) {
  14681. this.media = null;
  14682. this._stopCapping();
  14683. }
  14684. }
  14685. }, {
  14686. key: 'onFpsDropLevelCapping',
  14687. value: function onFpsDropLevelCapping(data) {
  14688. // Don't add a restricted level more than once
  14689. if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {
  14690. this.restrictedLevels.push(data.droppedLevel);
  14691. }
  14692. }
  14693. }, {
  14694. key: 'onMediaAttaching',
  14695. value: function onMediaAttaching(data) {
  14696. this.media = data.media instanceof window.HTMLVideoElement ? data.media : null;
  14697. }
  14698. }, {
  14699. key: 'onManifestParsed',
  14700. value: function onManifestParsed(data) {
  14701. var hls = this.hls;
  14702. this.restrictedLevels = [];
  14703. this.levels = data.levels;
  14704. this.firstLevel = data.firstLevel;
  14705. if (hls.config.capLevelToPlayerSize && data.video) {
  14706. // Start capping immediately if the manifest has signaled video codecs
  14707. this._startCapping();
  14708. }
  14709. }
  14710. // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  14711. // to the first level
  14712. }, {
  14713. key: 'onBufferCodecs',
  14714. value: function onBufferCodecs(data) {
  14715. var hls = this.hls;
  14716. if (hls.config.capLevelToPlayerSize && data.video) {
  14717. // If the manifest did not signal a video codec capping has been deferred until we're certain video is present
  14718. this._startCapping();
  14719. }
  14720. }
  14721. }, {
  14722. key: 'onLevelsUpdated',
  14723. value: function onLevelsUpdated(data) {
  14724. this.levels = data.levels;
  14725. }
  14726. }, {
  14727. key: 'onMediaDetaching',
  14728. value: function onMediaDetaching() {
  14729. this._stopCapping();
  14730. }
  14731. }, {
  14732. key: 'detectPlayerSize',
  14733. value: function detectPlayerSize() {
  14734. if (this.media) {
  14735. var levelsLength = this.levels ? this.levels.length : 0;
  14736. if (levelsLength) {
  14737. var hls = this.hls;
  14738. hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);
  14739. if (hls.autoLevelCapping > this.autoLevelCapping) {
  14740. // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
  14741. // usually happen when the user go to the fullscreen mode.
  14742. hls.streamController.nextLevelSwitch();
  14743. }
  14744. this.autoLevelCapping = hls.autoLevelCapping;
  14745. }
  14746. }
  14747. }
  14748. /*
  14749. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  14750. */
  14751. }, {
  14752. key: 'getMaxLevel',
  14753. value: function getMaxLevel(capLevelIndex) {
  14754. var _this2 = this;
  14755. if (!this.levels) {
  14756. return -1;
  14757. }
  14758. var validLevels = this.levels.filter(function (level, index) {
  14759. return CapLevelController.isLevelAllowed(index, _this2.restrictedLevels) && index <= capLevelIndex;
  14760. });
  14761. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  14762. }
  14763. }, {
  14764. key: '_startCapping',
  14765. value: function _startCapping() {
  14766. if (this.timer) {
  14767. // Don't reset capping if started twice; this can happen if the manifest signals a video codec
  14768. return;
  14769. }
  14770. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  14771. this.hls.firstLevel = this.getMaxLevel(this.firstLevel);
  14772. clearInterval(this.timer);
  14773. this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);
  14774. this.detectPlayerSize();
  14775. }
  14776. }, {
  14777. key: '_stopCapping',
  14778. value: function _stopCapping() {
  14779. this.restrictedLevels = [];
  14780. this.firstLevel = null;
  14781. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  14782. if (this.timer) {
  14783. this.timer = clearInterval(this.timer);
  14784. this.timer = null;
  14785. }
  14786. }
  14787. }, {
  14788. key: 'mediaWidth',
  14789. get: function get() {
  14790. var width = void 0;
  14791. var media = this.media;
  14792. if (media) {
  14793. width = media.width || media.clientWidth || media.offsetWidth;
  14794. width *= CapLevelController.contentScaleFactor;
  14795. }
  14796. return width;
  14797. }
  14798. }, {
  14799. key: 'mediaHeight',
  14800. get: function get() {
  14801. var height = void 0;
  14802. var media = this.media;
  14803. if (media) {
  14804. height = media.height || media.clientHeight || media.offsetHeight;
  14805. height *= CapLevelController.contentScaleFactor;
  14806. }
  14807. return height;
  14808. }
  14809. }], [{
  14810. key: 'isLevelAllowed',
  14811. value: function isLevelAllowed(level) {
  14812. var restrictedLevels = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  14813. return restrictedLevels.indexOf(level) === -1;
  14814. }
  14815. }, {
  14816. key: 'getMaxLevelByMediaSize',
  14817. value: function getMaxLevelByMediaSize(levels, width, height) {
  14818. if (!levels || levels && !levels.length) {
  14819. return -1;
  14820. }
  14821. // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
  14822. // to determine whether we've chosen the greatest bandwidth for the media's dimensions
  14823. var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) {
  14824. if (!nextLevel) {
  14825. return true;
  14826. }
  14827. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  14828. };
  14829. // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
  14830. // the max level
  14831. var maxLevelIndex = levels.length - 1;
  14832. for (var i = 0; i < levels.length; i += 1) {
  14833. var level = levels[i];
  14834. if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {
  14835. maxLevelIndex = i;
  14836. break;
  14837. }
  14838. }
  14839. return maxLevelIndex;
  14840. }
  14841. }, {
  14842. key: 'contentScaleFactor',
  14843. get: function get() {
  14844. var pixelRatio = 1;
  14845. try {
  14846. pixelRatio = window.devicePixelRatio;
  14847. } catch (e) {}
  14848. return pixelRatio;
  14849. }
  14850. }]);
  14851. return CapLevelController;
  14852. }(_eventHandler2.default);
  14853. exports.default = CapLevelController;
  14854. module.exports = exports['default'];
  14855. /***/ }),
  14856. /* 66 */
  14857. /***/ (function(module, exports, __webpack_require__) {
  14858. "use strict";
  14859. Object.defineProperty(exports, "__esModule", {
  14860. value: true
  14861. });
  14862. 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; }; }();
  14863. var _events = __webpack_require__(1);
  14864. var _events2 = _interopRequireDefault(_events);
  14865. var _eventHandler = __webpack_require__(3);
  14866. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  14867. var _logger = __webpack_require__(0);
  14868. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  14869. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  14870. 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; }
  14871. 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; } /*
  14872. * FPS Controller
  14873. */
  14874. var _window = window,
  14875. performance = _window.performance;
  14876. var FPSController = function (_EventHandler) {
  14877. _inherits(FPSController, _EventHandler);
  14878. function FPSController(hls) {
  14879. _classCallCheck(this, FPSController);
  14880. return _possibleConstructorReturn(this, (FPSController.__proto__ || Object.getPrototypeOf(FPSController)).call(this, hls, _events2.default.MEDIA_ATTACHING));
  14881. }
  14882. _createClass(FPSController, [{
  14883. key: 'destroy',
  14884. value: function destroy() {
  14885. if (this.timer) {
  14886. clearInterval(this.timer);
  14887. }
  14888. this.isVideoPlaybackQualityAvailable = false;
  14889. }
  14890. }, {
  14891. key: 'onMediaAttaching',
  14892. value: function onMediaAttaching(data) {
  14893. var config = this.hls.config;
  14894. if (config.capLevelOnFPSDrop) {
  14895. var video = this.video = data.media instanceof window.HTMLVideoElement ? data.media : null;
  14896. if (typeof video.getVideoPlaybackQuality === 'function') {
  14897. this.isVideoPlaybackQualityAvailable = true;
  14898. }
  14899. clearInterval(this.timer);
  14900. this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  14901. }
  14902. }
  14903. }, {
  14904. key: 'checkFPS',
  14905. value: function checkFPS(video, decodedFrames, droppedFrames) {
  14906. var currentTime = performance.now();
  14907. if (decodedFrames) {
  14908. if (this.lastTime) {
  14909. var currentPeriod = currentTime - this.lastTime,
  14910. currentDropped = droppedFrames - this.lastDroppedFrames,
  14911. currentDecoded = decodedFrames - this.lastDecodedFrames,
  14912. droppedFPS = 1000 * currentDropped / currentPeriod,
  14913. hls = this.hls;
  14914. hls.trigger(_events2.default.FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames });
  14915. if (droppedFPS > 0) {
  14916. // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
  14917. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  14918. var currentLevel = hls.currentLevel;
  14919. _logger.logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
  14920. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  14921. currentLevel = currentLevel - 1;
  14922. hls.trigger(_events2.default.FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: hls.currentLevel });
  14923. hls.autoLevelCapping = currentLevel;
  14924. hls.streamController.nextLevelSwitch();
  14925. }
  14926. }
  14927. }
  14928. }
  14929. this.lastTime = currentTime;
  14930. this.lastDroppedFrames = droppedFrames;
  14931. this.lastDecodedFrames = decodedFrames;
  14932. }
  14933. }
  14934. }, {
  14935. key: 'checkFPSInterval',
  14936. value: function checkFPSInterval() {
  14937. var video = this.video;
  14938. if (video) {
  14939. if (this.isVideoPlaybackQualityAvailable) {
  14940. var videoPlaybackQuality = video.getVideoPlaybackQuality();
  14941. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  14942. } else {
  14943. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  14944. }
  14945. }
  14946. }
  14947. }]);
  14948. return FPSController;
  14949. }(_eventHandler2.default);
  14950. exports.default = FPSController;
  14951. module.exports = exports['default'];
  14952. /***/ }),
  14953. /* 67 */
  14954. /***/ (function(module, exports, __webpack_require__) {
  14955. "use strict";
  14956. Object.defineProperty(exports, "__esModule", {
  14957. value: true
  14958. });
  14959. 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; }; }(); /**
  14960. * XHR based logger
  14961. */
  14962. var _logger = __webpack_require__(0);
  14963. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  14964. var _window = window,
  14965. performance = _window.performance,
  14966. XMLHttpRequest = _window.XMLHttpRequest;
  14967. var XhrLoader = function () {
  14968. function XhrLoader(config) {
  14969. _classCallCheck(this, XhrLoader);
  14970. if (config && config.xhrSetup) {
  14971. this.xhrSetup = config.xhrSetup;
  14972. }
  14973. }
  14974. _createClass(XhrLoader, [{
  14975. key: 'destroy',
  14976. value: function destroy() {
  14977. this.abort();
  14978. this.loader = null;
  14979. }
  14980. }, {
  14981. key: 'abort',
  14982. value: function abort() {
  14983. var loader = this.loader;
  14984. if (loader && loader.readyState !== 4) {
  14985. this.stats.aborted = true;
  14986. loader.abort();
  14987. }
  14988. window.clearTimeout(this.requestTimeout);
  14989. this.requestTimeout = null;
  14990. window.clearTimeout(this.retryTimeout);
  14991. this.retryTimeout = null;
  14992. }
  14993. }, {
  14994. key: 'load',
  14995. value: function load(context, config, callbacks) {
  14996. this.context = context;
  14997. this.config = config;
  14998. this.callbacks = callbacks;
  14999. this.stats = { trequest: performance.now(), retry: 0 };
  15000. this.retryDelay = config.retryDelay;
  15001. this.loadInternal();
  15002. }
  15003. }, {
  15004. key: 'loadInternal',
  15005. value: function loadInternal() {
  15006. var xhr = void 0,
  15007. context = this.context;
  15008. xhr = this.loader = new XMLHttpRequest();
  15009. var stats = this.stats;
  15010. stats.tfirst = 0;
  15011. stats.loaded = 0;
  15012. var xhrSetup = this.xhrSetup;
  15013. try {
  15014. if (xhrSetup) {
  15015. try {
  15016. xhrSetup(xhr, context.url);
  15017. } catch (e) {
  15018. // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");}
  15019. // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN
  15020. xhr.open('GET', context.url, true);
  15021. xhrSetup(xhr, context.url);
  15022. }
  15023. }
  15024. if (!xhr.readyState) {
  15025. xhr.open('GET', context.url, true);
  15026. }
  15027. } catch (e) {
  15028. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  15029. this.callbacks.onError({ code: xhr.status, text: e.message }, context, xhr);
  15030. return;
  15031. }
  15032. if (context.rangeEnd) {
  15033. xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
  15034. }
  15035. xhr.onreadystatechange = this.readystatechange.bind(this);
  15036. xhr.onprogress = this.loadprogress.bind(this);
  15037. xhr.responseType = context.responseType;
  15038. // setup timeout before we perform request
  15039. this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout);
  15040. xhr.send();
  15041. }
  15042. }, {
  15043. key: 'readystatechange',
  15044. value: function readystatechange(event) {
  15045. var xhr = event.currentTarget,
  15046. readyState = xhr.readyState,
  15047. stats = this.stats,
  15048. context = this.context,
  15049. config = this.config;
  15050. // don't proceed if xhr has been aborted
  15051. if (stats.aborted) {
  15052. return;
  15053. }
  15054. // >= HEADERS_RECEIVED
  15055. if (readyState >= 2) {
  15056. // clear xhr timeout and rearm it if readyState less than 4
  15057. window.clearTimeout(this.requestTimeout);
  15058. if (stats.tfirst === 0) {
  15059. stats.tfirst = Math.max(performance.now(), stats.trequest);
  15060. }
  15061. if (readyState === 4) {
  15062. var status = xhr.status;
  15063. // http status between 200 to 299 are all successful
  15064. if (status >= 200 && status < 300) {
  15065. stats.tload = Math.max(stats.tfirst, performance.now());
  15066. var data = void 0,
  15067. len = void 0;
  15068. if (context.responseType === 'arraybuffer') {
  15069. data = xhr.response;
  15070. len = data.byteLength;
  15071. } else {
  15072. data = xhr.responseText;
  15073. len = data.length;
  15074. }
  15075. stats.loaded = stats.total = len;
  15076. var response = { url: xhr.responseURL, data: data };
  15077. this.callbacks.onSuccess(response, stats, context, xhr);
  15078. } else {
  15079. // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
  15080. if (stats.retry >= config.maxRetry || status >= 400 && status < 499) {
  15081. _logger.logger.error(status + ' while loading ' + context.url);
  15082. this.callbacks.onError({ code: status, text: xhr.statusText }, context, xhr);
  15083. } else {
  15084. // retry
  15085. _logger.logger.warn(status + ' while loading ' + context.url + ', retrying in ' + this.retryDelay + '...');
  15086. // aborts and resets internal state
  15087. this.destroy();
  15088. // schedule retry
  15089. this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  15090. // set exponential backoff
  15091. this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);
  15092. stats.retry++;
  15093. }
  15094. }
  15095. } else {
  15096. // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
  15097. this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout);
  15098. }
  15099. }
  15100. }
  15101. }, {
  15102. key: 'loadtimeout',
  15103. value: function loadtimeout() {
  15104. _logger.logger.warn('timeout while loading ' + this.context.url);
  15105. this.callbacks.onTimeout(this.stats, this.context, null);
  15106. }
  15107. }, {
  15108. key: 'loadprogress',
  15109. value: function loadprogress(event) {
  15110. var xhr = event.currentTarget,
  15111. stats = this.stats;
  15112. stats.loaded = event.loaded;
  15113. if (event.lengthComputable) {
  15114. stats.total = event.total;
  15115. }
  15116. var onProgress = this.callbacks.onProgress;
  15117. if (onProgress) {
  15118. // third arg is to provide on progress data
  15119. onProgress(stats, this.context, null, xhr);
  15120. }
  15121. }
  15122. }]);
  15123. return XhrLoader;
  15124. }();
  15125. exports.default = XhrLoader;
  15126. module.exports = exports['default'];
  15127. /***/ }),
  15128. /* 68 */
  15129. /***/ (function(module, exports, __webpack_require__) {
  15130. "use strict";
  15131. Object.defineProperty(exports, "__esModule", {
  15132. value: true
  15133. });
  15134. 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; }; }();
  15135. var _events = __webpack_require__(1);
  15136. var _events2 = _interopRequireDefault(_events);
  15137. var _taskLoop = __webpack_require__(28);
  15138. var _taskLoop2 = _interopRequireDefault(_taskLoop);
  15139. var _logger = __webpack_require__(0);
  15140. var _errors = __webpack_require__(2);
  15141. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  15142. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  15143. 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; }
  15144. 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; }
  15145. /**
  15146. * @class AudioTrackController
  15147. * @implements {EventHandler}
  15148. *
  15149. * Handles main manifest and audio-track metadata loaded,
  15150. * owns and exposes the selectable audio-tracks data-models.
  15151. *
  15152. * Exposes internal interface to select available audio-tracks.
  15153. *
  15154. * Handles errors on loading audio-track playlists. Manages fallback mechanism
  15155. * with redundants tracks (group-IDs).
  15156. *
  15157. * Handles level-loading and group-ID switches for video (fallback on video levels),
  15158. * and eventually adapts the audio-track group-ID to match.
  15159. *
  15160. * @fires AUDIO_TRACK_LOADING
  15161. * @fires AUDIO_TRACK_SWITCHING
  15162. * @fires AUDIO_TRACKS_UPDATED
  15163. * @fires ERROR
  15164. *
  15165. */
  15166. var AudioTrackController = function (_TaskLoop) {
  15167. _inherits(AudioTrackController, _TaskLoop);
  15168. function AudioTrackController(hls) {
  15169. _classCallCheck(this, AudioTrackController);
  15170. /**
  15171. * @private
  15172. * Currently selected index in `tracks`
  15173. * @member {number} trackId
  15174. */
  15175. 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));
  15176. _this._trackId = -1;
  15177. /**
  15178. * @private
  15179. * If should select tracks according to default track attribute
  15180. * @member {boolean} _selectDefaultTrack
  15181. */
  15182. _this._selectDefaultTrack = true;
  15183. /**
  15184. * @public
  15185. * All tracks available
  15186. * @member {AudioTrack[]}
  15187. */
  15188. _this.tracks = [];
  15189. /**
  15190. * @public
  15191. * List of blacklisted audio track IDs (that have caused failure)
  15192. * @member {number[]}
  15193. */
  15194. _this.trackIdBlacklist = Object.create(null);
  15195. /**
  15196. * @public
  15197. * The currently running group ID for audio
  15198. * (we grab this on manifest-parsed and new level-loaded)
  15199. * @member {string}
  15200. */
  15201. _this.audioGroupId = null;
  15202. return _this;
  15203. }
  15204. /**
  15205. * Reset audio tracks on new manifest loading.
  15206. */
  15207. _createClass(AudioTrackController, [{
  15208. key: 'onManifestLoading',
  15209. value: function onManifestLoading() {
  15210. this.tracks = [];
  15211. this._trackId = -1;
  15212. this._selectDefaultTrack = true;
  15213. }
  15214. /**
  15215. * Store tracks data from manifest parsed data.
  15216. *
  15217. * Trigger AUDIO_TRACKS_UPDATED event.
  15218. *
  15219. * @param {*} data
  15220. */
  15221. }, {
  15222. key: 'onManifestParsed',
  15223. value: function onManifestParsed(data) {
  15224. var tracks = this.tracks = data.audioTracks || [];
  15225. this.hls.trigger(_events2.default.AUDIO_TRACKS_UPDATED, { audioTracks: tracks });
  15226. }
  15227. /**
  15228. * Store track details of loaded track in our data-model.
  15229. *
  15230. * Set-up metadata update interval task for live-mode streams.
  15231. *
  15232. * @param {} data
  15233. */
  15234. }, {
  15235. key: 'onAudioTrackLoaded',
  15236. value: function onAudioTrackLoaded(data) {
  15237. if (data.id >= this.tracks.length) {
  15238. _logger.logger.warn('Invalid audio track id:', data.id);
  15239. return;
  15240. }
  15241. _logger.logger.log('audioTrack ' + data.id + ' loaded');
  15242. this.tracks[data.id].details = data.details;
  15243. // check if current playlist is a live playlist
  15244. // and if we have already our reload interval setup
  15245. if (data.details.live && !this.hasInterval()) {
  15246. // if live playlist we will have to reload it periodically
  15247. // set reload period to playlist target duration
  15248. var updatePeriodMs = data.details.targetduration * 1000;
  15249. this.setInterval(updatePeriodMs);
  15250. }
  15251. if (!data.details.live && this.hasInterval()) {
  15252. // playlist is not live and timer is scheduled: cancel it
  15253. this.clearInterval();
  15254. }
  15255. }
  15256. /**
  15257. * Update the internal group ID to any audio-track we may have set manually
  15258. * or because of a failure-handling fallback.
  15259. *
  15260. * Quality-levels should update to that group ID in this case.
  15261. *
  15262. * @param {*} data
  15263. */
  15264. }, {
  15265. key: 'onAudioTrackSwitched',
  15266. value: function onAudioTrackSwitched(data) {
  15267. var audioGroupId = this.tracks[data.id].groupId;
  15268. if (audioGroupId && this.audioGroupId !== audioGroupId) {
  15269. this.audioGroupId = audioGroupId;
  15270. }
  15271. }
  15272. /**
  15273. * When a level gets loaded, if it has redundant audioGroupIds (in the same ordinality as it's redundant URLs)
  15274. * we are setting our audio-group ID internally to the one set, if it is different from the group ID currently set.
  15275. *
  15276. * If group-ID got update, we re-select the appropriate audio-track with this group-ID matching the currently
  15277. * selected one (based on NAME property).
  15278. *
  15279. * @param {*} data
  15280. */
  15281. }, {
  15282. key: 'onLevelLoaded',
  15283. value: function onLevelLoaded(data) {
  15284. // FIXME: crashes because currentLevel is undefined
  15285. // const levelInfo = this.hls.levels[this.hls.currentLevel];
  15286. var levelInfo = this.hls.levels[data.level];
  15287. if (!levelInfo.audioGroupIds) {
  15288. return;
  15289. }
  15290. var audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];
  15291. if (this.audioGroupId !== audioGroupId) {
  15292. this.audioGroupId = audioGroupId;
  15293. this._selectInitialAudioTrack();
  15294. }
  15295. }
  15296. /**
  15297. * Handle network errors loading audio track manifests
  15298. * and also pausing on any netwok errors.
  15299. *
  15300. * @param {ErrorEventData} data
  15301. */
  15302. }, {
  15303. key: 'onError',
  15304. value: function onError(data) {
  15305. // Only handle network errors
  15306. if (data.type !== _errors.ErrorTypes.NETWORK_ERROR) {
  15307. return;
  15308. }
  15309. // If fatal network error, cancel update task
  15310. if (data.fatal) {
  15311. this.clearInterval();
  15312. }
  15313. // If not an audio-track loading error don't handle further
  15314. if (data.details !== _errors.ErrorDetails.AUDIO_TRACK_LOAD_ERROR) {
  15315. return;
  15316. }
  15317. _logger.logger.warn('Network failure on audio-track id:', data.context.id);
  15318. this._handleLoadError();
  15319. }
  15320. /**
  15321. * @type {AudioTrack[]} Audio-track list we own
  15322. */
  15323. }, {
  15324. key: '_setAudioTrack',
  15325. /**
  15326. * @private
  15327. * @param {number} newId
  15328. */
  15329. value: function _setAudioTrack(newId) {
  15330. // noop on same audio track id as already set
  15331. if (this._trackId === newId && this.tracks[this._trackId].details) {
  15332. _logger.logger.debug('Same id as current audio-track passed, and track details available -> no-op');
  15333. return;
  15334. }
  15335. // check if level idx is valid
  15336. if (newId < 0 || newId >= this.tracks.length) {
  15337. _logger.logger.warn('Invalid id passed to audio-track controller');
  15338. return;
  15339. }
  15340. var audioTrack = this.tracks[newId];
  15341. _logger.logger.log('Now switching to audio-track index ' + newId);
  15342. // stopping live reloading timer if any
  15343. this.clearInterval();
  15344. this._trackId = newId;
  15345. var url = audioTrack.url,
  15346. type = audioTrack.type,
  15347. id = audioTrack.id;
  15348. this.hls.trigger(_events2.default.AUDIO_TRACK_SWITCHING, { id: id, type: type, url: url });
  15349. this._loadTrackDetailsIfNeeded(audioTrack);
  15350. }
  15351. /**
  15352. * @override
  15353. */
  15354. }, {
  15355. key: 'doTick',
  15356. value: function doTick() {
  15357. this._updateTrack(this._trackId);
  15358. }
  15359. /**
  15360. * Select initial track
  15361. * @private
  15362. */
  15363. }, {
  15364. key: '_selectInitialAudioTrack',
  15365. value: function _selectInitialAudioTrack() {
  15366. var _this2 = this;
  15367. var tracks = this.tracks;
  15368. if (!tracks.length) {
  15369. return;
  15370. }
  15371. var currentAudioTrack = this.tracks[this._trackId];
  15372. var name = null;
  15373. if (currentAudioTrack) {
  15374. name = currentAudioTrack.name;
  15375. }
  15376. // Pre-select default tracks if there are any
  15377. if (this._selectDefaultTrack) {
  15378. var defaultTracks = tracks.filter(function (track) {
  15379. return track.default;
  15380. });
  15381. if (defaultTracks.length) {
  15382. tracks = defaultTracks;
  15383. } else {
  15384. _logger.logger.warn('No default audio tracks defined');
  15385. }
  15386. }
  15387. var trackFound = false;
  15388. var traverseTracks = function traverseTracks() {
  15389. // Select track with right group ID
  15390. tracks.forEach(function (track) {
  15391. if (trackFound) {
  15392. return;
  15393. }
  15394. // We need to match the (pre-)selected group ID
  15395. // and the NAME of the current track.
  15396. if ((!_this2.audioGroupId || track.groupId === _this2.audioGroupId) && (!name || name === track.name)) {
  15397. // If there was a previous track try to stay with the same `NAME`.
  15398. // It should be unique across tracks of same group, and consistent through redundant track groups.
  15399. _this2._setAudioTrack(track.id);
  15400. trackFound = true;
  15401. }
  15402. });
  15403. };
  15404. traverseTracks();
  15405. if (!trackFound) {
  15406. name = null;
  15407. traverseTracks();
  15408. }
  15409. if (!trackFound) {
  15410. _logger.logger.error('No track found for running audio group-ID: ' + this.audioGroupId);
  15411. this.hls.trigger(_events2.default.ERROR, {
  15412. type: _errors.ErrorTypes.MEDIA_ERROR,
  15413. details: _errors.ErrorDetails.AUDIO_TRACK_LOAD_ERROR,
  15414. fatal: true
  15415. });
  15416. }
  15417. }
  15418. /**
  15419. * @private
  15420. * @param {AudioTrack} audioTrack
  15421. * @returns {boolean}
  15422. */
  15423. }, {
  15424. key: '_needsTrackLoading',
  15425. value: function _needsTrackLoading(audioTrack) {
  15426. var details = audioTrack.details,
  15427. url = audioTrack.url;
  15428. if (!details || details.live) {
  15429. // check if we face an audio track embedded in main playlist (audio track without URI attribute)
  15430. return !!url;
  15431. }
  15432. return false;
  15433. }
  15434. /**
  15435. * @private
  15436. * @param {AudioTrack} audioTrack
  15437. */
  15438. }, {
  15439. key: '_loadTrackDetailsIfNeeded',
  15440. value: function _loadTrackDetailsIfNeeded(audioTrack) {
  15441. if (this._needsTrackLoading(audioTrack)) {
  15442. var url = audioTrack.url,
  15443. id = audioTrack.id;
  15444. // track not retrieved yet, or live playlist we need to (re)load it
  15445. _logger.logger.log('loading audio-track playlist for id: ' + id);
  15446. this.hls.trigger(_events2.default.AUDIO_TRACK_LOADING, { url: url, id: id });
  15447. }
  15448. }
  15449. /**
  15450. * @private
  15451. * @param {number} newId
  15452. */
  15453. }, {
  15454. key: '_updateTrack',
  15455. value: function _updateTrack(newId) {
  15456. // check if level idx is valid
  15457. if (newId < 0 || newId >= this.tracks.length) {
  15458. return;
  15459. }
  15460. // stopping live reloading timer if any
  15461. this.clearInterval();
  15462. this._trackId = newId;
  15463. _logger.logger.log('trying to update audio-track ' + newId);
  15464. var audioTrack = this.tracks[newId];
  15465. this._loadTrackDetailsIfNeeded(audioTrack);
  15466. }
  15467. /**
  15468. * @private
  15469. */
  15470. }, {
  15471. key: '_handleLoadError',
  15472. value: function _handleLoadError() {
  15473. // First, let's black list current track id
  15474. this.trackIdBlacklist[this._trackId] = true;
  15475. // Let's try to fall back on a functional audio-track with the same group ID
  15476. var previousId = this._trackId;
  15477. var _tracks$previousId = this.tracks[previousId],
  15478. name = _tracks$previousId.name,
  15479. language = _tracks$previousId.language,
  15480. groupId = _tracks$previousId.groupId;
  15481. _logger.logger.warn('Loading failed on audio track id: ' + previousId + ', group-id: ' + groupId + ', name/language: "' + name + '" / "' + language + '"');
  15482. // Find a non-blacklisted track ID with the same NAME
  15483. // At least a track that is not blacklisted, thus on another group-ID.
  15484. var newId = previousId;
  15485. for (var i = 0; i < this.tracks.length; i++) {
  15486. if (this.trackIdBlacklist[i]) {
  15487. continue;
  15488. }
  15489. var newTrack = this.tracks[i];
  15490. if (newTrack.name === name) {
  15491. newId = i;
  15492. break;
  15493. }
  15494. }
  15495. if (newId === previousId) {
  15496. _logger.logger.warn('No fallback audio-track found for name/language: "' + name + '" / "' + language + '"');
  15497. return;
  15498. }
  15499. _logger.logger.log('Attempting audio-track fallback id:', newId, 'group-id:', this.tracks[newId].groupId);
  15500. this._setAudioTrack(newId);
  15501. }
  15502. }, {
  15503. key: 'audioTracks',
  15504. get: function get() {
  15505. return this.tracks;
  15506. }
  15507. /**
  15508. * @type {number} Index into audio-tracks list of currently selected track.
  15509. */
  15510. }, {
  15511. key: 'audioTrack',
  15512. get: function get() {
  15513. return this._trackId;
  15514. }
  15515. /**
  15516. * Select current track by index
  15517. */
  15518. ,
  15519. set: function set(newId) {
  15520. this._setAudioTrack(newId);
  15521. // If audio track is selected from API then don't choose from the manifest default track
  15522. this._selectDefaultTrack = false;
  15523. }
  15524. }]);
  15525. return AudioTrackController;
  15526. }(_taskLoop2.default);
  15527. exports.default = AudioTrackController;
  15528. module.exports = exports['default'];
  15529. /***/ }),
  15530. /* 69 */
  15531. /***/ (function(module, exports, __webpack_require__) {
  15532. "use strict";
  15533. Object.defineProperty(exports, "__esModule", {
  15534. value: true
  15535. });
  15536. 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; }; }();
  15537. var _binarySearch = __webpack_require__(9);
  15538. var _binarySearch2 = _interopRequireDefault(_binarySearch);
  15539. var _bufferHelper = __webpack_require__(4);
  15540. var _demuxer = __webpack_require__(19);
  15541. var _demuxer2 = _interopRequireDefault(_demuxer);
  15542. var _events = __webpack_require__(1);
  15543. var _events2 = _interopRequireDefault(_events);
  15544. var _levelHelper = __webpack_require__(7);
  15545. var LevelHelper = _interopRequireWildcard(_levelHelper);
  15546. var _timeRanges = __webpack_require__(25);
  15547. var _timeRanges2 = _interopRequireDefault(_timeRanges);
  15548. var _errors = __webpack_require__(2);
  15549. var _logger = __webpack_require__(0);
  15550. var _discontinuities = __webpack_require__(26);
  15551. var _fragmentTracker = __webpack_require__(6);
  15552. var _fragment = __webpack_require__(11);
  15553. var _fragment2 = _interopRequireDefault(_fragment);
  15554. var _baseStreamController = __webpack_require__(14);
  15555. var _baseStreamController2 = _interopRequireDefault(_baseStreamController);
  15556. 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; } }
  15557. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  15558. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  15559. 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; }
  15560. 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; } /*
  15561. * Audio Stream Controller
  15562. */
  15563. var _window = window,
  15564. performance = _window.performance;
  15565. var TICK_INTERVAL = 100; // how often to tick in ms
  15566. var AudioStreamController = function (_BaseStreamController) {
  15567. _inherits(AudioStreamController, _BaseStreamController);
  15568. function AudioStreamController(hls, fragmentTracker) {
  15569. _classCallCheck(this, AudioStreamController);
  15570. 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));
  15571. _this.fragmentTracker = fragmentTracker;
  15572. _this.config = hls.config;
  15573. _this.audioCodecSwap = false;
  15574. _this._state = _baseStreamController.State.STOPPED;
  15575. _this.initPTS = [];
  15576. _this.waitingFragment = null;
  15577. _this.videoTrackCC = null;
  15578. return _this;
  15579. }
  15580. // Signal that video PTS was found
  15581. _createClass(AudioStreamController, [{
  15582. key: 'onInitPtsFound',
  15583. value: function onInitPtsFound(data) {
  15584. var demuxerId = data.id,
  15585. cc = data.frag.cc,
  15586. initPTS = data.initPTS;
  15587. if (demuxerId === 'main') {
  15588. // Always update the new INIT PTS
  15589. // Can change due level switch
  15590. this.initPTS[cc] = initPTS;
  15591. this.videoTrackCC = cc;
  15592. _logger.logger.log('InitPTS for cc: ' + cc + ' found from video track: ' + initPTS);
  15593. // If we are waiting we need to demux/remux the waiting frag
  15594. // With the new initPTS
  15595. if (this.state === _baseStreamController.State.WAITING_INIT_PTS) {
  15596. this.tick();
  15597. }
  15598. }
  15599. }
  15600. }, {
  15601. key: 'startLoad',
  15602. value: function startLoad(startPosition) {
  15603. if (this.tracks) {
  15604. var lastCurrentTime = this.lastCurrentTime;
  15605. this.stopLoad();
  15606. this.setInterval(TICK_INTERVAL);
  15607. this.fragLoadError = 0;
  15608. if (lastCurrentTime > 0 && startPosition === -1) {
  15609. _logger.logger.log('audio:override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3));
  15610. this.state = _baseStreamController.State.IDLE;
  15611. } else {
  15612. this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition;
  15613. this.state = _baseStreamController.State.STARTING;
  15614. }
  15615. this.nextLoadPosition = this.startPosition = this.lastCurrentTime;
  15616. this.tick();
  15617. } else {
  15618. this.startPosition = startPosition;
  15619. this.state = _baseStreamController.State.STOPPED;
  15620. }
  15621. }
  15622. }, {
  15623. key: 'doTick',
  15624. value: function doTick() {
  15625. var pos = void 0,
  15626. track = void 0,
  15627. trackDetails = void 0,
  15628. hls = this.hls,
  15629. config = hls.config;
  15630. // logger.log('audioStream:' + this.state);
  15631. switch (this.state) {
  15632. case _baseStreamController.State.ERROR:
  15633. // don't do anything in error state to avoid breaking further ...
  15634. case _baseStreamController.State.PAUSED:
  15635. // don't do anything in paused state either ...
  15636. case _baseStreamController.State.BUFFER_FLUSHING:
  15637. break;
  15638. case _baseStreamController.State.STARTING:
  15639. this.state = _baseStreamController.State.WAITING_TRACK;
  15640. this.loadedmetadata = false;
  15641. break;
  15642. case _baseStreamController.State.IDLE:
  15643. var tracks = this.tracks;
  15644. // audio tracks not received => exit loop
  15645. if (!tracks) {
  15646. break;
  15647. }
  15648. // if video not attached AND
  15649. // start fragment already requested OR start frag prefetch disable
  15650. // exit loop
  15651. // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
  15652. if (!this.media && (this.startFragRequested || !config.startFragPrefetch)) {
  15653. break;
  15654. }
  15655. // determine next candidate fragment to be loaded, based on current position and
  15656. // end of buffer position
  15657. // if we have not yet loaded any fragment, start loading from start position
  15658. if (this.loadedmetadata) {
  15659. pos = this.media.currentTime;
  15660. } else {
  15661. pos = this.nextLoadPosition;
  15662. if (pos === undefined) {
  15663. break;
  15664. }
  15665. }
  15666. var media = this.mediaBuffer ? this.mediaBuffer : this.media,
  15667. videoBuffer = this.videoBuffer ? this.videoBuffer : this.media,
  15668. bufferInfo = _bufferHelper.BufferHelper.bufferInfo(media, pos, config.maxBufferHole),
  15669. mainBufferInfo = _bufferHelper.BufferHelper.bufferInfo(videoBuffer, pos, config.maxBufferHole),
  15670. bufferLen = bufferInfo.len,
  15671. bufferEnd = bufferInfo.end,
  15672. fragPrevious = this.fragPrevious,
  15673. // ensure we buffer at least config.maxBufferLength (default 30s) or config.maxMaxBufferLength (default: 600s)
  15674. // whichever is smaller.
  15675. // once we reach that threshold, don't buffer more than video (mainBufferInfo.len)
  15676. maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength),
  15677. maxBufLen = Math.max(maxConfigBuffer, mainBufferInfo.len),
  15678. audioSwitch = this.audioSwitch,
  15679. trackId = this.trackId;
  15680. // if buffer length is less than maxBufLen try to load a new fragment
  15681. if ((bufferLen < maxBufLen || audioSwitch) && trackId < tracks.length) {
  15682. trackDetails = tracks[trackId].details;
  15683. // if track info not retrieved yet, switch state and wait for track retrieval
  15684. if (typeof trackDetails === 'undefined') {
  15685. this.state = _baseStreamController.State.WAITING_TRACK;
  15686. break;
  15687. }
  15688. if (!audioSwitch && this._streamEnded(bufferInfo, trackDetails)) {
  15689. this.hls.trigger(_events2.default.BUFFER_EOS, { type: 'audio' });
  15690. this.state = _baseStreamController.State.ENDED;
  15691. return;
  15692. }
  15693. // find fragment index, contiguous with end of buffer position
  15694. var fragments = trackDetails.fragments,
  15695. fragLen = fragments.length,
  15696. start = fragments[0].start,
  15697. end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
  15698. frag = void 0;
  15699. // When switching audio track, reload audio as close as possible to currentTime
  15700. if (audioSwitch) {
  15701. if (trackDetails.live && !trackDetails.PTSKnown) {
  15702. _logger.logger.log('switching audiotrack, live stream, unknown PTS,load first fragment');
  15703. bufferEnd = 0;
  15704. } else {
  15705. bufferEnd = pos;
  15706. // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime
  15707. if (trackDetails.PTSKnown && pos < start) {
  15708. // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start
  15709. if (bufferInfo.end > start || bufferInfo.nextStart) {
  15710. _logger.logger.log('alt audio track ahead of main track, seek to start of alt audio track');
  15711. this.media.currentTime = start + 0.05;
  15712. } else {
  15713. return;
  15714. }
  15715. }
  15716. }
  15717. }
  15718. if (trackDetails.initSegment && !trackDetails.initSegment.data) {
  15719. frag = trackDetails.initSegment;
  15720. } // eslint-disable-line brace-style
  15721. // if bufferEnd before start of playlist, load first fragment
  15722. else if (bufferEnd <= start) {
  15723. frag = fragments[0];
  15724. if (this.videoTrackCC !== null && frag.cc !== this.videoTrackCC) {
  15725. // Ensure we find a fragment which matches the continuity of the video track
  15726. frag = (0, _discontinuities.findFragWithCC)(fragments, this.videoTrackCC);
  15727. }
  15728. if (trackDetails.live && frag.loadIdx && frag.loadIdx === this.fragLoadIdx) {
  15729. // we just loaded this first fragment, and we are still lagging behind the start of the live playlist
  15730. // let's force seek to start
  15731. var nextBuffered = bufferInfo.nextStart ? bufferInfo.nextStart : start;
  15732. _logger.logger.log('no alt audio available @currentTime:' + this.media.currentTime + ', seeking @' + (nextBuffered + 0.05));
  15733. this.media.currentTime = nextBuffered + 0.05;
  15734. return;
  15735. }
  15736. } else {
  15737. var foundFrag = void 0;
  15738. var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
  15739. var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;
  15740. var fragmentWithinToleranceTest = function fragmentWithinToleranceTest(candidate) {
  15741. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  15742. // this is to cope with situations like
  15743. // bufferEnd = 9.991
  15744. // frag[Ø] : [0,10]
  15745. // frag[1] : [10,20]
  15746. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  15747. // frag start frag start+duration
  15748. // |-----------------------------|
  15749. // <---> <--->
  15750. // ...--------><-----------------------------><---------....
  15751. // previous frag matching fragment next frag
  15752. // return -1 return 0 return 1
  15753. // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  15754. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  15755. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration);
  15756. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  15757. return 1;
  15758. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  15759. // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  15760. return -1;
  15761. }
  15762. return 0;
  15763. };
  15764. if (bufferEnd < end) {
  15765. if (bufferEnd > end - maxFragLookUpTolerance) {
  15766. maxFragLookUpTolerance = 0;
  15767. }
  15768. // Prefer the next fragment if it's within tolerance
  15769. if (fragNext && !fragmentWithinToleranceTest(fragNext)) {
  15770. foundFrag = fragNext;
  15771. } else {
  15772. foundFrag = _binarySearch2.default.search(fragments, fragmentWithinToleranceTest);
  15773. }
  15774. } else {
  15775. // reach end of playlist
  15776. foundFrag = fragments[fragLen - 1];
  15777. }
  15778. if (foundFrag) {
  15779. frag = foundFrag;
  15780. start = foundFrag.start;
  15781. // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
  15782. if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) {
  15783. if (frag.sn < trackDetails.endSN) {
  15784. frag = fragments[frag.sn + 1 - trackDetails.startSN];
  15785. _logger.logger.log('SN just loaded, load next one: ' + frag.sn);
  15786. } else {
  15787. frag = null;
  15788. }
  15789. }
  15790. }
  15791. }
  15792. if (frag) {
  15793. // logger.log(' loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));
  15794. if (frag.encrypted) {
  15795. _logger.logger.log('Loading key for ' + frag.sn + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId);
  15796. this.state = _baseStreamController.State.KEY_LOADING;
  15797. hls.trigger(_events2.default.KEY_LOADING, { frag: frag });
  15798. } else {
  15799. _logger.logger.log('Loading ' + frag.sn + ', cc: ' + frag.cc + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId + ', currentTime:' + pos + ',bufferEnd:' + bufferEnd.toFixed(3));
  15800. // only load if fragment is not loaded or if in audio switch
  15801. // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch
  15802. this.fragCurrent = frag;
  15803. if (audioSwitch || this.fragmentTracker.getState(frag) === _fragmentTracker.FragmentState.NOT_LOADED) {
  15804. this.startFragRequested = true;
  15805. if (Number.isFinite(frag.sn)) {
  15806. this.nextLoadPosition = frag.start + frag.duration;
  15807. }
  15808. hls.trigger(_events2.default.FRAG_LOADING, { frag: frag });
  15809. this.state = _baseStreamController.State.FRAG_LOADING;
  15810. }
  15811. }
  15812. }
  15813. }
  15814. break;
  15815. case _baseStreamController.State.WAITING_TRACK:
  15816. track = this.tracks[this.trackId];
  15817. // check if playlist is already loaded
  15818. if (track && track.details) {
  15819. this.state = _baseStreamController.State.IDLE;
  15820. }
  15821. break;
  15822. case _baseStreamController.State.FRAG_LOADING_WAITING_RETRY:
  15823. var now = performance.now();
  15824. var retryDate = this.retryDate;
  15825. media = this.media;
  15826. var isSeeking = media && media.seeking;
  15827. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  15828. if (!retryDate || now >= retryDate || isSeeking) {
  15829. _logger.logger.log('audioStreamController: retryDate reached, switch back to IDLE state');
  15830. this.state = _baseStreamController.State.IDLE;
  15831. }
  15832. break;
  15833. case _baseStreamController.State.WAITING_INIT_PTS:
  15834. var videoTrackCC = this.videoTrackCC;
  15835. if (this.initPTS[videoTrackCC] === undefined) {
  15836. break;
  15837. }
  15838. // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS
  15839. var waitingFrag = this.waitingFragment;
  15840. if (waitingFrag) {
  15841. var waitingFragCC = waitingFrag.frag.cc;
  15842. if (videoTrackCC !== waitingFragCC) {
  15843. track = this.tracks[this.trackId];
  15844. if (track.details && track.details.live) {
  15845. _logger.logger.warn('Waiting fragment CC (' + waitingFragCC + ') does not match video track CC (' + videoTrackCC + ')');
  15846. this.waitingFragment = null;
  15847. this.state = _baseStreamController.State.IDLE;
  15848. }
  15849. } else {
  15850. this.state = _baseStreamController.State.FRAG_LOADING;
  15851. this.onFragLoaded(this.waitingFragment);
  15852. this.waitingFragment = null;
  15853. }
  15854. } else {
  15855. this.state = _baseStreamController.State.IDLE;
  15856. }
  15857. break;
  15858. case _baseStreamController.State.STOPPED:
  15859. case _baseStreamController.State.FRAG_LOADING:
  15860. case _baseStreamController.State.PARSING:
  15861. case _baseStreamController.State.PARSED:
  15862. case _baseStreamController.State.ENDED:
  15863. break;
  15864. default:
  15865. break;
  15866. }
  15867. }
  15868. }, {
  15869. key: 'onMediaAttached',
  15870. value: function onMediaAttached(data) {
  15871. var media = this.media = this.mediaBuffer = data.media;
  15872. this.onvseeking = this.onMediaSeeking.bind(this);
  15873. this.onvended = this.onMediaEnded.bind(this);
  15874. media.addEventListener('seeking', this.onvseeking);
  15875. media.addEventListener('ended', this.onvended);
  15876. var config = this.config;
  15877. if (this.tracks && config.autoStartLoad) {
  15878. this.startLoad(config.startPosition);
  15879. }
  15880. }
  15881. }, {
  15882. key: 'onMediaDetaching',
  15883. value: function onMediaDetaching() {
  15884. var media = this.media;
  15885. if (media && media.ended) {
  15886. _logger.logger.log('MSE detaching and video ended, reset startPosition');
  15887. this.startPosition = this.lastCurrentTime = 0;
  15888. }
  15889. // remove video listeners
  15890. if (media) {
  15891. media.removeEventListener('seeking', this.onvseeking);
  15892. media.removeEventListener('ended', this.onvended);
  15893. this.onvseeking = this.onvseeked = this.onvended = null;
  15894. }
  15895. this.media = this.mediaBuffer = this.videoBuffer = null;
  15896. this.loadedmetadata = false;
  15897. this.stopLoad();
  15898. }
  15899. }, {
  15900. key: 'onAudioTracksUpdated',
  15901. value: function onAudioTracksUpdated(data) {
  15902. _logger.logger.log('audio tracks updated');
  15903. this.tracks = data.audioTracks;
  15904. }
  15905. }, {
  15906. key: 'onAudioTrackSwitching',
  15907. value: function onAudioTrackSwitching(data) {
  15908. // if any URL found on new audio track, it is an alternate audio track
  15909. var altAudio = !!data.url;
  15910. this.trackId = data.id;
  15911. this.fragCurrent = null;
  15912. this.state = _baseStreamController.State.PAUSED;
  15913. this.waitingFragment = null;
  15914. // destroy useless demuxer when switching audio to main
  15915. if (!altAudio) {
  15916. if (this.demuxer) {
  15917. this.demuxer.destroy();
  15918. this.demuxer = null;
  15919. }
  15920. } else {
  15921. // switching to audio track, start timer if not already started
  15922. this.setInterval(TICK_INTERVAL);
  15923. }
  15924. // should we switch tracks ?
  15925. if (altAudio) {
  15926. this.audioSwitch = true;
  15927. // main audio track are handled by stream-controller, just do something if switching to alt audio track
  15928. this.state = _baseStreamController.State.IDLE;
  15929. }
  15930. this.tick();
  15931. }
  15932. }, {
  15933. key: 'onAudioTrackLoaded',
  15934. value: function onAudioTrackLoaded(data) {
  15935. var newDetails = data.details,
  15936. trackId = data.id,
  15937. track = this.tracks[trackId],
  15938. duration = newDetails.totalduration,
  15939. sliding = 0;
  15940. _logger.logger.log('track ' + trackId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration);
  15941. if (newDetails.live) {
  15942. var curDetails = track.details;
  15943. if (curDetails && newDetails.fragments.length > 0) {
  15944. // we already have details for that level, merge them
  15945. LevelHelper.mergeDetails(curDetails, newDetails);
  15946. sliding = newDetails.fragments[0].start;
  15947. // TODO
  15948. // this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
  15949. if (newDetails.PTSKnown) {
  15950. _logger.logger.log('live audio playlist sliding:' + sliding.toFixed(3));
  15951. } else {
  15952. _logger.logger.log('live audio playlist - outdated PTS, unknown sliding');
  15953. }
  15954. } else {
  15955. newDetails.PTSKnown = false;
  15956. _logger.logger.log('live audio playlist - first load, unknown sliding');
  15957. }
  15958. } else {
  15959. newDetails.PTSKnown = false;
  15960. }
  15961. track.details = newDetails;
  15962. // compute start position
  15963. if (!this.startFragRequested) {
  15964. // compute start position if set to -1. use it straight away if value is defined
  15965. if (this.startPosition === -1) {
  15966. // first, check if start time offset has been set in playlist, if yes, use this value
  15967. var startTimeOffset = newDetails.startTimeOffset;
  15968. if (Number.isFinite(startTimeOffset)) {
  15969. _logger.logger.log('start time offset found in playlist, adjust startPosition to ' + startTimeOffset);
  15970. this.startPosition = startTimeOffset;
  15971. } else {
  15972. this.startPosition = 0;
  15973. }
  15974. }
  15975. this.nextLoadPosition = this.startPosition;
  15976. }
  15977. // only switch batck to IDLE state if we were waiting for track to start downloading a new fragment
  15978. if (this.state === _baseStreamController.State.WAITING_TRACK) {
  15979. this.state = _baseStreamController.State.IDLE;
  15980. }
  15981. // trigger handler right now
  15982. this.tick();
  15983. }
  15984. }, {
  15985. key: 'onKeyLoaded',
  15986. value: function onKeyLoaded() {
  15987. if (this.state === _baseStreamController.State.KEY_LOADING) {
  15988. this.state = _baseStreamController.State.IDLE;
  15989. this.tick();
  15990. }
  15991. }
  15992. }, {
  15993. key: 'onFragLoaded',
  15994. value: function onFragLoaded(data) {
  15995. var fragCurrent = this.fragCurrent,
  15996. fragLoaded = data.frag;
  15997. if (this.state === _baseStreamController.State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'audio' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
  15998. var track = this.tracks[this.trackId],
  15999. details = track.details,
  16000. duration = details.totalduration,
  16001. trackId = fragCurrent.level,
  16002. sn = fragCurrent.sn,
  16003. cc = fragCurrent.cc,
  16004. audioCodec = this.config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2',
  16005. stats = this.stats = data.stats;
  16006. if (sn === 'initSegment') {
  16007. this.state = _baseStreamController.State.IDLE;
  16008. stats.tparsed = stats.tbuffered = performance.now();
  16009. details.initSegment.data = data.payload;
  16010. this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'audio' });
  16011. this.tick();
  16012. } else {
  16013. this.state = _baseStreamController.State.PARSING;
  16014. // transmux the MPEG-TS data to ISO-BMFF segments
  16015. this.appended = false;
  16016. if (!this.demuxer) {
  16017. this.demuxer = new _demuxer2.default(this.hls, 'audio');
  16018. }
  16019. // Check if we have video initPTS
  16020. // If not we need to wait for it
  16021. var initPTS = this.initPTS[cc];
  16022. var initSegmentData = details.initSegment ? details.initSegment.data : [];
  16023. if (details.initSegment || initPTS !== undefined) {
  16024. this.pendingBuffering = true;
  16025. _logger.logger.log('Demuxing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],track ' + trackId);
  16026. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  16027. var accurateTimeOffset = false; // details.PTSKnown || !details.live;
  16028. this.demuxer.push(data.payload, initSegmentData, audioCodec, null, fragCurrent, duration, accurateTimeOffset, initPTS);
  16029. } else {
  16030. _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);
  16031. this.waitingFragment = data;
  16032. this.state = _baseStreamController.State.WAITING_INIT_PTS;
  16033. }
  16034. }
  16035. }
  16036. this.fragLoadError = 0;
  16037. }
  16038. }, {
  16039. key: 'onFragParsingInitSegment',
  16040. value: function onFragParsingInitSegment(data) {
  16041. var fragCurrent = this.fragCurrent;
  16042. var fragNew = data.frag;
  16043. if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === _baseStreamController.State.PARSING) {
  16044. var tracks = data.tracks,
  16045. track = void 0;
  16046. // delete any video track found on audio demuxer
  16047. if (tracks.video) {
  16048. delete tracks.video;
  16049. }
  16050. // include levelCodec in audio and video tracks
  16051. track = tracks.audio;
  16052. if (track) {
  16053. track.levelCodec = track.codec;
  16054. track.id = data.id;
  16055. this.hls.trigger(_events2.default.BUFFER_CODECS, tracks);
  16056. _logger.logger.log('audio track:audio,container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']');
  16057. var initSegment = track.initSegment;
  16058. if (initSegment) {
  16059. var appendObj = { type: 'audio', data: initSegment, parent: 'audio', content: 'initSegment' };
  16060. if (this.audioSwitch) {
  16061. this.pendingData = [appendObj];
  16062. } else {
  16063. this.appended = true;
  16064. // arm pending Buffering flag before appending a segment
  16065. this.pendingBuffering = true;
  16066. this.hls.trigger(_events2.default.BUFFER_APPENDING, appendObj);
  16067. }
  16068. }
  16069. // trigger handler right now
  16070. this.tick();
  16071. }
  16072. }
  16073. }
  16074. }, {
  16075. key: 'onFragParsingData',
  16076. value: function onFragParsingData(data) {
  16077. var _this2 = this;
  16078. var fragCurrent = this.fragCurrent;
  16079. var fragNew = data.frag;
  16080. if (fragCurrent && data.id === 'audio' && data.type === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === _baseStreamController.State.PARSING) {
  16081. var trackId = this.trackId,
  16082. track = this.tracks[trackId],
  16083. hls = this.hls;
  16084. if (!Number.isFinite(data.endPTS)) {
  16085. data.endPTS = data.startPTS + fragCurrent.duration;
  16086. data.endDTS = data.startDTS + fragCurrent.duration;
  16087. }
  16088. fragCurrent.addElementaryStream(_fragment2.default.ElementaryStreamTypes.AUDIO);
  16089. _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);
  16090. LevelHelper.updateFragPTSDTS(track.details, fragCurrent, data.startPTS, data.endPTS);
  16091. var audioSwitch = this.audioSwitch,
  16092. media = this.media,
  16093. appendOnBufferFlush = false;
  16094. // Only flush audio from old audio tracks when PTS is known on new audio track
  16095. if (audioSwitch && media) {
  16096. if (media.readyState) {
  16097. var currentTime = media.currentTime;
  16098. _logger.logger.log('switching audio track : currentTime:' + currentTime);
  16099. if (currentTime >= data.startPTS) {
  16100. _logger.logger.log('switching audio track : flushing all audio');
  16101. this.state = _baseStreamController.State.BUFFER_FLUSHING;
  16102. hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
  16103. appendOnBufferFlush = true;
  16104. // Lets announce that the initial audio track switch flush occur
  16105. this.audioSwitch = false;
  16106. hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: trackId });
  16107. }
  16108. } else {
  16109. // Lets announce that the initial audio track switch flush occur
  16110. this.audioSwitch = false;
  16111. hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: trackId });
  16112. }
  16113. }
  16114. var pendingData = this.pendingData;
  16115. if (!pendingData) {
  16116. _logger.logger.warn('Apparently attempt to enqueue media payload without codec initialization data upfront');
  16117. hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: null, fatal: true });
  16118. return;
  16119. }
  16120. if (!this.audioSwitch) {
  16121. [data.data1, data.data2].forEach(function (buffer) {
  16122. if (buffer && buffer.length) {
  16123. pendingData.push({ type: data.type, data: buffer, parent: 'audio', content: 'data' });
  16124. }
  16125. });
  16126. if (!appendOnBufferFlush && pendingData.length) {
  16127. pendingData.forEach(function (appendObj) {
  16128. // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
  16129. // in that case it is useless to append following segments
  16130. if (_this2.state === _baseStreamController.State.PARSING) {
  16131. // arm pending Buffering flag before appending a segment
  16132. _this2.pendingBuffering = true;
  16133. _this2.hls.trigger(_events2.default.BUFFER_APPENDING, appendObj);
  16134. }
  16135. });
  16136. this.pendingData = [];
  16137. this.appended = true;
  16138. }
  16139. }
  16140. // trigger handler right now
  16141. this.tick();
  16142. }
  16143. }
  16144. }, {
  16145. key: 'onFragParsed',
  16146. value: function onFragParsed(data) {
  16147. var fragCurrent = this.fragCurrent;
  16148. var fragNew = data.frag;
  16149. if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === _baseStreamController.State.PARSING) {
  16150. this.stats.tparsed = performance.now();
  16151. this.state = _baseStreamController.State.PARSED;
  16152. this._checkAppendedParsed();
  16153. }
  16154. }
  16155. }, {
  16156. key: 'onBufferReset',
  16157. value: function onBufferReset() {
  16158. // reset reference to sourcebuffers
  16159. this.mediaBuffer = this.videoBuffer = null;
  16160. this.loadedmetadata = false;
  16161. }
  16162. }, {
  16163. key: 'onBufferCreated',
  16164. value: function onBufferCreated(data) {
  16165. var audioTrack = data.tracks.audio;
  16166. if (audioTrack) {
  16167. this.mediaBuffer = audioTrack.buffer;
  16168. this.loadedmetadata = true;
  16169. }
  16170. if (data.tracks.video) {
  16171. this.videoBuffer = data.tracks.video.buffer;
  16172. }
  16173. }
  16174. }, {
  16175. key: 'onBufferAppended',
  16176. value: function onBufferAppended(data) {
  16177. if (data.parent === 'audio') {
  16178. var state = this.state;
  16179. if (state === _baseStreamController.State.PARSING || state === _baseStreamController.State.PARSED) {
  16180. // check if all buffers have been appended
  16181. this.pendingBuffering = data.pending > 0;
  16182. this._checkAppendedParsed();
  16183. }
  16184. }
  16185. }
  16186. }, {
  16187. key: '_checkAppendedParsed',
  16188. value: function _checkAppendedParsed() {
  16189. // trigger handler right now
  16190. if (this.state === _baseStreamController.State.PARSED && (!this.appended || !this.pendingBuffering)) {
  16191. var frag = this.fragCurrent,
  16192. stats = this.stats,
  16193. hls = this.hls;
  16194. if (frag) {
  16195. this.fragPrevious = frag;
  16196. stats.tbuffered = performance.now();
  16197. hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'audio' });
  16198. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  16199. _logger.logger.log('audio buffered : ' + _timeRanges2.default.toString(media.buffered));
  16200. if (this.audioSwitch && this.appended) {
  16201. this.audioSwitch = false;
  16202. hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: this.trackId });
  16203. }
  16204. this.state = _baseStreamController.State.IDLE;
  16205. }
  16206. this.tick();
  16207. }
  16208. }
  16209. }, {
  16210. key: 'onError',
  16211. value: function onError(data) {
  16212. var frag = data.frag;
  16213. // don't handle frag error not related to audio fragment
  16214. if (frag && frag.type !== 'audio') {
  16215. return;
  16216. }
  16217. switch (data.details) {
  16218. case _errors.ErrorDetails.FRAG_LOAD_ERROR:
  16219. case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
  16220. var _frag = data.frag;
  16221. // don't handle frag error not related to audio fragment
  16222. if (_frag && _frag.type !== 'audio') {
  16223. break;
  16224. }
  16225. if (!data.fatal) {
  16226. var loadError = this.fragLoadError;
  16227. if (loadError) {
  16228. loadError++;
  16229. } else {
  16230. loadError = 1;
  16231. }
  16232. var config = this.config;
  16233. if (loadError <= config.fragLoadingMaxRetry) {
  16234. this.fragLoadError = loadError;
  16235. // exponential backoff capped to config.fragLoadingMaxRetryTimeout
  16236. var delay = Math.min(Math.pow(2, loadError - 1) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);
  16237. _logger.logger.warn('AudioStreamController: frag loading failed, retry in ' + delay + ' ms');
  16238. this.retryDate = performance.now() + delay;
  16239. // retry loading state
  16240. this.state = _baseStreamController.State.FRAG_LOADING_WAITING_RETRY;
  16241. } else {
  16242. _logger.logger.error('AudioStreamController: ' + data.details + ' reaches max retry, redispatch as fatal ...');
  16243. // switch error to fatal
  16244. data.fatal = true;
  16245. this.state = _baseStreamController.State.ERROR;
  16246. }
  16247. }
  16248. break;
  16249. case _errors.ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  16250. case _errors.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  16251. case _errors.ErrorDetails.KEY_LOAD_ERROR:
  16252. case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
  16253. // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received
  16254. if (this.state !== _baseStreamController.State.ERROR) {
  16255. // if fatal error, stop processing, otherwise move to IDLE to retry loading
  16256. this.state = data.fatal ? _baseStreamController.State.ERROR : _baseStreamController.State.IDLE;
  16257. _logger.logger.warn('AudioStreamController: ' + data.details + ' while loading frag, now switching to ' + this.state + ' state ...');
  16258. }
  16259. break;
  16260. case _errors.ErrorDetails.BUFFER_FULL_ERROR:
  16261. // if in appending state
  16262. if (data.parent === 'audio' && (this.state === _baseStreamController.State.PARSING || this.state === _baseStreamController.State.PARSED)) {
  16263. var media = this.mediaBuffer,
  16264. currentTime = this.media.currentTime,
  16265. mediaBuffered = media && _bufferHelper.BufferHelper.isBuffered(media, currentTime) && _bufferHelper.BufferHelper.isBuffered(media, currentTime + 0.5);
  16266. // reduce max buf len if current position is buffered
  16267. if (mediaBuffered) {
  16268. var _config = this.config;
  16269. if (_config.maxMaxBufferLength >= _config.maxBufferLength) {
  16270. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  16271. _config.maxMaxBufferLength /= 2;
  16272. _logger.logger.warn('AudioStreamController: reduce max buffer length to ' + _config.maxMaxBufferLength + 's');
  16273. }
  16274. this.state = _baseStreamController.State.IDLE;
  16275. } else {
  16276. // current position is not buffered, but browser is still complaining about buffer full error
  16277. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  16278. // in that case flush the whole audio buffer to recover
  16279. _logger.logger.warn('AudioStreamController: buffer full error also media.currentTime is not buffered, flush audio buffer');
  16280. this.fragCurrent = null;
  16281. // flush everything
  16282. this.state = _baseStreamController.State.BUFFER_FLUSHING;
  16283. this.hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
  16284. }
  16285. }
  16286. break;
  16287. default:
  16288. break;
  16289. }
  16290. }
  16291. }, {
  16292. key: 'onBufferFlushed',
  16293. value: function onBufferFlushed() {
  16294. var _this3 = this;
  16295. var pendingData = this.pendingData;
  16296. if (pendingData && pendingData.length) {
  16297. _logger.logger.log('AudioStreamController: appending pending audio data after buffer flushed');
  16298. pendingData.forEach(function (appendObj) {
  16299. _this3.hls.trigger(_events2.default.BUFFER_APPENDING, appendObj);
  16300. });
  16301. this.appended = true;
  16302. this.pendingData = [];
  16303. this.state = _baseStreamController.State.PARSED;
  16304. } else {
  16305. // move to IDLE once flush complete. this should trigger new fragment loading
  16306. this.state = _baseStreamController.State.IDLE;
  16307. // reset reference to frag
  16308. this.fragPrevious = null;
  16309. this.tick();
  16310. }
  16311. }
  16312. }, {
  16313. key: 'state',
  16314. set: function set(nextState) {
  16315. if (this.state !== nextState) {
  16316. var previousState = this.state;
  16317. this._state = nextState;
  16318. _logger.logger.log('audio stream:' + previousState + '->' + nextState);
  16319. }
  16320. },
  16321. get: function get() {
  16322. return this._state;
  16323. }
  16324. }]);
  16325. return AudioStreamController;
  16326. }(_baseStreamController2.default);
  16327. exports.default = AudioStreamController;
  16328. module.exports = exports['default'];
  16329. /***/ }),
  16330. /* 70 */
  16331. /***/ (function(module, exports, __webpack_require__) {
  16332. "use strict";
  16333. Object.defineProperty(exports, "__esModule", {
  16334. value: true
  16335. });
  16336. exports.newCue = newCue;
  16337. var _vttparser = __webpack_require__(30);
  16338. function newCue(track, startTime, endTime, captionScreen) {
  16339. var row = void 0;
  16340. var cue = void 0;
  16341. var indenting = void 0;
  16342. var indent = void 0;
  16343. var text = void 0;
  16344. var VTTCue = window.VTTCue || window.TextTrackCue;
  16345. for (var r = 0; r < captionScreen.rows.length; r++) {
  16346. row = captionScreen.rows[r];
  16347. indenting = true;
  16348. indent = 0;
  16349. text = '';
  16350. if (!row.isEmpty()) {
  16351. for (var c = 0; c < row.chars.length; c++) {
  16352. if (row.chars[c].uchar.match(/\s/) && indenting) {
  16353. indent++;
  16354. } else {
  16355. text += row.chars[c].uchar;
  16356. indenting = false;
  16357. }
  16358. }
  16359. // To be used for cleaning-up orphaned roll-up captions
  16360. row.cueStartTime = startTime;
  16361. // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
  16362. if (startTime === endTime) {
  16363. endTime += 0.0001;
  16364. }
  16365. cue = new VTTCue(startTime, endTime, (0, _vttparser.fixLineBreaks)(text.trim()));
  16366. if (indent >= 16) {
  16367. indent--;
  16368. } else {
  16369. indent++;
  16370. }
  16371. // VTTCue.line get's flakey when using controls, so let's now include line 13&14
  16372. // also, drop line 1 since it's to close to the top
  16373. if (navigator.userAgent.match(/Firefox\//)) {
  16374. cue.line = r + 1;
  16375. } else {
  16376. cue.line = r > 7 ? r - 2 : r + 1;
  16377. }
  16378. cue.align = 'left';
  16379. // Clamp the position between 0 and 100 - if out of these bounds, Firefox throws an exception and captions break
  16380. cue.position = Math.max(0, Math.min(100, 100 * (indent / 32) + (navigator.userAgent.match(/Firefox\//) ? 50 : 0)));
  16381. track.addCue(cue);
  16382. }
  16383. }
  16384. }
  16385. /***/ }),
  16386. /* 71 */
  16387. /***/ (function(module, exports, __webpack_require__) {
  16388. "use strict";
  16389. Object.defineProperty(exports, "__esModule", {
  16390. value: true
  16391. });
  16392. /**
  16393. * Copyright 2013 vtt.js Contributors
  16394. *
  16395. * Licensed under the Apache License, Version 2.0 (the "License");
  16396. * you may not use this file except in compliance with the License.
  16397. * You may obtain a copy of the License at
  16398. *
  16399. * http://www.apache.org/licenses/LICENSE-2.0
  16400. *
  16401. * Unless required by applicable law or agreed to in writing, software
  16402. * distributed under the License is distributed on an "AS IS" BASIS,
  16403. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16404. * See the License for the specific language governing permissions and
  16405. * limitations under the License.
  16406. */
  16407. exports.default = function () {
  16408. if (typeof window !== 'undefined' && window.VTTCue) {
  16409. return window.VTTCue;
  16410. }
  16411. var autoKeyword = 'auto';
  16412. var directionSetting = {
  16413. '': true,
  16414. lr: true,
  16415. rl: true
  16416. };
  16417. var alignSetting = {
  16418. start: true,
  16419. middle: true,
  16420. end: true,
  16421. left: true,
  16422. right: true
  16423. };
  16424. function findDirectionSetting(value) {
  16425. if (typeof value !== 'string') {
  16426. return false;
  16427. }
  16428. var dir = directionSetting[value.toLowerCase()];
  16429. return dir ? value.toLowerCase() : false;
  16430. }
  16431. function findAlignSetting(value) {
  16432. if (typeof value !== 'string') {
  16433. return false;
  16434. }
  16435. var align = alignSetting[value.toLowerCase()];
  16436. return align ? value.toLowerCase() : false;
  16437. }
  16438. function extend(obj) {
  16439. var i = 1;
  16440. for (; i < arguments.length; i++) {
  16441. var cobj = arguments[i];
  16442. for (var p in cobj) {
  16443. obj[p] = cobj[p];
  16444. }
  16445. }
  16446. return obj;
  16447. }
  16448. function VTTCue(startTime, endTime, text) {
  16449. var cue = this;
  16450. var isIE8 = function () {
  16451. if (typeof navigator === 'undefined') {
  16452. return;
  16453. }
  16454. return (/MSIE\s8\.0/.test(navigator.userAgent)
  16455. );
  16456. }();
  16457. var baseObj = {};
  16458. if (isIE8) {
  16459. cue = document.createElement('custom');
  16460. } else {
  16461. baseObj.enumerable = true;
  16462. }
  16463. /**
  16464. * Shim implementation specific properties. These properties are not in
  16465. * the spec.
  16466. */
  16467. // Lets us know when the VTTCue's data has changed in such a way that we need
  16468. // to recompute its display state. This lets us compute its display state
  16469. // lazily.
  16470. cue.hasBeenReset = false;
  16471. /**
  16472. * VTTCue and TextTrackCue properties
  16473. * http://dev.w3.org/html5/webvtt/#vttcue-interface
  16474. */
  16475. var _id = '';
  16476. var _pauseOnExit = false;
  16477. var _startTime = startTime;
  16478. var _endTime = endTime;
  16479. var _text = text;
  16480. var _region = null;
  16481. var _vertical = '';
  16482. var _snapToLines = true;
  16483. var _line = 'auto';
  16484. var _lineAlign = 'start';
  16485. var _position = 50;
  16486. var _positionAlign = 'middle';
  16487. var _size = 50;
  16488. var _align = 'middle';
  16489. Object.defineProperty(cue, 'id', extend({}, baseObj, {
  16490. get: function get() {
  16491. return _id;
  16492. },
  16493. set: function set(value) {
  16494. _id = '' + value;
  16495. }
  16496. }));
  16497. Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {
  16498. get: function get() {
  16499. return _pauseOnExit;
  16500. },
  16501. set: function set(value) {
  16502. _pauseOnExit = !!value;
  16503. }
  16504. }));
  16505. Object.defineProperty(cue, 'startTime', extend({}, baseObj, {
  16506. get: function get() {
  16507. return _startTime;
  16508. },
  16509. set: function set(value) {
  16510. if (typeof value !== 'number') {
  16511. throw new TypeError('Start time must be set to a number.');
  16512. }
  16513. _startTime = value;
  16514. this.hasBeenReset = true;
  16515. }
  16516. }));
  16517. Object.defineProperty(cue, 'endTime', extend({}, baseObj, {
  16518. get: function get() {
  16519. return _endTime;
  16520. },
  16521. set: function set(value) {
  16522. if (typeof value !== 'number') {
  16523. throw new TypeError('End time must be set to a number.');
  16524. }
  16525. _endTime = value;
  16526. this.hasBeenReset = true;
  16527. }
  16528. }));
  16529. Object.defineProperty(cue, 'text', extend({}, baseObj, {
  16530. get: function get() {
  16531. return _text;
  16532. },
  16533. set: function set(value) {
  16534. _text = '' + value;
  16535. this.hasBeenReset = true;
  16536. }
  16537. }));
  16538. Object.defineProperty(cue, 'region', extend({}, baseObj, {
  16539. get: function get() {
  16540. return _region;
  16541. },
  16542. set: function set(value) {
  16543. _region = value;
  16544. this.hasBeenReset = true;
  16545. }
  16546. }));
  16547. Object.defineProperty(cue, 'vertical', extend({}, baseObj, {
  16548. get: function get() {
  16549. return _vertical;
  16550. },
  16551. set: function set(value) {
  16552. var setting = findDirectionSetting(value);
  16553. // Have to check for false because the setting an be an empty string.
  16554. if (setting === false) {
  16555. throw new SyntaxError('An invalid or illegal string was specified.');
  16556. }
  16557. _vertical = setting;
  16558. this.hasBeenReset = true;
  16559. }
  16560. }));
  16561. Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {
  16562. get: function get() {
  16563. return _snapToLines;
  16564. },
  16565. set: function set(value) {
  16566. _snapToLines = !!value;
  16567. this.hasBeenReset = true;
  16568. }
  16569. }));
  16570. Object.defineProperty(cue, 'line', extend({}, baseObj, {
  16571. get: function get() {
  16572. return _line;
  16573. },
  16574. set: function set(value) {
  16575. if (typeof value !== 'number' && value !== autoKeyword) {
  16576. throw new SyntaxError('An invalid number or illegal string was specified.');
  16577. }
  16578. _line = value;
  16579. this.hasBeenReset = true;
  16580. }
  16581. }));
  16582. Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {
  16583. get: function get() {
  16584. return _lineAlign;
  16585. },
  16586. set: function set(value) {
  16587. var setting = findAlignSetting(value);
  16588. if (!setting) {
  16589. throw new SyntaxError('An invalid or illegal string was specified.');
  16590. }
  16591. _lineAlign = setting;
  16592. this.hasBeenReset = true;
  16593. }
  16594. }));
  16595. Object.defineProperty(cue, 'position', extend({}, baseObj, {
  16596. get: function get() {
  16597. return _position;
  16598. },
  16599. set: function set(value) {
  16600. if (value < 0 || value > 100) {
  16601. throw new Error('Position must be between 0 and 100.');
  16602. }
  16603. _position = value;
  16604. this.hasBeenReset = true;
  16605. }
  16606. }));
  16607. Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {
  16608. get: function get() {
  16609. return _positionAlign;
  16610. },
  16611. set: function set(value) {
  16612. var setting = findAlignSetting(value);
  16613. if (!setting) {
  16614. throw new SyntaxError('An invalid or illegal string was specified.');
  16615. }
  16616. _positionAlign = setting;
  16617. this.hasBeenReset = true;
  16618. }
  16619. }));
  16620. Object.defineProperty(cue, 'size', extend({}, baseObj, {
  16621. get: function get() {
  16622. return _size;
  16623. },
  16624. set: function set(value) {
  16625. if (value < 0 || value > 100) {
  16626. throw new Error('Size must be between 0 and 100.');
  16627. }
  16628. _size = value;
  16629. this.hasBeenReset = true;
  16630. }
  16631. }));
  16632. Object.defineProperty(cue, 'align', extend({}, baseObj, {
  16633. get: function get() {
  16634. return _align;
  16635. },
  16636. set: function set(value) {
  16637. var setting = findAlignSetting(value);
  16638. if (!setting) {
  16639. throw new SyntaxError('An invalid or illegal string was specified.');
  16640. }
  16641. _align = setting;
  16642. this.hasBeenReset = true;
  16643. }
  16644. }));
  16645. /**
  16646. * Other <track> spec defined properties
  16647. */
  16648. // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
  16649. cue.displayState = undefined;
  16650. if (isIE8) {
  16651. return cue;
  16652. }
  16653. }
  16654. /**
  16655. * VTTCue methods
  16656. */
  16657. VTTCue.prototype.getCueAsHTML = function () {
  16658. // Assume WebVTT.convertCueToDOMTree is on the global.
  16659. var WebVTT = window.WebVTT;
  16660. return WebVTT.convertCueToDOMTree(window, this.text);
  16661. };
  16662. return VTTCue;
  16663. }();
  16664. module.exports = exports['default'];
  16665. /***/ }),
  16666. /* 72 */
  16667. /***/ (function(module, exports, __webpack_require__) {
  16668. "use strict";
  16669. Object.defineProperty(exports, "__esModule", {
  16670. value: true
  16671. });
  16672. 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; }; }();
  16673. var _events = __webpack_require__(1);
  16674. var _events2 = _interopRequireDefault(_events);
  16675. var _eventHandler = __webpack_require__(3);
  16676. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  16677. var _cea608Parser = __webpack_require__(73);
  16678. var _cea608Parser2 = _interopRequireDefault(_cea608Parser);
  16679. var _outputFilter = __webpack_require__(74);
  16680. var _outputFilter2 = _interopRequireDefault(_outputFilter);
  16681. var _webvttParser = __webpack_require__(75);
  16682. var _webvttParser2 = _interopRequireDefault(_webvttParser);
  16683. var _logger = __webpack_require__(0);
  16684. var _texttrackUtils = __webpack_require__(29);
  16685. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  16686. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  16687. 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; }
  16688. 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; } /*
  16689. * Timeline Controller
  16690. */
  16691. function canReuseVttTextTrack(inUseTrack, manifestTrack) {
  16692. return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);
  16693. }
  16694. function intersection(x1, x2, y1, y2) {
  16695. return Math.min(x2, y2) - Math.max(x1, y1);
  16696. }
  16697. var TimelineController = function (_EventHandler) {
  16698. _inherits(TimelineController, _EventHandler);
  16699. function TimelineController(hls) {
  16700. _classCallCheck(this, TimelineController);
  16701. 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));
  16702. _this.hls = hls;
  16703. _this.config = hls.config;
  16704. _this.enabled = true;
  16705. _this.Cues = hls.config.cueHandler;
  16706. _this.textTracks = [];
  16707. _this.tracks = [];
  16708. _this.unparsedVttFrags = [];
  16709. _this.initPTS = [];
  16710. _this.cueRanges = [];
  16711. _this.captionsTracks = {};
  16712. _this.captionsProperties = {
  16713. textTrack1: {
  16714. label: _this.config.captionsTextTrack1Label,
  16715. languageCode: _this.config.captionsTextTrack1LanguageCode
  16716. },
  16717. textTrack2: {
  16718. label: _this.config.captionsTextTrack2Label,
  16719. languageCode: _this.config.captionsTextTrack2LanguageCode
  16720. }
  16721. };
  16722. if (_this.config.enableCEA708Captions) {
  16723. var channel1 = new _outputFilter2.default(_this, 'textTrack1');
  16724. var channel2 = new _outputFilter2.default(_this, 'textTrack2');
  16725. _this.cea608Parser = new _cea608Parser2.default(0, channel1, channel2);
  16726. }
  16727. return _this;
  16728. }
  16729. _createClass(TimelineController, [{
  16730. key: 'addCues',
  16731. value: function addCues(trackName, startTime, endTime, screen) {
  16732. // skip cues which overlap more than 50% with previously parsed time ranges
  16733. var ranges = this.cueRanges;
  16734. var merged = false;
  16735. for (var i = ranges.length; i--;) {
  16736. var cueRange = ranges[i];
  16737. var overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
  16738. if (overlap >= 0) {
  16739. cueRange[0] = Math.min(cueRange[0], startTime);
  16740. cueRange[1] = Math.max(cueRange[1], endTime);
  16741. merged = true;
  16742. if (overlap / (endTime - startTime) > 0.5) {
  16743. return;
  16744. }
  16745. }
  16746. }
  16747. if (!merged) {
  16748. ranges.push([startTime, endTime]);
  16749. }
  16750. this.Cues.newCue(this.captionsTracks[trackName], startTime, endTime, screen);
  16751. }
  16752. // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
  16753. }, {
  16754. key: 'onInitPtsFound',
  16755. value: function onInitPtsFound(data) {
  16756. var _this2 = this;
  16757. if (data.id === 'main') {
  16758. this.initPTS[data.frag.cc] = data.initPTS;
  16759. }
  16760. // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.
  16761. // Parse any unparsed fragments upon receiving the initial PTS.
  16762. if (this.unparsedVttFrags.length) {
  16763. var unparsedVttFrags = this.unparsedVttFrags;
  16764. this.unparsedVttFrags = [];
  16765. unparsedVttFrags.forEach(function (frag) {
  16766. _this2.onFragLoaded(frag);
  16767. });
  16768. }
  16769. }
  16770. }, {
  16771. key: 'getExistingTrack',
  16772. value: function getExistingTrack(trackName) {
  16773. var media = this.media;
  16774. if (media) {
  16775. for (var i = 0; i < media.textTracks.length; i++) {
  16776. var textTrack = media.textTracks[i];
  16777. if (textTrack[trackName]) {
  16778. return textTrack;
  16779. }
  16780. }
  16781. }
  16782. return null;
  16783. }
  16784. }, {
  16785. key: 'createCaptionsTrack',
  16786. value: function createCaptionsTrack(trackName) {
  16787. var _captionsProperties$t = this.captionsProperties[trackName],
  16788. label = _captionsProperties$t.label,
  16789. languageCode = _captionsProperties$t.languageCode;
  16790. var captionsTracks = this.captionsTracks;
  16791. if (!captionsTracks[trackName]) {
  16792. // Enable reuse of existing text track.
  16793. var existingTrack = this.getExistingTrack(trackName);
  16794. if (!existingTrack) {
  16795. var textTrack = this.createTextTrack('captions', label, languageCode);
  16796. if (textTrack) {
  16797. // Set a special property on the track so we know it's managed by Hls.js
  16798. textTrack[trackName] = true;
  16799. captionsTracks[trackName] = textTrack;
  16800. }
  16801. } else {
  16802. captionsTracks[trackName] = existingTrack;
  16803. (0, _texttrackUtils.clearCurrentCues)(captionsTracks[trackName]);
  16804. (0, _texttrackUtils.sendAddTrackEvent)(captionsTracks[trackName], this.media);
  16805. }
  16806. }
  16807. }
  16808. }, {
  16809. key: 'createTextTrack',
  16810. value: function createTextTrack(kind, label, lang) {
  16811. var media = this.media;
  16812. if (media) {
  16813. return media.addTextTrack(kind, label, lang);
  16814. }
  16815. }
  16816. }, {
  16817. key: 'destroy',
  16818. value: function destroy() {
  16819. _eventHandler2.default.prototype.destroy.call(this);
  16820. }
  16821. }, {
  16822. key: 'onMediaAttaching',
  16823. value: function onMediaAttaching(data) {
  16824. this.media = data.media;
  16825. this._cleanTracks();
  16826. }
  16827. }, {
  16828. key: 'onMediaDetaching',
  16829. value: function onMediaDetaching() {
  16830. var captionsTracks = this.captionsTracks;
  16831. Object.keys(captionsTracks).forEach(function (trackName) {
  16832. (0, _texttrackUtils.clearCurrentCues)(captionsTracks[trackName]);
  16833. delete captionsTracks[trackName];
  16834. });
  16835. }
  16836. }, {
  16837. key: 'onManifestLoading',
  16838. value: function onManifestLoading() {
  16839. this.lastSn = -1; // Detect discontiguity in fragment parsing
  16840. this.prevCC = -1;
  16841. this.vttCCs = { // Detect discontinuity in subtitle manifests
  16842. ccOffset: 0,
  16843. presentationOffset: 0,
  16844. 0: {
  16845. start: 0, prevCC: -1, new: false
  16846. }
  16847. };
  16848. this._cleanTracks();
  16849. }
  16850. }, {
  16851. key: '_cleanTracks',
  16852. value: function _cleanTracks() {
  16853. // clear outdated subtitles
  16854. var media = this.media;
  16855. if (media) {
  16856. var textTracks = media.textTracks;
  16857. if (textTracks) {
  16858. for (var i = 0; i < textTracks.length; i++) {
  16859. (0, _texttrackUtils.clearCurrentCues)(textTracks[i]);
  16860. }
  16861. }
  16862. }
  16863. }
  16864. }, {
  16865. key: 'onManifestLoaded',
  16866. value: function onManifestLoaded(data) {
  16867. var _this3 = this;
  16868. this.textTracks = [];
  16869. this.unparsedVttFrags = this.unparsedVttFrags || [];
  16870. this.initPTS = [];
  16871. this.cueRanges = [];
  16872. if (this.config.enableWebVTT) {
  16873. this.tracks = data.subtitles || [];
  16874. var inUseTracks = this.media ? this.media.textTracks : [];
  16875. this.tracks.forEach(function (track, index) {
  16876. var textTrack = void 0;
  16877. if (index < inUseTracks.length) {
  16878. var inUseTrack = null;
  16879. for (var i = 0; i < inUseTracks.length; i++) {
  16880. if (canReuseVttTextTrack(inUseTracks[i], track)) {
  16881. inUseTrack = inUseTracks[i];
  16882. break;
  16883. }
  16884. }
  16885. // Reuse tracks with the same label, but do not reuse 608/708 tracks
  16886. if (inUseTrack) {
  16887. textTrack = inUseTrack;
  16888. }
  16889. }
  16890. if (!textTrack) {
  16891. textTrack = _this3.createTextTrack('subtitles', track.name, track.lang);
  16892. }
  16893. if (track.default) {
  16894. textTrack.mode = _this3.hls.subtitleDisplay ? 'showing' : 'hidden';
  16895. } else {
  16896. textTrack.mode = 'disabled';
  16897. }
  16898. _this3.textTracks.push(textTrack);
  16899. });
  16900. }
  16901. }
  16902. }, {
  16903. key: 'onLevelSwitching',
  16904. value: function onLevelSwitching() {
  16905. this.enabled = this.hls.currentLevel.closedCaptions !== 'NONE';
  16906. }
  16907. }, {
  16908. key: 'onFragLoaded',
  16909. value: function onFragLoaded(data) {
  16910. var frag = data.frag,
  16911. payload = data.payload;
  16912. if (frag.type === 'main') {
  16913. var sn = frag.sn;
  16914. // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
  16915. if (sn !== this.lastSn + 1) {
  16916. var cea608Parser = this.cea608Parser;
  16917. if (cea608Parser) {
  16918. cea608Parser.reset();
  16919. }
  16920. }
  16921. this.lastSn = sn;
  16922. } // eslint-disable-line brace-style
  16923. // If fragment is subtitle type, parse as WebVTT.
  16924. else if (frag.type === 'subtitle') {
  16925. if (payload.byteLength) {
  16926. // We need an initial synchronisation PTS. Store fragments as long as none has arrived.
  16927. if (!Number.isFinite(this.initPTS[frag.cc])) {
  16928. this.unparsedVttFrags.push(data);
  16929. if (this.initPTS.length) {
  16930. // finish unsuccessfully, otherwise the subtitle-stream-controller could be blocked from loading new frags.
  16931. this.hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  16932. }
  16933. return;
  16934. }
  16935. var decryptData = frag.decryptdata;
  16936. // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.
  16937. if (decryptData == null || decryptData.key == null || decryptData.method !== 'AES-128') {
  16938. this._parseVTTs(frag, payload);
  16939. }
  16940. } else {
  16941. // In case there is no payload, finish unsuccessfully.
  16942. this.hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  16943. }
  16944. }
  16945. }
  16946. }, {
  16947. key: '_parseVTTs',
  16948. value: function _parseVTTs(frag, payload) {
  16949. var vttCCs = this.vttCCs;
  16950. if (!vttCCs[frag.cc]) {
  16951. vttCCs[frag.cc] = { start: frag.start, prevCC: this.prevCC, new: true };
  16952. this.prevCC = frag.cc;
  16953. }
  16954. var textTracks = this.textTracks,
  16955. hls = this.hls;
  16956. // Parse the WebVTT file contents.
  16957. _webvttParser2.default.parse(payload, this.initPTS[frag.cc], vttCCs, frag.cc, function (cues) {
  16958. var currentTrack = textTracks[frag.level];
  16959. // WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled"
  16960. // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null
  16961. // and trying to access getCueById method of cues will throw an exception
  16962. if (currentTrack.mode === 'disabled') {
  16963. hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  16964. return;
  16965. }
  16966. // Add cues and trigger event with success true.
  16967. cues.forEach(function (cue) {
  16968. // Sometimes there are cue overlaps on segmented vtts so the same
  16969. // cue can appear more than once in different vtt files.
  16970. // This avoid showing duplicated cues with same timecode and text.
  16971. if (!currentTrack.cues.getCueById(cue.id)) {
  16972. try {
  16973. currentTrack.addCue(cue);
  16974. } catch (err) {
  16975. var textTrackCue = new window.TextTrackCue(cue.startTime, cue.endTime, cue.text);
  16976. textTrackCue.id = cue.id;
  16977. currentTrack.addCue(textTrackCue);
  16978. }
  16979. }
  16980. });
  16981. hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: true, frag: frag });
  16982. }, function (e) {
  16983. // Something went wrong while parsing. Trigger event with success false.
  16984. _logger.logger.log('Failed to parse VTT cue: ' + e);
  16985. hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  16986. });
  16987. }
  16988. }, {
  16989. key: 'onFragDecrypted',
  16990. value: function onFragDecrypted(data) {
  16991. var decryptedData = data.payload,
  16992. frag = data.frag;
  16993. if (frag.type === 'subtitle') {
  16994. if (!Number.isFinite(this.initPTS[frag.cc])) {
  16995. this.unparsedVttFrags.push(data);
  16996. return;
  16997. }
  16998. this._parseVTTs(frag, decryptedData);
  16999. }
  17000. }
  17001. }, {
  17002. key: 'onFragParsingUserdata',
  17003. value: function onFragParsingUserdata(data) {
  17004. // push all of the CEA-708 messages into the interpreter
  17005. // immediately. It will create the proper timestamps based on our PTS value
  17006. if (this.enabled && this.config.enableCEA708Captions) {
  17007. for (var i = 0; i < data.samples.length; i++) {
  17008. var ccdatas = this.extractCea608Data(data.samples[i].bytes);
  17009. this.cea608Parser.addData(data.samples[i].pts, ccdatas);
  17010. }
  17011. }
  17012. }
  17013. }, {
  17014. key: 'extractCea608Data',
  17015. value: function extractCea608Data(byteArray) {
  17016. var count = byteArray[0] & 31;
  17017. var position = 2;
  17018. var tmpByte = void 0,
  17019. ccbyte1 = void 0,
  17020. ccbyte2 = void 0,
  17021. ccValid = void 0,
  17022. ccType = void 0;
  17023. var actualCCBytes = [];
  17024. for (var j = 0; j < count; j++) {
  17025. tmpByte = byteArray[position++];
  17026. ccbyte1 = 0x7F & byteArray[position++];
  17027. ccbyte2 = 0x7F & byteArray[position++];
  17028. ccValid = (4 & tmpByte) !== 0;
  17029. ccType = 3 & tmpByte;
  17030. if (ccbyte1 === 0 && ccbyte2 === 0) {
  17031. continue;
  17032. }
  17033. if (ccValid) {
  17034. if (ccType === 0) {
  17035. // || ccType === 1
  17036. actualCCBytes.push(ccbyte1);
  17037. actualCCBytes.push(ccbyte2);
  17038. }
  17039. }
  17040. }
  17041. return actualCCBytes;
  17042. }
  17043. }]);
  17044. return TimelineController;
  17045. }(_eventHandler2.default);
  17046. exports.default = TimelineController;
  17047. module.exports = exports['default'];
  17048. /***/ }),
  17049. /* 73 */
  17050. /***/ (function(module, exports, __webpack_require__) {
  17051. "use strict";
  17052. Object.defineProperty(exports, "__esModule", {
  17053. value: true
  17054. });
  17055. 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; }; }();
  17056. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  17057. /**
  17058. *
  17059. * This code was ported from the dash.js project at:
  17060. * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
  17061. * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
  17062. *
  17063. * The original copyright appears below:
  17064. *
  17065. * The copyright in this software is being made available under the BSD License,
  17066. * included below. This software may be subject to other third party and contributor
  17067. * rights, including patent rights, and no such rights are granted under this license.
  17068. *
  17069. * Copyright (c) 2015-2016, DASH Industry Forum.
  17070. * All rights reserved.
  17071. *
  17072. * Redistribution and use in source and binary forms, with or without modification,
  17073. * are permitted provided that the following conditions are met:
  17074. * 1. Redistributions of source code must retain the above copyright notice, this
  17075. * list of conditions and the following disclaimer.
  17076. * * Redistributions in binary form must reproduce the above copyright notice,
  17077. * this list of conditions and the following disclaimer in the documentation and/or
  17078. * other materials provided with the distribution.
  17079. * 2. Neither the name of Dash Industry Forum nor the names of its
  17080. * contributors may be used to endorse or promote products derived from this software
  17081. * without specific prior written permission.
  17082. *
  17083. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
  17084. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  17085. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  17086. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  17087. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  17088. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  17089. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  17090. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  17091. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  17092. * POSSIBILITY OF SUCH DAMAGE.
  17093. */
  17094. /**
  17095. * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes
  17096. */
  17097. var specialCea608CharsCodes = {
  17098. 0x2a: 0xe1, // lowercase a, acute accent
  17099. 0x5c: 0xe9, // lowercase e, acute accent
  17100. 0x5e: 0xed, // lowercase i, acute accent
  17101. 0x5f: 0xf3, // lowercase o, acute accent
  17102. 0x60: 0xfa, // lowercase u, acute accent
  17103. 0x7b: 0xe7, // lowercase c with cedilla
  17104. 0x7c: 0xf7, // division symbol
  17105. 0x7d: 0xd1, // uppercase N tilde
  17106. 0x7e: 0xf1, // lowercase n tilde
  17107. 0x7f: 0x2588, // Full block
  17108. // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  17109. // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
  17110. // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
  17111. 0x80: 0xae, // Registered symbol (R)
  17112. 0x81: 0xb0, // degree sign
  17113. 0x82: 0xbd, // 1/2 symbol
  17114. 0x83: 0xbf, // Inverted (open) question mark
  17115. 0x84: 0x2122, // Trademark symbol (TM)
  17116. 0x85: 0xa2, // Cents symbol
  17117. 0x86: 0xa3, // Pounds sterling
  17118. 0x87: 0x266a, // Music 8'th note
  17119. 0x88: 0xe0, // lowercase a, grave accent
  17120. 0x89: 0x20, // transparent space (regular)
  17121. 0x8a: 0xe8, // lowercase e, grave accent
  17122. 0x8b: 0xe2, // lowercase a, circumflex accent
  17123. 0x8c: 0xea, // lowercase e, circumflex accent
  17124. 0x8d: 0xee, // lowercase i, circumflex accent
  17125. 0x8e: 0xf4, // lowercase o, circumflex accent
  17126. 0x8f: 0xfb, // lowercase u, circumflex accent
  17127. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  17128. // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
  17129. 0x90: 0xc1, // capital letter A with acute
  17130. 0x91: 0xc9, // capital letter E with acute
  17131. 0x92: 0xd3, // capital letter O with acute
  17132. 0x93: 0xda, // capital letter U with acute
  17133. 0x94: 0xdc, // capital letter U with diaresis
  17134. 0x95: 0xfc, // lowercase letter U with diaeresis
  17135. 0x96: 0x2018, // opening single quote
  17136. 0x97: 0xa1, // inverted exclamation mark
  17137. 0x98: 0x2a, // asterisk
  17138. 0x99: 0x2019, // closing single quote
  17139. 0x9a: 0x2501, // box drawings heavy horizontal
  17140. 0x9b: 0xa9, // copyright sign
  17141. 0x9c: 0x2120, // Service mark
  17142. 0x9d: 0x2022, // (round) bullet
  17143. 0x9e: 0x201c, // Left double quotation mark
  17144. 0x9f: 0x201d, // Right double quotation mark
  17145. 0xa0: 0xc0, // uppercase A, grave accent
  17146. 0xa1: 0xc2, // uppercase A, circumflex
  17147. 0xa2: 0xc7, // uppercase C with cedilla
  17148. 0xa3: 0xc8, // uppercase E, grave accent
  17149. 0xa4: 0xca, // uppercase E, circumflex
  17150. 0xa5: 0xcb, // capital letter E with diaresis
  17151. 0xa6: 0xeb, // lowercase letter e with diaresis
  17152. 0xa7: 0xce, // uppercase I, circumflex
  17153. 0xa8: 0xcf, // uppercase I, with diaresis
  17154. 0xa9: 0xef, // lowercase i, with diaresis
  17155. 0xaa: 0xd4, // uppercase O, circumflex
  17156. 0xab: 0xd9, // uppercase U, grave accent
  17157. 0xac: 0xf9, // lowercase u, grave accent
  17158. 0xad: 0xdb, // uppercase U, circumflex
  17159. 0xae: 0xab, // left-pointing double angle quotation mark
  17160. 0xaf: 0xbb, // right-pointing double angle quotation mark
  17161. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  17162. // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
  17163. 0xb0: 0xc3, // Uppercase A, tilde
  17164. 0xb1: 0xe3, // Lowercase a, tilde
  17165. 0xb2: 0xcd, // Uppercase I, acute accent
  17166. 0xb3: 0xcc, // Uppercase I, grave accent
  17167. 0xb4: 0xec, // Lowercase i, grave accent
  17168. 0xb5: 0xd2, // Uppercase O, grave accent
  17169. 0xb6: 0xf2, // Lowercase o, grave accent
  17170. 0xb7: 0xd5, // Uppercase O, tilde
  17171. 0xb8: 0xf5, // Lowercase o, tilde
  17172. 0xb9: 0x7b, // Open curly brace
  17173. 0xba: 0x7d, // Closing curly brace
  17174. 0xbb: 0x5c, // Backslash
  17175. 0xbc: 0x5e, // Caret
  17176. 0xbd: 0x5f, // Underscore
  17177. 0xbe: 0x7c, // Pipe (vertical line)
  17178. 0xbf: 0x223c, // Tilde operator
  17179. 0xc0: 0xc4, // Uppercase A, umlaut
  17180. 0xc1: 0xe4, // Lowercase A, umlaut
  17181. 0xc2: 0xd6, // Uppercase O, umlaut
  17182. 0xc3: 0xf6, // Lowercase o, umlaut
  17183. 0xc4: 0xdf, // Esszett (sharp S)
  17184. 0xc5: 0xa5, // Yen symbol
  17185. 0xc6: 0xa4, // Generic currency sign
  17186. 0xc7: 0x2503, // Box drawings heavy vertical
  17187. 0xc8: 0xc5, // Uppercase A, ring
  17188. 0xc9: 0xe5, // Lowercase A, ring
  17189. 0xca: 0xd8, // Uppercase O, stroke
  17190. 0xcb: 0xf8, // Lowercase o, strok
  17191. 0xcc: 0x250f, // Box drawings heavy down and right
  17192. 0xcd: 0x2513, // Box drawings heavy down and left
  17193. 0xce: 0x2517, // Box drawings heavy up and right
  17194. 0xcf: 0x251b // Box drawings heavy up and left
  17195. };
  17196. /**
  17197. * Utils
  17198. */
  17199. var getCharForByte = function getCharForByte(byte) {
  17200. var charCode = byte;
  17201. if (specialCea608CharsCodes.hasOwnProperty(byte)) {
  17202. charCode = specialCea608CharsCodes[byte];
  17203. }
  17204. return String.fromCharCode(charCode);
  17205. };
  17206. var NR_ROWS = 15,
  17207. NR_COLS = 100;
  17208. // Tables to look up row from PAC data
  17209. var rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 };
  17210. var rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 };
  17211. var rowsLowCh2 = { 0x19: 1, 0x1A: 3, 0x1D: 5, 0x1E: 7, 0x1F: 9, 0x18: 11, 0x1B: 12, 0x1C: 14 };
  17212. var rowsHighCh2 = { 0x19: 2, 0x1A: 4, 0x1D: 6, 0x1E: 8, 0x1F: 10, 0x1B: 13, 0x1C: 15 };
  17213. var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];
  17214. /**
  17215. * Simple logger class to be able to write with time-stamps and filter on level.
  17216. */
  17217. var logger = {
  17218. verboseFilter: { 'DATA': 3, 'DEBUG': 3, 'INFO': 2, 'WARNING': 2, 'TEXT': 1, 'ERROR': 0 },
  17219. time: null,
  17220. verboseLevel: 0, // Only write errors
  17221. setTime: function setTime(newTime) {
  17222. this.time = newTime;
  17223. },
  17224. log: function log(severity, msg) {
  17225. var minLevel = this.verboseFilter[severity];
  17226. if (this.verboseLevel >= minLevel) {
  17227. // console.log(this.time + ' [' + severity + '] ' + msg);
  17228. }
  17229. }
  17230. };
  17231. var numArrayToHexArray = function numArrayToHexArray(numArray) {
  17232. var hexArray = [];
  17233. for (var j = 0; j < numArray.length; j++) {
  17234. hexArray.push(numArray[j].toString(16));
  17235. }
  17236. return hexArray;
  17237. };
  17238. var PenState = function () {
  17239. function PenState(foreground, underline, italics, background, flash) {
  17240. _classCallCheck(this, PenState);
  17241. this.foreground = foreground || 'white';
  17242. this.underline = underline || false;
  17243. this.italics = italics || false;
  17244. this.background = background || 'black';
  17245. this.flash = flash || false;
  17246. }
  17247. _createClass(PenState, [{
  17248. key: 'reset',
  17249. value: function reset() {
  17250. this.foreground = 'white';
  17251. this.underline = false;
  17252. this.italics = false;
  17253. this.background = 'black';
  17254. this.flash = false;
  17255. }
  17256. }, {
  17257. key: 'setStyles',
  17258. value: function setStyles(styles) {
  17259. var attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];
  17260. for (var i = 0; i < attribs.length; i++) {
  17261. var style = attribs[i];
  17262. if (styles.hasOwnProperty(style)) {
  17263. this[style] = styles[style];
  17264. }
  17265. }
  17266. }
  17267. }, {
  17268. key: 'isDefault',
  17269. value: function isDefault() {
  17270. return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;
  17271. }
  17272. }, {
  17273. key: 'equals',
  17274. value: function equals(other) {
  17275. return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
  17276. }
  17277. }, {
  17278. key: 'copy',
  17279. value: function copy(newPenState) {
  17280. this.foreground = newPenState.foreground;
  17281. this.underline = newPenState.underline;
  17282. this.italics = newPenState.italics;
  17283. this.background = newPenState.background;
  17284. this.flash = newPenState.flash;
  17285. }
  17286. }, {
  17287. key: 'toString',
  17288. value: function toString() {
  17289. return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;
  17290. }
  17291. }]);
  17292. return PenState;
  17293. }();
  17294. /**
  17295. * Unicode character with styling and background.
  17296. * @constructor
  17297. */
  17298. var StyledUnicodeChar = function () {
  17299. function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) {
  17300. _classCallCheck(this, StyledUnicodeChar);
  17301. this.uchar = uchar || ' '; // unicode character
  17302. this.penState = new PenState(foreground, underline, italics, background, flash);
  17303. }
  17304. _createClass(StyledUnicodeChar, [{
  17305. key: 'reset',
  17306. value: function reset() {
  17307. this.uchar = ' ';
  17308. this.penState.reset();
  17309. }
  17310. }, {
  17311. key: 'setChar',
  17312. value: function setChar(uchar, newPenState) {
  17313. this.uchar = uchar;
  17314. this.penState.copy(newPenState);
  17315. }
  17316. }, {
  17317. key: 'setPenState',
  17318. value: function setPenState(newPenState) {
  17319. this.penState.copy(newPenState);
  17320. }
  17321. }, {
  17322. key: 'equals',
  17323. value: function equals(other) {
  17324. return this.uchar === other.uchar && this.penState.equals(other.penState);
  17325. }
  17326. }, {
  17327. key: 'copy',
  17328. value: function copy(newChar) {
  17329. this.uchar = newChar.uchar;
  17330. this.penState.copy(newChar.penState);
  17331. }
  17332. }, {
  17333. key: 'isEmpty',
  17334. value: function isEmpty() {
  17335. return this.uchar === ' ' && this.penState.isDefault();
  17336. }
  17337. }]);
  17338. return StyledUnicodeChar;
  17339. }();
  17340. /**
  17341. * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
  17342. * @constructor
  17343. */
  17344. var Row = function () {
  17345. function Row() {
  17346. _classCallCheck(this, Row);
  17347. this.chars = [];
  17348. for (var i = 0; i < NR_COLS; i++) {
  17349. this.chars.push(new StyledUnicodeChar());
  17350. }
  17351. this.pos = 0;
  17352. this.currPenState = new PenState();
  17353. }
  17354. _createClass(Row, [{
  17355. key: 'equals',
  17356. value: function equals(other) {
  17357. var equal = true;
  17358. for (var i = 0; i < NR_COLS; i++) {
  17359. if (!this.chars[i].equals(other.chars[i])) {
  17360. equal = false;
  17361. break;
  17362. }
  17363. }
  17364. return equal;
  17365. }
  17366. }, {
  17367. key: 'copy',
  17368. value: function copy(other) {
  17369. for (var i = 0; i < NR_COLS; i++) {
  17370. this.chars[i].copy(other.chars[i]);
  17371. }
  17372. }
  17373. }, {
  17374. key: 'isEmpty',
  17375. value: function isEmpty() {
  17376. var empty = true;
  17377. for (var i = 0; i < NR_COLS; i++) {
  17378. if (!this.chars[i].isEmpty()) {
  17379. empty = false;
  17380. break;
  17381. }
  17382. }
  17383. return empty;
  17384. }
  17385. /**
  17386. * Set the cursor to a valid column.
  17387. */
  17388. }, {
  17389. key: 'setCursor',
  17390. value: function setCursor(absPos) {
  17391. if (this.pos !== absPos) {
  17392. this.pos = absPos;
  17393. }
  17394. if (this.pos < 0) {
  17395. logger.log('ERROR', 'Negative cursor position ' + this.pos);
  17396. this.pos = 0;
  17397. } else if (this.pos > NR_COLS) {
  17398. logger.log('ERROR', 'Too large cursor position ' + this.pos);
  17399. this.pos = NR_COLS;
  17400. }
  17401. }
  17402. /**
  17403. * Move the cursor relative to current position.
  17404. */
  17405. }, {
  17406. key: 'moveCursor',
  17407. value: function moveCursor(relPos) {
  17408. var newPos = this.pos + relPos;
  17409. if (relPos > 1) {
  17410. for (var i = this.pos + 1; i < newPos + 1; i++) {
  17411. this.chars[i].setPenState(this.currPenState);
  17412. }
  17413. }
  17414. this.setCursor(newPos);
  17415. }
  17416. /**
  17417. * Backspace, move one step back and clear character.
  17418. */
  17419. }, {
  17420. key: 'backSpace',
  17421. value: function backSpace() {
  17422. this.moveCursor(-1);
  17423. this.chars[this.pos].setChar(' ', this.currPenState);
  17424. }
  17425. }, {
  17426. key: 'insertChar',
  17427. value: function insertChar(byte) {
  17428. if (byte >= 0x90) {
  17429. // Extended char
  17430. this.backSpace();
  17431. }
  17432. var char = getCharForByte(byte);
  17433. if (this.pos >= NR_COLS) {
  17434. logger.log('ERROR', 'Cannot insert ' + byte.toString(16) + ' (' + char + ') at position ' + this.pos + '. Skipping it!');
  17435. return;
  17436. }
  17437. this.chars[this.pos].setChar(char, this.currPenState);
  17438. this.moveCursor(1);
  17439. }
  17440. }, {
  17441. key: 'clearFromPos',
  17442. value: function clearFromPos(startPos) {
  17443. var i = void 0;
  17444. for (i = startPos; i < NR_COLS; i++) {
  17445. this.chars[i].reset();
  17446. }
  17447. }
  17448. }, {
  17449. key: 'clear',
  17450. value: function clear() {
  17451. this.clearFromPos(0);
  17452. this.pos = 0;
  17453. this.currPenState.reset();
  17454. }
  17455. }, {
  17456. key: 'clearToEndOfRow',
  17457. value: function clearToEndOfRow() {
  17458. this.clearFromPos(this.pos);
  17459. }
  17460. }, {
  17461. key: 'getTextString',
  17462. value: function getTextString() {
  17463. var chars = [];
  17464. var empty = true;
  17465. for (var i = 0; i < NR_COLS; i++) {
  17466. var char = this.chars[i].uchar;
  17467. if (char !== ' ') {
  17468. empty = false;
  17469. }
  17470. chars.push(char);
  17471. }
  17472. if (empty) {
  17473. return '';
  17474. } else {
  17475. return chars.join('');
  17476. }
  17477. }
  17478. }, {
  17479. key: 'setPenStyles',
  17480. value: function setPenStyles(styles) {
  17481. this.currPenState.setStyles(styles);
  17482. var currChar = this.chars[this.pos];
  17483. currChar.setPenState(this.currPenState);
  17484. }
  17485. }]);
  17486. return Row;
  17487. }();
  17488. /**
  17489. * Keep a CEA-608 screen of 32x15 styled characters
  17490. * @constructor
  17491. */
  17492. var CaptionScreen = function () {
  17493. function CaptionScreen() {
  17494. _classCallCheck(this, CaptionScreen);
  17495. this.rows = [];
  17496. for (var i = 0; i < NR_ROWS; i++) {
  17497. this.rows.push(new Row());
  17498. } // Note that we use zero-based numbering (0-14)
  17499. this.currRow = NR_ROWS - 1;
  17500. this.nrRollUpRows = null;
  17501. this.reset();
  17502. }
  17503. _createClass(CaptionScreen, [{
  17504. key: 'reset',
  17505. value: function reset() {
  17506. for (var i = 0; i < NR_ROWS; i++) {
  17507. this.rows[i].clear();
  17508. }
  17509. this.currRow = NR_ROWS - 1;
  17510. }
  17511. }, {
  17512. key: 'equals',
  17513. value: function equals(other) {
  17514. var equal = true;
  17515. for (var i = 0; i < NR_ROWS; i++) {
  17516. if (!this.rows[i].equals(other.rows[i])) {
  17517. equal = false;
  17518. break;
  17519. }
  17520. }
  17521. return equal;
  17522. }
  17523. }, {
  17524. key: 'copy',
  17525. value: function copy(other) {
  17526. for (var i = 0; i < NR_ROWS; i++) {
  17527. this.rows[i].copy(other.rows[i]);
  17528. }
  17529. }
  17530. }, {
  17531. key: 'isEmpty',
  17532. value: function isEmpty() {
  17533. var empty = true;
  17534. for (var i = 0; i < NR_ROWS; i++) {
  17535. if (!this.rows[i].isEmpty()) {
  17536. empty = false;
  17537. break;
  17538. }
  17539. }
  17540. return empty;
  17541. }
  17542. }, {
  17543. key: 'backSpace',
  17544. value: function backSpace() {
  17545. var row = this.rows[this.currRow];
  17546. row.backSpace();
  17547. }
  17548. }, {
  17549. key: 'clearToEndOfRow',
  17550. value: function clearToEndOfRow() {
  17551. var row = this.rows[this.currRow];
  17552. row.clearToEndOfRow();
  17553. }
  17554. /**
  17555. * Insert a character (without styling) in the current row.
  17556. */
  17557. }, {
  17558. key: 'insertChar',
  17559. value: function insertChar(char) {
  17560. var row = this.rows[this.currRow];
  17561. row.insertChar(char);
  17562. }
  17563. }, {
  17564. key: 'setPen',
  17565. value: function setPen(styles) {
  17566. var row = this.rows[this.currRow];
  17567. row.setPenStyles(styles);
  17568. }
  17569. }, {
  17570. key: 'moveCursor',
  17571. value: function moveCursor(relPos) {
  17572. var row = this.rows[this.currRow];
  17573. row.moveCursor(relPos);
  17574. }
  17575. }, {
  17576. key: 'setCursor',
  17577. value: function setCursor(absPos) {
  17578. logger.log('INFO', 'setCursor: ' + absPos);
  17579. var row = this.rows[this.currRow];
  17580. row.setCursor(absPos);
  17581. }
  17582. }, {
  17583. key: 'setPAC',
  17584. value: function setPAC(pacData) {
  17585. logger.log('INFO', 'pacData = ' + JSON.stringify(pacData));
  17586. var newRow = pacData.row - 1;
  17587. if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
  17588. newRow = this.nrRollUpRows - 1;
  17589. }
  17590. // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows
  17591. if (this.nrRollUpRows && this.currRow !== newRow) {
  17592. // clear all rows first
  17593. for (var i = 0; i < NR_ROWS; i++) {
  17594. this.rows[i].clear();
  17595. }
  17596. // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location
  17597. // topRowIndex - the start of rows to copy (inclusive index)
  17598. var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  17599. // We only copy if the last position was already shown.
  17600. // We use the cueStartTime value to check this.
  17601. var lastOutputScreen = this.lastOutputScreen;
  17602. if (lastOutputScreen) {
  17603. var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
  17604. if (prevLineTime && prevLineTime < logger.time) {
  17605. for (var _i = 0; _i < this.nrRollUpRows; _i++) {
  17606. this.rows[newRow - this.nrRollUpRows + _i + 1].copy(lastOutputScreen.rows[topRowIndex + _i]);
  17607. }
  17608. }
  17609. }
  17610. }
  17611. this.currRow = newRow;
  17612. var row = this.rows[this.currRow];
  17613. if (pacData.indent !== null) {
  17614. var indent = pacData.indent;
  17615. var prevPos = Math.max(indent - 1, 0);
  17616. row.setCursor(pacData.indent);
  17617. pacData.color = row.chars[prevPos].penState.foreground;
  17618. }
  17619. var styles = { foreground: pacData.color, underline: pacData.underline, italics: pacData.italics, background: 'black', flash: false };
  17620. this.setPen(styles);
  17621. }
  17622. /**
  17623. * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
  17624. */
  17625. }, {
  17626. key: 'setBkgData',
  17627. value: function setBkgData(bkgData) {
  17628. logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData));
  17629. this.backSpace();
  17630. this.setPen(bkgData);
  17631. this.insertChar(0x20); // Space
  17632. }
  17633. }, {
  17634. key: 'setRollUpRows',
  17635. value: function setRollUpRows(nrRows) {
  17636. this.nrRollUpRows = nrRows;
  17637. }
  17638. }, {
  17639. key: 'rollUp',
  17640. value: function rollUp() {
  17641. if (this.nrRollUpRows === null) {
  17642. logger.log('DEBUG', 'roll_up but nrRollUpRows not set yet');
  17643. return; // Not properly setup
  17644. }
  17645. logger.log('TEXT', this.getDisplayText());
  17646. var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  17647. var topRow = this.rows.splice(topRowIndex, 1)[0];
  17648. topRow.clear();
  17649. this.rows.splice(this.currRow, 0, topRow);
  17650. logger.log('INFO', 'Rolling up');
  17651. // logger.log('TEXT', this.get_display_text())
  17652. }
  17653. /**
  17654. * Get all non-empty rows with as unicode text.
  17655. */
  17656. }, {
  17657. key: 'getDisplayText',
  17658. value: function getDisplayText(asOneRow) {
  17659. asOneRow = asOneRow || false;
  17660. var displayText = [];
  17661. var text = '';
  17662. var rowNr = -1;
  17663. for (var i = 0; i < NR_ROWS; i++) {
  17664. var rowText = this.rows[i].getTextString();
  17665. if (rowText) {
  17666. rowNr = i + 1;
  17667. if (asOneRow) {
  17668. displayText.push('Row ' + rowNr + ': \'' + rowText + '\'');
  17669. } else {
  17670. displayText.push(rowText.trim());
  17671. }
  17672. }
  17673. }
  17674. if (displayText.length > 0) {
  17675. if (asOneRow) {
  17676. text = '[' + displayText.join(' | ') + ']';
  17677. } else {
  17678. text = displayText.join('\n');
  17679. }
  17680. }
  17681. return text;
  17682. }
  17683. }, {
  17684. key: 'getTextAndFormat',
  17685. value: function getTextAndFormat() {
  17686. return this.rows;
  17687. }
  17688. }]);
  17689. return CaptionScreen;
  17690. }();
  17691. // var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
  17692. var Cea608Channel = function () {
  17693. function Cea608Channel(channelNumber, outputFilter) {
  17694. _classCallCheck(this, Cea608Channel);
  17695. this.chNr = channelNumber;
  17696. this.outputFilter = outputFilter;
  17697. this.mode = null;
  17698. this.verbose = 0;
  17699. this.displayedMemory = new CaptionScreen();
  17700. this.nonDisplayedMemory = new CaptionScreen();
  17701. this.lastOutputScreen = new CaptionScreen();
  17702. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  17703. this.writeScreen = this.displayedMemory;
  17704. this.mode = null;
  17705. this.cueStartTime = null; // Keeps track of where a cue started.
  17706. }
  17707. _createClass(Cea608Channel, [{
  17708. key: 'reset',
  17709. value: function reset() {
  17710. this.mode = null;
  17711. this.displayedMemory.reset();
  17712. this.nonDisplayedMemory.reset();
  17713. this.lastOutputScreen.reset();
  17714. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  17715. this.writeScreen = this.displayedMemory;
  17716. this.mode = null;
  17717. this.cueStartTime = null;
  17718. this.lastCueEndTime = null;
  17719. }
  17720. }, {
  17721. key: 'getHandler',
  17722. value: function getHandler() {
  17723. return this.outputFilter;
  17724. }
  17725. }, {
  17726. key: 'setHandler',
  17727. value: function setHandler(newHandler) {
  17728. this.outputFilter = newHandler;
  17729. }
  17730. }, {
  17731. key: 'setPAC',
  17732. value: function setPAC(pacData) {
  17733. this.writeScreen.setPAC(pacData);
  17734. }
  17735. }, {
  17736. key: 'setBkgData',
  17737. value: function setBkgData(bkgData) {
  17738. this.writeScreen.setBkgData(bkgData);
  17739. }
  17740. }, {
  17741. key: 'setMode',
  17742. value: function setMode(newMode) {
  17743. if (newMode === this.mode) {
  17744. return;
  17745. }
  17746. this.mode = newMode;
  17747. logger.log('INFO', 'MODE=' + newMode);
  17748. if (this.mode === 'MODE_POP-ON') {
  17749. this.writeScreen = this.nonDisplayedMemory;
  17750. } else {
  17751. this.writeScreen = this.displayedMemory;
  17752. this.writeScreen.reset();
  17753. }
  17754. if (this.mode !== 'MODE_ROLL-UP') {
  17755. this.displayedMemory.nrRollUpRows = null;
  17756. this.nonDisplayedMemory.nrRollUpRows = null;
  17757. }
  17758. this.mode = newMode;
  17759. }
  17760. }, {
  17761. key: 'insertChars',
  17762. value: function insertChars(chars) {
  17763. for (var i = 0; i < chars.length; i++) {
  17764. this.writeScreen.insertChar(chars[i]);
  17765. }
  17766. var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';
  17767. logger.log('INFO', screen + ': ' + this.writeScreen.getDisplayText(true));
  17768. if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
  17769. logger.log('TEXT', 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));
  17770. this.outputDataUpdate();
  17771. }
  17772. }
  17773. }, {
  17774. key: 'ccRCL',
  17775. value: function ccRCL() {
  17776. // Resume Caption Loading (switch mode to Pop On)
  17777. logger.log('INFO', 'RCL - Resume Caption Loading');
  17778. this.setMode('MODE_POP-ON');
  17779. }
  17780. }, {
  17781. key: 'ccBS',
  17782. value: function ccBS() {
  17783. // BackSpace
  17784. logger.log('INFO', 'BS - BackSpace');
  17785. if (this.mode === 'MODE_TEXT') {
  17786. return;
  17787. }
  17788. this.writeScreen.backSpace();
  17789. if (this.writeScreen === this.displayedMemory) {
  17790. this.outputDataUpdate();
  17791. }
  17792. }
  17793. }, {
  17794. key: 'ccAOF',
  17795. value: function ccAOF() {// Reserved (formerly Alarm Off)
  17796. }
  17797. }, {
  17798. key: 'ccAON',
  17799. value: function ccAON() {// Reserved (formerly Alarm On)
  17800. }
  17801. }, {
  17802. key: 'ccDER',
  17803. value: function ccDER() {
  17804. // Delete to End of Row
  17805. logger.log('INFO', 'DER- Delete to End of Row');
  17806. this.writeScreen.clearToEndOfRow();
  17807. this.outputDataUpdate();
  17808. }
  17809. }, {
  17810. key: 'ccRU',
  17811. value: function ccRU(nrRows) {
  17812. // Roll-Up Captions-2,3,or 4 Rows
  17813. logger.log('INFO', 'RU(' + nrRows + ') - Roll Up');
  17814. this.writeScreen = this.displayedMemory;
  17815. this.setMode('MODE_ROLL-UP');
  17816. this.writeScreen.setRollUpRows(nrRows);
  17817. }
  17818. }, {
  17819. key: 'ccFON',
  17820. value: function ccFON() {
  17821. // Flash On
  17822. logger.log('INFO', 'FON - Flash On');
  17823. this.writeScreen.setPen({ flash: true });
  17824. }
  17825. }, {
  17826. key: 'ccRDC',
  17827. value: function ccRDC() {
  17828. // Resume Direct Captioning (switch mode to PaintOn)
  17829. logger.log('INFO', 'RDC - Resume Direct Captioning');
  17830. this.setMode('MODE_PAINT-ON');
  17831. }
  17832. }, {
  17833. key: 'ccTR',
  17834. value: function ccTR() {
  17835. // Text Restart in text mode (not supported, however)
  17836. logger.log('INFO', 'TR');
  17837. this.setMode('MODE_TEXT');
  17838. }
  17839. }, {
  17840. key: 'ccRTD',
  17841. value: function ccRTD() {
  17842. // Resume Text Display in Text mode (not supported, however)
  17843. logger.log('INFO', 'RTD');
  17844. this.setMode('MODE_TEXT');
  17845. }
  17846. }, {
  17847. key: 'ccEDM',
  17848. value: function ccEDM() {
  17849. // Erase Displayed Memory
  17850. logger.log('INFO', 'EDM - Erase Displayed Memory');
  17851. this.displayedMemory.reset();
  17852. this.outputDataUpdate(true);
  17853. }
  17854. }, {
  17855. key: 'ccCR',
  17856. value: function ccCR() {
  17857. // Carriage Return
  17858. logger.log('CR - Carriage Return');
  17859. this.writeScreen.rollUp();
  17860. this.outputDataUpdate(true);
  17861. }
  17862. }, {
  17863. key: 'ccENM',
  17864. value: function ccENM() {
  17865. // Erase Non-Displayed Memory
  17866. logger.log('INFO', 'ENM - Erase Non-displayed Memory');
  17867. this.nonDisplayedMemory.reset();
  17868. }
  17869. }, {
  17870. key: 'ccEOC',
  17871. value: function ccEOC() {
  17872. // End of Caption (Flip Memories)
  17873. logger.log('INFO', 'EOC - End Of Caption');
  17874. if (this.mode === 'MODE_POP-ON') {
  17875. var tmp = this.displayedMemory;
  17876. this.displayedMemory = this.nonDisplayedMemory;
  17877. this.nonDisplayedMemory = tmp;
  17878. this.writeScreen = this.nonDisplayedMemory;
  17879. logger.log('TEXT', 'DISP: ' + this.displayedMemory.getDisplayText());
  17880. }
  17881. this.outputDataUpdate(true);
  17882. }
  17883. }, {
  17884. key: 'ccTO',
  17885. value: function ccTO(nrCols) {
  17886. // Tab Offset 1,2, or 3 columns
  17887. logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset');
  17888. this.writeScreen.moveCursor(nrCols);
  17889. }
  17890. }, {
  17891. key: 'ccMIDROW',
  17892. value: function ccMIDROW(secondByte) {
  17893. // Parse MIDROW command
  17894. var styles = { flash: false };
  17895. styles.underline = secondByte % 2 === 1;
  17896. styles.italics = secondByte >= 0x2e;
  17897. if (!styles.italics) {
  17898. var colorIndex = Math.floor(secondByte / 2) - 0x10;
  17899. var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];
  17900. styles.foreground = colors[colorIndex];
  17901. } else {
  17902. styles.foreground = 'white';
  17903. }
  17904. logger.log('INFO', 'MIDROW: ' + JSON.stringify(styles));
  17905. this.writeScreen.setPen(styles);
  17906. }
  17907. }, {
  17908. key: 'outputDataUpdate',
  17909. value: function outputDataUpdate() {
  17910. var dispatch = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  17911. var t = logger.time;
  17912. if (t === null) {
  17913. return;
  17914. }
  17915. if (this.outputFilter) {
  17916. if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
  17917. // Start of a new cue
  17918. this.cueStartTime = t;
  17919. } else {
  17920. if (!this.displayedMemory.equals(this.lastOutputScreen)) {
  17921. if (this.outputFilter.newCue) {
  17922. this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen);
  17923. if (dispatch === true && this.outputFilter.dispatchCue) {
  17924. this.outputFilter.dispatchCue();
  17925. }
  17926. }
  17927. this.cueStartTime = this.displayedMemory.isEmpty() ? null : t;
  17928. }
  17929. }
  17930. this.lastOutputScreen.copy(this.displayedMemory);
  17931. }
  17932. }
  17933. }, {
  17934. key: 'cueSplitAtTime',
  17935. value: function cueSplitAtTime(t) {
  17936. if (this.outputFilter) {
  17937. if (!this.displayedMemory.isEmpty()) {
  17938. if (this.outputFilter.newCue) {
  17939. this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
  17940. }
  17941. this.cueStartTime = t;
  17942. }
  17943. }
  17944. }
  17945. }]);
  17946. return Cea608Channel;
  17947. }();
  17948. var Cea608Parser = function () {
  17949. function Cea608Parser(field, out1, out2) {
  17950. _classCallCheck(this, Cea608Parser);
  17951. this.field = field || 1;
  17952. this.outputs = [out1, out2];
  17953. this.channels = [new Cea608Channel(1, out1), new Cea608Channel(2, out2)];
  17954. this.currChNr = -1; // Will be 1 or 2
  17955. this.lastCmdA = null; // First byte of last command
  17956. this.lastCmdB = null; // Second byte of last command
  17957. this.bufferedData = [];
  17958. this.startTime = null;
  17959. this.lastTime = null;
  17960. this.dataCounters = { 'padding': 0, 'char': 0, 'cmd': 0, 'other': 0 };
  17961. }
  17962. _createClass(Cea608Parser, [{
  17963. key: 'getHandler',
  17964. value: function getHandler(index) {
  17965. return this.channels[index].getHandler();
  17966. }
  17967. }, {
  17968. key: 'setHandler',
  17969. value: function setHandler(index, newHandler) {
  17970. this.channels[index].setHandler(newHandler);
  17971. }
  17972. /**
  17973. * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
  17974. */
  17975. }, {
  17976. key: 'addData',
  17977. value: function addData(t, byteList) {
  17978. var cmdFound = void 0,
  17979. a = void 0,
  17980. b = void 0,
  17981. charsFound = false;
  17982. this.lastTime = t;
  17983. logger.setTime(t);
  17984. for (var i = 0; i < byteList.length; i += 2) {
  17985. a = byteList[i] & 0x7f;
  17986. b = byteList[i + 1] & 0x7f;
  17987. if (a === 0 && b === 0) {
  17988. this.dataCounters.padding += 2;
  17989. continue;
  17990. } else {
  17991. logger.log('DATA', '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');
  17992. }
  17993. cmdFound = this.parseCmd(a, b);
  17994. if (!cmdFound) {
  17995. cmdFound = this.parseMidrow(a, b);
  17996. }
  17997. if (!cmdFound) {
  17998. cmdFound = this.parsePAC(a, b);
  17999. }
  18000. if (!cmdFound) {
  18001. cmdFound = this.parseBackgroundAttributes(a, b);
  18002. }
  18003. if (!cmdFound) {
  18004. charsFound = this.parseChars(a, b);
  18005. if (charsFound) {
  18006. if (this.currChNr && this.currChNr >= 0) {
  18007. var channel = this.channels[this.currChNr - 1];
  18008. channel.insertChars(charsFound);
  18009. } else {
  18010. logger.log('WARNING', 'No channel found yet. TEXT-MODE?');
  18011. }
  18012. }
  18013. }
  18014. if (cmdFound) {
  18015. this.dataCounters.cmd += 2;
  18016. } else if (charsFound) {
  18017. this.dataCounters.char += 2;
  18018. } else {
  18019. this.dataCounters.other += 2;
  18020. logger.log('WARNING', 'Couldn\'t parse cleaned data ' + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));
  18021. }
  18022. }
  18023. }
  18024. /**
  18025. * Parse Command.
  18026. * @returns {Boolean} Tells if a command was found
  18027. */
  18028. }, {
  18029. key: 'parseCmd',
  18030. value: function parseCmd(a, b) {
  18031. var chNr = null;
  18032. var cond1 = (a === 0x14 || a === 0x1C) && b >= 0x20 && b <= 0x2F;
  18033. var cond2 = (a === 0x17 || a === 0x1F) && b >= 0x21 && b <= 0x23;
  18034. if (!(cond1 || cond2)) {
  18035. return false;
  18036. }
  18037. if (a === this.lastCmdA && b === this.lastCmdB) {
  18038. this.lastCmdA = null;
  18039. this.lastCmdB = null; // Repeated commands are dropped (once)
  18040. logger.log('DEBUG', 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');
  18041. return true;
  18042. }
  18043. if (a === 0x14 || a === 0x17) {
  18044. chNr = 1;
  18045. } else {
  18046. chNr = 2;
  18047. } // (a === 0x1C || a=== 0x1f)
  18048. var channel = this.channels[chNr - 1];
  18049. if (a === 0x14 || a === 0x1C) {
  18050. if (b === 0x20) {
  18051. channel.ccRCL();
  18052. } else if (b === 0x21) {
  18053. channel.ccBS();
  18054. } else if (b === 0x22) {
  18055. channel.ccAOF();
  18056. } else if (b === 0x23) {
  18057. channel.ccAON();
  18058. } else if (b === 0x24) {
  18059. channel.ccDER();
  18060. } else if (b === 0x25) {
  18061. channel.ccRU(2);
  18062. } else if (b === 0x26) {
  18063. channel.ccRU(3);
  18064. } else if (b === 0x27) {
  18065. channel.ccRU(4);
  18066. } else if (b === 0x28) {
  18067. channel.ccFON();
  18068. } else if (b === 0x29) {
  18069. channel.ccRDC();
  18070. } else if (b === 0x2A) {
  18071. channel.ccTR();
  18072. } else if (b === 0x2B) {
  18073. channel.ccRTD();
  18074. } else if (b === 0x2C) {
  18075. channel.ccEDM();
  18076. } else if (b === 0x2D) {
  18077. channel.ccCR();
  18078. } else if (b === 0x2E) {
  18079. channel.ccENM();
  18080. } else if (b === 0x2F) {
  18081. channel.ccEOC();
  18082. }
  18083. } else {
  18084. // a == 0x17 || a == 0x1F
  18085. channel.ccTO(b - 0x20);
  18086. }
  18087. this.lastCmdA = a;
  18088. this.lastCmdB = b;
  18089. this.currChNr = chNr;
  18090. return true;
  18091. }
  18092. /**
  18093. * Parse midrow styling command
  18094. * @returns {Boolean}
  18095. */
  18096. }, {
  18097. key: 'parseMidrow',
  18098. value: function parseMidrow(a, b) {
  18099. var chNr = null;
  18100. if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {
  18101. if (a === 0x11) {
  18102. chNr = 1;
  18103. } else {
  18104. chNr = 2;
  18105. }
  18106. if (chNr !== this.currChNr) {
  18107. logger.log('ERROR', 'Mismatch channel in midrow parsing');
  18108. return false;
  18109. }
  18110. var channel = this.channels[chNr - 1];
  18111. channel.ccMIDROW(b);
  18112. logger.log('DEBUG', 'MIDROW (' + numArrayToHexArray([a, b]) + ')');
  18113. return true;
  18114. }
  18115. return false;
  18116. }
  18117. /**
  18118. * Parse Preable Access Codes (Table 53).
  18119. * @returns {Boolean} Tells if PAC found
  18120. */
  18121. }, {
  18122. key: 'parsePAC',
  18123. value: function parsePAC(a, b) {
  18124. var chNr = null;
  18125. var row = null;
  18126. var case1 = (a >= 0x11 && a <= 0x17 || a >= 0x19 && a <= 0x1F) && b >= 0x40 && b <= 0x7F;
  18127. var case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5F;
  18128. if (!(case1 || case2)) {
  18129. return false;
  18130. }
  18131. if (a === this.lastCmdA && b === this.lastCmdB) {
  18132. this.lastCmdA = null;
  18133. this.lastCmdB = null;
  18134. return true; // Repeated commands are dropped (once)
  18135. }
  18136. chNr = a <= 0x17 ? 1 : 2;
  18137. if (b >= 0x40 && b <= 0x5F) {
  18138. row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
  18139. } else {
  18140. // 0x60 <= b <= 0x7F
  18141. row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
  18142. }
  18143. var pacData = this.interpretPAC(row, b);
  18144. var channel = this.channels[chNr - 1];
  18145. channel.setPAC(pacData);
  18146. this.lastCmdA = a;
  18147. this.lastCmdB = b;
  18148. this.currChNr = chNr;
  18149. return true;
  18150. }
  18151. /**
  18152. * Interpret the second byte of the pac, and return the information.
  18153. * @returns {Object} pacData with style parameters.
  18154. */
  18155. }, {
  18156. key: 'interpretPAC',
  18157. value: function interpretPAC(row, byte) {
  18158. var pacIndex = byte;
  18159. var pacData = { color: null, italics: false, indent: null, underline: false, row: row };
  18160. if (byte > 0x5F) {
  18161. pacIndex = byte - 0x60;
  18162. } else {
  18163. pacIndex = byte - 0x40;
  18164. }
  18165. pacData.underline = (pacIndex & 1) === 1;
  18166. if (pacIndex <= 0xd) {
  18167. pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];
  18168. } else if (pacIndex <= 0xf) {
  18169. pacData.italics = true;
  18170. pacData.color = 'white';
  18171. } else {
  18172. pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;
  18173. }
  18174. return pacData; // Note that row has zero offset. The spec uses 1.
  18175. }
  18176. /**
  18177. * Parse characters.
  18178. * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
  18179. */
  18180. }, {
  18181. key: 'parseChars',
  18182. value: function parseChars(a, b) {
  18183. var channelNr = null,
  18184. charCodes = null,
  18185. charCode1 = null;
  18186. if (a >= 0x19) {
  18187. channelNr = 2;
  18188. charCode1 = a - 8;
  18189. } else {
  18190. channelNr = 1;
  18191. charCode1 = a;
  18192. }
  18193. if (charCode1 >= 0x11 && charCode1 <= 0x13) {
  18194. // Special character
  18195. var oneCode = b;
  18196. if (charCode1 === 0x11) {
  18197. oneCode = b + 0x50;
  18198. } else if (charCode1 === 0x12) {
  18199. oneCode = b + 0x70;
  18200. } else {
  18201. oneCode = b + 0x90;
  18202. }
  18203. logger.log('INFO', 'Special char \'' + getCharForByte(oneCode) + '\' in channel ' + channelNr);
  18204. charCodes = [oneCode];
  18205. } else if (a >= 0x20 && a <= 0x7f) {
  18206. charCodes = b === 0 ? [a] : [a, b];
  18207. }
  18208. if (charCodes) {
  18209. var hexCodes = numArrayToHexArray(charCodes);
  18210. logger.log('DEBUG', 'Char codes = ' + hexCodes.join(','));
  18211. this.lastCmdA = null;
  18212. this.lastCmdB = null;
  18213. }
  18214. return charCodes;
  18215. }
  18216. /**
  18217. * Parse extended background attributes as well as new foreground color black.
  18218. * @returns{Boolean} Tells if background attributes are found
  18219. */
  18220. }, {
  18221. key: 'parseBackgroundAttributes',
  18222. value: function parseBackgroundAttributes(a, b) {
  18223. var bkgData = void 0,
  18224. index = void 0,
  18225. chNr = void 0,
  18226. channel = void 0;
  18227. var case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;
  18228. var case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;
  18229. if (!(case1 || case2)) {
  18230. return false;
  18231. }
  18232. bkgData = {};
  18233. if (a === 0x10 || a === 0x18) {
  18234. index = Math.floor((b - 0x20) / 2);
  18235. bkgData.background = backgroundColors[index];
  18236. if (b % 2 === 1) {
  18237. bkgData.background = bkgData.background + '_semi';
  18238. }
  18239. } else if (b === 0x2d) {
  18240. bkgData.background = 'transparent';
  18241. } else {
  18242. bkgData.foreground = 'black';
  18243. if (b === 0x2f) {
  18244. bkgData.underline = true;
  18245. }
  18246. }
  18247. chNr = a < 0x18 ? 1 : 2;
  18248. channel = this.channels[chNr - 1];
  18249. channel.setBkgData(bkgData);
  18250. this.lastCmdA = null;
  18251. this.lastCmdB = null;
  18252. return true;
  18253. }
  18254. /**
  18255. * Reset state of parser and its channels.
  18256. */
  18257. }, {
  18258. key: 'reset',
  18259. value: function reset() {
  18260. for (var i = 0; i < this.channels.length; i++) {
  18261. if (this.channels[i]) {
  18262. this.channels[i].reset();
  18263. }
  18264. }
  18265. this.lastCmdA = null;
  18266. this.lastCmdB = null;
  18267. }
  18268. /**
  18269. * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
  18270. */
  18271. }, {
  18272. key: 'cueSplitAtTime',
  18273. value: function cueSplitAtTime(t) {
  18274. for (var i = 0; i < this.channels.length; i++) {
  18275. if (this.channels[i]) {
  18276. this.channels[i].cueSplitAtTime(t);
  18277. }
  18278. }
  18279. }
  18280. }]);
  18281. return Cea608Parser;
  18282. }();
  18283. exports.default = Cea608Parser;
  18284. module.exports = exports['default'];
  18285. /***/ }),
  18286. /* 74 */
  18287. /***/ (function(module, exports, __webpack_require__) {
  18288. "use strict";
  18289. Object.defineProperty(exports, "__esModule", {
  18290. value: true
  18291. });
  18292. 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; }; }();
  18293. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  18294. var OutputFilter = function () {
  18295. function OutputFilter(timelineController, trackName) {
  18296. _classCallCheck(this, OutputFilter);
  18297. this.timelineController = timelineController;
  18298. this.trackName = trackName;
  18299. this.startTime = null;
  18300. this.endTime = null;
  18301. this.screen = null;
  18302. }
  18303. _createClass(OutputFilter, [{
  18304. key: "dispatchCue",
  18305. value: function dispatchCue() {
  18306. if (this.startTime === null) {
  18307. return;
  18308. }
  18309. this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen);
  18310. this.startTime = null;
  18311. }
  18312. }, {
  18313. key: "newCue",
  18314. value: function newCue(startTime, endTime, screen) {
  18315. if (this.startTime === null || this.startTime > startTime) {
  18316. this.startTime = startTime;
  18317. }
  18318. this.endTime = endTime;
  18319. this.screen = screen;
  18320. this.timelineController.createCaptionsTrack(this.trackName);
  18321. }
  18322. }]);
  18323. return OutputFilter;
  18324. }();
  18325. exports.default = OutputFilter;
  18326. module.exports = exports["default"];
  18327. /***/ }),
  18328. /* 75 */
  18329. /***/ (function(module, exports, __webpack_require__) {
  18330. "use strict";
  18331. Object.defineProperty(exports, "__esModule", {
  18332. value: true
  18333. });
  18334. var _vttparser = __webpack_require__(30);
  18335. var _vttparser2 = _interopRequireDefault(_vttparser);
  18336. var _id = __webpack_require__(10);
  18337. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  18338. // String.prototype.startsWith is not supported in IE11
  18339. var startsWith = function startsWith(inputString, searchString, position) {
  18340. return inputString.substr(position || 0, searchString.length) === searchString;
  18341. };
  18342. var cueString2millis = function cueString2millis(timeString) {
  18343. var ts = parseInt(timeString.substr(-3));
  18344. var secs = parseInt(timeString.substr(-6, 2));
  18345. var mins = parseInt(timeString.substr(-9, 2));
  18346. var hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;
  18347. if (!Number.isFinite(ts) || !Number.isFinite(secs) || !Number.isFinite(mins) || !Number.isFinite(hours)) {
  18348. return -1;
  18349. }
  18350. ts += 1000 * secs;
  18351. ts += 60 * 1000 * mins;
  18352. ts += 60 * 60 * 1000 * hours;
  18353. return ts;
  18354. };
  18355. // From https://github.com/darkskyapp/string-hash
  18356. var hash = function hash(text) {
  18357. var hash = 5381;
  18358. var i = text.length;
  18359. while (i) {
  18360. hash = hash * 33 ^ text.charCodeAt(--i);
  18361. }
  18362. return (hash >>> 0).toString();
  18363. };
  18364. var calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {
  18365. var currCC = vttCCs[cc];
  18366. var prevCC = vttCCs[currCC.prevCC];
  18367. // This is the first discontinuity or cues have been processed since the last discontinuity
  18368. // Offset = current discontinuity time
  18369. if (!prevCC || !prevCC.new && currCC.new) {
  18370. vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
  18371. currCC.new = false;
  18372. return;
  18373. }
  18374. // There have been discontinuities since cues were last parsed.
  18375. // Offset = time elapsed
  18376. while (prevCC && prevCC.new) {
  18377. vttCCs.ccOffset += currCC.start - prevCC.start;
  18378. currCC.new = false;
  18379. currCC = prevCC;
  18380. prevCC = vttCCs[currCC.prevCC];
  18381. }
  18382. vttCCs.presentationOffset = presentationTime;
  18383. };
  18384. var WebVTTParser = {
  18385. parse: function parse(vttByteArray, syncPTS, vttCCs, cc, callBack, errorCallBack) {
  18386. // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character.
  18387. var re = /\r\n|\n\r|\n|\r/g;
  18388. // Uint8Array.prototype.reduce is not implemented in IE11
  18389. var vttLines = (0, _id.utf8ArrayToStr)(new Uint8Array(vttByteArray)).trim().replace(re, '\n').split('\n');
  18390. var cueTime = '00:00.000';
  18391. var mpegTs = 0;
  18392. var localTime = 0;
  18393. var presentationTime = 0;
  18394. var cues = [];
  18395. var parsingError = void 0;
  18396. var inHeader = true;
  18397. // let VTTCue = VTTCue || window.TextTrackCue;
  18398. // Create parser object using VTTCue with TextTrackCue fallback on certain browsers.
  18399. var parser = new _vttparser2.default();
  18400. parser.oncue = function (cue) {
  18401. // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.
  18402. var currCC = vttCCs[cc];
  18403. var cueOffset = vttCCs.ccOffset;
  18404. // Update offsets for new discontinuities
  18405. if (currCC && currCC.new) {
  18406. if (localTime !== undefined) {
  18407. // When local time is provided, offset = discontinuity start time - local time
  18408. cueOffset = vttCCs.ccOffset = currCC.start;
  18409. } else {
  18410. calculateOffset(vttCCs, cc, presentationTime);
  18411. }
  18412. }
  18413. if (presentationTime) {
  18414. // If we have MPEGTS, offset = presentation time + discontinuity offset
  18415. cueOffset = presentationTime - vttCCs.presentationOffset;
  18416. }
  18417. cue.startTime += cueOffset - localTime;
  18418. cue.endTime += cueOffset - localTime;
  18419. // Create a unique hash id for a cue based on start/end times and text.
  18420. // This helps timeline-controller to avoid showing repeated captions.
  18421. cue.id = hash(cue.startTime.toString()) + hash(cue.endTime.toString()) + hash(cue.text);
  18422. // Fix encoding of special characters. TODO: Test with all sorts of weird characters.
  18423. cue.text = decodeURIComponent(encodeURIComponent(cue.text));
  18424. if (cue.endTime > 0) {
  18425. cues.push(cue);
  18426. }
  18427. };
  18428. parser.onparsingerror = function (e) {
  18429. parsingError = e;
  18430. };
  18431. parser.onflush = function () {
  18432. if (parsingError && errorCallBack) {
  18433. errorCallBack(parsingError);
  18434. return;
  18435. }
  18436. callBack(cues);
  18437. };
  18438. // Go through contents line by line.
  18439. vttLines.forEach(function (line) {
  18440. if (inHeader) {
  18441. // Look for X-TIMESTAMP-MAP in header.
  18442. if (startsWith(line, 'X-TIMESTAMP-MAP=')) {
  18443. // Once found, no more are allowed anyway, so stop searching.
  18444. inHeader = false;
  18445. // Extract LOCAL and MPEGTS.
  18446. line.substr(16).split(',').forEach(function (timestamp) {
  18447. if (startsWith(timestamp, 'LOCAL:')) {
  18448. cueTime = timestamp.substr(6);
  18449. } else if (startsWith(timestamp, 'MPEGTS:')) {
  18450. mpegTs = parseInt(timestamp.substr(7));
  18451. }
  18452. });
  18453. try {
  18454. // Calculate subtitle offset in milliseconds.
  18455. if (syncPTS + (vttCCs[cc].start * 90000 || 0) < 0) {
  18456. syncPTS += 8589934592;
  18457. }
  18458. // Adjust MPEGTS by sync PTS.
  18459. mpegTs -= syncPTS;
  18460. // Convert cue time to seconds
  18461. localTime = cueString2millis(cueTime) / 1000;
  18462. // Convert MPEGTS to seconds from 90kHz.
  18463. presentationTime = mpegTs / 90000;
  18464. if (localTime === -1) {
  18465. parsingError = new Error('Malformed X-TIMESTAMP-MAP: ' + line);
  18466. }
  18467. } catch (e) {
  18468. parsingError = new Error('Malformed X-TIMESTAMP-MAP: ' + line);
  18469. }
  18470. // Return without parsing X-TIMESTAMP-MAP line.
  18471. return;
  18472. } else if (line === '') {
  18473. inHeader = false;
  18474. }
  18475. }
  18476. // Parse line by default.
  18477. parser.parse(line + '\n');
  18478. });
  18479. parser.flush();
  18480. }
  18481. };
  18482. exports.default = WebVTTParser;
  18483. module.exports = exports['default'];
  18484. /***/ }),
  18485. /* 76 */
  18486. /***/ (function(module, exports, __webpack_require__) {
  18487. "use strict";
  18488. Object.defineProperty(exports, "__esModule", {
  18489. value: true
  18490. });
  18491. 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; }; }();
  18492. var _events = __webpack_require__(1);
  18493. var _events2 = _interopRequireDefault(_events);
  18494. var _eventHandler = __webpack_require__(3);
  18495. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  18496. var _logger = __webpack_require__(0);
  18497. var _levelHelper = __webpack_require__(7);
  18498. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  18499. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  18500. 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; }
  18501. 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; }
  18502. var SubtitleTrackController = function (_EventHandler) {
  18503. _inherits(SubtitleTrackController, _EventHandler);
  18504. function SubtitleTrackController(hls) {
  18505. _classCallCheck(this, SubtitleTrackController);
  18506. 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));
  18507. _this.tracks = [];
  18508. _this.trackId = -1;
  18509. _this.media = null;
  18510. _this.stopped = true;
  18511. /**
  18512. * @member {boolean} subtitleDisplay Enable/disable subtitle display rendering
  18513. */
  18514. _this.subtitleDisplay = true;
  18515. return _this;
  18516. }
  18517. _createClass(SubtitleTrackController, [{
  18518. key: 'destroy',
  18519. value: function destroy() {
  18520. _eventHandler2.default.prototype.destroy.call(this);
  18521. }
  18522. // Listen for subtitle track change, then extract the current track ID.
  18523. }, {
  18524. key: 'onMediaAttached',
  18525. value: function onMediaAttached(data) {
  18526. var _this2 = this;
  18527. this.media = data.media;
  18528. if (!this.media) {
  18529. return;
  18530. }
  18531. if (this.queuedDefaultTrack) {
  18532. this.subtitleTrack = this.queuedDefaultTrack;
  18533. delete this.queuedDefaultTrack;
  18534. }
  18535. this.trackChangeListener = this._onTextTracksChanged.bind(this);
  18536. this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);
  18537. if (this.useTextTrackPolling) {
  18538. this.subtitlePollingInterval = setInterval(function () {
  18539. _this2.trackChangeListener();
  18540. }, 500);
  18541. } else {
  18542. this.media.textTracks.addEventListener('change', this.trackChangeListener);
  18543. }
  18544. }
  18545. }, {
  18546. key: 'onMediaDetaching',
  18547. value: function onMediaDetaching() {
  18548. if (!this.media) {
  18549. return;
  18550. }
  18551. if (this.useTextTrackPolling) {
  18552. clearInterval(this.subtitlePollingInterval);
  18553. } else {
  18554. this.media.textTracks.removeEventListener('change', this.trackChangeListener);
  18555. }
  18556. this.media = null;
  18557. }
  18558. // Fired whenever a new manifest is loaded.
  18559. }, {
  18560. key: 'onManifestLoaded',
  18561. value: function onManifestLoaded(data) {
  18562. var _this3 = this;
  18563. var tracks = data.subtitles || [];
  18564. this.tracks = tracks;
  18565. this.hls.trigger(_events2.default.SUBTITLE_TRACKS_UPDATED, { subtitleTracks: tracks });
  18566. // loop through available subtitle tracks and autoselect default if needed
  18567. // TODO: improve selection logic to handle forced, etc
  18568. tracks.forEach(function (track) {
  18569. if (track.default) {
  18570. // setting this.subtitleTrack will trigger internal logic
  18571. // if media has not been attached yet, it will fail
  18572. // we keep a reference to the default track id
  18573. // and we'll set subtitleTrack when onMediaAttached is triggered
  18574. if (_this3.media) {
  18575. _this3.subtitleTrack = track.id;
  18576. } else {
  18577. _this3.queuedDefaultTrack = track.id;
  18578. }
  18579. }
  18580. });
  18581. }
  18582. }, {
  18583. key: 'onSubtitleTrackLoaded',
  18584. value: function onSubtitleTrackLoaded(data) {
  18585. var _this4 = this;
  18586. var id = data.id,
  18587. details = data.details;
  18588. var trackId = this.trackId,
  18589. tracks = this.tracks;
  18590. var currentTrack = tracks[trackId];
  18591. if (id >= tracks.length || id !== trackId || !currentTrack || this.stopped) {
  18592. this._clearReloadTimer();
  18593. return;
  18594. }
  18595. _logger.logger.log('subtitle track ' + id + ' loaded');
  18596. if (details.live) {
  18597. var reloadInterval = (0, _levelHelper.computeReloadInterval)(currentTrack.details, details, data.stats.trequest);
  18598. _logger.logger.log('Reloading live subtitle playlist in ' + reloadInterval + 'ms');
  18599. this.timer = setTimeout(function () {
  18600. _this4._loadCurrentTrack();
  18601. }, reloadInterval);
  18602. } else {
  18603. this._clearReloadTimer();
  18604. }
  18605. }
  18606. }, {
  18607. key: 'startLoad',
  18608. value: function startLoad() {
  18609. this.stopped = false;
  18610. this._loadCurrentTrack();
  18611. }
  18612. }, {
  18613. key: 'stopLoad',
  18614. value: function stopLoad() {
  18615. this.stopped = true;
  18616. this._clearReloadTimer();
  18617. }
  18618. /** get alternate subtitle tracks list from playlist **/
  18619. }, {
  18620. key: '_clearReloadTimer',
  18621. value: function _clearReloadTimer() {
  18622. if (this.timer) {
  18623. clearTimeout(this.timer);
  18624. this.timer = null;
  18625. }
  18626. }
  18627. }, {
  18628. key: '_loadCurrentTrack',
  18629. value: function _loadCurrentTrack() {
  18630. var trackId = this.trackId,
  18631. tracks = this.tracks,
  18632. hls = this.hls;
  18633. var currentTrack = tracks[trackId];
  18634. if (trackId < 0 || !currentTrack || currentTrack.details && !currentTrack.details.live) {
  18635. return;
  18636. }
  18637. _logger.logger.log('Loading subtitle track ' + trackId);
  18638. hls.trigger(_events2.default.SUBTITLE_TRACK_LOADING, { url: currentTrack.url, id: trackId });
  18639. }
  18640. /**
  18641. * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
  18642. * This operates on the DOM textTracks.
  18643. * A value of -1 will disable all subtitle tracks.
  18644. * @param newId - The id of the next track to enable
  18645. * @private
  18646. */
  18647. }, {
  18648. key: '_toggleTrackModes',
  18649. value: function _toggleTrackModes(newId) {
  18650. var media = this.media,
  18651. subtitleDisplay = this.subtitleDisplay,
  18652. trackId = this.trackId;
  18653. if (!media) {
  18654. return;
  18655. }
  18656. var textTracks = filterSubtitleTracks(media.textTracks);
  18657. if (newId === -1) {
  18658. [].slice.call(textTracks).forEach(function (track) {
  18659. track.mode = 'disabled';
  18660. });
  18661. } else {
  18662. var oldTrack = textTracks[trackId];
  18663. if (oldTrack) {
  18664. oldTrack.mode = 'disabled';
  18665. }
  18666. }
  18667. var nextTrack = textTracks[newId];
  18668. if (nextTrack) {
  18669. nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden';
  18670. }
  18671. }
  18672. /**
  18673. * This method is responsible for validating the subtitle index and periodically reloading if live.
  18674. * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
  18675. * @param newId - The id of the subtitle track to activate.
  18676. */
  18677. }, {
  18678. key: '_setSubtitleTrackInternal',
  18679. value: function _setSubtitleTrackInternal(newId) {
  18680. var hls = this.hls,
  18681. tracks = this.tracks;
  18682. if (!Number.isFinite(newId) || newId < -1 || newId >= tracks.length) {
  18683. return;
  18684. }
  18685. this.trackId = newId;
  18686. _logger.logger.log('Switching to subtitle track ' + newId);
  18687. hls.trigger(_events2.default.SUBTITLE_TRACK_SWITCH, { id: newId });
  18688. this._loadCurrentTrack();
  18689. }
  18690. }, {
  18691. key: '_onTextTracksChanged',
  18692. value: function _onTextTracksChanged() {
  18693. // Media is undefined when switching streams via loadSource()
  18694. if (!this.media) {
  18695. return;
  18696. }
  18697. var trackId = -1;
  18698. var tracks = filterSubtitleTracks(this.media.textTracks);
  18699. for (var id = 0; id < tracks.length; id++) {
  18700. if (tracks[id].mode === 'hidden') {
  18701. // Do not break in case there is a following track with showing.
  18702. trackId = id;
  18703. } else if (tracks[id].mode === 'showing') {
  18704. trackId = id;
  18705. break;
  18706. }
  18707. }
  18708. // Setting current subtitleTrack will invoke code.
  18709. this.subtitleTrack = trackId;
  18710. }
  18711. }, {
  18712. key: 'subtitleTracks',
  18713. get: function get() {
  18714. return this.tracks;
  18715. }
  18716. /** get index of the selected subtitle track (index in subtitle track lists) **/
  18717. }, {
  18718. key: 'subtitleTrack',
  18719. get: function get() {
  18720. return this.trackId;
  18721. }
  18722. /** select a subtitle track, based on its index in subtitle track lists**/
  18723. ,
  18724. set: function set(subtitleTrackId) {
  18725. if (this.trackId !== subtitleTrackId) {
  18726. this._toggleTrackModes(subtitleTrackId);
  18727. this._setSubtitleTrackInternal(subtitleTrackId);
  18728. }
  18729. }
  18730. }]);
  18731. return SubtitleTrackController;
  18732. }(_eventHandler2.default);
  18733. function filterSubtitleTracks(textTrackList) {
  18734. var tracks = [];
  18735. for (var i = 0; i < textTrackList.length; i++) {
  18736. var track = textTrackList[i];
  18737. // Edge adds a track without a label; we don't want to use it
  18738. if (track.kind === 'subtitles' && track.label) {
  18739. tracks.push(textTrackList[i]);
  18740. }
  18741. }
  18742. return tracks;
  18743. }
  18744. exports.default = SubtitleTrackController;
  18745. module.exports = exports['default'];
  18746. /***/ }),
  18747. /* 77 */
  18748. /***/ (function(module, exports, __webpack_require__) {
  18749. "use strict";
  18750. Object.defineProperty(exports, "__esModule", {
  18751. value: true
  18752. });
  18753. exports.SubtitleStreamController = undefined;
  18754. 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; }; }();
  18755. 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); } };
  18756. var _events = __webpack_require__(1);
  18757. var _events2 = _interopRequireDefault(_events);
  18758. var _logger = __webpack_require__(0);
  18759. var _decrypter = __webpack_require__(12);
  18760. var _decrypter2 = _interopRequireDefault(_decrypter);
  18761. var _bufferHelper = __webpack_require__(4);
  18762. var _fragmentFinders = __webpack_require__(27);
  18763. var _fragmentTracker = __webpack_require__(6);
  18764. var _baseStreamController = __webpack_require__(14);
  18765. var _baseStreamController2 = _interopRequireDefault(_baseStreamController);
  18766. var _levelHelper = __webpack_require__(7);
  18767. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  18768. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  18769. 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; }
  18770. 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; } /**
  18771. * @class SubtitleStreamController
  18772. */
  18773. var _window = window,
  18774. performance = _window.performance;
  18775. var TICK_INTERVAL = 500; // how often to tick in ms
  18776. var SubtitleStreamController = exports.SubtitleStreamController = function (_BaseStreamController) {
  18777. _inherits(SubtitleStreamController, _BaseStreamController);
  18778. function SubtitleStreamController(hls, fragmentTracker) {
  18779. _classCallCheck(this, SubtitleStreamController);
  18780. 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));
  18781. _this.fragmentTracker = fragmentTracker;
  18782. _this.config = hls.config;
  18783. _this.state = _baseStreamController.State.STOPPED;
  18784. _this.tracks = [];
  18785. _this.tracksBuffered = [];
  18786. _this.currentTrackId = -1;
  18787. _this.decrypter = new _decrypter2.default(hls, hls.config);
  18788. // lastAVStart stores the time in seconds for the start time of a level load
  18789. _this.lastAVStart = 0;
  18790. _this._onMediaSeeking = _this.onMediaSeeking.bind(_this);
  18791. return _this;
  18792. }
  18793. _createClass(SubtitleStreamController, [{
  18794. key: 'onSubtitleFragProcessed',
  18795. value: function onSubtitleFragProcessed(data) {
  18796. var frag = data.frag,
  18797. success = data.success;
  18798. this.fragPrevious = frag;
  18799. this.state = _baseStreamController.State.IDLE;
  18800. if (!success) {
  18801. return;
  18802. }
  18803. var buffered = this.tracksBuffered[this.currentTrackId];
  18804. if (!buffered) {
  18805. return;
  18806. }
  18807. // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo
  18808. // so we can re-use the logic used to detect how much have been buffered
  18809. var timeRange = void 0;
  18810. var fragStart = frag.start;
  18811. for (var i = 0; i < buffered.length; i++) {
  18812. if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
  18813. timeRange = buffered[i];
  18814. break;
  18815. }
  18816. }
  18817. var fragEnd = frag.start + frag.duration;
  18818. if (timeRange) {
  18819. timeRange.end = fragEnd;
  18820. } else {
  18821. timeRange = {
  18822. start: fragStart,
  18823. end: fragEnd
  18824. };
  18825. buffered.push(timeRange);
  18826. }
  18827. }
  18828. }, {
  18829. key: 'onMediaAttached',
  18830. value: function onMediaAttached(_ref) {
  18831. var media = _ref.media;
  18832. this.media = media;
  18833. media.addEventListener('seeking', this._onMediaSeeking);
  18834. this.state = _baseStreamController.State.IDLE;
  18835. }
  18836. }, {
  18837. key: 'onMediaDetaching',
  18838. value: function onMediaDetaching() {
  18839. this.media.removeEventListener('seeking', this._onMediaSeeking);
  18840. this.media = null;
  18841. this.state = _baseStreamController.State.STOPPED;
  18842. }
  18843. // If something goes wrong, proceed to next frag, if we were processing one.
  18844. }, {
  18845. key: 'onError',
  18846. value: function onError(data) {
  18847. var frag = data.frag;
  18848. // don't handle error not related to subtitle fragment
  18849. if (!frag || frag.type !== 'subtitle') {
  18850. return;
  18851. }
  18852. this.state = _baseStreamController.State.IDLE;
  18853. }
  18854. // Got all new subtitle tracks.
  18855. }, {
  18856. key: 'onSubtitleTracksUpdated',
  18857. value: function onSubtitleTracksUpdated(data) {
  18858. var _this2 = this;
  18859. _logger.logger.log('subtitle tracks updated');
  18860. this.tracksBuffered = [];
  18861. this.tracks = data.subtitleTracks;
  18862. this.tracks.forEach(function (track) {
  18863. _this2.tracksBuffered[track.id] = [];
  18864. });
  18865. }
  18866. }, {
  18867. key: 'onSubtitleTrackSwitch',
  18868. value: function onSubtitleTrackSwitch(data) {
  18869. this.currentTrackId = data.id;
  18870. if (!this.tracks || this.currentTrackId === -1) {
  18871. this.clearInterval();
  18872. return;
  18873. }
  18874. // Check if track has the necessary details to load fragments
  18875. var currentTrack = this.tracks[this.currentTrackId];
  18876. if (currentTrack && currentTrack.details) {
  18877. this.setInterval(TICK_INTERVAL);
  18878. }
  18879. }
  18880. // Got a new set of subtitle fragments.
  18881. }, {
  18882. key: 'onSubtitleTrackLoaded',
  18883. value: function onSubtitleTrackLoaded(data) {
  18884. var id = data.id,
  18885. details = data.details;
  18886. var currentTrackId = this.currentTrackId,
  18887. tracks = this.tracks;
  18888. var currentTrack = tracks[currentTrackId];
  18889. if (id >= tracks.length || id !== currentTrackId || !currentTrack) {
  18890. return;
  18891. }
  18892. if (details.live) {
  18893. (0, _levelHelper.mergeSubtitlePlaylists)(currentTrack.details, details, this.lastAVStart);
  18894. }
  18895. currentTrack.details = details;
  18896. this.setInterval(TICK_INTERVAL);
  18897. }
  18898. }, {
  18899. key: 'onKeyLoaded',
  18900. value: function onKeyLoaded() {
  18901. if (this.state === _baseStreamController.State.KEY_LOADING) {
  18902. this.state = _baseStreamController.State.IDLE;
  18903. }
  18904. }
  18905. }, {
  18906. key: 'onFragLoaded',
  18907. value: function onFragLoaded(data) {
  18908. var fragCurrent = this.fragCurrent;
  18909. var decryptData = data.frag.decryptdata;
  18910. var fragLoaded = data.frag;
  18911. var hls = this.hls;
  18912. if (this.state === _baseStreamController.State.FRAG_LOADING && fragCurrent && data.frag.type === 'subtitle' && fragCurrent.sn === data.frag.sn) {
  18913. // check to see if the payload needs to be decrypted
  18914. if (data.payload.byteLength > 0 && decryptData && decryptData.key && decryptData.method === 'AES-128') {
  18915. var startTime = performance.now();
  18916. // decrypt the subtitles
  18917. this.decrypter.decrypt(data.payload, decryptData.key.buffer, decryptData.iv.buffer, function (decryptedData) {
  18918. var endTime = performance.now();
  18919. hls.trigger(_events2.default.FRAG_DECRYPTED, { frag: fragLoaded, payload: decryptedData, stats: { tstart: startTime, tdecrypt: endTime } });
  18920. });
  18921. }
  18922. }
  18923. }
  18924. }, {
  18925. key: 'onLevelUpdated',
  18926. value: function onLevelUpdated(_ref2) {
  18927. var details = _ref2.details;
  18928. var frags = details.fragments;
  18929. this.lastAVStart = frags.length ? frags[0].start : 0;
  18930. }
  18931. }, {
  18932. key: 'doTick',
  18933. value: function doTick() {
  18934. if (!this.media) {
  18935. this.state = _baseStreamController.State.IDLE;
  18936. return;
  18937. }
  18938. switch (this.state) {
  18939. case _baseStreamController.State.IDLE:
  18940. {
  18941. var config = this.config,
  18942. currentTrackId = this.currentTrackId,
  18943. fragmentTracker = this.fragmentTracker,
  18944. media = this.media,
  18945. tracks = this.tracks;
  18946. if (!tracks || !tracks[currentTrackId] || !tracks[currentTrackId].details) {
  18947. break;
  18948. }
  18949. var maxBufferHole = config.maxBufferHole,
  18950. maxFragLookUpTolerance = config.maxFragLookUpTolerance;
  18951. var maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);
  18952. var bufferedInfo = _bufferHelper.BufferHelper.bufferedInfo(this._getBuffered(), media.currentTime, maxBufferHole);
  18953. var bufferEnd = bufferedInfo.end,
  18954. bufferLen = bufferedInfo.len;
  18955. var trackDetails = tracks[currentTrackId].details;
  18956. var fragments = trackDetails.fragments;
  18957. var fragLen = fragments.length;
  18958. var end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration;
  18959. if (bufferLen > maxConfigBuffer) {
  18960. return;
  18961. }
  18962. var foundFrag = void 0;
  18963. var fragPrevious = this.fragPrevious;
  18964. if (bufferEnd < end) {
  18965. if (fragPrevious && trackDetails.hasProgramDateTime) {
  18966. foundFrag = (0, _fragmentFinders.findFragmentByPDT)(fragments, fragPrevious.endProgramDateTime, maxFragLookUpTolerance);
  18967. }
  18968. if (!foundFrag) {
  18969. foundFrag = (0, _fragmentFinders.findFragmentByPTS)(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance);
  18970. }
  18971. } else {
  18972. foundFrag = fragments[fragLen - 1];
  18973. }
  18974. if (foundFrag && foundFrag.encrypted) {
  18975. _logger.logger.log('Loading key for ' + foundFrag.sn);
  18976. this.state = _baseStreamController.State.KEY_LOADING;
  18977. this.hls.trigger(_events2.default.KEY_LOADING, { frag: foundFrag });
  18978. } else if (foundFrag && fragmentTracker.getState(foundFrag) === _fragmentTracker.FragmentState.NOT_LOADED) {
  18979. // only load if fragment is not loaded
  18980. this.fragCurrent = foundFrag;
  18981. this.state = _baseStreamController.State.FRAG_LOADING;
  18982. this.hls.trigger(_events2.default.FRAG_LOADING, { frag: foundFrag });
  18983. }
  18984. }
  18985. }
  18986. }
  18987. }, {
  18988. key: 'stopLoad',
  18989. value: function stopLoad() {
  18990. this.lastAVStart = 0;
  18991. _get(SubtitleStreamController.prototype.__proto__ || Object.getPrototypeOf(SubtitleStreamController.prototype), 'stopLoad', this).call(this);
  18992. }
  18993. }, {
  18994. key: '_getBuffered',
  18995. value: function _getBuffered() {
  18996. return this.tracksBuffered[this.currentTrackId] || [];
  18997. }
  18998. }, {
  18999. key: 'onMediaSeeking',
  19000. value: function onMediaSeeking() {
  19001. this.fragPrevious = null;
  19002. }
  19003. }]);
  19004. return SubtitleStreamController;
  19005. }(_baseStreamController2.default);
  19006. /***/ }),
  19007. /* 78 */
  19008. /***/ (function(module, exports, __webpack_require__) {
  19009. "use strict";
  19010. Object.defineProperty(exports, "__esModule", {
  19011. value: true
  19012. });
  19013. 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; }; }();
  19014. var _eventHandler = __webpack_require__(3);
  19015. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  19016. var _events = __webpack_require__(1);
  19017. var _events2 = _interopRequireDefault(_events);
  19018. var _errors = __webpack_require__(2);
  19019. var _logger = __webpack_require__(0);
  19020. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  19021. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  19022. 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; }
  19023. 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; } /**
  19024. * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>
  19025. *
  19026. * DRM support for Hls.js
  19027. */
  19028. var _window = window,
  19029. XMLHttpRequest = _window.XMLHttpRequest;
  19030. var MAX_LICENSE_REQUEST_FAILURES = 3;
  19031. /**
  19032. * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess
  19033. */
  19034. var KeySystems = {
  19035. WIDEVINE: 'com.widevine.alpha',
  19036. PLAYREADY: 'com.microsoft.playready'
  19037. };
  19038. /**
  19039. * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration
  19040. * @param {Array<string>} audioCodecs List of required audio codecs to support
  19041. * @param {Array<string>} videoCodecs List of required video codecs to support
  19042. * @param {object} drmSystemOptions Optional parameters/requirements for the key-system
  19043. * @returns {Array<MediaSystemConfiguration>} An array of supported configurations
  19044. */
  19045. var createWidevineMediaKeySystemConfigurations = function createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions) {
  19046. /* jshint ignore:line */
  19047. var baseConfig = {
  19048. // initDataTypes: ['keyids', 'mp4'],
  19049. // label: "",
  19050. // persistentState: "not-allowed", // or "required" ?
  19051. // distinctiveIdentifier: "not-allowed", // or "required" ?
  19052. // sessionTypes: ['temporary'],
  19053. videoCapabilities: [
  19054. // { contentType: 'video/mp4; codecs="avc1.42E01E"' }
  19055. ]
  19056. };
  19057. videoCodecs.forEach(function (codec) {
  19058. baseConfig.videoCapabilities.push({
  19059. contentType: 'video/mp4; codecs="' + codec + '"'
  19060. });
  19061. });
  19062. return [baseConfig];
  19063. };
  19064. /**
  19065. * The idea here is to handle key-system (and their respective platforms) specific configuration differences
  19066. * in order to work with the local requestMediaKeySystemAccess method.
  19067. *
  19068. * We can also rule-out platform-related key-system support at this point by throwing an error or returning null.
  19069. *
  19070. * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
  19071. * @param {Array<string>} audioCodecs List of required audio codecs to support
  19072. * @param {Array<string>} videoCodecs List of required video codecs to support
  19073. * @returns {Array<MediaSystemConfiguration> | null} A non-empty Array of MediaKeySystemConfiguration objects or `null`
  19074. */
  19075. var getSupportedMediaKeySystemConfigurations = function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs) {
  19076. switch (keySystem) {
  19077. case KeySystems.WIDEVINE:
  19078. return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs);
  19079. default:
  19080. throw Error('Unknown key-system: ' + keySystem);
  19081. }
  19082. };
  19083. /**
  19084. * Controller to deal with encrypted media extensions (EME)
  19085. * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API
  19086. *
  19087. * @class
  19088. * @constructor
  19089. */
  19090. var EMEController = function (_EventHandler) {
  19091. _inherits(EMEController, _EventHandler);
  19092. /**
  19093. * @constructs
  19094. * @param {Hls} hls Our Hls.js instance
  19095. */
  19096. function EMEController(hls) {
  19097. _classCallCheck(this, EMEController);
  19098. var _this = _possibleConstructorReturn(this, (EMEController.__proto__ || Object.getPrototypeOf(EMEController)).call(this, hls, _events2.default.MEDIA_ATTACHED, _events2.default.MANIFEST_PARSED));
  19099. _this._widevineLicenseUrl = hls.config.widevineLicenseUrl;
  19100. _this._licenseXhrSetup = hls.config.licenseXhrSetup;
  19101. _this._emeEnabled = hls.config.emeEnabled;
  19102. _this._requestMediaKeySystemAccess = hls.config.requestMediaKeySystemAccessFunc;
  19103. _this._mediaKeysList = [];
  19104. _this._media = null;
  19105. _this._hasSetMediaKeys = false;
  19106. _this._isMediaEncrypted = false;
  19107. _this._requestLicenseFailureCount = 0;
  19108. return _this;
  19109. }
  19110. /**
  19111. *
  19112. * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
  19113. * @returns {string} License server URL for key-system (if any configured, otherwise causes error)
  19114. */
  19115. _createClass(EMEController, [{
  19116. key: 'getLicenseServerUrl',
  19117. value: function getLicenseServerUrl(keySystem) {
  19118. var url = void 0;
  19119. switch (keySystem) {
  19120. case KeySystems.WIDEVINE:
  19121. url = this._widevineLicenseUrl;
  19122. break;
  19123. default:
  19124. url = null;
  19125. break;
  19126. }
  19127. if (!url) {
  19128. _logger.logger.error('No license server URL configured for key-system "' + keySystem + '"');
  19129. this.hls.trigger(_events2.default.ERROR, {
  19130. type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
  19131. details: _errors.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  19132. fatal: true
  19133. });
  19134. }
  19135. return url;
  19136. }
  19137. /**
  19138. * Requests access object and adds it to our list upon success
  19139. * @private
  19140. * @param {string} keySystem System ID (see `KeySystems`)
  19141. * @param {Array<string>} audioCodecs List of required audio codecs to support
  19142. * @param {Array<string>} videoCodecs List of required video codecs to support
  19143. */
  19144. }, {
  19145. key: '_attemptKeySystemAccess',
  19146. value: function _attemptKeySystemAccess(keySystem, audioCodecs, videoCodecs) {
  19147. var _this2 = this;
  19148. // TODO: add other DRM "options"
  19149. var mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs);
  19150. if (!mediaKeySystemConfigs) {
  19151. _logger.logger.warn('Can not create config for key-system (maybe because platform is not supported):', keySystem);
  19152. return;
  19153. }
  19154. _logger.logger.log('Requesting encrypted media key-system access');
  19155. // expecting interface like window.navigator.requestMediaKeySystemAccess
  19156. this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs).then(function (mediaKeySystemAccess) {
  19157. _this2._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);
  19158. }).catch(function (err) {
  19159. _logger.logger.error('Failed to obtain key-system "' + keySystem + '" access:', err);
  19160. });
  19161. }
  19162. }, {
  19163. key: '_onMediaKeySystemAccessObtained',
  19164. /**
  19165. * Handles obtaining access to a key-system
  19166. *
  19167. * @param {string} keySystem
  19168. * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess
  19169. */
  19170. value: function _onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess) {
  19171. var _this3 = this;
  19172. _logger.logger.log('Access for key-system "' + keySystem + '" obtained');
  19173. var mediaKeysListItem = {
  19174. mediaKeys: null,
  19175. mediaKeysSession: null,
  19176. mediaKeysSessionInitialized: false,
  19177. mediaKeySystemAccess: mediaKeySystemAccess,
  19178. mediaKeySystemDomain: keySystem
  19179. };
  19180. this._mediaKeysList.push(mediaKeysListItem);
  19181. mediaKeySystemAccess.createMediaKeys().then(function (mediaKeys) {
  19182. mediaKeysListItem.mediaKeys = mediaKeys;
  19183. _logger.logger.log('Media-keys created for key-system "' + keySystem + '"');
  19184. _this3._onMediaKeysCreated();
  19185. }).catch(function (err) {
  19186. _logger.logger.error('Failed to create media-keys:', err);
  19187. });
  19188. }
  19189. /**
  19190. * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this
  19191. * for all existing keys where no session exists yet.
  19192. */
  19193. }, {
  19194. key: '_onMediaKeysCreated',
  19195. value: function _onMediaKeysCreated() {
  19196. var _this4 = this;
  19197. // check for all key-list items if a session exists, otherwise, create one
  19198. this._mediaKeysList.forEach(function (mediaKeysListItem) {
  19199. if (!mediaKeysListItem.mediaKeysSession) {
  19200. mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession();
  19201. _this4._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);
  19202. }
  19203. });
  19204. }
  19205. /**
  19206. *
  19207. * @param {*} keySession
  19208. */
  19209. }, {
  19210. key: '_onNewMediaKeySession',
  19211. value: function _onNewMediaKeySession(keySession) {
  19212. var _this5 = this;
  19213. _logger.logger.log('New key-system session ' + keySession.sessionId);
  19214. keySession.addEventListener('message', function (event) {
  19215. _this5._onKeySessionMessage(keySession, event.message);
  19216. }, false);
  19217. }
  19218. }, {
  19219. key: '_onKeySessionMessage',
  19220. value: function _onKeySessionMessage(keySession, message) {
  19221. _logger.logger.log('Got EME message event, creating license request');
  19222. this._requestLicense(message, function (data) {
  19223. _logger.logger.log('Received license data, updating key-session');
  19224. keySession.update(data);
  19225. });
  19226. }
  19227. }, {
  19228. key: '_onMediaEncrypted',
  19229. value: function _onMediaEncrypted(initDataType, initData) {
  19230. _logger.logger.log('Media is encrypted using "' + initDataType + '" init data type');
  19231. this._isMediaEncrypted = true;
  19232. this._mediaEncryptionInitDataType = initDataType;
  19233. this._mediaEncryptionInitData = initData;
  19234. this._attemptSetMediaKeys();
  19235. this._generateRequestWithPreferredKeySession();
  19236. }
  19237. }, {
  19238. key: '_attemptSetMediaKeys',
  19239. value: function _attemptSetMediaKeys() {
  19240. if (!this._hasSetMediaKeys) {
  19241. // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
  19242. var keysListItem = this._mediaKeysList[0];
  19243. if (!keysListItem || !keysListItem.mediaKeys) {
  19244. _logger.logger.error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');
  19245. this.hls.trigger(_events2.default.ERROR, {
  19246. type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
  19247. details: _errors.ErrorDetails.KEY_SYSTEM_NO_KEYS,
  19248. fatal: true
  19249. });
  19250. return;
  19251. }
  19252. _logger.logger.log('Setting keys for encrypted media');
  19253. this._media.setMediaKeys(keysListItem.mediaKeys);
  19254. this._hasSetMediaKeys = true;
  19255. }
  19256. }
  19257. }, {
  19258. key: '_generateRequestWithPreferredKeySession',
  19259. value: function _generateRequestWithPreferredKeySession() {
  19260. var _this6 = this;
  19261. // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
  19262. var keysListItem = this._mediaKeysList[0];
  19263. if (!keysListItem) {
  19264. _logger.logger.error('Fatal: Media is encrypted but not any key-system access has been obtained yet');
  19265. this.hls.trigger(_events2.default.ERROR, {
  19266. type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
  19267. details: _errors.ErrorDetails.KEY_SYSTEM_NO_ACCESS,
  19268. fatal: true
  19269. });
  19270. return;
  19271. }
  19272. if (keysListItem.mediaKeysSessionInitialized) {
  19273. _logger.logger.warn('Key-Session already initialized but requested again');
  19274. return;
  19275. }
  19276. var keySession = keysListItem.mediaKeysSession;
  19277. if (!keySession) {
  19278. _logger.logger.error('Fatal: Media is encrypted but no key-session existing');
  19279. this.hls.trigger(_events2.default.ERROR, {
  19280. type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
  19281. details: _errors.ErrorDetails.KEY_SYSTEM_NO_SESSION,
  19282. fatal: true
  19283. });
  19284. }
  19285. var initDataType = this._mediaEncryptionInitDataType;
  19286. var initData = this._mediaEncryptionInitData;
  19287. _logger.logger.log('Generating key-session request for "' + initDataType + '" init data type');
  19288. keysListItem.mediaKeysSessionInitialized = true;
  19289. keySession.generateRequest(initDataType, initData).then(function () {
  19290. _logger.logger.debug('Key-session generation succeeded');
  19291. }).catch(function (err) {
  19292. _logger.logger.error('Error generating key-session request:', err);
  19293. _this6.hls.trigger(_events2.default.ERROR, {
  19294. type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
  19295. details: _errors.ErrorDetails.KEY_SYSTEM_NO_SESSION,
  19296. fatal: false
  19297. });
  19298. });
  19299. }
  19300. /**
  19301. * @param {string} url License server URL
  19302. * @param {ArrayBuffer} keyMessage Message data issued by key-system
  19303. * @param {function} callback Called when XHR has succeeded
  19304. * @returns {XMLHttpRequest} Unsent (but opened state) XHR object
  19305. */
  19306. }, {
  19307. key: '_createLicenseXhr',
  19308. value: function _createLicenseXhr(url, keyMessage, callback) {
  19309. var xhr = new XMLHttpRequest();
  19310. var licenseXhrSetup = this._licenseXhrSetup;
  19311. try {
  19312. if (licenseXhrSetup) {
  19313. try {
  19314. licenseXhrSetup(xhr, url);
  19315. } catch (e) {
  19316. // let's try to open before running setup
  19317. xhr.open('POST', url, true);
  19318. licenseXhrSetup(xhr, url);
  19319. }
  19320. }
  19321. // if licenseXhrSetup did not yet call open, let's do it now
  19322. if (!xhr.readyState) {
  19323. xhr.open('POST', url, true);
  19324. }
  19325. } catch (e) {
  19326. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  19327. _logger.logger.error('Error setting up key-system license XHR', e);
  19328. this.hls.trigger(_events2.default.ERROR, {
  19329. type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
  19330. details: _errors.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  19331. fatal: true
  19332. });
  19333. return;
  19334. }
  19335. xhr.responseType = 'arraybuffer';
  19336. xhr.onreadystatechange = this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);
  19337. return xhr;
  19338. }
  19339. /**
  19340. * @param {XMLHttpRequest} xhr
  19341. * @param {string} url License server URL
  19342. * @param {ArrayBuffer} keyMessage Message data issued by key-system
  19343. * @param {function} callback Called when XHR has succeeded
  19344. *
  19345. */
  19346. }, {
  19347. key: '_onLicenseRequestReadyStageChange',
  19348. value: function _onLicenseRequestReadyStageChange(xhr, url, keyMessage, callback) {
  19349. switch (xhr.readyState) {
  19350. case 4:
  19351. if (xhr.status === 200) {
  19352. this._requestLicenseFailureCount = 0;
  19353. _logger.logger.log('License request succeeded');
  19354. callback(xhr.response);
  19355. } else {
  19356. _logger.logger.error('License Request XHR failed (' + url + '). Status: ' + xhr.status + ' (' + xhr.statusText + ')');
  19357. this._requestLicenseFailureCount++;
  19358. if (this._requestLicenseFailureCount <= MAX_LICENSE_REQUEST_FAILURES) {
  19359. var attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;
  19360. _logger.logger.warn('Retrying license request, ' + attemptsLeft + ' attempts left');
  19361. this._requestLicense(keyMessage, callback);
  19362. return;
  19363. }
  19364. this.hls.trigger(_events2.default.ERROR, {
  19365. type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
  19366. details: _errors.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  19367. fatal: true
  19368. });
  19369. }
  19370. break;
  19371. }
  19372. }
  19373. /**
  19374. * @param {object} keysListItem
  19375. * @param {ArrayBuffer} keyMessage
  19376. * @returns {ArrayBuffer} Challenge data posted to license server
  19377. */
  19378. }, {
  19379. key: '_generateLicenseRequestChallenge',
  19380. value: function _generateLicenseRequestChallenge(keysListItem, keyMessage) {
  19381. var challenge = void 0;
  19382. if (keysListItem.mediaKeySystemDomain === KeySystems.PLAYREADY) {
  19383. _logger.logger.error('PlayReady is not supported (yet)');
  19384. // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js
  19385. /*
  19386. if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {
  19387. // For PlayReady CDMs, we need to dig the Challenge out of the XML.
  19388. var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');
  19389. if (keyMessageXml.getElementsByTagName('Challenge')[0]) {
  19390. challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);
  19391. } else {
  19392. throw 'Cannot find <Challenge> in key message';
  19393. }
  19394. var headerNames = keyMessageXml.getElementsByTagName('name');
  19395. var headerValues = keyMessageXml.getElementsByTagName('value');
  19396. if (headerNames.length !== headerValues.length) {
  19397. throw 'Mismatched header <name>/<value> pair in key message';
  19398. }
  19399. for (var i = 0; i < headerNames.length; i++) {
  19400. xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);
  19401. }
  19402. }
  19403. */
  19404. } else if (keysListItem.mediaKeySystemDomain === KeySystems.WIDEVINE) {
  19405. // For Widevine CDMs, the challenge is the keyMessage.
  19406. challenge = keyMessage;
  19407. } else {
  19408. _logger.logger.error('Unsupported key-system:', keysListItem.mediaKeySystemDomain);
  19409. }
  19410. return challenge;
  19411. }
  19412. }, {
  19413. key: '_requestLicense',
  19414. value: function _requestLicense(keyMessage, callback) {
  19415. _logger.logger.log('Requesting content license for key-system');
  19416. var keysListItem = this._mediaKeysList[0];
  19417. if (!keysListItem) {
  19418. _logger.logger.error('Fatal error: Media is encrypted but no key-system access has been obtained yet');
  19419. this.hls.trigger(_events2.default.ERROR, {
  19420. type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
  19421. details: _errors.ErrorDetails.KEY_SYSTEM_NO_ACCESS,
  19422. fatal: true
  19423. });
  19424. return;
  19425. }
  19426. var url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);
  19427. var xhr = this._createLicenseXhr(url, keyMessage, callback);
  19428. _logger.logger.log('Sending license request to URL: ' + url);
  19429. xhr.send(this._generateLicenseRequestChallenge(keysListItem, keyMessage));
  19430. }
  19431. }, {
  19432. key: 'onMediaAttached',
  19433. value: function onMediaAttached(data) {
  19434. var _this7 = this;
  19435. if (!this._emeEnabled) {
  19436. return;
  19437. }
  19438. var media = data.media;
  19439. // keep reference of media
  19440. this._media = media;
  19441. // FIXME: also handle detaching media !
  19442. media.addEventListener('encrypted', function (e) {
  19443. _this7._onMediaEncrypted(e.initDataType, e.initData);
  19444. });
  19445. }
  19446. }, {
  19447. key: 'onManifestParsed',
  19448. value: function onManifestParsed(data) {
  19449. if (!this._emeEnabled) {
  19450. return;
  19451. }
  19452. var audioCodecs = data.levels.map(function (level) {
  19453. return level.audioCodec;
  19454. });
  19455. var videoCodecs = data.levels.map(function (level) {
  19456. return level.videoCodec;
  19457. });
  19458. this._attemptKeySystemAccess(KeySystems.WIDEVINE, audioCodecs, videoCodecs);
  19459. }
  19460. }, {
  19461. key: 'requestMediaKeySystemAccess',
  19462. get: function get() {
  19463. if (!this._requestMediaKeySystemAccess) {
  19464. throw new Error('No requestMediaKeySystemAccess function configured');
  19465. }
  19466. return this._requestMediaKeySystemAccess;
  19467. }
  19468. }]);
  19469. return EMEController;
  19470. }(_eventHandler2.default);
  19471. exports.default = EMEController;
  19472. module.exports = exports['default'];
  19473. /***/ }),
  19474. /* 79 */
  19475. /***/ (function(module, exports, __webpack_require__) {
  19476. "use strict";
  19477. Object.defineProperty(exports, "__esModule", {
  19478. value: true
  19479. });
  19480. var requestMediaKeySystemAccess = function () {
  19481. if (typeof window !== 'undefined' && window.navigator && window.navigator.requestMediaKeySystemAccess) {
  19482. return window.navigator.requestMediaKeySystemAccess.bind(window.navigator);
  19483. } else {
  19484. return null;
  19485. }
  19486. }();
  19487. exports.requestMediaKeySystemAccess = requestMediaKeySystemAccess;
  19488. /***/ }),
  19489. /* 80 */
  19490. /***/ (function(module, exports, __webpack_require__) {
  19491. "use strict";
  19492. Object.defineProperty(exports, "__esModule", {
  19493. value: true
  19494. });
  19495. var util = {};
  19496. util.getBrowserVersion = function () {
  19497. var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  19498. if (userAgent.toLowerCase().indexOf("mobile") > -1) {
  19499. return "Unknown";
  19500. }
  19501. if (userAgent.indexOf("Firefox") > -1) {
  19502. var version = userAgent.match(/firefox\/[\d.]+/gi)[0].match(/[\d]+/)[0];
  19503. return "Firefox " + version;
  19504. } else if (userAgent.indexOf("Edge") > -1) {
  19505. var _version = userAgent.match(/edge\/[\d.]+/gi)[0].match(/[\d]+/)[0];
  19506. return "Edge " + _version;
  19507. } else if (userAgent.indexOf("rv:11") > -1) {
  19508. return "IE 11";
  19509. } else if (userAgent.indexOf("Opera") > -1 || userAgent.indexOf("OPR") > -1) {
  19510. if (userAgent.indexOf("Opera") > -1) {
  19511. var _version2 = userAgent.match(/opera\/[\d.]+/gi)[0].match(/[\d]+/)[0];
  19512. return "Opera " + _version2;
  19513. }
  19514. if (userAgent.indexOf("OPR") > -1) {
  19515. var _version3 = userAgent.match(/opr\/[\d.]+/gi)[0].match(/[\d]+/)[0];
  19516. return "Opera " + _version3;
  19517. }
  19518. } else if (userAgent.indexOf("Chrome") > -1) {
  19519. var _version4 = userAgent.match(/chrome\/[\d.]+/gi)[0].match(/[\d]+/)[0];
  19520. return "Chrome " + _version4;
  19521. } else if (userAgent.indexOf("Safari") > -1) {
  19522. var _version5 = userAgent.match(/safari\/[\d.]+/gi)[0].match(/[\d]+/)[0];
  19523. return "Safari " + _version5;
  19524. } else if (userAgent.indexOf("MSIE") > -1 || userAgent.indexOf("Trident") > -1) {
  19525. if (userAgent.indexOf("MSIE") > -1) {
  19526. var _version6 = userAgent.match(/msie [\d.]+/gi)[0].match(/[\d]+/)[0];
  19527. return "IE " + _version6;
  19528. }
  19529. if (userAgent.indexOf("Trident") > -1) {
  19530. var versionTrident = userAgent.match(/trident\/[\d.]+/gi)[0].match(/[\d]+/)[0];
  19531. var _version7 = parseInt(versionTrident) + 4;
  19532. return "IE " + _version7;
  19533. }
  19534. } else {
  19535. return "Unknown";
  19536. }
  19537. };
  19538. exports.default = util;
  19539. module.exports = exports["default"];
  19540. /***/ })
  19541. /******/ ]);
  19542. });
  19543. /***/ }),
  19544. /***/ "90e3":
  19545. /***/ (function(module, exports) {
  19546. var id = 0;
  19547. var postfix = Math.random();
  19548. module.exports = function (key) {
  19549. return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);
  19550. };
  19551. /***/ }),
  19552. /***/ "9112":
  19553. /***/ (function(module, exports, __webpack_require__) {
  19554. var DESCRIPTORS = __webpack_require__("83ab");
  19555. var definePropertyModule = __webpack_require__("9bf2");
  19556. var createPropertyDescriptor = __webpack_require__("5c6c");
  19557. module.exports = DESCRIPTORS ? function (object, key, value) {
  19558. return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
  19559. } : function (object, key, value) {
  19560. object[key] = value;
  19561. return object;
  19562. };
  19563. /***/ }),
  19564. /***/ "94ca":
  19565. /***/ (function(module, exports, __webpack_require__) {
  19566. var fails = __webpack_require__("d039");
  19567. var replacement = /#|\.prototype\./;
  19568. var isForced = function (feature, detection) {
  19569. var value = data[normalize(feature)];
  19570. return value == POLYFILL ? true
  19571. : value == NATIVE ? false
  19572. : typeof detection == 'function' ? fails(detection)
  19573. : !!detection;
  19574. };
  19575. var normalize = isForced.normalize = function (string) {
  19576. return String(string).replace(replacement, '.').toLowerCase();
  19577. };
  19578. var data = isForced.data = {};
  19579. var NATIVE = isForced.NATIVE = 'N';
  19580. var POLYFILL = isForced.POLYFILL = 'P';
  19581. module.exports = isForced;
  19582. /***/ }),
  19583. /***/ "9bf2":
  19584. /***/ (function(module, exports, __webpack_require__) {
  19585. var DESCRIPTORS = __webpack_require__("83ab");
  19586. var IE8_DOM_DEFINE = __webpack_require__("0cfb");
  19587. var anObject = __webpack_require__("825a");
  19588. var toPrimitive = __webpack_require__("c04e");
  19589. var nativeDefineProperty = Object.defineProperty;
  19590. // `Object.defineProperty` method
  19591. // https://tc39.github.io/ecma262/#sec-object.defineproperty
  19592. exports.f = DESCRIPTORS ? nativeDefineProperty : function defineProperty(O, P, Attributes) {
  19593. anObject(O);
  19594. P = toPrimitive(P, true);
  19595. anObject(Attributes);
  19596. if (IE8_DOM_DEFINE) try {
  19597. return nativeDefineProperty(O, P, Attributes);
  19598. } catch (error) { /* empty */ }
  19599. if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
  19600. if ('value' in Attributes) O[P] = Attributes.value;
  19601. return O;
  19602. };
  19603. /***/ }),
  19604. /***/ "a691":
  19605. /***/ (function(module, exports) {
  19606. var ceil = Math.ceil;
  19607. var floor = Math.floor;
  19608. // `ToInteger` abstract operation
  19609. // https://tc39.github.io/ecma262/#sec-tointeger
  19610. module.exports = function (argument) {
  19611. return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);
  19612. };
  19613. /***/ }),
  19614. /***/ "b402":
  19615. /***/ (function(module, exports, __webpack_require__) {
  19616. (function webpackUniversalModuleDefinition(root, factory) {
  19617. if(true)
  19618. module.exports = factory(__webpack_require__("5392"));
  19619. else {}
  19620. })(window, function(__WEBPACK_EXTERNAL_MODULE__20__) {
  19621. return /******/ (function(modules) { // webpackBootstrap
  19622. /******/ // The module cache
  19623. /******/ var installedModules = {};
  19624. /******/
  19625. /******/ // The require function
  19626. /******/ function __webpack_require__(moduleId) {
  19627. /******/
  19628. /******/ // Check if module is in cache
  19629. /******/ if(installedModules[moduleId]) {
  19630. /******/ return installedModules[moduleId].exports;
  19631. /******/ }
  19632. /******/ // Create a new module (and put it into the cache)
  19633. /******/ var module = installedModules[moduleId] = {
  19634. /******/ i: moduleId,
  19635. /******/ l: false,
  19636. /******/ exports: {}
  19637. /******/ };
  19638. /******/
  19639. /******/ // Execute the module function
  19640. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  19641. /******/
  19642. /******/ // Flag the module as loaded
  19643. /******/ module.l = true;
  19644. /******/
  19645. /******/ // Return the exports of the module
  19646. /******/ return module.exports;
  19647. /******/ }
  19648. /******/
  19649. /******/
  19650. /******/ // expose the modules object (__webpack_modules__)
  19651. /******/ __webpack_require__.m = modules;
  19652. /******/
  19653. /******/ // expose the module cache
  19654. /******/ __webpack_require__.c = installedModules;
  19655. /******/
  19656. /******/ // define getter function for harmony exports
  19657. /******/ __webpack_require__.d = function(exports, name, getter) {
  19658. /******/ if(!__webpack_require__.o(exports, name)) {
  19659. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  19660. /******/ }
  19661. /******/ };
  19662. /******/
  19663. /******/ // define __esModule on exports
  19664. /******/ __webpack_require__.r = function(exports) {
  19665. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  19666. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  19667. /******/ }
  19668. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  19669. /******/ };
  19670. /******/
  19671. /******/ // create a fake namespace object
  19672. /******/ // mode & 1: value is a module id, require it
  19673. /******/ // mode & 2: merge all properties of value into the ns
  19674. /******/ // mode & 4: return value when already ns object
  19675. /******/ // mode & 8|1: behave like require
  19676. /******/ __webpack_require__.t = function(value, mode) {
  19677. /******/ if(mode & 1) value = __webpack_require__(value);
  19678. /******/ if(mode & 8) return value;
  19679. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  19680. /******/ var ns = Object.create(null);
  19681. /******/ __webpack_require__.r(ns);
  19682. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  19683. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  19684. /******/ return ns;
  19685. /******/ };
  19686. /******/
  19687. /******/ // getDefaultExport function for compatibility with non-harmony modules
  19688. /******/ __webpack_require__.n = function(module) {
  19689. /******/ var getter = module && module.__esModule ?
  19690. /******/ function getDefault() { return module['default']; } :
  19691. /******/ function getModuleExports() { return module; };
  19692. /******/ __webpack_require__.d(getter, 'a', getter);
  19693. /******/ return getter;
  19694. /******/ };
  19695. /******/
  19696. /******/ // Object.prototype.hasOwnProperty.call
  19697. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  19698. /******/
  19699. /******/ // __webpack_public_path__
  19700. /******/ __webpack_require__.p = "";
  19701. /******/
  19702. /******/
  19703. /******/ // Load entry module and return exports
  19704. /******/ return __webpack_require__(__webpack_require__.s = 18);
  19705. /******/ })
  19706. /************************************************************************/
  19707. /******/ ([
  19708. /* 0 */
  19709. /***/ (function(module, exports, __webpack_require__) {
  19710. "use strict";
  19711. Object.defineProperty(exports, "__esModule", {
  19712. value: true
  19713. });
  19714. 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; }; }(); /*
  19715. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  19716. *
  19717. * @author zheng qian <xqq@xqq.im>
  19718. *
  19719. * Licensed under the Apache License, Version 2.0 (the "License");
  19720. * you may not use this file except in compliance with the License.
  19721. * You may obtain a copy of the License at
  19722. *
  19723. * http://www.apache.org/licenses/LICENSE-2.0
  19724. *
  19725. * Unless required by applicable law or agreed to in writing, software
  19726. * distributed under the License is distributed on an "AS IS" BASIS,
  19727. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19728. * See the License for the specific language governing permissions and
  19729. * limitations under the License.
  19730. */
  19731. var _events = __webpack_require__(2);
  19732. var _events2 = _interopRequireDefault(_events);
  19733. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  19734. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  19735. var Log = function () {
  19736. function Log() {
  19737. _classCallCheck(this, Log);
  19738. }
  19739. _createClass(Log, null, [{
  19740. key: 'e',
  19741. value: function e(tag, msg) {
  19742. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  19743. var str = '[' + tag + '] > ' + msg;
  19744. if (Log.ENABLE_CALLBACK) {
  19745. Log.emitter.emit('log', 'error', str);
  19746. }
  19747. if (!Log.ENABLE_ERROR) {
  19748. return;
  19749. }
  19750. }
  19751. }, {
  19752. key: 'i',
  19753. value: function i(tag, msg) {
  19754. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  19755. var str = '[' + tag + '] > ' + msg;
  19756. if (Log.ENABLE_CALLBACK) {
  19757. Log.emitter.emit('log', 'info', str);
  19758. }
  19759. if (!Log.ENABLE_INFO) {
  19760. return;
  19761. }
  19762. }
  19763. }, {
  19764. key: 'w',
  19765. value: function w(tag, msg) {
  19766. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  19767. var str = '[' + tag + '] > ' + msg;
  19768. if (Log.ENABLE_CALLBACK) {
  19769. Log.emitter.emit('log', 'warn', str);
  19770. }
  19771. if (!Log.ENABLE_WARN) {
  19772. return;
  19773. }
  19774. }
  19775. }, {
  19776. key: 'd',
  19777. value: function d(tag, msg) {
  19778. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  19779. var str = '[' + tag + '] > ' + msg;
  19780. if (Log.ENABLE_CALLBACK) {
  19781. Log.emitter.emit('log', 'debug', str);
  19782. }
  19783. if (!Log.ENABLE_DEBUG) {
  19784. return;
  19785. }
  19786. }
  19787. }, {
  19788. key: 'v',
  19789. value: function v(tag, msg) {
  19790. if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
  19791. var str = '[' + tag + '] > ' + msg;
  19792. if (Log.ENABLE_CALLBACK) {
  19793. Log.emitter.emit('log', 'verbose', str);
  19794. }
  19795. if (!Log.ENABLE_VERBOSE) {
  19796. return;
  19797. }
  19798. }
  19799. }]);
  19800. return Log;
  19801. }();
  19802. Log.GLOBAL_TAG = 'flv.js';
  19803. Log.FORCE_GLOBAL_TAG = false;
  19804. Log.ENABLE_ERROR = true;
  19805. Log.ENABLE_INFO = true;
  19806. Log.ENABLE_WARN = true;
  19807. Log.ENABLE_DEBUG = true;
  19808. Log.ENABLE_VERBOSE = true;
  19809. Log.ENABLE_CALLBACK = false;
  19810. Log.emitter = new _events2.default();
  19811. exports.default = Log;
  19812. module.exports = exports['default'];
  19813. /***/ }),
  19814. /* 1 */
  19815. /***/ (function(module, exports, __webpack_require__) {
  19816. "use strict";
  19817. Object.defineProperty(exports, "__esModule", {
  19818. value: true
  19819. });
  19820. 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; }; }();
  19821. 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; }
  19822. 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; }
  19823. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  19824. /*
  19825. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  19826. *
  19827. * @author zheng qian <xqq@xqq.im>
  19828. *
  19829. * Licensed under the Apache License, Version 2.0 (the "License");
  19830. * you may not use this file except in compliance with the License.
  19831. * You may obtain a copy of the License at
  19832. *
  19833. * http://www.apache.org/licenses/LICENSE-2.0
  19834. *
  19835. * Unless required by applicable law or agreed to in writing, software
  19836. * distributed under the License is distributed on an "AS IS" BASIS,
  19837. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19838. * See the License for the specific language governing permissions and
  19839. * limitations under the License.
  19840. */
  19841. var RuntimeException = exports.RuntimeException = function () {
  19842. function RuntimeException(message) {
  19843. _classCallCheck(this, RuntimeException);
  19844. this._message = message;
  19845. }
  19846. _createClass(RuntimeException, [{
  19847. key: 'toString',
  19848. value: function toString() {
  19849. return this.name + ': ' + this.message;
  19850. }
  19851. }, {
  19852. key: 'name',
  19853. get: function get() {
  19854. return 'RuntimeException';
  19855. }
  19856. }, {
  19857. key: 'message',
  19858. get: function get() {
  19859. return this._message;
  19860. }
  19861. }]);
  19862. return RuntimeException;
  19863. }();
  19864. var IllegalStateException = exports.IllegalStateException = function (_RuntimeException) {
  19865. _inherits(IllegalStateException, _RuntimeException);
  19866. function IllegalStateException(message) {
  19867. _classCallCheck(this, IllegalStateException);
  19868. return _possibleConstructorReturn(this, (IllegalStateException.__proto__ || Object.getPrototypeOf(IllegalStateException)).call(this, message));
  19869. }
  19870. _createClass(IllegalStateException, [{
  19871. key: 'name',
  19872. get: function get() {
  19873. return 'IllegalStateException';
  19874. }
  19875. }]);
  19876. return IllegalStateException;
  19877. }(RuntimeException);
  19878. var InvalidArgumentException = exports.InvalidArgumentException = function (_RuntimeException2) {
  19879. _inherits(InvalidArgumentException, _RuntimeException2);
  19880. function InvalidArgumentException(message) {
  19881. _classCallCheck(this, InvalidArgumentException);
  19882. return _possibleConstructorReturn(this, (InvalidArgumentException.__proto__ || Object.getPrototypeOf(InvalidArgumentException)).call(this, message));
  19883. }
  19884. _createClass(InvalidArgumentException, [{
  19885. key: 'name',
  19886. get: function get() {
  19887. return 'InvalidArgumentException';
  19888. }
  19889. }]);
  19890. return InvalidArgumentException;
  19891. }(RuntimeException);
  19892. var NotImplementedException = exports.NotImplementedException = function (_RuntimeException3) {
  19893. _inherits(NotImplementedException, _RuntimeException3);
  19894. function NotImplementedException(message) {
  19895. _classCallCheck(this, NotImplementedException);
  19896. return _possibleConstructorReturn(this, (NotImplementedException.__proto__ || Object.getPrototypeOf(NotImplementedException)).call(this, message));
  19897. }
  19898. _createClass(NotImplementedException, [{
  19899. key: 'name',
  19900. get: function get() {
  19901. return 'NotImplementedException';
  19902. }
  19903. }]);
  19904. return NotImplementedException;
  19905. }(RuntimeException);
  19906. /***/ }),
  19907. /* 2 */
  19908. /***/ (function(module, exports, __webpack_require__) {
  19909. "use strict";
  19910. // Copyright Joyent, Inc. and other Node contributors.
  19911. //
  19912. // Permission is hereby granted, free of charge, to any person obtaining a
  19913. // copy of this software and associated documentation files (the
  19914. // "Software"), to deal in the Software without restriction, including
  19915. // without limitation the rights to use, copy, modify, merge, publish,
  19916. // distribute, sublicense, and/or sell copies of the Software, and to permit
  19917. // persons to whom the Software is furnished to do so, subject to the
  19918. // following conditions:
  19919. //
  19920. // The above copyright notice and this permission notice shall be included
  19921. // in all copies or substantial portions of the Software.
  19922. //
  19923. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19924. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19925. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  19926. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19927. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19928. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  19929. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  19930. var R = typeof Reflect === 'object' ? Reflect : null
  19931. var ReflectApply = R && typeof R.apply === 'function'
  19932. ? R.apply
  19933. : function ReflectApply(target, receiver, args) {
  19934. return Function.prototype.apply.call(target, receiver, args);
  19935. }
  19936. var ReflectOwnKeys
  19937. if (R && typeof R.ownKeys === 'function') {
  19938. ReflectOwnKeys = R.ownKeys
  19939. } else if (Object.getOwnPropertySymbols) {
  19940. ReflectOwnKeys = function ReflectOwnKeys(target) {
  19941. return Object.getOwnPropertyNames(target)
  19942. .concat(Object.getOwnPropertySymbols(target));
  19943. };
  19944. } else {
  19945. ReflectOwnKeys = function ReflectOwnKeys(target) {
  19946. return Object.getOwnPropertyNames(target);
  19947. };
  19948. }
  19949. function ProcessEmitWarning(warning) {
  19950. if (console && console.warn) console.warn(warning);
  19951. }
  19952. var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
  19953. return value !== value;
  19954. }
  19955. function EventEmitter() {
  19956. EventEmitter.init.call(this);
  19957. }
  19958. module.exports = EventEmitter;
  19959. // Backwards-compat with node 0.10.x
  19960. EventEmitter.EventEmitter = EventEmitter;
  19961. EventEmitter.prototype._events = undefined;
  19962. EventEmitter.prototype._eventsCount = 0;
  19963. EventEmitter.prototype._maxListeners = undefined;
  19964. // By default EventEmitters will print a warning if more than 10 listeners are
  19965. // added to it. This is a useful default which helps finding memory leaks.
  19966. var defaultMaxListeners = 10;
  19967. function checkListener(listener) {
  19968. if (typeof listener !== 'function') {
  19969. throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
  19970. }
  19971. }
  19972. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  19973. enumerable: true,
  19974. get: function() {
  19975. return defaultMaxListeners;
  19976. },
  19977. set: function(arg) {
  19978. if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
  19979. throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
  19980. }
  19981. defaultMaxListeners = arg;
  19982. }
  19983. });
  19984. EventEmitter.init = function() {
  19985. if (this._events === undefined ||
  19986. this._events === Object.getPrototypeOf(this)._events) {
  19987. this._events = Object.create(null);
  19988. this._eventsCount = 0;
  19989. }
  19990. this._maxListeners = this._maxListeners || undefined;
  19991. };
  19992. // Obviously not all Emitters should be limited to 10. This function allows
  19993. // that to be increased. Set to zero for unlimited.
  19994. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  19995. if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
  19996. throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
  19997. }
  19998. this._maxListeners = n;
  19999. return this;
  20000. };
  20001. function _getMaxListeners(that) {
  20002. if (that._maxListeners === undefined)
  20003. return EventEmitter.defaultMaxListeners;
  20004. return that._maxListeners;
  20005. }
  20006. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  20007. return _getMaxListeners(this);
  20008. };
  20009. EventEmitter.prototype.emit = function emit(type) {
  20010. var args = [];
  20011. for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
  20012. var doError = (type === 'error');
  20013. var events = this._events;
  20014. if (events !== undefined)
  20015. doError = (doError && events.error === undefined);
  20016. else if (!doError)
  20017. return false;
  20018. // If there is no 'error' event listener then throw.
  20019. if (doError) {
  20020. var er;
  20021. if (args.length > 0)
  20022. er = args[0];
  20023. if (er instanceof Error) {
  20024. // Note: The comments on the `throw` lines are intentional, they show
  20025. // up in Node's output if this results in an unhandled exception.
  20026. throw er; // Unhandled 'error' event
  20027. }
  20028. // At least give some kind of context to the user
  20029. var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
  20030. err.context = er;
  20031. throw err; // Unhandled 'error' event
  20032. }
  20033. var handler = events[type];
  20034. if (handler === undefined)
  20035. return false;
  20036. if (typeof handler === 'function') {
  20037. ReflectApply(handler, this, args);
  20038. } else {
  20039. var len = handler.length;
  20040. var listeners = arrayClone(handler, len);
  20041. for (var i = 0; i < len; ++i)
  20042. ReflectApply(listeners[i], this, args);
  20043. }
  20044. return true;
  20045. };
  20046. function _addListener(target, type, listener, prepend) {
  20047. var m;
  20048. var events;
  20049. var existing;
  20050. checkListener(listener);
  20051. events = target._events;
  20052. if (events === undefined) {
  20053. events = target._events = Object.create(null);
  20054. target._eventsCount = 0;
  20055. } else {
  20056. // To avoid recursion in the case that type === "newListener"! Before
  20057. // adding it to the listeners, first emit "newListener".
  20058. if (events.newListener !== undefined) {
  20059. target.emit('newListener', type,
  20060. listener.listener ? listener.listener : listener);
  20061. // Re-assign `events` because a newListener handler could have caused the
  20062. // this._events to be assigned to a new object
  20063. events = target._events;
  20064. }
  20065. existing = events[type];
  20066. }
  20067. if (existing === undefined) {
  20068. // Optimize the case of one listener. Don't need the extra array object.
  20069. existing = events[type] = listener;
  20070. ++target._eventsCount;
  20071. } else {
  20072. if (typeof existing === 'function') {
  20073. // Adding the second element, need to change to array.
  20074. existing = events[type] =
  20075. prepend ? [listener, existing] : [existing, listener];
  20076. // If we've already got an array, just append.
  20077. } else if (prepend) {
  20078. existing.unshift(listener);
  20079. } else {
  20080. existing.push(listener);
  20081. }
  20082. // Check for listener leak
  20083. m = _getMaxListeners(target);
  20084. if (m > 0 && existing.length > m && !existing.warned) {
  20085. existing.warned = true;
  20086. // No error code for this since it is a Warning
  20087. // eslint-disable-next-line no-restricted-syntax
  20088. var w = new Error('Possible EventEmitter memory leak detected. ' +
  20089. existing.length + ' ' + String(type) + ' listeners ' +
  20090. 'added. Use emitter.setMaxListeners() to ' +
  20091. 'increase limit');
  20092. w.name = 'MaxListenersExceededWarning';
  20093. w.emitter = target;
  20094. w.type = type;
  20095. w.count = existing.length;
  20096. ProcessEmitWarning(w);
  20097. }
  20098. }
  20099. return target;
  20100. }
  20101. EventEmitter.prototype.addListener = function addListener(type, listener) {
  20102. return _addListener(this, type, listener, false);
  20103. };
  20104. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  20105. EventEmitter.prototype.prependListener =
  20106. function prependListener(type, listener) {
  20107. return _addListener(this, type, listener, true);
  20108. };
  20109. function onceWrapper() {
  20110. if (!this.fired) {
  20111. this.target.removeListener(this.type, this.wrapFn);
  20112. this.fired = true;
  20113. if (arguments.length === 0)
  20114. return this.listener.call(this.target);
  20115. return this.listener.apply(this.target, arguments);
  20116. }
  20117. }
  20118. function _onceWrap(target, type, listener) {
  20119. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  20120. var wrapped = onceWrapper.bind(state);
  20121. wrapped.listener = listener;
  20122. state.wrapFn = wrapped;
  20123. return wrapped;
  20124. }
  20125. EventEmitter.prototype.once = function once(type, listener) {
  20126. checkListener(listener);
  20127. this.on(type, _onceWrap(this, type, listener));
  20128. return this;
  20129. };
  20130. EventEmitter.prototype.prependOnceListener =
  20131. function prependOnceListener(type, listener) {
  20132. checkListener(listener);
  20133. this.prependListener(type, _onceWrap(this, type, listener));
  20134. return this;
  20135. };
  20136. // Emits a 'removeListener' event if and only if the listener was removed.
  20137. EventEmitter.prototype.removeListener =
  20138. function removeListener(type, listener) {
  20139. var list, events, position, i, originalListener;
  20140. checkListener(listener);
  20141. events = this._events;
  20142. if (events === undefined)
  20143. return this;
  20144. list = events[type];
  20145. if (list === undefined)
  20146. return this;
  20147. if (list === listener || list.listener === listener) {
  20148. if (--this._eventsCount === 0)
  20149. this._events = Object.create(null);
  20150. else {
  20151. delete events[type];
  20152. if (events.removeListener)
  20153. this.emit('removeListener', type, list.listener || listener);
  20154. }
  20155. } else if (typeof list !== 'function') {
  20156. position = -1;
  20157. for (i = list.length - 1; i >= 0; i--) {
  20158. if (list[i] === listener || list[i].listener === listener) {
  20159. originalListener = list[i].listener;
  20160. position = i;
  20161. break;
  20162. }
  20163. }
  20164. if (position < 0)
  20165. return this;
  20166. if (position === 0)
  20167. list.shift();
  20168. else {
  20169. spliceOne(list, position);
  20170. }
  20171. if (list.length === 1)
  20172. events[type] = list[0];
  20173. if (events.removeListener !== undefined)
  20174. this.emit('removeListener', type, originalListener || listener);
  20175. }
  20176. return this;
  20177. };
  20178. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  20179. EventEmitter.prototype.removeAllListeners =
  20180. function removeAllListeners(type) {
  20181. var listeners, events, i;
  20182. events = this._events;
  20183. if (events === undefined)
  20184. return this;
  20185. // not listening for removeListener, no need to emit
  20186. if (events.removeListener === undefined) {
  20187. if (arguments.length === 0) {
  20188. this._events = Object.create(null);
  20189. this._eventsCount = 0;
  20190. } else if (events[type] !== undefined) {
  20191. if (--this._eventsCount === 0)
  20192. this._events = Object.create(null);
  20193. else
  20194. delete events[type];
  20195. }
  20196. return this;
  20197. }
  20198. // emit removeListener for all listeners on all events
  20199. if (arguments.length === 0) {
  20200. var keys = Object.keys(events);
  20201. var key;
  20202. for (i = 0; i < keys.length; ++i) {
  20203. key = keys[i];
  20204. if (key === 'removeListener') continue;
  20205. this.removeAllListeners(key);
  20206. }
  20207. this.removeAllListeners('removeListener');
  20208. this._events = Object.create(null);
  20209. this._eventsCount = 0;
  20210. return this;
  20211. }
  20212. listeners = events[type];
  20213. if (typeof listeners === 'function') {
  20214. this.removeListener(type, listeners);
  20215. } else if (listeners !== undefined) {
  20216. // LIFO order
  20217. for (i = listeners.length - 1; i >= 0; i--) {
  20218. this.removeListener(type, listeners[i]);
  20219. }
  20220. }
  20221. return this;
  20222. };
  20223. function _listeners(target, type, unwrap) {
  20224. var events = target._events;
  20225. if (events === undefined)
  20226. return [];
  20227. var evlistener = events[type];
  20228. if (evlistener === undefined)
  20229. return [];
  20230. if (typeof evlistener === 'function')
  20231. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  20232. return unwrap ?
  20233. unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  20234. }
  20235. EventEmitter.prototype.listeners = function listeners(type) {
  20236. return _listeners(this, type, true);
  20237. };
  20238. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  20239. return _listeners(this, type, false);
  20240. };
  20241. EventEmitter.listenerCount = function(emitter, type) {
  20242. if (typeof emitter.listenerCount === 'function') {
  20243. return emitter.listenerCount(type);
  20244. } else {
  20245. return listenerCount.call(emitter, type);
  20246. }
  20247. };
  20248. EventEmitter.prototype.listenerCount = listenerCount;
  20249. function listenerCount(type) {
  20250. var events = this._events;
  20251. if (events !== undefined) {
  20252. var evlistener = events[type];
  20253. if (typeof evlistener === 'function') {
  20254. return 1;
  20255. } else if (evlistener !== undefined) {
  20256. return evlistener.length;
  20257. }
  20258. }
  20259. return 0;
  20260. }
  20261. EventEmitter.prototype.eventNames = function eventNames() {
  20262. return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
  20263. };
  20264. function arrayClone(arr, n) {
  20265. var copy = new Array(n);
  20266. for (var i = 0; i < n; ++i)
  20267. copy[i] = arr[i];
  20268. return copy;
  20269. }
  20270. function spliceOne(list, index) {
  20271. for (; index + 1 < list.length; index++)
  20272. list[index] = list[index + 1];
  20273. list.pop();
  20274. }
  20275. function unwrapListeners(arr) {
  20276. var ret = new Array(arr.length);
  20277. for (var i = 0; i < ret.length; ++i) {
  20278. ret[i] = arr[i].listener || arr[i];
  20279. }
  20280. return ret;
  20281. }
  20282. /***/ }),
  20283. /* 3 */
  20284. /***/ (function(module, exports, __webpack_require__) {
  20285. "use strict";
  20286. Object.defineProperty(exports, "__esModule", {
  20287. value: true
  20288. });
  20289. exports.BaseLoader = exports.LoaderErrors = exports.LoaderStatus = undefined;
  20290. 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; }; }(); /*
  20291. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20292. *
  20293. * @author zheng qian <xqq@xqq.im>
  20294. *
  20295. * Licensed under the Apache License, Version 2.0 (the "License");
  20296. * you may not use this file except in compliance with the License.
  20297. * You may obtain a copy of the License at
  20298. *
  20299. * http://www.apache.org/licenses/LICENSE-2.0
  20300. *
  20301. * Unless required by applicable law or agreed to in writing, software
  20302. * distributed under the License is distributed on an "AS IS" BASIS,
  20303. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20304. * See the License for the specific language governing permissions and
  20305. * limitations under the License.
  20306. */
  20307. var _exception = __webpack_require__(1);
  20308. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  20309. var LoaderStatus = exports.LoaderStatus = {
  20310. kIdle: 0,
  20311. kConnecting: 1,
  20312. kBuffering: 2,
  20313. kError: 3,
  20314. kComplete: 4
  20315. };
  20316. var LoaderErrors = exports.LoaderErrors = {
  20317. OK: 'OK',
  20318. EXCEPTION: 'Exception',
  20319. HTTP_STATUS_CODE_INVALID: 'HttpStatusCodeInvalid',
  20320. CONNECTING_TIMEOUT: 'ConnectingTimeout',
  20321. EARLY_EOF: 'EarlyEof',
  20322. UNRECOVERABLE_EARLY_EOF: 'UnrecoverableEarlyEof'
  20323. };
  20324. /* Loader has callbacks which have following prototypes:
  20325. * function onContentLengthKnown(contentLength: number): void
  20326. * function onURLRedirect(url: string): void
  20327. * function onDataArrival(chunk: ArrayBuffer, byteStart: number, receivedLength: number): void
  20328. * function onError(errorType: number, errorInfo: {code: number, msg: string}): void
  20329. * function onComplete(rangeFrom: number, rangeTo: number): void
  20330. */
  20331. var BaseLoader = exports.BaseLoader = function () {
  20332. function BaseLoader(typeName) {
  20333. _classCallCheck(this, BaseLoader);
  20334. this._type = typeName || 'undefined';
  20335. this._status = LoaderStatus.kIdle;
  20336. this._needStash = false;
  20337. // callbacks
  20338. this._onContentLengthKnown = null;
  20339. this._onURLRedirect = null;
  20340. this._onDataArrival = null;
  20341. this._onError = null;
  20342. this._onComplete = null;
  20343. }
  20344. _createClass(BaseLoader, [{
  20345. key: 'destroy',
  20346. value: function destroy() {
  20347. this._status = LoaderStatus.kIdle;
  20348. this._onContentLengthKnown = null;
  20349. this._onURLRedirect = null;
  20350. this._onDataArrival = null;
  20351. this._onError = null;
  20352. this._onComplete = null;
  20353. }
  20354. }, {
  20355. key: 'isWorking',
  20356. value: function isWorking() {
  20357. return this._status === LoaderStatus.kConnecting || this._status === LoaderStatus.kBuffering;
  20358. }
  20359. }, {
  20360. key: 'open',
  20361. // pure virtual
  20362. value: function open(dataSource, range) {
  20363. throw new _exception.NotImplementedException('Unimplemented abstract function!');
  20364. }
  20365. }, {
  20366. key: 'abort',
  20367. value: function abort() {
  20368. throw new _exception.NotImplementedException('Unimplemented abstract function!');
  20369. }
  20370. }, {
  20371. key: 'type',
  20372. get: function get() {
  20373. return this._type;
  20374. }
  20375. }, {
  20376. key: 'status',
  20377. get: function get() {
  20378. return this._status;
  20379. }
  20380. }, {
  20381. key: 'needStashBuffer',
  20382. get: function get() {
  20383. return this._needStash;
  20384. }
  20385. }, {
  20386. key: 'onContentLengthKnown',
  20387. get: function get() {
  20388. return this._onContentLengthKnown;
  20389. },
  20390. set: function set(callback) {
  20391. this._onContentLengthKnown = callback;
  20392. }
  20393. }, {
  20394. key: 'onURLRedirect',
  20395. get: function get() {
  20396. return this._onURLRedirect;
  20397. },
  20398. set: function set(callback) {
  20399. this._onURLRedirect = callback;
  20400. }
  20401. }, {
  20402. key: 'onDataArrival',
  20403. get: function get() {
  20404. return this._onDataArrival;
  20405. },
  20406. set: function set(callback) {
  20407. this._onDataArrival = callback;
  20408. }
  20409. }, {
  20410. key: 'onError',
  20411. get: function get() {
  20412. return this._onError;
  20413. },
  20414. set: function set(callback) {
  20415. this._onError = callback;
  20416. }
  20417. }, {
  20418. key: 'onComplete',
  20419. get: function get() {
  20420. return this._onComplete;
  20421. },
  20422. set: function set(callback) {
  20423. this._onComplete = callback;
  20424. }
  20425. }]);
  20426. return BaseLoader;
  20427. }();
  20428. /***/ }),
  20429. /* 4 */
  20430. /***/ (function(module, exports, __webpack_require__) {
  20431. "use strict";
  20432. Object.defineProperty(exports, "__esModule", {
  20433. value: true
  20434. });
  20435. /*
  20436. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20437. *
  20438. * @author zheng qian <xqq@xqq.im>
  20439. *
  20440. * Licensed under the Apache License, Version 2.0 (the "License");
  20441. * you may not use this file except in compliance with the License.
  20442. * You may obtain a copy of the License at
  20443. *
  20444. * http://www.apache.org/licenses/LICENSE-2.0
  20445. *
  20446. * Unless required by applicable law or agreed to in writing, software
  20447. * distributed under the License is distributed on an "AS IS" BASIS,
  20448. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20449. * See the License for the specific language governing permissions and
  20450. * limitations under the License.
  20451. */
  20452. var Browser = {};
  20453. function detect() {
  20454. // modified from jquery-browser-plugin
  20455. var ua = self.navigator.userAgent.toLowerCase();
  20456. 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) || [];
  20457. 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) || [];
  20458. var matched = {
  20459. browser: match[5] || match[3] || match[1] || '',
  20460. version: match[2] || match[4] || '0',
  20461. majorVersion: match[4] || match[2] || '0',
  20462. platform: platform_match[0] || ''
  20463. };
  20464. var browser = {};
  20465. if (matched.browser) {
  20466. browser[matched.browser] = true;
  20467. var versionArray = matched.majorVersion.split('.');
  20468. browser.version = {
  20469. major: parseInt(matched.majorVersion, 10),
  20470. string: matched.version
  20471. };
  20472. if (versionArray.length > 1) {
  20473. browser.version.minor = parseInt(versionArray[1], 10);
  20474. }
  20475. if (versionArray.length > 2) {
  20476. browser.version.build = parseInt(versionArray[2], 10);
  20477. }
  20478. }
  20479. if (matched.platform) {
  20480. browser[matched.platform] = true;
  20481. }
  20482. if (browser.chrome || browser.opr || browser.safari) {
  20483. browser.webkit = true;
  20484. }
  20485. // MSIE. IE11 has 'rv' identifer
  20486. if (browser.rv || browser.iemobile) {
  20487. if (browser.rv) {
  20488. delete browser.rv;
  20489. }
  20490. var msie = 'msie';
  20491. matched.browser = msie;
  20492. browser[msie] = true;
  20493. }
  20494. // Microsoft Edge
  20495. if (browser.edge) {
  20496. delete browser.edge;
  20497. var msedge = 'msedge';
  20498. matched.browser = msedge;
  20499. browser[msedge] = true;
  20500. }
  20501. // Opera 15+
  20502. if (browser.opr) {
  20503. var opera = 'opera';
  20504. matched.browser = opera;
  20505. browser[opera] = true;
  20506. }
  20507. // Stock android browsers are marked as Safari
  20508. if (browser.safari && browser.android) {
  20509. var android = 'android';
  20510. matched.browser = android;
  20511. browser[android] = true;
  20512. }
  20513. browser.name = matched.browser;
  20514. browser.platform = matched.platform;
  20515. for (var key in Browser) {
  20516. if (Browser.hasOwnProperty(key)) {
  20517. delete Browser[key];
  20518. }
  20519. }
  20520. Object.assign(Browser, browser);
  20521. }
  20522. detect();
  20523. exports.default = Browser;
  20524. module.exports = exports['default'];
  20525. /***/ }),
  20526. /* 5 */
  20527. /***/ (function(module, exports, __webpack_require__) {
  20528. "use strict";
  20529. Object.defineProperty(exports, "__esModule", {
  20530. value: true
  20531. });
  20532. /*
  20533. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20534. *
  20535. * @author zheng qian <xqq@xqq.im>
  20536. *
  20537. * Licensed under the Apache License, Version 2.0 (the "License");
  20538. * you may not use this file except in compliance with the License.
  20539. * You may obtain a copy of the License at
  20540. *
  20541. * http://www.apache.org/licenses/LICENSE-2.0
  20542. *
  20543. * Unless required by applicable law or agreed to in writing, software
  20544. * distributed under the License is distributed on an "AS IS" BASIS,
  20545. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20546. * See the License for the specific language governing permissions and
  20547. * limitations under the License.
  20548. */
  20549. var TransmuxingEvents = {
  20550. IO_ERROR: 'io_error',
  20551. DEMUX_ERROR: 'demux_error',
  20552. INIT_SEGMENT: 'init_segment',
  20553. MEDIA_SEGMENT: 'media_segment',
  20554. LOADING_COMPLETE: 'loading_complete',
  20555. RECOVERED_EARLY_EOF: 'recovered_early_eof',
  20556. MEDIA_INFO: 'media_info',
  20557. STATISTICS_INFO: 'statistics_info',
  20558. RECOMMEND_SEEKPOINT: 'recommend_seekpoint',
  20559. LOADED_SEI: 'loaded_sei'
  20560. };
  20561. exports.default = TransmuxingEvents;
  20562. module.exports = exports['default'];
  20563. /***/ }),
  20564. /* 6 */
  20565. /***/ (function(module, exports, __webpack_require__) {
  20566. "use strict";
  20567. Object.defineProperty(exports, "__esModule", {
  20568. value: true
  20569. });
  20570. exports.createDefaultConfig = createDefaultConfig;
  20571. /*
  20572. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20573. *
  20574. * @author zheng qian <xqq@xqq.im>
  20575. *
  20576. * Licensed under the Apache License, Version 2.0 (the "License");
  20577. * you may not use this file except in compliance with the License.
  20578. * You may obtain a copy of the License at
  20579. *
  20580. * http://www.apache.org/licenses/LICENSE-2.0
  20581. *
  20582. * Unless required by applicable law or agreed to in writing, software
  20583. * distributed under the License is distributed on an "AS IS" BASIS,
  20584. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20585. * See the License for the specific language governing permissions and
  20586. * limitations under the License.
  20587. */
  20588. var defaultConfig = exports.defaultConfig = {
  20589. enableWorker: false,
  20590. enableStashBuffer: true,
  20591. stashInitialSize: undefined,
  20592. isLive: false,
  20593. lazyLoad: true,
  20594. lazyLoadMaxDuration: 3 * 60,
  20595. lazyLoadRecoverDuration: 30,
  20596. deferLoadAfterSourceOpen: true,
  20597. // autoCleanupSourceBuffer: default as false, leave unspecified
  20598. autoCleanupMaxBackwardDuration: 3 * 60,
  20599. autoCleanupMinBackwardDuration: 2 * 60,
  20600. statisticsInfoReportInterval: 600,
  20601. fixAudioTimestampGap: true,
  20602. accurateSeek: false,
  20603. seekType: 'range', // [range, param, custom]
  20604. seekParamStart: 'bstart',
  20605. seekParamEnd: 'bend',
  20606. rangeLoadZeroStart: false,
  20607. customSeekHandler: undefined,
  20608. reuseRedirectedURL: false
  20609. // referrerPolicy: leave as unspecified
  20610. };
  20611. function createDefaultConfig() {
  20612. return Object.assign({}, defaultConfig);
  20613. }
  20614. /***/ }),
  20615. /* 7 */
  20616. /***/ (function(module, exports, __webpack_require__) {
  20617. "use strict";
  20618. Object.defineProperty(exports, "__esModule", {
  20619. value: true
  20620. });
  20621. /*
  20622. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20623. *
  20624. * @author zheng qian <xqq@xqq.im>
  20625. *
  20626. * Licensed under the Apache License, Version 2.0 (the "License");
  20627. * you may not use this file except in compliance with the License.
  20628. * You may obtain a copy of the License at
  20629. *
  20630. * http://www.apache.org/licenses/LICENSE-2.0
  20631. *
  20632. * Unless required by applicable law or agreed to in writing, software
  20633. * distributed under the License is distributed on an "AS IS" BASIS,
  20634. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20635. * See the License for the specific language governing permissions and
  20636. * limitations under the License.
  20637. */
  20638. var PlayerEvents = {
  20639. ERROR: 'error',
  20640. LOADING_COMPLETE: 'loading_complete',
  20641. RECOVERED_EARLY_EOF: 'recovered_early_eof',
  20642. MEDIA_INFO: 'media_info',
  20643. STATISTICS_INFO: 'statistics_info',
  20644. LOADED_SEI: 'loaded_sei'
  20645. };
  20646. exports.default = PlayerEvents;
  20647. module.exports = exports['default'];
  20648. /***/ }),
  20649. /* 8 */
  20650. /***/ (function(module, exports, __webpack_require__) {
  20651. "use strict";
  20652. Object.defineProperty(exports, "__esModule", {
  20653. value: true
  20654. });
  20655. 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; }; }(); /*
  20656. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20657. *
  20658. * @author zheng qian <xqq@xqq.im>
  20659. *
  20660. * Licensed under the Apache License, Version 2.0 (the "License");
  20661. * you may not use this file except in compliance with the License.
  20662. * You may obtain a copy of the License at
  20663. *
  20664. * http://www.apache.org/licenses/LICENSE-2.0
  20665. *
  20666. * Unless required by applicable law or agreed to in writing, software
  20667. * distributed under the License is distributed on an "AS IS" BASIS,
  20668. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20669. * See the License for the specific language governing permissions and
  20670. * limitations under the License.
  20671. */
  20672. var _events = __webpack_require__(2);
  20673. var _events2 = _interopRequireDefault(_events);
  20674. var _logger = __webpack_require__(0);
  20675. var _logger2 = _interopRequireDefault(_logger);
  20676. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  20677. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  20678. var LoggingControl = function () {
  20679. function LoggingControl() {
  20680. _classCallCheck(this, LoggingControl);
  20681. }
  20682. _createClass(LoggingControl, null, [{
  20683. key: 'getConfig',
  20684. value: function getConfig() {
  20685. return {
  20686. globalTag: _logger2.default.GLOBAL_TAG,
  20687. forceGlobalTag: _logger2.default.FORCE_GLOBAL_TAG,
  20688. enableVerbose: _logger2.default.ENABLE_VERBOSE,
  20689. enableDebug: _logger2.default.ENABLE_DEBUG,
  20690. enableInfo: _logger2.default.ENABLE_INFO,
  20691. enableWarn: _logger2.default.ENABLE_WARN,
  20692. enableError: _logger2.default.ENABLE_ERROR,
  20693. enableCallback: _logger2.default.ENABLE_CALLBACK
  20694. };
  20695. }
  20696. }, {
  20697. key: 'applyConfig',
  20698. value: function applyConfig(config) {
  20699. _logger2.default.GLOBAL_TAG = config.globalTag;
  20700. _logger2.default.FORCE_GLOBAL_TAG = config.forceGlobalTag;
  20701. _logger2.default.ENABLE_VERBOSE = config.enableVerbose;
  20702. _logger2.default.ENABLE_DEBUG = config.enableDebug;
  20703. _logger2.default.ENABLE_INFO = config.enableInfo;
  20704. _logger2.default.ENABLE_WARN = config.enableWarn;
  20705. _logger2.default.ENABLE_ERROR = config.enableError;
  20706. _logger2.default.ENABLE_CALLBACK = config.enableCallback;
  20707. }
  20708. }, {
  20709. key: '_notifyChange',
  20710. value: function _notifyChange() {
  20711. var emitter = LoggingControl.emitter;
  20712. if (emitter.listenerCount('change') > 0) {
  20713. var config = LoggingControl.getConfig();
  20714. emitter.emit('change', config);
  20715. }
  20716. }
  20717. }, {
  20718. key: 'registerListener',
  20719. value: function registerListener(listener) {
  20720. LoggingControl.emitter.addListener('change', listener);
  20721. }
  20722. }, {
  20723. key: 'removeListener',
  20724. value: function removeListener(listener) {
  20725. LoggingControl.emitter.removeListener('change', listener);
  20726. }
  20727. }, {
  20728. key: 'addLogListener',
  20729. value: function addLogListener(listener) {
  20730. _logger2.default.emitter.addListener('log', listener);
  20731. if (_logger2.default.emitter.listenerCount('log') > 0) {
  20732. _logger2.default.ENABLE_CALLBACK = true;
  20733. LoggingControl._notifyChange();
  20734. }
  20735. }
  20736. }, {
  20737. key: 'removeLogListener',
  20738. value: function removeLogListener(listener) {
  20739. _logger2.default.emitter.removeListener('log', listener);
  20740. if (_logger2.default.emitter.listenerCount('log') === 0) {
  20741. _logger2.default.ENABLE_CALLBACK = false;
  20742. LoggingControl._notifyChange();
  20743. }
  20744. }
  20745. }, {
  20746. key: 'forceGlobalTag',
  20747. get: function get() {
  20748. return _logger2.default.FORCE_GLOBAL_TAG;
  20749. },
  20750. set: function set(enable) {
  20751. _logger2.default.FORCE_GLOBAL_TAG = enable;
  20752. LoggingControl._notifyChange();
  20753. }
  20754. }, {
  20755. key: 'globalTag',
  20756. get: function get() {
  20757. return _logger2.default.GLOBAL_TAG;
  20758. },
  20759. set: function set(tag) {
  20760. _logger2.default.GLOBAL_TAG = tag;
  20761. LoggingControl._notifyChange();
  20762. }
  20763. }, {
  20764. key: 'enableAll',
  20765. get: function get() {
  20766. return _logger2.default.ENABLE_VERBOSE && _logger2.default.ENABLE_DEBUG && _logger2.default.ENABLE_INFO && _logger2.default.ENABLE_WARN && _logger2.default.ENABLE_ERROR;
  20767. },
  20768. set: function set(enable) {
  20769. _logger2.default.ENABLE_VERBOSE = enable;
  20770. _logger2.default.ENABLE_DEBUG = enable;
  20771. _logger2.default.ENABLE_INFO = enable;
  20772. _logger2.default.ENABLE_WARN = enable;
  20773. _logger2.default.ENABLE_ERROR = enable;
  20774. LoggingControl._notifyChange();
  20775. }
  20776. }, {
  20777. key: 'enableDebug',
  20778. get: function get() {
  20779. return _logger2.default.ENABLE_DEBUG;
  20780. },
  20781. set: function set(enable) {
  20782. _logger2.default.ENABLE_DEBUG = enable;
  20783. LoggingControl._notifyChange();
  20784. }
  20785. }, {
  20786. key: 'enableVerbose',
  20787. get: function get() {
  20788. return _logger2.default.ENABLE_VERBOSE;
  20789. },
  20790. set: function set(enable) {
  20791. _logger2.default.ENABLE_VERBOSE = enable;
  20792. LoggingControl._notifyChange();
  20793. }
  20794. }, {
  20795. key: 'enableInfo',
  20796. get: function get() {
  20797. return _logger2.default.ENABLE_INFO;
  20798. },
  20799. set: function set(enable) {
  20800. _logger2.default.ENABLE_INFO = enable;
  20801. LoggingControl._notifyChange();
  20802. }
  20803. }, {
  20804. key: 'enableWarn',
  20805. get: function get() {
  20806. return _logger2.default.ENABLE_WARN;
  20807. },
  20808. set: function set(enable) {
  20809. _logger2.default.ENABLE_WARN = enable;
  20810. LoggingControl._notifyChange();
  20811. }
  20812. }, {
  20813. key: 'enableError',
  20814. get: function get() {
  20815. return _logger2.default.ENABLE_ERROR;
  20816. },
  20817. set: function set(enable) {
  20818. _logger2.default.ENABLE_ERROR = enable;
  20819. LoggingControl._notifyChange();
  20820. }
  20821. }]);
  20822. return LoggingControl;
  20823. }();
  20824. LoggingControl.emitter = new _events2.default();
  20825. exports.default = LoggingControl;
  20826. module.exports = exports['default'];
  20827. /***/ }),
  20828. /* 9 */
  20829. /***/ (function(module, exports, __webpack_require__) {
  20830. "use strict";
  20831. Object.defineProperty(exports, "__esModule", {
  20832. value: true
  20833. });
  20834. 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; }; }();
  20835. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  20836. /*
  20837. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20838. *
  20839. * @author zheng qian <xqq@xqq.im>
  20840. *
  20841. * Licensed under the Apache License, Version 2.0 (the "License");
  20842. * you may not use this file except in compliance with the License.
  20843. * You may obtain a copy of the License at
  20844. *
  20845. * http://www.apache.org/licenses/LICENSE-2.0
  20846. *
  20847. * Unless required by applicable law or agreed to in writing, software
  20848. * distributed under the License is distributed on an "AS IS" BASIS,
  20849. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20850. * See the License for the specific language governing permissions and
  20851. * limitations under the License.
  20852. */
  20853. var MediaInfo = function () {
  20854. function MediaInfo() {
  20855. _classCallCheck(this, MediaInfo);
  20856. this.mimeType = null;
  20857. this.duration = null;
  20858. this.hasAudio = null;
  20859. this.hasVideo = null;
  20860. this.audioCodec = null;
  20861. this.videoCodec = null;
  20862. this.audioDataRate = null;
  20863. this.videoDataRate = null;
  20864. this.audioSampleRate = null;
  20865. this.audioChannelCount = null;
  20866. this.width = null;
  20867. this.height = null;
  20868. this.fps = null;
  20869. this.profile = null;
  20870. this.level = null;
  20871. this.refFrames = null;
  20872. this.chromaFormat = null;
  20873. this.sarNum = null;
  20874. this.sarDen = null;
  20875. this.metadata = null;
  20876. this.segments = null; // MediaInfo[]
  20877. this.segmentCount = null;
  20878. this.hasKeyframesIndex = null;
  20879. this.keyframesIndex = null;
  20880. }
  20881. _createClass(MediaInfo, [{
  20882. key: "isComplete",
  20883. value: function isComplete() {
  20884. var audioInfoComplete = this.hasAudio === false || this.hasAudio === true && this.audioCodec != null && this.audioSampleRate != null && this.audioChannelCount != null;
  20885. 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;
  20886. // keyframesIndex may not be present
  20887. return this.mimeType != null && this.duration != null && this.metadata != null && this.hasKeyframesIndex != null && audioInfoComplete && videoInfoComplete;
  20888. }
  20889. }, {
  20890. key: "isSeekable",
  20891. value: function isSeekable() {
  20892. return this.hasKeyframesIndex === true;
  20893. }
  20894. }, {
  20895. key: "getNearestKeyframe",
  20896. value: function getNearestKeyframe(milliseconds) {
  20897. if (this.keyframesIndex == null) {
  20898. return null;
  20899. }
  20900. var table = this.keyframesIndex;
  20901. var keyframeIdx = this._search(table.times, milliseconds);
  20902. return {
  20903. index: keyframeIdx,
  20904. milliseconds: table.times[keyframeIdx],
  20905. fileposition: table.filepositions[keyframeIdx]
  20906. };
  20907. }
  20908. }, {
  20909. key: "_search",
  20910. value: function _search(list, value) {
  20911. var idx = 0;
  20912. var last = list.length - 1;
  20913. var mid = 0;
  20914. var lbound = 0;
  20915. var ubound = last;
  20916. if (value < list[0]) {
  20917. idx = 0;
  20918. lbound = ubound + 1; // skip search
  20919. }
  20920. while (lbound <= ubound) {
  20921. mid = lbound + Math.floor((ubound - lbound) / 2);
  20922. if (mid === last || value >= list[mid] && value < list[mid + 1]) {
  20923. idx = mid;
  20924. break;
  20925. } else if (list[mid] < value) {
  20926. lbound = mid + 1;
  20927. } else {
  20928. ubound = mid - 1;
  20929. }
  20930. }
  20931. return idx;
  20932. }
  20933. }]);
  20934. return MediaInfo;
  20935. }();
  20936. exports.default = MediaInfo;
  20937. module.exports = exports["default"];
  20938. /***/ }),
  20939. /* 10 */
  20940. /***/ (function(module, exports, __webpack_require__) {
  20941. "use strict";
  20942. Object.defineProperty(exports, "__esModule", {
  20943. value: true
  20944. });
  20945. /*
  20946. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20947. *
  20948. * @author zheng qian <xqq@xqq.im>
  20949. *
  20950. * Licensed under the Apache License, Version 2.0 (the "License");
  20951. * you may not use this file except in compliance with the License.
  20952. * You may obtain a copy of the License at
  20953. *
  20954. * http://www.apache.org/licenses/LICENSE-2.0
  20955. *
  20956. * Unless required by applicable law or agreed to in writing, software
  20957. * distributed under the License is distributed on an "AS IS" BASIS,
  20958. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20959. * See the License for the specific language governing permissions and
  20960. * limitations under the License.
  20961. */
  20962. var DemuxErrors = {
  20963. OK: 'OK',
  20964. FORMAT_ERROR: 'FormatError',
  20965. FORMAT_UNSUPPORTED: 'FormatUnsupported',
  20966. CODEC_UNSUPPORTED: 'CodecUnsupported'
  20967. };
  20968. exports.default = DemuxErrors;
  20969. module.exports = exports['default'];
  20970. /***/ }),
  20971. /* 11 */
  20972. /***/ (function(module, exports, __webpack_require__) {
  20973. "use strict";
  20974. Object.defineProperty(exports, "__esModule", {
  20975. value: true
  20976. });
  20977. 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; }; }();
  20978. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  20979. /*
  20980. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  20981. *
  20982. * @author zheng qian <xqq@xqq.im>
  20983. *
  20984. * Licensed under the Apache License, Version 2.0 (the "License");
  20985. * you may not use this file except in compliance with the License.
  20986. * You may obtain a copy of the License at
  20987. *
  20988. * http://www.apache.org/licenses/LICENSE-2.0
  20989. *
  20990. * Unless required by applicable law or agreed to in writing, software
  20991. * distributed under the License is distributed on an "AS IS" BASIS,
  20992. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20993. * See the License for the specific language governing permissions and
  20994. * limitations under the License.
  20995. */
  20996. var Polyfill = function () {
  20997. function Polyfill() {
  20998. _classCallCheck(this, Polyfill);
  20999. }
  21000. _createClass(Polyfill, null, [{
  21001. key: 'install',
  21002. value: function install() {
  21003. // ES6 Object.setPrototypeOf
  21004. Object.setPrototypeOf = Object.setPrototypeOf || function (obj, proto) {
  21005. obj.__proto__ = proto;
  21006. return obj;
  21007. };
  21008. // ES6 Object.assign
  21009. Object.assign = Object.assign || function (target) {
  21010. if (target === undefined || target === null) {
  21011. throw new TypeError('Cannot convert undefined or null to object');
  21012. }
  21013. var output = Object(target);
  21014. for (var i = 1; i < arguments.length; i++) {
  21015. var source = arguments[i];
  21016. if (source !== undefined && source !== null) {
  21017. for (var key in source) {
  21018. if (source.hasOwnProperty(key)) {
  21019. output[key] = source[key];
  21020. }
  21021. }
  21022. }
  21023. }
  21024. return output;
  21025. };
  21026. // ES6 Promise (missing support in IE11)
  21027. if (typeof self.Promise !== 'function') {
  21028. __webpack_require__(22).polyfill();
  21029. }
  21030. }
  21031. }]);
  21032. return Polyfill;
  21033. }();
  21034. Polyfill.install();
  21035. exports.default = Polyfill;
  21036. module.exports = exports['default'];
  21037. /***/ }),
  21038. /* 12 */
  21039. /***/ (function(module, exports, __webpack_require__) {
  21040. "use strict";
  21041. Object.defineProperty(exports, "__esModule", {
  21042. value: true
  21043. });
  21044. 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; }; }(); /*
  21045. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  21046. *
  21047. * @author zheng qian <xqq@xqq.im>
  21048. *
  21049. * Licensed under the Apache License, Version 2.0 (the "License");
  21050. * you may not use this file except in compliance with the License.
  21051. * You may obtain a copy of the License at
  21052. *
  21053. * http://www.apache.org/licenses/LICENSE-2.0
  21054. *
  21055. * Unless required by applicable law or agreed to in writing, software
  21056. * distributed under the License is distributed on an "AS IS" BASIS,
  21057. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21058. * See the License for the specific language governing permissions and
  21059. * limitations under the License.
  21060. */
  21061. var _logger = __webpack_require__(0);
  21062. var _logger2 = _interopRequireDefault(_logger);
  21063. var _speedSampler = __webpack_require__(13);
  21064. var _speedSampler2 = _interopRequireDefault(_speedSampler);
  21065. var _loader = __webpack_require__(3);
  21066. var _fetchStreamLoader = __webpack_require__(26);
  21067. var _fetchStreamLoader2 = _interopRequireDefault(_fetchStreamLoader);
  21068. var _xhrMozChunkedLoader = __webpack_require__(27);
  21069. var _xhrMozChunkedLoader2 = _interopRequireDefault(_xhrMozChunkedLoader);
  21070. var _xhrMsstreamLoader = __webpack_require__(28);
  21071. var _xhrMsstreamLoader2 = _interopRequireDefault(_xhrMsstreamLoader);
  21072. var _xhrRangeLoader = __webpack_require__(29);
  21073. var _xhrRangeLoader2 = _interopRequireDefault(_xhrRangeLoader);
  21074. var _websocketLoader = __webpack_require__(30);
  21075. var _websocketLoader2 = _interopRequireDefault(_websocketLoader);
  21076. var _rangeSeekHandler = __webpack_require__(31);
  21077. var _rangeSeekHandler2 = _interopRequireDefault(_rangeSeekHandler);
  21078. var _paramSeekHandler = __webpack_require__(32);
  21079. var _paramSeekHandler2 = _interopRequireDefault(_paramSeekHandler);
  21080. var _exception = __webpack_require__(1);
  21081. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  21082. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  21083. /**
  21084. * DataSource: {
  21085. * url: string,
  21086. * filesize: number,
  21087. * cors: boolean,
  21088. * withCredentials: boolean
  21089. * }
  21090. *
  21091. */
  21092. // Manage IO Loaders
  21093. var IOController = function () {
  21094. function IOController(dataSource, config, extraData) {
  21095. _classCallCheck(this, IOController);
  21096. this.TAG = 'IOController';
  21097. this._config = config;
  21098. this._extraData = extraData;
  21099. this._stashInitialSize = 1024 * 384; // default initial size: 384KB
  21100. if (config.stashInitialSize != undefined && config.stashInitialSize > 0) {
  21101. // apply from config
  21102. this._stashInitialSize = config.stashInitialSize;
  21103. }
  21104. this._stashUsed = 0;
  21105. this._stashSize = this._stashInitialSize;
  21106. this._bufferSize = 1024 * 1024 * 3; // initial size: 3MB
  21107. this._stashBuffer = new ArrayBuffer(this._bufferSize);
  21108. this._stashByteStart = 0;
  21109. this._enableStash = true;
  21110. if (config.enableStashBuffer === false) {
  21111. this._enableStash = false;
  21112. }
  21113. this._loader = null;
  21114. this._loaderClass = null;
  21115. this._seekHandler = null;
  21116. this._dataSource = dataSource;
  21117. this._isWebSocketURL = /wss?:\/\/(.+?)/.test(dataSource.url);
  21118. this._refTotalLength = dataSource.filesize ? dataSource.filesize : null;
  21119. this._totalLength = this._refTotalLength;
  21120. this._fullRequestFlag = false;
  21121. this._currentRange = null;
  21122. this._redirectedURL = null;
  21123. this._speedNormalized = 0;
  21124. this._speedSampler = new _speedSampler2.default();
  21125. this._speedNormalizeList = [64, 128, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096];
  21126. this._isEarlyEofReconnecting = false;
  21127. this._paused = false;
  21128. this._resumeFrom = 0;
  21129. this._onDataArrival = null;
  21130. this._onSeeked = null;
  21131. this._onError = null;
  21132. this._onComplete = null;
  21133. this._onRedirect = null;
  21134. this._onRecoveredEarlyEof = null;
  21135. this._selectSeekHandler();
  21136. this._selectLoader();
  21137. this._createLoader();
  21138. }
  21139. _createClass(IOController, [{
  21140. key: 'destroy',
  21141. value: function destroy() {
  21142. if (this._loader.isWorking()) {
  21143. this._loader.abort();
  21144. }
  21145. this._loader.destroy();
  21146. this._loader = null;
  21147. this._loaderClass = null;
  21148. this._dataSource = null;
  21149. this._stashBuffer = null;
  21150. this._stashUsed = this._stashSize = this._bufferSize = this._stashByteStart = 0;
  21151. this._currentRange = null;
  21152. this._speedSampler = null;
  21153. this._isEarlyEofReconnecting = false;
  21154. this._onDataArrival = null;
  21155. this._onSeeked = null;
  21156. this._onError = null;
  21157. this._onComplete = null;
  21158. this._onRedirect = null;
  21159. this._onRecoveredEarlyEof = null;
  21160. this._extraData = null;
  21161. }
  21162. }, {
  21163. key: 'isWorking',
  21164. value: function isWorking() {
  21165. return this._loader && this._loader.isWorking() && !this._paused;
  21166. }
  21167. }, {
  21168. key: 'isPaused',
  21169. value: function isPaused() {
  21170. return this._paused;
  21171. }
  21172. }, {
  21173. key: '_selectSeekHandler',
  21174. value: function _selectSeekHandler() {
  21175. var config = this._config;
  21176. if (config.seekType === 'range') {
  21177. this._seekHandler = new _rangeSeekHandler2.default(this._config.rangeLoadZeroStart);
  21178. } else if (config.seekType === 'param') {
  21179. var paramStart = config.seekParamStart || 'bstart';
  21180. var paramEnd = config.seekParamEnd || 'bend';
  21181. this._seekHandler = new _paramSeekHandler2.default(paramStart, paramEnd);
  21182. } else if (config.seekType === 'custom') {
  21183. if (typeof config.customSeekHandler !== 'function') {
  21184. throw new _exception.InvalidArgumentException('Custom seekType specified in config but invalid customSeekHandler!');
  21185. }
  21186. this._seekHandler = new config.customSeekHandler();
  21187. } else {
  21188. throw new _exception.InvalidArgumentException('Invalid seekType in config: ' + config.seekType);
  21189. }
  21190. }
  21191. }, {
  21192. key: '_selectLoader',
  21193. value: function _selectLoader() {
  21194. if (this._isWebSocketURL) {
  21195. this._loaderClass = _websocketLoader2.default;
  21196. } else if (_fetchStreamLoader2.default.isSupported()) {
  21197. this._loaderClass = _fetchStreamLoader2.default;
  21198. } else if (_xhrMozChunkedLoader2.default.isSupported()) {
  21199. this._loaderClass = _xhrMozChunkedLoader2.default;
  21200. } else if (_xhrRangeLoader2.default.isSupported()) {
  21201. this._loaderClass = _xhrRangeLoader2.default;
  21202. } else {
  21203. throw new _exception.RuntimeException('Your browser doesn\'t support xhr with arraybuffer responseType!');
  21204. }
  21205. }
  21206. }, {
  21207. key: '_createLoader',
  21208. value: function _createLoader() {
  21209. this._loader = new this._loaderClass(this._seekHandler, this._config);
  21210. if (this._loader.needStashBuffer === false) {
  21211. this._enableStash = false;
  21212. }
  21213. this._loader.onContentLengthKnown = this._onContentLengthKnown.bind(this);
  21214. this._loader.onURLRedirect = this._onURLRedirect.bind(this);
  21215. this._loader.onDataArrival = this._onLoaderChunkArrival.bind(this);
  21216. this._loader.onComplete = this._onLoaderComplete.bind(this);
  21217. this._loader.onError = this._onLoaderError.bind(this);
  21218. }
  21219. }, {
  21220. key: 'open',
  21221. value: function open(optionalFrom) {
  21222. this._currentRange = { from: 0, to: -1 };
  21223. if (optionalFrom) {
  21224. this._currentRange.from = optionalFrom;
  21225. }
  21226. this._speedSampler.reset();
  21227. if (!optionalFrom) {
  21228. this._fullRequestFlag = true;
  21229. }
  21230. this._loader.open(this._dataSource, Object.assign({}, this._currentRange));
  21231. }
  21232. }, {
  21233. key: 'abort',
  21234. value: function abort() {
  21235. this._loader.abort();
  21236. if (this._paused) {
  21237. this._paused = false;
  21238. this._resumeFrom = 0;
  21239. }
  21240. }
  21241. }, {
  21242. key: 'pause',
  21243. value: function pause() {
  21244. if (this.isWorking()) {
  21245. this._loader.abort();
  21246. if (this._stashUsed !== 0) {
  21247. this._resumeFrom = this._stashByteStart;
  21248. this._currentRange.to = this._stashByteStart - 1;
  21249. } else {
  21250. this._resumeFrom = this._currentRange.to + 1;
  21251. }
  21252. this._stashUsed = 0;
  21253. this._stashByteStart = 0;
  21254. this._paused = true;
  21255. }
  21256. }
  21257. }, {
  21258. key: 'resume',
  21259. value: function resume() {
  21260. if (this._paused) {
  21261. this._paused = false;
  21262. var bytes = this._resumeFrom;
  21263. this._resumeFrom = 0;
  21264. this._internalSeek(bytes, true);
  21265. }
  21266. }
  21267. }, {
  21268. key: 'seek',
  21269. value: function seek(bytes) {
  21270. this._paused = false;
  21271. this._stashUsed = 0;
  21272. this._stashByteStart = 0;
  21273. this._internalSeek(bytes, true);
  21274. }
  21275. /**
  21276. * When seeking request is from media seeking, unconsumed stash data should be dropped
  21277. * However, stash data shouldn't be dropped if seeking requested from http reconnection
  21278. *
  21279. * @dropUnconsumed: Ignore and discard all unconsumed data in stash buffer
  21280. */
  21281. }, {
  21282. key: '_internalSeek',
  21283. value: function _internalSeek(bytes, dropUnconsumed) {
  21284. if (this._loader.isWorking()) {
  21285. this._loader.abort();
  21286. }
  21287. // dispatch & flush stash buffer before seek
  21288. this._flushStashBuffer(dropUnconsumed);
  21289. this._loader.destroy();
  21290. this._loader = null;
  21291. var requestRange = { from: bytes, to: -1 };
  21292. this._currentRange = { from: requestRange.from, to: -1 };
  21293. this._speedSampler.reset();
  21294. this._stashSize = this._stashInitialSize;
  21295. this._createLoader();
  21296. this._loader.open(this._dataSource, requestRange);
  21297. if (this._onSeeked) {
  21298. this._onSeeked();
  21299. }
  21300. }
  21301. }, {
  21302. key: 'updateUrl',
  21303. value: function updateUrl(url) {
  21304. if (!url || typeof url !== 'string' || url.length === 0) {
  21305. throw new _exception.InvalidArgumentException('Url must be a non-empty string!');
  21306. }
  21307. this._dataSource.url = url;
  21308. // TODO: replace with new url
  21309. }
  21310. }, {
  21311. key: '_expandBuffer',
  21312. value: function _expandBuffer(expectedBytes) {
  21313. var bufferNewSize = this._stashSize;
  21314. while (bufferNewSize + 1024 * 1024 * 1 < expectedBytes) {
  21315. bufferNewSize *= 2;
  21316. }
  21317. bufferNewSize += 1024 * 1024 * 1; // bufferSize = stashSize + 1MB
  21318. if (bufferNewSize === this._bufferSize) {
  21319. return;
  21320. }
  21321. var newBuffer = new ArrayBuffer(bufferNewSize);
  21322. if (this._stashUsed > 0) {
  21323. // copy existing data into new buffer
  21324. var stashOldArray = new Uint8Array(this._stashBuffer, 0, this._stashUsed);
  21325. var stashNewArray = new Uint8Array(newBuffer, 0, bufferNewSize);
  21326. stashNewArray.set(stashOldArray, 0);
  21327. }
  21328. this._stashBuffer = newBuffer;
  21329. this._bufferSize = bufferNewSize;
  21330. }
  21331. }, {
  21332. key: '_normalizeSpeed',
  21333. value: function _normalizeSpeed(input) {
  21334. var list = this._speedNormalizeList;
  21335. var last = list.length - 1;
  21336. var mid = 0;
  21337. var lbound = 0;
  21338. var ubound = last;
  21339. if (input < list[0]) {
  21340. return list[0];
  21341. }
  21342. // binary search
  21343. while (lbound <= ubound) {
  21344. mid = lbound + Math.floor((ubound - lbound) / 2);
  21345. if (mid === last || input >= list[mid] && input < list[mid + 1]) {
  21346. return list[mid];
  21347. } else if (list[mid] < input) {
  21348. lbound = mid + 1;
  21349. } else {
  21350. ubound = mid - 1;
  21351. }
  21352. }
  21353. }
  21354. }, {
  21355. key: '_adjustStashSize',
  21356. value: function _adjustStashSize(normalized) {
  21357. var stashSizeKB = 0;
  21358. if (this._config.isLive) {
  21359. // live stream: always use single normalized speed for size of stashSizeKB
  21360. stashSizeKB = normalized;
  21361. } else {
  21362. if (normalized < 512) {
  21363. stashSizeKB = normalized;
  21364. } else if (normalized >= 512 && normalized <= 1024) {
  21365. stashSizeKB = Math.floor(normalized * 1.5);
  21366. } else {
  21367. stashSizeKB = normalized * 2;
  21368. }
  21369. }
  21370. if (stashSizeKB > 8192) {
  21371. stashSizeKB = 8192;
  21372. }
  21373. var bufferSize = stashSizeKB * 1024 + 1024 * 1024 * 1; // stashSize + 1MB
  21374. if (this._bufferSize < bufferSize) {
  21375. this._expandBuffer(bufferSize);
  21376. }
  21377. this._stashSize = stashSizeKB * 1024;
  21378. }
  21379. }, {
  21380. key: '_dispatchChunks',
  21381. value: function _dispatchChunks(chunks, byteStart) {
  21382. this._currentRange.to = byteStart + chunks.byteLength - 1;
  21383. return this._onDataArrival(chunks, byteStart);
  21384. }
  21385. }, {
  21386. key: '_onURLRedirect',
  21387. value: function _onURLRedirect(redirectedURL) {
  21388. this._redirectedURL = redirectedURL;
  21389. if (this._onRedirect) {
  21390. this._onRedirect(redirectedURL);
  21391. }
  21392. }
  21393. }, {
  21394. key: '_onContentLengthKnown',
  21395. value: function _onContentLengthKnown(contentLength) {
  21396. if (contentLength && this._fullRequestFlag) {
  21397. this._totalLength = contentLength;
  21398. this._fullRequestFlag = false;
  21399. }
  21400. }
  21401. }, {
  21402. key: '_onLoaderChunkArrival',
  21403. value: function _onLoaderChunkArrival(chunk, byteStart, receivedLength) {
  21404. if (!this._onDataArrival) {
  21405. throw new _exception.IllegalStateException('IOController: No existing consumer (onDataArrival) callback!');
  21406. }
  21407. if (this._paused) {
  21408. return;
  21409. }
  21410. if (this._isEarlyEofReconnecting) {
  21411. // Auto-reconnect for EarlyEof succeed, notify to upper-layer by callback
  21412. this._isEarlyEofReconnecting = false;
  21413. if (this._onRecoveredEarlyEof) {
  21414. this._onRecoveredEarlyEof();
  21415. }
  21416. }
  21417. this._speedSampler.addBytes(chunk.byteLength);
  21418. // adjust stash buffer size according to network speed dynamically
  21419. var KBps = this._speedSampler.lastSecondKBps;
  21420. if (KBps !== 0) {
  21421. var normalized = this._normalizeSpeed(KBps);
  21422. if (this._speedNormalized !== normalized) {
  21423. this._speedNormalized = normalized;
  21424. this._adjustStashSize(normalized);
  21425. }
  21426. }
  21427. if (!this._enableStash) {
  21428. // disable stash
  21429. if (this._stashUsed === 0) {
  21430. // dispatch chunk directly to consumer;
  21431. // check ret value (consumed bytes) and stash unconsumed to stashBuffer
  21432. var consumed = this._dispatchChunks(chunk, byteStart);
  21433. if (consumed < chunk.byteLength) {
  21434. // unconsumed data remain.
  21435. var remain = chunk.byteLength - consumed;
  21436. if (remain > this._bufferSize) {
  21437. this._expandBuffer(remain);
  21438. }
  21439. var stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  21440. stashArray.set(new Uint8Array(chunk, consumed), 0);
  21441. this._stashUsed += remain;
  21442. this._stashByteStart = byteStart + consumed;
  21443. }
  21444. } else {
  21445. // else: Merge chunk into stashBuffer, and dispatch stashBuffer to consumer.
  21446. if (this._stashUsed + chunk.byteLength > this._bufferSize) {
  21447. this._expandBuffer(this._stashUsed + chunk.byteLength);
  21448. }
  21449. var _stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  21450. _stashArray.set(new Uint8Array(chunk), this._stashUsed);
  21451. this._stashUsed += chunk.byteLength;
  21452. var _consumed = this._dispatchChunks(this._stashBuffer.slice(0, this._stashUsed), this._stashByteStart);
  21453. if (_consumed < this._stashUsed && _consumed > 0) {
  21454. // unconsumed data remain
  21455. var remainArray = new Uint8Array(this._stashBuffer, _consumed);
  21456. _stashArray.set(remainArray, 0);
  21457. }
  21458. this._stashUsed -= _consumed;
  21459. this._stashByteStart += _consumed;
  21460. }
  21461. } else {
  21462. // enable stash
  21463. if (this._stashUsed === 0 && this._stashByteStart === 0) {
  21464. // seeked? or init chunk?
  21465. // This is the first chunk after seek action
  21466. this._stashByteStart = byteStart;
  21467. }
  21468. if (this._stashUsed + chunk.byteLength <= this._stashSize) {
  21469. // just stash
  21470. var _stashArray2 = new Uint8Array(this._stashBuffer, 0, this._stashSize);
  21471. _stashArray2.set(new Uint8Array(chunk), this._stashUsed);
  21472. this._stashUsed += chunk.byteLength;
  21473. } else {
  21474. // stashUsed + chunkSize > stashSize, size limit exceeded
  21475. var _stashArray3 = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  21476. if (this._stashUsed > 0) {
  21477. // There're stash datas in buffer
  21478. // dispatch the whole stashBuffer, and stash remain data
  21479. // then append chunk to stashBuffer (stash)
  21480. var buffer = this._stashBuffer.slice(0, this._stashUsed);
  21481. var _consumed2 = this._dispatchChunks(buffer, this._stashByteStart);
  21482. if (_consumed2 < buffer.byteLength) {
  21483. if (_consumed2 > 0) {
  21484. var _remainArray = new Uint8Array(buffer, _consumed2);
  21485. _stashArray3.set(_remainArray, 0);
  21486. this._stashUsed = _remainArray.byteLength;
  21487. this._stashByteStart += _consumed2;
  21488. }
  21489. } else {
  21490. this._stashUsed = 0;
  21491. this._stashByteStart += _consumed2;
  21492. }
  21493. if (this._stashUsed + chunk.byteLength > this._bufferSize) {
  21494. this._expandBuffer(this._stashUsed + chunk.byteLength);
  21495. _stashArray3 = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  21496. }
  21497. _stashArray3.set(new Uint8Array(chunk), this._stashUsed);
  21498. this._stashUsed += chunk.byteLength;
  21499. } else {
  21500. // stash buffer empty, but chunkSize > stashSize (oh, holy shit)
  21501. // dispatch chunk directly and stash remain data
  21502. var _consumed3 = this._dispatchChunks(chunk, byteStart);
  21503. if (_consumed3 < chunk.byteLength) {
  21504. var _remain = chunk.byteLength - _consumed3;
  21505. if (_remain > this._bufferSize) {
  21506. this._expandBuffer(_remain);
  21507. _stashArray3 = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  21508. }
  21509. _stashArray3.set(new Uint8Array(chunk, _consumed3), 0);
  21510. this._stashUsed += _remain;
  21511. this._stashByteStart = byteStart + _consumed3;
  21512. }
  21513. }
  21514. }
  21515. }
  21516. }
  21517. }, {
  21518. key: '_flushStashBuffer',
  21519. value: function _flushStashBuffer(dropUnconsumed) {
  21520. if (this._stashUsed > 0) {
  21521. var buffer = this._stashBuffer.slice(0, this._stashUsed);
  21522. var consumed = this._dispatchChunks(buffer, this._stashByteStart);
  21523. var remain = buffer.byteLength - consumed;
  21524. if (consumed < buffer.byteLength) {
  21525. if (dropUnconsumed) {
  21526. _logger2.default.w(this.TAG, remain + ' bytes unconsumed data remain when flush buffer, dropped');
  21527. } else {
  21528. if (consumed > 0) {
  21529. var stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
  21530. var remainArray = new Uint8Array(buffer, consumed);
  21531. stashArray.set(remainArray, 0);
  21532. this._stashUsed = remainArray.byteLength;
  21533. this._stashByteStart += consumed;
  21534. }
  21535. return 0;
  21536. }
  21537. }
  21538. this._stashUsed = 0;
  21539. this._stashByteStart = 0;
  21540. return remain;
  21541. }
  21542. return 0;
  21543. }
  21544. }, {
  21545. key: '_onLoaderComplete',
  21546. value: function _onLoaderComplete(from, to) {
  21547. // Force-flush stash buffer, and drop unconsumed data
  21548. this._flushStashBuffer(true);
  21549. if (this._onComplete) {
  21550. this._onComplete(this._extraData);
  21551. }
  21552. }
  21553. }, {
  21554. key: '_onLoaderError',
  21555. value: function _onLoaderError(type, data) {
  21556. _logger2.default.e(this.TAG, 'Loader error, code = ' + data.code + ', msg = ' + data.msg);
  21557. this._flushStashBuffer(false);
  21558. if (this._isEarlyEofReconnecting) {
  21559. // Auto-reconnect for EarlyEof failed, throw UnrecoverableEarlyEof error to upper-layer
  21560. this._isEarlyEofReconnecting = false;
  21561. type = _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF;
  21562. }
  21563. switch (type) {
  21564. case _loader.LoaderErrors.EARLY_EOF:
  21565. {
  21566. if (!this._config.isLive) {
  21567. // Do internal http reconnect if not live stream
  21568. if (this._totalLength) {
  21569. var nextFrom = this._currentRange.to + 1;
  21570. if (nextFrom < this._totalLength) {
  21571. _logger2.default.w(this.TAG, 'Connection lost, trying reconnect...');
  21572. this._isEarlyEofReconnecting = true;
  21573. this._internalSeek(nextFrom, false);
  21574. }
  21575. return;
  21576. }
  21577. // else: We don't know totalLength, throw UnrecoverableEarlyEof
  21578. }
  21579. // live stream: throw UnrecoverableEarlyEof error to upper-layer
  21580. type = _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF;
  21581. break;
  21582. }
  21583. case _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF:
  21584. case _loader.LoaderErrors.CONNECTING_TIMEOUT:
  21585. case _loader.LoaderErrors.HTTP_STATUS_CODE_INVALID:
  21586. case _loader.LoaderErrors.EXCEPTION:
  21587. break;
  21588. }
  21589. if (this._onError) {
  21590. this._onError(type, data);
  21591. } else {
  21592. throw new _exception.RuntimeException('IOException: ' + data.msg);
  21593. }
  21594. }
  21595. }, {
  21596. key: 'status',
  21597. get: function get() {
  21598. return this._loader.status;
  21599. }
  21600. }, {
  21601. key: 'extraData',
  21602. get: function get() {
  21603. return this._extraData;
  21604. },
  21605. set: function set(data) {
  21606. this._extraData = data;
  21607. }
  21608. // prototype: function onDataArrival(chunks: ArrayBuffer, byteStart: number): number
  21609. }, {
  21610. key: 'onDataArrival',
  21611. get: function get() {
  21612. return this._onDataArrival;
  21613. },
  21614. set: function set(callback) {
  21615. this._onDataArrival = callback;
  21616. }
  21617. }, {
  21618. key: 'onSeeked',
  21619. get: function get() {
  21620. return this._onSeeked;
  21621. },
  21622. set: function set(callback) {
  21623. this._onSeeked = callback;
  21624. }
  21625. // prototype: function onError(type: number, info: {code: number, msg: string}): void
  21626. }, {
  21627. key: 'onError',
  21628. get: function get() {
  21629. return this._onError;
  21630. },
  21631. set: function set(callback) {
  21632. this._onError = callback;
  21633. }
  21634. }, {
  21635. key: 'onComplete',
  21636. get: function get() {
  21637. return this._onComplete;
  21638. },
  21639. set: function set(callback) {
  21640. this._onComplete = callback;
  21641. }
  21642. }, {
  21643. key: 'onRedirect',
  21644. get: function get() {
  21645. return this._onRedirect;
  21646. },
  21647. set: function set(callback) {
  21648. this._onRedirect = callback;
  21649. }
  21650. }, {
  21651. key: 'onRecoveredEarlyEof',
  21652. get: function get() {
  21653. return this._onRecoveredEarlyEof;
  21654. },
  21655. set: function set(callback) {
  21656. this._onRecoveredEarlyEof = callback;
  21657. }
  21658. }, {
  21659. key: 'currentURL',
  21660. get: function get() {
  21661. return this._dataSource.url;
  21662. }
  21663. }, {
  21664. key: 'hasRedirect',
  21665. get: function get() {
  21666. return this._redirectedURL != null || this._dataSource.redirectedURL != undefined;
  21667. }
  21668. }, {
  21669. key: 'currentRedirectedURL',
  21670. get: function get() {
  21671. return this._redirectedURL || this._dataSource.redirectedURL;
  21672. }
  21673. // in KB/s
  21674. }, {
  21675. key: 'currentSpeed',
  21676. get: function get() {
  21677. if (this._loaderClass === _xhrRangeLoader2.default) {
  21678. // SpeedSampler is inaccuracy if loader is RangeLoader
  21679. return this._loader.currentSpeed;
  21680. }
  21681. return this._speedSampler.lastSecondKBps;
  21682. }
  21683. }, {
  21684. key: 'loaderType',
  21685. get: function get() {
  21686. return this._loader.type;
  21687. }
  21688. }]);
  21689. return IOController;
  21690. }();
  21691. exports.default = IOController;
  21692. module.exports = exports['default'];
  21693. /***/ }),
  21694. /* 13 */
  21695. /***/ (function(module, exports, __webpack_require__) {
  21696. "use strict";
  21697. Object.defineProperty(exports, "__esModule", {
  21698. value: true
  21699. });
  21700. 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; }; }();
  21701. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  21702. /*
  21703. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  21704. *
  21705. * @author zheng qian <xqq@xqq.im>
  21706. *
  21707. * Licensed under the Apache License, Version 2.0 (the "License");
  21708. * you may not use this file except in compliance with the License.
  21709. * You may obtain a copy of the License at
  21710. *
  21711. * http://www.apache.org/licenses/LICENSE-2.0
  21712. *
  21713. * Unless required by applicable law or agreed to in writing, software
  21714. * distributed under the License is distributed on an "AS IS" BASIS,
  21715. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21716. * See the License for the specific language governing permissions and
  21717. * limitations under the License.
  21718. */
  21719. // Utility class to calculate realtime network I/O speed
  21720. var SpeedSampler = function () {
  21721. function SpeedSampler() {
  21722. _classCallCheck(this, SpeedSampler);
  21723. // milliseconds
  21724. this._firstCheckpoint = 0;
  21725. this._lastCheckpoint = 0;
  21726. this._intervalBytes = 0;
  21727. this._totalBytes = 0;
  21728. this._lastSecondBytes = 0;
  21729. // compatibility detection
  21730. if (self.performance && self.performance.now) {
  21731. this._now = self.performance.now.bind(self.performance);
  21732. } else {
  21733. this._now = Date.now;
  21734. }
  21735. }
  21736. _createClass(SpeedSampler, [{
  21737. key: "reset",
  21738. value: function reset() {
  21739. this._firstCheckpoint = this._lastCheckpoint = 0;
  21740. this._totalBytes = this._intervalBytes = 0;
  21741. this._lastSecondBytes = 0;
  21742. }
  21743. }, {
  21744. key: "addBytes",
  21745. value: function addBytes(bytes) {
  21746. if (this._firstCheckpoint === 0) {
  21747. this._firstCheckpoint = this._now();
  21748. this._lastCheckpoint = this._firstCheckpoint;
  21749. this._intervalBytes += bytes;
  21750. this._totalBytes += bytes;
  21751. } else if (this._now() - this._lastCheckpoint < 1000) {
  21752. this._intervalBytes += bytes;
  21753. this._totalBytes += bytes;
  21754. } else {
  21755. // duration >= 1000
  21756. this._lastSecondBytes = this._intervalBytes;
  21757. this._intervalBytes = bytes;
  21758. this._totalBytes += bytes;
  21759. this._lastCheckpoint = this._now();
  21760. }
  21761. }
  21762. }, {
  21763. key: "currentKBps",
  21764. get: function get() {
  21765. this.addBytes(0);
  21766. var durationSeconds = (this._now() - this._lastCheckpoint) / 1000;
  21767. if (durationSeconds == 0) durationSeconds = 1;
  21768. return this._intervalBytes / durationSeconds / 1024;
  21769. }
  21770. }, {
  21771. key: "lastSecondKBps",
  21772. get: function get() {
  21773. this.addBytes(0);
  21774. if (this._lastSecondBytes !== 0) {
  21775. return this._lastSecondBytes / 1024;
  21776. } else {
  21777. // lastSecondBytes === 0
  21778. if (this._now() - this._lastCheckpoint >= 500) {
  21779. // if time interval since last checkpoint has exceeded 500ms
  21780. // the speed is nearly accurate
  21781. return this.currentKBps;
  21782. } else {
  21783. // We don't know
  21784. return 0;
  21785. }
  21786. }
  21787. }
  21788. }, {
  21789. key: "averageKBps",
  21790. get: function get() {
  21791. var durationSeconds = (this._now() - this._firstCheckpoint) / 1000;
  21792. return this._totalBytes / durationSeconds / 1024;
  21793. }
  21794. }]);
  21795. return SpeedSampler;
  21796. }();
  21797. exports.default = SpeedSampler;
  21798. module.exports = exports["default"];
  21799. /***/ }),
  21800. /* 14 */
  21801. /***/ (function(module, exports, __webpack_require__) {
  21802. "use strict";
  21803. Object.defineProperty(exports, "__esModule", {
  21804. value: true
  21805. });
  21806. 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; }; }(); /*
  21807. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  21808. *
  21809. * @author zheng qian <xqq@xqq.im>
  21810. *
  21811. * Licensed under the Apache License, Version 2.0 (the "License");
  21812. * you may not use this file except in compliance with the License.
  21813. * You may obtain a copy of the License at
  21814. *
  21815. * http://www.apache.org/licenses/LICENSE-2.0
  21816. *
  21817. * Unless required by applicable law or agreed to in writing, software
  21818. * distributed under the License is distributed on an "AS IS" BASIS,
  21819. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21820. * See the License for the specific language governing permissions and
  21821. * limitations under the License.
  21822. */
  21823. var _events = __webpack_require__(2);
  21824. var _events2 = _interopRequireDefault(_events);
  21825. var _logger = __webpack_require__(0);
  21826. var _logger2 = _interopRequireDefault(_logger);
  21827. var _browser = __webpack_require__(4);
  21828. var _browser2 = _interopRequireDefault(_browser);
  21829. var _mediaInfo = __webpack_require__(9);
  21830. var _mediaInfo2 = _interopRequireDefault(_mediaInfo);
  21831. var _flvDemuxer = __webpack_require__(35);
  21832. var _flvDemuxer2 = _interopRequireDefault(_flvDemuxer);
  21833. var _mp4Remuxer = __webpack_require__(40);
  21834. var _mp4Remuxer2 = _interopRequireDefault(_mp4Remuxer);
  21835. var _demuxErrors = __webpack_require__(10);
  21836. var _demuxErrors2 = _interopRequireDefault(_demuxErrors);
  21837. var _ioController = __webpack_require__(12);
  21838. var _ioController2 = _interopRequireDefault(_ioController);
  21839. var _transmuxingEvents = __webpack_require__(5);
  21840. var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
  21841. var _loader = __webpack_require__(3);
  21842. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  21843. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  21844. // Transmuxing (IO, Demuxing, Remuxing) controller, with multipart support
  21845. var TransmuxingController = function () {
  21846. function TransmuxingController(mediaDataSource, config) {
  21847. _classCallCheck(this, TransmuxingController);
  21848. this.TAG = 'TransmuxingController';
  21849. this._emitter = new _events2.default();
  21850. this._config = config;
  21851. // treat single part media as multipart media, which has only one segment
  21852. if (!mediaDataSource.segments) {
  21853. mediaDataSource.segments = [{
  21854. duration: mediaDataSource.duration,
  21855. filesize: mediaDataSource.filesize,
  21856. url: mediaDataSource.url
  21857. }];
  21858. }
  21859. // fill in default IO params if not exists
  21860. if (typeof mediaDataSource.cors !== 'boolean') {
  21861. mediaDataSource.cors = true;
  21862. }
  21863. if (typeof mediaDataSource.withCredentials !== 'boolean') {
  21864. mediaDataSource.withCredentials = false;
  21865. }
  21866. this._mediaDataSource = mediaDataSource;
  21867. this._currentSegmentIndex = 0;
  21868. var totalDuration = 0;
  21869. this._mediaDataSource.segments.forEach(function (segment) {
  21870. // timestampBase for each segment, and calculate total duration
  21871. segment.timestampBase = totalDuration;
  21872. totalDuration += segment.duration;
  21873. // params needed by IOController
  21874. segment.cors = mediaDataSource.cors;
  21875. segment.withCredentials = mediaDataSource.withCredentials;
  21876. // referrer policy control, if exist
  21877. if (config.referrerPolicy) {
  21878. segment.referrerPolicy = config.referrerPolicy;
  21879. }
  21880. });
  21881. if (!isNaN(totalDuration) && this._mediaDataSource.duration !== totalDuration) {
  21882. this._mediaDataSource.duration = totalDuration;
  21883. }
  21884. this._mediaInfo = null;
  21885. this._demuxer = null;
  21886. this._remuxer = null;
  21887. this._ioctl = null;
  21888. this._pendingSeekTime = null;
  21889. this._pendingResolveSeekPoint = null;
  21890. this._statisticsReporter = null;
  21891. }
  21892. _createClass(TransmuxingController, [{
  21893. key: 'destroy',
  21894. value: function destroy() {
  21895. this._mediaInfo = null;
  21896. this._mediaDataSource = null;
  21897. if (this._statisticsReporter) {
  21898. this._disableStatisticsReporter();
  21899. }
  21900. if (this._ioctl) {
  21901. this._ioctl.destroy();
  21902. this._ioctl = null;
  21903. }
  21904. if (this._demuxer) {
  21905. this._demuxer.destroy();
  21906. this._demuxer = null;
  21907. }
  21908. if (this._remuxer) {
  21909. this._remuxer.destroy();
  21910. this._remuxer = null;
  21911. }
  21912. this._emitter.removeAllListeners();
  21913. this._emitter = null;
  21914. }
  21915. }, {
  21916. key: 'on',
  21917. value: function on(event, listener) {
  21918. this._emitter.addListener(event, listener);
  21919. }
  21920. }, {
  21921. key: 'off',
  21922. value: function off(event, listener) {
  21923. this._emitter.removeListener(event, listener);
  21924. }
  21925. }, {
  21926. key: 'start',
  21927. value: function start() {
  21928. this._loadSegment(0);
  21929. this._enableStatisticsReporter();
  21930. }
  21931. }, {
  21932. key: '_loadSegment',
  21933. value: function _loadSegment(segmentIndex, optionalFrom) {
  21934. this._currentSegmentIndex = segmentIndex;
  21935. var dataSource = this._mediaDataSource.segments[segmentIndex];
  21936. var ioctl = this._ioctl = new _ioController2.default(dataSource, this._config, segmentIndex);
  21937. ioctl.onError = this._onIOException.bind(this);
  21938. ioctl.onSeeked = this._onIOSeeked.bind(this);
  21939. ioctl.onComplete = this._onIOComplete.bind(this);
  21940. ioctl.onRedirect = this._onIORedirect.bind(this);
  21941. ioctl.onRecoveredEarlyEof = this._onIORecoveredEarlyEof.bind(this);
  21942. if (optionalFrom) {
  21943. this._demuxer.bindDataSource(this._ioctl);
  21944. } else {
  21945. ioctl.onDataArrival = this._onInitChunkArrival.bind(this);
  21946. }
  21947. ioctl.open(optionalFrom);
  21948. }
  21949. }, {
  21950. key: 'stop',
  21951. value: function stop() {
  21952. this._internalAbort();
  21953. this._disableStatisticsReporter();
  21954. }
  21955. }, {
  21956. key: '_internalAbort',
  21957. value: function _internalAbort() {
  21958. if (this._ioctl) {
  21959. this._ioctl.destroy();
  21960. this._ioctl = null;
  21961. }
  21962. }
  21963. }, {
  21964. key: 'pause',
  21965. value: function pause() {
  21966. // take a rest
  21967. if (this._ioctl && this._ioctl.isWorking()) {
  21968. this._ioctl.pause();
  21969. this._disableStatisticsReporter();
  21970. }
  21971. }
  21972. }, {
  21973. key: 'resume',
  21974. value: function resume() {
  21975. if (this._ioctl && this._ioctl.isPaused()) {
  21976. this._ioctl.resume();
  21977. this._enableStatisticsReporter();
  21978. }
  21979. }
  21980. }, {
  21981. key: 'seek',
  21982. value: function seek(milliseconds) {
  21983. if (this._mediaInfo == null || !this._mediaInfo.isSeekable()) {
  21984. return;
  21985. }
  21986. var targetSegmentIndex = this._searchSegmentIndexContains(milliseconds);
  21987. if (targetSegmentIndex === this._currentSegmentIndex) {
  21988. // intra-segment seeking
  21989. var segmentInfo = this._mediaInfo.segments[targetSegmentIndex];
  21990. if (segmentInfo == undefined) {
  21991. // current segment loading started, but mediainfo hasn't received yet
  21992. // wait for the metadata loaded, then seek to expected position
  21993. this._pendingSeekTime = milliseconds;
  21994. } else {
  21995. var keyframe = segmentInfo.getNearestKeyframe(milliseconds);
  21996. this._remuxer.seek(keyframe.milliseconds);
  21997. this._ioctl.seek(keyframe.fileposition);
  21998. // Will be resolved in _onRemuxerMediaSegmentArrival()
  21999. this._pendingResolveSeekPoint = keyframe.milliseconds;
  22000. }
  22001. } else {
  22002. // cross-segment seeking
  22003. var targetSegmentInfo = this._mediaInfo.segments[targetSegmentIndex];
  22004. if (targetSegmentInfo == undefined) {
  22005. // target segment hasn't been loaded. We need metadata then seek to expected time
  22006. this._pendingSeekTime = milliseconds;
  22007. this._internalAbort();
  22008. this._remuxer.seek();
  22009. this._remuxer.insertDiscontinuity();
  22010. this._loadSegment(targetSegmentIndex);
  22011. // Here we wait for the metadata loaded, then seek to expected position
  22012. } else {
  22013. // We have target segment's metadata, direct seek to target position
  22014. var _keyframe = targetSegmentInfo.getNearestKeyframe(milliseconds);
  22015. this._internalAbort();
  22016. this._remuxer.seek(milliseconds);
  22017. this._remuxer.insertDiscontinuity();
  22018. this._demuxer.resetMediaInfo();
  22019. this._demuxer.timestampBase = this._mediaDataSource.segments[targetSegmentIndex].timestampBase;
  22020. this._loadSegment(targetSegmentIndex, _keyframe.fileposition);
  22021. this._pendingResolveSeekPoint = _keyframe.milliseconds;
  22022. this._reportSegmentMediaInfo(targetSegmentIndex);
  22023. }
  22024. }
  22025. this._enableStatisticsReporter();
  22026. }
  22027. }, {
  22028. key: '_searchSegmentIndexContains',
  22029. value: function _searchSegmentIndexContains(milliseconds) {
  22030. var segments = this._mediaDataSource.segments;
  22031. var idx = segments.length - 1;
  22032. for (var i = 0; i < segments.length; i++) {
  22033. if (milliseconds < segments[i].timestampBase) {
  22034. idx = i - 1;
  22035. break;
  22036. }
  22037. }
  22038. return idx;
  22039. }
  22040. }, {
  22041. key: '_onInitChunkArrival',
  22042. value: function _onInitChunkArrival(data, byteStart) {
  22043. var _this = this;
  22044. var probeData = null;
  22045. var consumed = 0;
  22046. if (byteStart > 0) {
  22047. // IOController seeked immediately after opened, byteStart > 0 callback may received
  22048. this._demuxer.bindDataSource(this._ioctl);
  22049. this._demuxer.timestampBase = this._mediaDataSource.segments[this._currentSegmentIndex].timestampBase;
  22050. consumed = this._demuxer.parseChunks(data, byteStart);
  22051. } else if ((probeData = _flvDemuxer2.default.probe(data)).match) {
  22052. // Always create new FLVDemuxer
  22053. this._demuxer = new _flvDemuxer2.default(probeData, this._config);
  22054. if (!this._remuxer) {
  22055. this._remuxer = new _mp4Remuxer2.default(this._config);
  22056. }
  22057. var mds = this._mediaDataSource;
  22058. if (mds.duration != undefined && !isNaN(mds.duration)) {
  22059. this._demuxer.overridedDuration = mds.duration;
  22060. }
  22061. if (typeof mds.hasAudio === 'boolean') {
  22062. this._demuxer.overridedHasAudio = mds.hasAudio;
  22063. }
  22064. if (typeof mds.hasVideo === 'boolean') {
  22065. this._demuxer.overridedHasVideo = mds.hasVideo;
  22066. }
  22067. this._demuxer.timestampBase = mds.segments[this._currentSegmentIndex].timestampBase;
  22068. this._demuxer.onError = this._onDemuxException.bind(this);
  22069. this._demuxer.onMediaInfo = this._onMediaInfo.bind(this);
  22070. this._demuxer.onLoadedSei = this._onLoadedSei.bind(this);
  22071. this._remuxer.bindDataSource(this._demuxer.bindDataSource(this._ioctl));
  22072. this._remuxer.onInitSegment = this._onRemuxerInitSegmentArrival.bind(this);
  22073. this._remuxer.onMediaSegment = this._onRemuxerMediaSegmentArrival.bind(this);
  22074. consumed = this._demuxer.parseChunks(data, byteStart);
  22075. } else {
  22076. probeData = null;
  22077. _logger2.default.e(this.TAG, 'Non-FLV, Unsupported media type!');
  22078. Promise.resolve().then(function () {
  22079. _this._internalAbort();
  22080. });
  22081. this._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR, _demuxErrors2.default.FORMAT_UNSUPPORTED, 'Non-FLV, Unsupported media type');
  22082. consumed = 0;
  22083. }
  22084. return consumed;
  22085. }
  22086. }, {
  22087. key: '_onMediaInfo',
  22088. value: function _onMediaInfo(mediaInfo) {
  22089. var _this2 = this;
  22090. if (this._mediaInfo == null) {
  22091. // Store first segment's mediainfo as global mediaInfo
  22092. this._mediaInfo = Object.assign({}, mediaInfo);
  22093. this._mediaInfo.keyframesIndex = null;
  22094. this._mediaInfo.segments = [];
  22095. this._mediaInfo.segmentCount = this._mediaDataSource.segments.length;
  22096. Object.setPrototypeOf(this._mediaInfo, _mediaInfo2.default.prototype);
  22097. }
  22098. var segmentInfo = Object.assign({}, mediaInfo);
  22099. Object.setPrototypeOf(segmentInfo, _mediaInfo2.default.prototype);
  22100. this._mediaInfo.segments[this._currentSegmentIndex] = segmentInfo;
  22101. // notify mediaInfo update
  22102. this._reportSegmentMediaInfo(this._currentSegmentIndex);
  22103. if (this._pendingSeekTime != null) {
  22104. Promise.resolve().then(function () {
  22105. var target = _this2._pendingSeekTime;
  22106. _this2._pendingSeekTime = null;
  22107. _this2.seek(target);
  22108. });
  22109. }
  22110. }
  22111. }, {
  22112. key: '_onLoadedSei',
  22113. value: function _onLoadedSei(timestamp, data) {
  22114. this._emitter.emit(_transmuxingEvents2.default.LOADED_SEI, timestamp, data);
  22115. }
  22116. }, {
  22117. key: '_onIOSeeked',
  22118. value: function _onIOSeeked() {
  22119. this._remuxer.insertDiscontinuity();
  22120. }
  22121. }, {
  22122. key: '_onIOComplete',
  22123. value: function _onIOComplete(extraData) {
  22124. var segmentIndex = extraData;
  22125. var nextSegmentIndex = segmentIndex + 1;
  22126. if (nextSegmentIndex < this._mediaDataSource.segments.length) {
  22127. this._internalAbort();
  22128. this._remuxer.flushStashedSamples();
  22129. this._loadSegment(nextSegmentIndex);
  22130. } else {
  22131. this._remuxer.flushStashedSamples();
  22132. this._emitter.emit(_transmuxingEvents2.default.LOADING_COMPLETE);
  22133. this._disableStatisticsReporter();
  22134. }
  22135. }
  22136. }, {
  22137. key: '_onIORedirect',
  22138. value: function _onIORedirect(redirectedURL) {
  22139. var segmentIndex = this._ioctl.extraData;
  22140. this._mediaDataSource.segments[segmentIndex].redirectedURL = redirectedURL;
  22141. }
  22142. }, {
  22143. key: '_onIORecoveredEarlyEof',
  22144. value: function _onIORecoveredEarlyEof() {
  22145. this._emitter.emit(_transmuxingEvents2.default.RECOVERED_EARLY_EOF);
  22146. }
  22147. }, {
  22148. key: '_onIOException',
  22149. value: function _onIOException(type, info) {
  22150. _logger2.default.e(this.TAG, 'IOException: type = ' + type + ', code = ' + info.code + ', msg = ' + info.msg);
  22151. this._emitter.emit(_transmuxingEvents2.default.IO_ERROR, type, info);
  22152. this._disableStatisticsReporter();
  22153. }
  22154. }, {
  22155. key: '_onDemuxException',
  22156. value: function _onDemuxException(type, info) {
  22157. _logger2.default.e(this.TAG, 'DemuxException: type = ' + type + ', info = ' + info);
  22158. this._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR, type, info);
  22159. }
  22160. }, {
  22161. key: '_onRemuxerInitSegmentArrival',
  22162. value: function _onRemuxerInitSegmentArrival(type, initSegment) {
  22163. this._emitter.emit(_transmuxingEvents2.default.INIT_SEGMENT, type, initSegment);
  22164. }
  22165. }, {
  22166. key: '_onRemuxerMediaSegmentArrival',
  22167. value: function _onRemuxerMediaSegmentArrival(type, mediaSegment) {
  22168. if (this._pendingSeekTime != null) {
  22169. // Media segments after new-segment cross-seeking should be dropped.
  22170. return;
  22171. }
  22172. this._emitter.emit(_transmuxingEvents2.default.MEDIA_SEGMENT, type, mediaSegment);
  22173. // Resolve pending seekPoint
  22174. if (this._pendingResolveSeekPoint != null && type === 'video') {
  22175. var syncPoints = mediaSegment.info.syncPoints;
  22176. var seekpoint = this._pendingResolveSeekPoint;
  22177. this._pendingResolveSeekPoint = null;
  22178. // Safari: Pass PTS for recommend_seekpoint
  22179. if (_browser2.default.safari && syncPoints.length > 0 && syncPoints[0].originalDts === seekpoint) {
  22180. seekpoint = syncPoints[0].pts;
  22181. }
  22182. // else: use original DTS (keyframe.milliseconds)
  22183. this._emitter.emit(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, seekpoint);
  22184. }
  22185. }
  22186. }, {
  22187. key: '_enableStatisticsReporter',
  22188. value: function _enableStatisticsReporter() {
  22189. if (this._statisticsReporter == null) {
  22190. this._statisticsReporter = self.setInterval(this._reportStatisticsInfo.bind(this), this._config.statisticsInfoReportInterval);
  22191. }
  22192. }
  22193. }, {
  22194. key: '_disableStatisticsReporter',
  22195. value: function _disableStatisticsReporter() {
  22196. if (this._statisticsReporter) {
  22197. self.clearInterval(this._statisticsReporter);
  22198. this._statisticsReporter = null;
  22199. }
  22200. }
  22201. }, {
  22202. key: '_reportSegmentMediaInfo',
  22203. value: function _reportSegmentMediaInfo(segmentIndex) {
  22204. var segmentInfo = this._mediaInfo.segments[segmentIndex];
  22205. var exportInfo = Object.assign({}, segmentInfo);
  22206. exportInfo.duration = this._mediaInfo.duration;
  22207. exportInfo.segmentCount = this._mediaInfo.segmentCount;
  22208. delete exportInfo.segments;
  22209. delete exportInfo.keyframesIndex;
  22210. this._emitter.emit(_transmuxingEvents2.default.MEDIA_INFO, exportInfo);
  22211. }
  22212. }, {
  22213. key: '_reportStatisticsInfo',
  22214. value: function _reportStatisticsInfo() {
  22215. var info = {};
  22216. info.url = this._ioctl.currentURL;
  22217. info.hasRedirect = this._ioctl.hasRedirect;
  22218. if (info.hasRedirect) {
  22219. info.redirectedURL = this._ioctl.currentRedirectedURL;
  22220. }
  22221. info.speed = this._ioctl.currentSpeed;
  22222. info.loaderType = this._ioctl.loaderType;
  22223. info.currentSegmentIndex = this._currentSegmentIndex;
  22224. info.totalSegmentCount = this._mediaDataSource.segments.length;
  22225. this._emitter.emit(_transmuxingEvents2.default.STATISTICS_INFO, info);
  22226. }
  22227. }]);
  22228. return TransmuxingController;
  22229. }();
  22230. exports.default = TransmuxingController;
  22231. module.exports = exports['default'];
  22232. /***/ }),
  22233. /* 15 */
  22234. /***/ (function(module, exports, __webpack_require__) {
  22235. "use strict";
  22236. Object.defineProperty(exports, "__esModule", {
  22237. value: true
  22238. });
  22239. 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; }; }();
  22240. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  22241. /*
  22242. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  22243. *
  22244. * @author zheng qian <xqq@xqq.im>
  22245. *
  22246. * Licensed under the Apache License, Version 2.0 (the "License");
  22247. * you may not use this file except in compliance with the License.
  22248. * You may obtain a copy of the License at
  22249. *
  22250. * http://www.apache.org/licenses/LICENSE-2.0
  22251. *
  22252. * Unless required by applicable law or agreed to in writing, software
  22253. * distributed under the License is distributed on an "AS IS" BASIS,
  22254. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22255. * See the License for the specific language governing permissions and
  22256. * limitations under the License.
  22257. */
  22258. // Represents an media sample (audio / video)
  22259. var SampleInfo = exports.SampleInfo = function SampleInfo(dts, pts, duration, originalDts, isSync) {
  22260. _classCallCheck(this, SampleInfo);
  22261. this.dts = dts;
  22262. this.pts = pts;
  22263. this.duration = duration;
  22264. this.originalDts = originalDts;
  22265. this.isSyncPoint = isSync;
  22266. this.fileposition = null;
  22267. };
  22268. // Media Segment concept is defined in Media Source Extensions spec.
  22269. // Particularly in ISO BMFF format, an Media Segment contains a moof box followed by a mdat box.
  22270. var MediaSegmentInfo = exports.MediaSegmentInfo = function () {
  22271. function MediaSegmentInfo() {
  22272. _classCallCheck(this, MediaSegmentInfo);
  22273. this.beginDts = 0;
  22274. this.endDts = 0;
  22275. this.beginPts = 0;
  22276. this.endPts = 0;
  22277. this.originalBeginDts = 0;
  22278. this.originalEndDts = 0;
  22279. this.syncPoints = []; // SampleInfo[n], for video IDR frames only
  22280. this.firstSample = null; // SampleInfo
  22281. this.lastSample = null; // SampleInfo
  22282. }
  22283. _createClass(MediaSegmentInfo, [{
  22284. key: "appendSyncPoint",
  22285. value: function appendSyncPoint(sampleInfo) {
  22286. // also called Random Access Point
  22287. sampleInfo.isSyncPoint = true;
  22288. this.syncPoints.push(sampleInfo);
  22289. }
  22290. }]);
  22291. return MediaSegmentInfo;
  22292. }();
  22293. // Ordered list for recording video IDR frames, sorted by originalDts
  22294. var IDRSampleList = exports.IDRSampleList = function () {
  22295. function IDRSampleList() {
  22296. _classCallCheck(this, IDRSampleList);
  22297. this._list = [];
  22298. }
  22299. _createClass(IDRSampleList, [{
  22300. key: "clear",
  22301. value: function clear() {
  22302. this._list = [];
  22303. }
  22304. }, {
  22305. key: "appendArray",
  22306. value: function appendArray(syncPoints) {
  22307. var list = this._list;
  22308. if (syncPoints.length === 0) {
  22309. return;
  22310. }
  22311. if (list.length > 0 && syncPoints[0].originalDts < list[list.length - 1].originalDts) {
  22312. this.clear();
  22313. }
  22314. Array.prototype.push.apply(list, syncPoints);
  22315. }
  22316. }, {
  22317. key: "getLastSyncPointBeforeDts",
  22318. value: function getLastSyncPointBeforeDts(dts) {
  22319. if (this._list.length == 0) {
  22320. return null;
  22321. }
  22322. var list = this._list;
  22323. var idx = 0;
  22324. var last = list.length - 1;
  22325. var mid = 0;
  22326. var lbound = 0;
  22327. var ubound = last;
  22328. if (dts < list[0].dts) {
  22329. idx = 0;
  22330. lbound = ubound + 1;
  22331. }
  22332. while (lbound <= ubound) {
  22333. mid = lbound + Math.floor((ubound - lbound) / 2);
  22334. if (mid === last || dts >= list[mid].dts && dts < list[mid + 1].dts) {
  22335. idx = mid;
  22336. break;
  22337. } else if (list[mid].dts < dts) {
  22338. lbound = mid + 1;
  22339. } else {
  22340. ubound = mid - 1;
  22341. }
  22342. }
  22343. return this._list[idx];
  22344. }
  22345. }]);
  22346. return IDRSampleList;
  22347. }();
  22348. // Data structure for recording information of media segments in single track.
  22349. var MediaSegmentInfoList = exports.MediaSegmentInfoList = function () {
  22350. function MediaSegmentInfoList(type) {
  22351. _classCallCheck(this, MediaSegmentInfoList);
  22352. this._type = type;
  22353. this._list = [];
  22354. this._lastAppendLocation = -1; // cached last insert location
  22355. }
  22356. _createClass(MediaSegmentInfoList, [{
  22357. key: "isEmpty",
  22358. value: function isEmpty() {
  22359. return this._list.length === 0;
  22360. }
  22361. }, {
  22362. key: "clear",
  22363. value: function clear() {
  22364. this._list = [];
  22365. this._lastAppendLocation = -1;
  22366. }
  22367. }, {
  22368. key: "_searchNearestSegmentBefore",
  22369. value: function _searchNearestSegmentBefore(originalBeginDts) {
  22370. var list = this._list;
  22371. if (list.length === 0) {
  22372. return -2;
  22373. }
  22374. var last = list.length - 1;
  22375. var mid = 0;
  22376. var lbound = 0;
  22377. var ubound = last;
  22378. var idx = 0;
  22379. if (originalBeginDts < list[0].originalBeginDts) {
  22380. idx = -1;
  22381. return idx;
  22382. }
  22383. while (lbound <= ubound) {
  22384. mid = lbound + Math.floor((ubound - lbound) / 2);
  22385. if (mid === last || originalBeginDts > list[mid].lastSample.originalDts && originalBeginDts < list[mid + 1].originalBeginDts) {
  22386. idx = mid;
  22387. break;
  22388. } else if (list[mid].originalBeginDts < originalBeginDts) {
  22389. lbound = mid + 1;
  22390. } else {
  22391. ubound = mid - 1;
  22392. }
  22393. }
  22394. return idx;
  22395. }
  22396. }, {
  22397. key: "_searchNearestSegmentAfter",
  22398. value: function _searchNearestSegmentAfter(originalBeginDts) {
  22399. return this._searchNearestSegmentBefore(originalBeginDts) + 1;
  22400. }
  22401. }, {
  22402. key: "append",
  22403. value: function append(mediaSegmentInfo) {
  22404. var list = this._list;
  22405. var msi = mediaSegmentInfo;
  22406. var lastAppendIdx = this._lastAppendLocation;
  22407. var insertIdx = 0;
  22408. 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)) {
  22409. insertIdx = lastAppendIdx + 1; // use cached location idx
  22410. } else {
  22411. if (list.length > 0) {
  22412. insertIdx = this._searchNearestSegmentBefore(msi.originalBeginDts) + 1;
  22413. }
  22414. }
  22415. this._lastAppendLocation = insertIdx;
  22416. this._list.splice(insertIdx, 0, msi);
  22417. }
  22418. }, {
  22419. key: "getLastSegmentBefore",
  22420. value: function getLastSegmentBefore(originalBeginDts) {
  22421. var idx = this._searchNearestSegmentBefore(originalBeginDts);
  22422. if (idx >= 0) {
  22423. return this._list[idx];
  22424. } else {
  22425. // -1
  22426. return null;
  22427. }
  22428. }
  22429. }, {
  22430. key: "getLastSampleBefore",
  22431. value: function getLastSampleBefore(originalBeginDts) {
  22432. var segment = this.getLastSegmentBefore(originalBeginDts);
  22433. if (segment != null) {
  22434. return segment.lastSample;
  22435. } else {
  22436. return null;
  22437. }
  22438. }
  22439. }, {
  22440. key: "getLastSyncPointBefore",
  22441. value: function getLastSyncPointBefore(originalBeginDts) {
  22442. var segmentIdx = this._searchNearestSegmentBefore(originalBeginDts);
  22443. var syncPoints = this._list[segmentIdx].syncPoints;
  22444. while (syncPoints.length === 0 && segmentIdx > 0) {
  22445. segmentIdx--;
  22446. syncPoints = this._list[segmentIdx].syncPoints;
  22447. }
  22448. if (syncPoints.length > 0) {
  22449. return syncPoints[syncPoints.length - 1];
  22450. } else {
  22451. return null;
  22452. }
  22453. }
  22454. }, {
  22455. key: "type",
  22456. get: function get() {
  22457. return this._type;
  22458. }
  22459. }, {
  22460. key: "length",
  22461. get: function get() {
  22462. return this._list.length;
  22463. }
  22464. }]);
  22465. return MediaSegmentInfoList;
  22466. }();
  22467. /***/ }),
  22468. /* 16 */
  22469. /***/ (function(module, exports, __webpack_require__) {
  22470. "use strict";
  22471. Object.defineProperty(exports, "__esModule", {
  22472. value: true
  22473. });
  22474. /*
  22475. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  22476. *
  22477. * @author zheng qian <xqq@xqq.im>
  22478. *
  22479. * Licensed under the Apache License, Version 2.0 (the "License");
  22480. * you may not use this file except in compliance with the License.
  22481. * You may obtain a copy of the License at
  22482. *
  22483. * http://www.apache.org/licenses/LICENSE-2.0
  22484. *
  22485. * Unless required by applicable law or agreed to in writing, software
  22486. * distributed under the License is distributed on an "AS IS" BASIS,
  22487. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22488. * See the License for the specific language governing permissions and
  22489. * limitations under the License.
  22490. */
  22491. var MSEEvents = {
  22492. ERROR: 'error',
  22493. SOURCE_OPEN: 'source_open',
  22494. UPDATE_END: 'update_end',
  22495. BUFFER_FULL: 'buffer_full'
  22496. };
  22497. exports.default = MSEEvents;
  22498. module.exports = exports['default'];
  22499. /***/ }),
  22500. /* 17 */
  22501. /***/ (function(module, exports, __webpack_require__) {
  22502. "use strict";
  22503. Object.defineProperty(exports, "__esModule", {
  22504. value: true
  22505. });
  22506. exports.ErrorDetails = exports.ErrorTypes = undefined;
  22507. var _loader = __webpack_require__(3);
  22508. var _demuxErrors = __webpack_require__(10);
  22509. var _demuxErrors2 = _interopRequireDefault(_demuxErrors);
  22510. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  22511. /*
  22512. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  22513. *
  22514. * @author zheng qian <xqq@xqq.im>
  22515. *
  22516. * Licensed under the Apache License, Version 2.0 (the "License");
  22517. * you may not use this file except in compliance with the License.
  22518. * You may obtain a copy of the License at
  22519. *
  22520. * http://www.apache.org/licenses/LICENSE-2.0
  22521. *
  22522. * Unless required by applicable law or agreed to in writing, software
  22523. * distributed under the License is distributed on an "AS IS" BASIS,
  22524. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22525. * See the License for the specific language governing permissions and
  22526. * limitations under the License.
  22527. */
  22528. var ErrorTypes = exports.ErrorTypes = {
  22529. NETWORK_ERROR: 'NetworkError',
  22530. MEDIA_ERROR: 'MediaError',
  22531. OTHER_ERROR: 'OtherError'
  22532. };
  22533. var ErrorDetails = exports.ErrorDetails = {
  22534. NETWORK_EXCEPTION: _loader.LoaderErrors.EXCEPTION,
  22535. NETWORK_STATUS_CODE_INVALID: _loader.LoaderErrors.HTTP_STATUS_CODE_INVALID,
  22536. NETWORK_TIMEOUT: _loader.LoaderErrors.CONNECTING_TIMEOUT,
  22537. NETWORK_UNRECOVERABLE_EARLY_EOF: _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF,
  22538. MEDIA_MSE_ERROR: 'MediaMSEError',
  22539. MEDIA_FORMAT_ERROR: _demuxErrors2.default.FORMAT_ERROR,
  22540. MEDIA_FORMAT_UNSUPPORTED: _demuxErrors2.default.FORMAT_UNSUPPORTED,
  22541. MEDIA_CODEC_UNSUPPORTED: _demuxErrors2.default.CODEC_UNSUPPORTED
  22542. };
  22543. /***/ }),
  22544. /* 18 */
  22545. /***/ (function(module, exports, __webpack_require__) {
  22546. module.exports = __webpack_require__(19);
  22547. /***/ }),
  22548. /* 19 */
  22549. /***/ (function(module, exports, __webpack_require__) {
  22550. "use strict";
  22551. Object.defineProperty(exports, "__esModule", {
  22552. value: true
  22553. });
  22554. 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; }; }();
  22555. var _xgplayer = __webpack_require__(20);
  22556. var _xgplayer2 = _interopRequireDefault(_xgplayer);
  22557. var _flv = __webpack_require__(21);
  22558. var _flv2 = _interopRequireDefault(_flv);
  22559. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  22560. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  22561. 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; }
  22562. 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; }
  22563. var FlvJsPlayer = function (_Player) {
  22564. _inherits(FlvJsPlayer, _Player);
  22565. function FlvJsPlayer(options) {
  22566. _classCallCheck(this, FlvJsPlayer);
  22567. var _this = _possibleConstructorReturn(this, (FlvJsPlayer.__proto__ || Object.getPrototypeOf(FlvJsPlayer)).call(this, options));
  22568. _this.flvOpts = { type: 'flv' };
  22569. _this.optionalConfig = {};
  22570. _xgplayer2.default.util.deepCopy(_this.flvOpts, options);
  22571. _xgplayer2.default.util.deepCopy(_this.optionalConfig, options.flvOptionalConfig);
  22572. var player = _this;
  22573. Object.defineProperty(player, 'src', {
  22574. get: function get() {
  22575. return player.currentSrc;
  22576. },
  22577. set: function set(url) {
  22578. player.flv_load(url);
  22579. var oldVol = player.volume;
  22580. player.video.muted = true;
  22581. _xgplayer2.default.util.addClass(player.root, 'xgplayer-is-enter');
  22582. player.once('playing', function () {
  22583. _xgplayer2.default.util.removeClass(player.root, 'xgplayer-is-enter');
  22584. player.video.muted = false;
  22585. });
  22586. player.once('canplay', function () {
  22587. player.play();
  22588. });
  22589. },
  22590. configurable: true
  22591. });
  22592. player.once('complete', function () {
  22593. player.__flv__ = _flv2.default.createPlayer(_this.flvOpts, _this.optionalConfig);
  22594. player.createInstance(player.__flv__);
  22595. if (player.config.isLive) {
  22596. _xgplayer2.default.util.addClass(player.root, 'xgplayer-is-live');
  22597. var live = _xgplayer2.default.util.createDom('xg-live', '正在直播', {}, 'xgplayer-live');
  22598. player.controls.appendChild(live);
  22599. }
  22600. });
  22601. return _this;
  22602. }
  22603. _createClass(FlvJsPlayer, [{
  22604. key: 'createInstance',
  22605. value: function createInstance(flv) {
  22606. var player = this;
  22607. player.video.addEventListener('contextmenu', function (e) {
  22608. e.preventDefault();
  22609. });
  22610. flv.attachMediaElement(player.video);
  22611. flv.load();
  22612. flv.play();
  22613. flv.on(_flv2.default.Events.ERROR, function (e) {
  22614. player.emit('error', new _xgplayer2.default.Errors('other', player.config.url));
  22615. });
  22616. flv.on(_flv2.default.Events.LOADED_SEI, function (timestamp, data) {
  22617. player.emit('loaded_sei', timestamp, data);
  22618. });
  22619. flv.on(_flv2.default.Events.STATISTICS_INFO, function (data) {
  22620. player.emit("statistics_info", data);
  22621. });
  22622. flv.on(_flv2.default.Events.MEDIA_INFO, function (data) {
  22623. player.mediainfo = data;
  22624. player.emit("MEDIA_INFO", data);
  22625. });
  22626. player.once('destroy', function () {
  22627. flv.destroy();
  22628. player.__flv__ = null;
  22629. });
  22630. }
  22631. }, {
  22632. key: 'flv_load',
  22633. value: function flv_load(newUrl) {
  22634. var mediaDataSource = this.flvOpts;
  22635. mediaDataSource.segments = [{
  22636. cors: true,
  22637. duration: undefined,
  22638. filesize: undefined,
  22639. timestampBase: 0,
  22640. url: newUrl,
  22641. withCredentials: false
  22642. }];
  22643. // mediaDataSource.cors = true
  22644. // mediaDataSource.hasAudio = true
  22645. // mediaDataSource.hasVideo = true
  22646. // mediaDataSource.isLive = true
  22647. mediaDataSource.url = newUrl;
  22648. // mediaDataSource.withCredentials = false
  22649. this.flv_load_mds(mediaDataSource);
  22650. }
  22651. }, {
  22652. key: 'flv_load_mds',
  22653. value: function flv_load_mds(mediaDataSource) {
  22654. var player = this;
  22655. if (typeof player.__flv__ !== 'undefined') {
  22656. if (player.__flv__ != null) {
  22657. player.__flv__.unload();
  22658. player.__flv__.detachMediaElement();
  22659. player.__flv__.destroy();
  22660. player.__flv__ = null;
  22661. }
  22662. }
  22663. player.__flv__ = _flv2.default.createPlayer(mediaDataSource, this.optionalConfig);
  22664. player.__flv__.attachMediaElement(player.video);
  22665. player.__flv__.load();
  22666. }
  22667. }, {
  22668. key: 'switchURL',
  22669. value: function switchURL(url) {
  22670. var player = this;
  22671. var curTime = 0;
  22672. if (!player.config.isLive) {
  22673. curTime = player.currentTime;
  22674. }
  22675. player.flv_load(url);
  22676. var oldVol = player.volume;
  22677. player.video.muted = true;
  22678. _xgplayer2.default.util.addClass(player.root, 'xgplayer-is-enter');
  22679. player.once('playing', function () {
  22680. _xgplayer2.default.util.removeClass(player.root, 'xgplayer-is-enter');
  22681. player.video.muted = false;
  22682. });
  22683. player.once('canplay', function () {
  22684. if (!player.config.isLive) {
  22685. player.currentTime = curTime;
  22686. }
  22687. player.play();
  22688. });
  22689. }
  22690. }]);
  22691. return FlvJsPlayer;
  22692. }(_xgplayer2.default);
  22693. FlvJsPlayer.isSupported = _flv2.default.isSupported;
  22694. exports.default = FlvJsPlayer;
  22695. module.exports = exports['default'];
  22696. /***/ }),
  22697. /* 20 */
  22698. /***/ (function(module, exports) {
  22699. module.exports = __WEBPACK_EXTERNAL_MODULE__20__;
  22700. /***/ }),
  22701. /* 21 */
  22702. /***/ (function(module, exports, __webpack_require__) {
  22703. "use strict";
  22704. Object.defineProperty(exports, "__esModule", {
  22705. value: true
  22706. });
  22707. 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; }; /*
  22708. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  22709. *
  22710. * @author zheng qian <xqq@xqq.im>
  22711. *
  22712. * Licensed under the Apache License, Version 2.0 (the "License");
  22713. * you may not use this file except in compliance with the License.
  22714. * You may obtain a copy of the License at
  22715. *
  22716. * http://www.apache.org/licenses/LICENSE-2.0
  22717. *
  22718. * Unless required by applicable law or agreed to in writing, software
  22719. * distributed under the License is distributed on an "AS IS" BASIS,
  22720. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22721. * See the License for the specific language governing permissions and
  22722. * limitations under the License.
  22723. */
  22724. var _polyfill = __webpack_require__(11);
  22725. var _polyfill2 = _interopRequireDefault(_polyfill);
  22726. var _features = __webpack_require__(25);
  22727. var _features2 = _interopRequireDefault(_features);
  22728. var _flvPlayer = __webpack_require__(33);
  22729. var _flvPlayer2 = _interopRequireDefault(_flvPlayer);
  22730. var _nativePlayer = __webpack_require__(46);
  22731. var _nativePlayer2 = _interopRequireDefault(_nativePlayer);
  22732. var _playerEvents = __webpack_require__(7);
  22733. var _playerEvents2 = _interopRequireDefault(_playerEvents);
  22734. var _playerErrors = __webpack_require__(17);
  22735. var _loggingControl = __webpack_require__(8);
  22736. var _loggingControl2 = _interopRequireDefault(_loggingControl);
  22737. var _exception = __webpack_require__(1);
  22738. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  22739. // here are all the interfaces
  22740. // install polyfills
  22741. _polyfill2.default.install();
  22742. // factory method
  22743. function createPlayer(mediaDataSource, optionalConfig) {
  22744. var mds = mediaDataSource;
  22745. if (mds == null || (typeof mds === 'undefined' ? 'undefined' : _typeof(mds)) !== 'object') {
  22746. throw new _exception.InvalidArgumentException('MediaDataSource must be an javascript object!');
  22747. }
  22748. if (!mds.hasOwnProperty('type')) {
  22749. throw new _exception.InvalidArgumentException('MediaDataSource must has type field to indicate video file type!');
  22750. }
  22751. switch (mds.type) {
  22752. case 'flv':
  22753. return new _flvPlayer2.default(mds, optionalConfig);
  22754. default:
  22755. return new _nativePlayer2.default(mds, optionalConfig);
  22756. }
  22757. }
  22758. // feature detection
  22759. function isSupported() {
  22760. return _features2.default.supportMSEH264Playback();
  22761. }
  22762. function getFeatureList() {
  22763. return _features2.default.getFeatureList();
  22764. }
  22765. // interfaces
  22766. var flvjs = {};
  22767. flvjs.createPlayer = createPlayer;
  22768. flvjs.isSupported = isSupported;
  22769. flvjs.getFeatureList = getFeatureList;
  22770. flvjs.Events = _playerEvents2.default;
  22771. flvjs.ErrorTypes = _playerErrors.ErrorTypes;
  22772. flvjs.ErrorDetails = _playerErrors.ErrorDetails;
  22773. flvjs.FlvPlayer = _flvPlayer2.default;
  22774. flvjs.NativePlayer = _nativePlayer2.default;
  22775. flvjs.LoggingControl = _loggingControl2.default;
  22776. Object.defineProperty(flvjs, 'version', {
  22777. enumerable: true,
  22778. get: function get() {
  22779. // replaced by browserify-versionify transform
  22780. return '__VERSION__';
  22781. }
  22782. });
  22783. exports.default = flvjs;
  22784. module.exports = exports['default'];
  22785. /***/ }),
  22786. /* 22 */
  22787. /***/ (function(module, exports, __webpack_require__) {
  22788. /* WEBPACK VAR INJECTION */(function(process, global) {/*!
  22789. * @overview es6-promise - a tiny implementation of Promises/A+.
  22790. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  22791. * @license Licensed under MIT license
  22792. * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
  22793. * @version v4.2.8+1e68dce6
  22794. */
  22795. (function (global, factory) {
  22796. true ? module.exports = factory() :
  22797. undefined;
  22798. }(this, (function () { 'use strict';
  22799. function objectOrFunction(x) {
  22800. var type = typeof x;
  22801. return x !== null && (type === 'object' || type === 'function');
  22802. }
  22803. function isFunction(x) {
  22804. return typeof x === 'function';
  22805. }
  22806. var _isArray = void 0;
  22807. if (Array.isArray) {
  22808. _isArray = Array.isArray;
  22809. } else {
  22810. _isArray = function (x) {
  22811. return Object.prototype.toString.call(x) === '[object Array]';
  22812. };
  22813. }
  22814. var isArray = _isArray;
  22815. var len = 0;
  22816. var vertxNext = void 0;
  22817. var customSchedulerFn = void 0;
  22818. var asap = function asap(callback, arg) {
  22819. queue[len] = callback;
  22820. queue[len + 1] = arg;
  22821. len += 2;
  22822. if (len === 2) {
  22823. // If len is 2, that means that we need to schedule an async flush.
  22824. // If additional callbacks are queued before the queue is flushed, they
  22825. // will be processed by this flush that we are scheduling.
  22826. if (customSchedulerFn) {
  22827. customSchedulerFn(flush);
  22828. } else {
  22829. scheduleFlush();
  22830. }
  22831. }
  22832. };
  22833. function setScheduler(scheduleFn) {
  22834. customSchedulerFn = scheduleFn;
  22835. }
  22836. function setAsap(asapFn) {
  22837. asap = asapFn;
  22838. }
  22839. var browserWindow = typeof window !== 'undefined' ? window : undefined;
  22840. var browserGlobal = browserWindow || {};
  22841. var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
  22842. var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  22843. // test for web worker but not in IE10
  22844. var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
  22845. // node
  22846. function useNextTick() {
  22847. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  22848. // see https://github.com/cujojs/when/issues/410 for details
  22849. return function () {
  22850. return process.nextTick(flush);
  22851. };
  22852. }
  22853. // vertx
  22854. function useVertxTimer() {
  22855. if (typeof vertxNext !== 'undefined') {
  22856. return function () {
  22857. vertxNext(flush);
  22858. };
  22859. }
  22860. return useSetTimeout();
  22861. }
  22862. function useMutationObserver() {
  22863. var iterations = 0;
  22864. var observer = new BrowserMutationObserver(flush);
  22865. var node = document.createTextNode('');
  22866. observer.observe(node, { characterData: true });
  22867. return function () {
  22868. node.data = iterations = ++iterations % 2;
  22869. };
  22870. }
  22871. // web worker
  22872. function useMessageChannel() {
  22873. var channel = new MessageChannel();
  22874. channel.port1.onmessage = flush;
  22875. return function () {
  22876. return channel.port2.postMessage(0);
  22877. };
  22878. }
  22879. function useSetTimeout() {
  22880. // Store setTimeout reference so es6-promise will be unaffected by
  22881. // other code modifying setTimeout (like sinon.useFakeTimers())
  22882. var globalSetTimeout = setTimeout;
  22883. return function () {
  22884. return globalSetTimeout(flush, 1);
  22885. };
  22886. }
  22887. var queue = new Array(1000);
  22888. function flush() {
  22889. for (var i = 0; i < len; i += 2) {
  22890. var callback = queue[i];
  22891. var arg = queue[i + 1];
  22892. callback(arg);
  22893. queue[i] = undefined;
  22894. queue[i + 1] = undefined;
  22895. }
  22896. len = 0;
  22897. }
  22898. function attemptVertx() {
  22899. try {
  22900. var vertx = Function('return this')().require('vertx');
  22901. vertxNext = vertx.runOnLoop || vertx.runOnContext;
  22902. return useVertxTimer();
  22903. } catch (e) {
  22904. return useSetTimeout();
  22905. }
  22906. }
  22907. var scheduleFlush = void 0;
  22908. // Decide what async method to use to triggering processing of queued callbacks:
  22909. if (isNode) {
  22910. scheduleFlush = useNextTick();
  22911. } else if (BrowserMutationObserver) {
  22912. scheduleFlush = useMutationObserver();
  22913. } else if (isWorker) {
  22914. scheduleFlush = useMessageChannel();
  22915. } else if (browserWindow === undefined && "function" === 'function') {
  22916. scheduleFlush = attemptVertx();
  22917. } else {
  22918. scheduleFlush = useSetTimeout();
  22919. }
  22920. function then(onFulfillment, onRejection) {
  22921. var parent = this;
  22922. var child = new this.constructor(noop);
  22923. if (child[PROMISE_ID] === undefined) {
  22924. makePromise(child);
  22925. }
  22926. var _state = parent._state;
  22927. if (_state) {
  22928. var callback = arguments[_state - 1];
  22929. asap(function () {
  22930. return invokeCallback(_state, child, callback, parent._result);
  22931. });
  22932. } else {
  22933. subscribe(parent, child, onFulfillment, onRejection);
  22934. }
  22935. return child;
  22936. }
  22937. /**
  22938. `Promise.resolve` returns a promise that will become resolved with the
  22939. passed `value`. It is shorthand for the following:
  22940. ```javascript
  22941. let promise = new Promise(function(resolve, reject){
  22942. resolve(1);
  22943. });
  22944. promise.then(function(value){
  22945. // value === 1
  22946. });
  22947. ```
  22948. Instead of writing the above, your code now simply becomes the following:
  22949. ```javascript
  22950. let promise = Promise.resolve(1);
  22951. promise.then(function(value){
  22952. // value === 1
  22953. });
  22954. ```
  22955. @method resolve
  22956. @static
  22957. @param {Any} value value that the returned promise will be resolved with
  22958. Useful for tooling.
  22959. @return {Promise} a promise that will become fulfilled with the given
  22960. `value`
  22961. */
  22962. function resolve$1(object) {
  22963. /*jshint validthis:true */
  22964. var Constructor = this;
  22965. if (object && typeof object === 'object' && object.constructor === Constructor) {
  22966. return object;
  22967. }
  22968. var promise = new Constructor(noop);
  22969. resolve(promise, object);
  22970. return promise;
  22971. }
  22972. var PROMISE_ID = Math.random().toString(36).substring(2);
  22973. function noop() {}
  22974. var PENDING = void 0;
  22975. var FULFILLED = 1;
  22976. var REJECTED = 2;
  22977. function selfFulfillment() {
  22978. return new TypeError("You cannot resolve a promise with itself");
  22979. }
  22980. function cannotReturnOwn() {
  22981. return new TypeError('A promises callback cannot return that same promise.');
  22982. }
  22983. function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
  22984. try {
  22985. then$$1.call(value, fulfillmentHandler, rejectionHandler);
  22986. } catch (e) {
  22987. return e;
  22988. }
  22989. }
  22990. function handleForeignThenable(promise, thenable, then$$1) {
  22991. asap(function (promise) {
  22992. var sealed = false;
  22993. var error = tryThen(then$$1, thenable, function (value) {
  22994. if (sealed) {
  22995. return;
  22996. }
  22997. sealed = true;
  22998. if (thenable !== value) {
  22999. resolve(promise, value);
  23000. } else {
  23001. fulfill(promise, value);
  23002. }
  23003. }, function (reason) {
  23004. if (sealed) {
  23005. return;
  23006. }
  23007. sealed = true;
  23008. reject(promise, reason);
  23009. }, 'Settle: ' + (promise._label || ' unknown promise'));
  23010. if (!sealed && error) {
  23011. sealed = true;
  23012. reject(promise, error);
  23013. }
  23014. }, promise);
  23015. }
  23016. function handleOwnThenable(promise, thenable) {
  23017. if (thenable._state === FULFILLED) {
  23018. fulfill(promise, thenable._result);
  23019. } else if (thenable._state === REJECTED) {
  23020. reject(promise, thenable._result);
  23021. } else {
  23022. subscribe(thenable, undefined, function (value) {
  23023. return resolve(promise, value);
  23024. }, function (reason) {
  23025. return reject(promise, reason);
  23026. });
  23027. }
  23028. }
  23029. function handleMaybeThenable(promise, maybeThenable, then$$1) {
  23030. if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
  23031. handleOwnThenable(promise, maybeThenable);
  23032. } else {
  23033. if (then$$1 === undefined) {
  23034. fulfill(promise, maybeThenable);
  23035. } else if (isFunction(then$$1)) {
  23036. handleForeignThenable(promise, maybeThenable, then$$1);
  23037. } else {
  23038. fulfill(promise, maybeThenable);
  23039. }
  23040. }
  23041. }
  23042. function resolve(promise, value) {
  23043. if (promise === value) {
  23044. reject(promise, selfFulfillment());
  23045. } else if (objectOrFunction(value)) {
  23046. var then$$1 = void 0;
  23047. try {
  23048. then$$1 = value.then;
  23049. } catch (error) {
  23050. reject(promise, error);
  23051. return;
  23052. }
  23053. handleMaybeThenable(promise, value, then$$1);
  23054. } else {
  23055. fulfill(promise, value);
  23056. }
  23057. }
  23058. function publishRejection(promise) {
  23059. if (promise._onerror) {
  23060. promise._onerror(promise._result);
  23061. }
  23062. publish(promise);
  23063. }
  23064. function fulfill(promise, value) {
  23065. if (promise._state !== PENDING) {
  23066. return;
  23067. }
  23068. promise._result = value;
  23069. promise._state = FULFILLED;
  23070. if (promise._subscribers.length !== 0) {
  23071. asap(publish, promise);
  23072. }
  23073. }
  23074. function reject(promise, reason) {
  23075. if (promise._state !== PENDING) {
  23076. return;
  23077. }
  23078. promise._state = REJECTED;
  23079. promise._result = reason;
  23080. asap(publishRejection, promise);
  23081. }
  23082. function subscribe(parent, child, onFulfillment, onRejection) {
  23083. var _subscribers = parent._subscribers;
  23084. var length = _subscribers.length;
  23085. parent._onerror = null;
  23086. _subscribers[length] = child;
  23087. _subscribers[length + FULFILLED] = onFulfillment;
  23088. _subscribers[length + REJECTED] = onRejection;
  23089. if (length === 0 && parent._state) {
  23090. asap(publish, parent);
  23091. }
  23092. }
  23093. function publish(promise) {
  23094. var subscribers = promise._subscribers;
  23095. var settled = promise._state;
  23096. if (subscribers.length === 0) {
  23097. return;
  23098. }
  23099. var child = void 0,
  23100. callback = void 0,
  23101. detail = promise._result;
  23102. for (var i = 0; i < subscribers.length; i += 3) {
  23103. child = subscribers[i];
  23104. callback = subscribers[i + settled];
  23105. if (child) {
  23106. invokeCallback(settled, child, callback, detail);
  23107. } else {
  23108. callback(detail);
  23109. }
  23110. }
  23111. promise._subscribers.length = 0;
  23112. }
  23113. function invokeCallback(settled, promise, callback, detail) {
  23114. var hasCallback = isFunction(callback),
  23115. value = void 0,
  23116. error = void 0,
  23117. succeeded = true;
  23118. if (hasCallback) {
  23119. try {
  23120. value = callback(detail);
  23121. } catch (e) {
  23122. succeeded = false;
  23123. error = e;
  23124. }
  23125. if (promise === value) {
  23126. reject(promise, cannotReturnOwn());
  23127. return;
  23128. }
  23129. } else {
  23130. value = detail;
  23131. }
  23132. if (promise._state !== PENDING) {
  23133. // noop
  23134. } else if (hasCallback && succeeded) {
  23135. resolve(promise, value);
  23136. } else if (succeeded === false) {
  23137. reject(promise, error);
  23138. } else if (settled === FULFILLED) {
  23139. fulfill(promise, value);
  23140. } else if (settled === REJECTED) {
  23141. reject(promise, value);
  23142. }
  23143. }
  23144. function initializePromise(promise, resolver) {
  23145. try {
  23146. resolver(function resolvePromise(value) {
  23147. resolve(promise, value);
  23148. }, function rejectPromise(reason) {
  23149. reject(promise, reason);
  23150. });
  23151. } catch (e) {
  23152. reject(promise, e);
  23153. }
  23154. }
  23155. var id = 0;
  23156. function nextId() {
  23157. return id++;
  23158. }
  23159. function makePromise(promise) {
  23160. promise[PROMISE_ID] = id++;
  23161. promise._state = undefined;
  23162. promise._result = undefined;
  23163. promise._subscribers = [];
  23164. }
  23165. function validationError() {
  23166. return new Error('Array Methods must be provided an Array');
  23167. }
  23168. var Enumerator = function () {
  23169. function Enumerator(Constructor, input) {
  23170. this._instanceConstructor = Constructor;
  23171. this.promise = new Constructor(noop);
  23172. if (!this.promise[PROMISE_ID]) {
  23173. makePromise(this.promise);
  23174. }
  23175. if (isArray(input)) {
  23176. this.length = input.length;
  23177. this._remaining = input.length;
  23178. this._result = new Array(this.length);
  23179. if (this.length === 0) {
  23180. fulfill(this.promise, this._result);
  23181. } else {
  23182. this.length = this.length || 0;
  23183. this._enumerate(input);
  23184. if (this._remaining === 0) {
  23185. fulfill(this.promise, this._result);
  23186. }
  23187. }
  23188. } else {
  23189. reject(this.promise, validationError());
  23190. }
  23191. }
  23192. Enumerator.prototype._enumerate = function _enumerate(input) {
  23193. for (var i = 0; this._state === PENDING && i < input.length; i++) {
  23194. this._eachEntry(input[i], i);
  23195. }
  23196. };
  23197. Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
  23198. var c = this._instanceConstructor;
  23199. var resolve$$1 = c.resolve;
  23200. if (resolve$$1 === resolve$1) {
  23201. var _then = void 0;
  23202. var error = void 0;
  23203. var didError = false;
  23204. try {
  23205. _then = entry.then;
  23206. } catch (e) {
  23207. didError = true;
  23208. error = e;
  23209. }
  23210. if (_then === then && entry._state !== PENDING) {
  23211. this._settledAt(entry._state, i, entry._result);
  23212. } else if (typeof _then !== 'function') {
  23213. this._remaining--;
  23214. this._result[i] = entry;
  23215. } else if (c === Promise$1) {
  23216. var promise = new c(noop);
  23217. if (didError) {
  23218. reject(promise, error);
  23219. } else {
  23220. handleMaybeThenable(promise, entry, _then);
  23221. }
  23222. this._willSettleAt(promise, i);
  23223. } else {
  23224. this._willSettleAt(new c(function (resolve$$1) {
  23225. return resolve$$1(entry);
  23226. }), i);
  23227. }
  23228. } else {
  23229. this._willSettleAt(resolve$$1(entry), i);
  23230. }
  23231. };
  23232. Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
  23233. var promise = this.promise;
  23234. if (promise._state === PENDING) {
  23235. this._remaining--;
  23236. if (state === REJECTED) {
  23237. reject(promise, value);
  23238. } else {
  23239. this._result[i] = value;
  23240. }
  23241. }
  23242. if (this._remaining === 0) {
  23243. fulfill(promise, this._result);
  23244. }
  23245. };
  23246. Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
  23247. var enumerator = this;
  23248. subscribe(promise, undefined, function (value) {
  23249. return enumerator._settledAt(FULFILLED, i, value);
  23250. }, function (reason) {
  23251. return enumerator._settledAt(REJECTED, i, reason);
  23252. });
  23253. };
  23254. return Enumerator;
  23255. }();
  23256. /**
  23257. `Promise.all` accepts an array of promises, and returns a new promise which
  23258. is fulfilled with an array of fulfillment values for the passed promises, or
  23259. rejected with the reason of the first passed promise to be rejected. It casts all
  23260. elements of the passed iterable to promises as it runs this algorithm.
  23261. Example:
  23262. ```javascript
  23263. let promise1 = resolve(1);
  23264. let promise2 = resolve(2);
  23265. let promise3 = resolve(3);
  23266. let promises = [ promise1, promise2, promise3 ];
  23267. Promise.all(promises).then(function(array){
  23268. // The array here would be [ 1, 2, 3 ];
  23269. });
  23270. ```
  23271. If any of the `promises` given to `all` are rejected, the first promise
  23272. that is rejected will be given as an argument to the returned promises's
  23273. rejection handler. For example:
  23274. Example:
  23275. ```javascript
  23276. let promise1 = resolve(1);
  23277. let promise2 = reject(new Error("2"));
  23278. let promise3 = reject(new Error("3"));
  23279. let promises = [ promise1, promise2, promise3 ];
  23280. Promise.all(promises).then(function(array){
  23281. // Code here never runs because there are rejected promises!
  23282. }, function(error) {
  23283. // error.message === "2"
  23284. });
  23285. ```
  23286. @method all
  23287. @static
  23288. @param {Array} entries array of promises
  23289. @param {String} label optional string for labeling the promise.
  23290. Useful for tooling.
  23291. @return {Promise} promise that is fulfilled when all `promises` have been
  23292. fulfilled, or rejected if any of them become rejected.
  23293. @static
  23294. */
  23295. function all(entries) {
  23296. return new Enumerator(this, entries).promise;
  23297. }
  23298. /**
  23299. `Promise.race` returns a new promise which is settled in the same way as the
  23300. first passed promise to settle.
  23301. Example:
  23302. ```javascript
  23303. let promise1 = new Promise(function(resolve, reject){
  23304. setTimeout(function(){
  23305. resolve('promise 1');
  23306. }, 200);
  23307. });
  23308. let promise2 = new Promise(function(resolve, reject){
  23309. setTimeout(function(){
  23310. resolve('promise 2');
  23311. }, 100);
  23312. });
  23313. Promise.race([promise1, promise2]).then(function(result){
  23314. // result === 'promise 2' because it was resolved before promise1
  23315. // was resolved.
  23316. });
  23317. ```
  23318. `Promise.race` is deterministic in that only the state of the first
  23319. settled promise matters. For example, even if other promises given to the
  23320. `promises` array argument are resolved, but the first settled promise has
  23321. become rejected before the other promises became fulfilled, the returned
  23322. promise will become rejected:
  23323. ```javascript
  23324. let promise1 = new Promise(function(resolve, reject){
  23325. setTimeout(function(){
  23326. resolve('promise 1');
  23327. }, 200);
  23328. });
  23329. let promise2 = new Promise(function(resolve, reject){
  23330. setTimeout(function(){
  23331. reject(new Error('promise 2'));
  23332. }, 100);
  23333. });
  23334. Promise.race([promise1, promise2]).then(function(result){
  23335. // Code here never runs
  23336. }, function(reason){
  23337. // reason.message === 'promise 2' because promise 2 became rejected before
  23338. // promise 1 became fulfilled
  23339. });
  23340. ```
  23341. An example real-world use case is implementing timeouts:
  23342. ```javascript
  23343. Promise.race([ajax('foo.json'), timeout(5000)])
  23344. ```
  23345. @method race
  23346. @static
  23347. @param {Array} promises array of promises to observe
  23348. Useful for tooling.
  23349. @return {Promise} a promise which settles in the same way as the first passed
  23350. promise to settle.
  23351. */
  23352. function race(entries) {
  23353. /*jshint validthis:true */
  23354. var Constructor = this;
  23355. if (!isArray(entries)) {
  23356. return new Constructor(function (_, reject) {
  23357. return reject(new TypeError('You must pass an array to race.'));
  23358. });
  23359. } else {
  23360. return new Constructor(function (resolve, reject) {
  23361. var length = entries.length;
  23362. for (var i = 0; i < length; i++) {
  23363. Constructor.resolve(entries[i]).then(resolve, reject);
  23364. }
  23365. });
  23366. }
  23367. }
  23368. /**
  23369. `Promise.reject` returns a promise rejected with the passed `reason`.
  23370. It is shorthand for the following:
  23371. ```javascript
  23372. let promise = new Promise(function(resolve, reject){
  23373. reject(new Error('WHOOPS'));
  23374. });
  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. Instead of writing the above, your code now simply becomes the following:
  23382. ```javascript
  23383. let promise = Promise.reject(new Error('WHOOPS'));
  23384. promise.then(function(value){
  23385. // Code here doesn't run because the promise is rejected!
  23386. }, function(reason){
  23387. // reason.message === 'WHOOPS'
  23388. });
  23389. ```
  23390. @method reject
  23391. @static
  23392. @param {Any} reason value that the returned promise will be rejected with.
  23393. Useful for tooling.
  23394. @return {Promise} a promise rejected with the given `reason`.
  23395. */
  23396. function reject$1(reason) {
  23397. /*jshint validthis:true */
  23398. var Constructor = this;
  23399. var promise = new Constructor(noop);
  23400. reject(promise, reason);
  23401. return promise;
  23402. }
  23403. function needsResolver() {
  23404. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  23405. }
  23406. function needsNew() {
  23407. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  23408. }
  23409. /**
  23410. Promise objects represent the eventual result of an asynchronous operation. The
  23411. primary way of interacting with a promise is through its `then` method, which
  23412. registers callbacks to receive either a promise's eventual value or the reason
  23413. why the promise cannot be fulfilled.
  23414. Terminology
  23415. -----------
  23416. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  23417. - `thenable` is an object or function that defines a `then` method.
  23418. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  23419. - `exception` is a value that is thrown using the throw statement.
  23420. - `reason` is a value that indicates why a promise was rejected.
  23421. - `settled` the final resting state of a promise, fulfilled or rejected.
  23422. A promise can be in one of three states: pending, fulfilled, or rejected.
  23423. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  23424. state. Promises that are rejected have a rejection reason and are in the
  23425. rejected state. A fulfillment value is never a thenable.
  23426. Promises can also be said to *resolve* a value. If this value is also a
  23427. promise, then the original promise's settled state will match the value's
  23428. settled state. So a promise that *resolves* a promise that rejects will
  23429. itself reject, and a promise that *resolves* a promise that fulfills will
  23430. itself fulfill.
  23431. Basic Usage:
  23432. ------------
  23433. ```js
  23434. let promise = new Promise(function(resolve, reject) {
  23435. // on success
  23436. resolve(value);
  23437. // on failure
  23438. reject(reason);
  23439. });
  23440. promise.then(function(value) {
  23441. // on fulfillment
  23442. }, function(reason) {
  23443. // on rejection
  23444. });
  23445. ```
  23446. Advanced Usage:
  23447. ---------------
  23448. Promises shine when abstracting away asynchronous interactions such as
  23449. `XMLHttpRequest`s.
  23450. ```js
  23451. function getJSON(url) {
  23452. return new Promise(function(resolve, reject){
  23453. let xhr = new XMLHttpRequest();
  23454. xhr.open('GET', url);
  23455. xhr.onreadystatechange = handler;
  23456. xhr.responseType = 'json';
  23457. xhr.setRequestHeader('Accept', 'application/json');
  23458. xhr.send();
  23459. function handler() {
  23460. if (this.readyState === this.DONE) {
  23461. if (this.status === 200) {
  23462. resolve(this.response);
  23463. } else {
  23464. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  23465. }
  23466. }
  23467. };
  23468. });
  23469. }
  23470. getJSON('/posts.json').then(function(json) {
  23471. // on fulfillment
  23472. }, function(reason) {
  23473. // on rejection
  23474. });
  23475. ```
  23476. Unlike callbacks, promises are great composable primitives.
  23477. ```js
  23478. Promise.all([
  23479. getJSON('/posts'),
  23480. getJSON('/comments')
  23481. ]).then(function(values){
  23482. values[0] // => postsJSON
  23483. values[1] // => commentsJSON
  23484. return values;
  23485. });
  23486. ```
  23487. @class Promise
  23488. @param {Function} resolver
  23489. Useful for tooling.
  23490. @constructor
  23491. */
  23492. var Promise$1 = function () {
  23493. function Promise(resolver) {
  23494. this[PROMISE_ID] = nextId();
  23495. this._result = this._state = undefined;
  23496. this._subscribers = [];
  23497. if (noop !== resolver) {
  23498. typeof resolver !== 'function' && needsResolver();
  23499. this instanceof Promise ? initializePromise(this, resolver) : needsNew();
  23500. }
  23501. }
  23502. /**
  23503. The primary way of interacting with a promise is through its `then` method,
  23504. which registers callbacks to receive either a promise's eventual value or the
  23505. reason why the promise cannot be fulfilled.
  23506. ```js
  23507. findUser().then(function(user){
  23508. // user is available
  23509. }, function(reason){
  23510. // user is unavailable, and you are given the reason why
  23511. });
  23512. ```
  23513. Chaining
  23514. --------
  23515. The return value of `then` is itself a promise. This second, 'downstream'
  23516. promise is resolved with the return value of the first promise's fulfillment
  23517. or rejection handler, or rejected if the handler throws an exception.
  23518. ```js
  23519. findUser().then(function (user) {
  23520. return user.name;
  23521. }, function (reason) {
  23522. return 'default name';
  23523. }).then(function (userName) {
  23524. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  23525. // will be `'default name'`
  23526. });
  23527. findUser().then(function (user) {
  23528. throw new Error('Found user, but still unhappy');
  23529. }, function (reason) {
  23530. throw new Error('`findUser` rejected and we're unhappy');
  23531. }).then(function (value) {
  23532. // never reached
  23533. }, function (reason) {
  23534. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  23535. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  23536. });
  23537. ```
  23538. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  23539. ```js
  23540. findUser().then(function (user) {
  23541. throw new PedagogicalException('Upstream error');
  23542. }).then(function (value) {
  23543. // never reached
  23544. }).then(function (value) {
  23545. // never reached
  23546. }, function (reason) {
  23547. // The `PedgagocialException` is propagated all the way down to here
  23548. });
  23549. ```
  23550. Assimilation
  23551. ------------
  23552. Sometimes the value you want to propagate to a downstream promise can only be
  23553. retrieved asynchronously. This can be achieved by returning a promise in the
  23554. fulfillment or rejection handler. The downstream promise will then be pending
  23555. until the returned promise is settled. This is called *assimilation*.
  23556. ```js
  23557. findUser().then(function (user) {
  23558. return findCommentsByAuthor(user);
  23559. }).then(function (comments) {
  23560. // The user's comments are now available
  23561. });
  23562. ```
  23563. If the assimliated promise rejects, then the downstream promise will also reject.
  23564. ```js
  23565. findUser().then(function (user) {
  23566. return findCommentsByAuthor(user);
  23567. }).then(function (comments) {
  23568. // If `findCommentsByAuthor` fulfills, we'll have the value here
  23569. }, function (reason) {
  23570. // If `findCommentsByAuthor` rejects, we'll have the reason here
  23571. });
  23572. ```
  23573. Simple Example
  23574. --------------
  23575. Synchronous Example
  23576. ```javascript
  23577. let result;
  23578. try {
  23579. result = findResult();
  23580. // success
  23581. } catch(reason) {
  23582. // failure
  23583. }
  23584. ```
  23585. Errback Example
  23586. ```js
  23587. findResult(function(result, err){
  23588. if (err) {
  23589. // failure
  23590. } else {
  23591. // success
  23592. }
  23593. });
  23594. ```
  23595. Promise Example;
  23596. ```javascript
  23597. findResult().then(function(result){
  23598. // success
  23599. }, function(reason){
  23600. // failure
  23601. });
  23602. ```
  23603. Advanced Example
  23604. --------------
  23605. Synchronous Example
  23606. ```javascript
  23607. let author, books;
  23608. try {
  23609. author = findAuthor();
  23610. books = findBooksByAuthor(author);
  23611. // success
  23612. } catch(reason) {
  23613. // failure
  23614. }
  23615. ```
  23616. Errback Example
  23617. ```js
  23618. function foundBooks(books) {
  23619. }
  23620. function failure(reason) {
  23621. }
  23622. findAuthor(function(author, err){
  23623. if (err) {
  23624. failure(err);
  23625. // failure
  23626. } else {
  23627. try {
  23628. findBoooksByAuthor(author, function(books, err) {
  23629. if (err) {
  23630. failure(err);
  23631. } else {
  23632. try {
  23633. foundBooks(books);
  23634. } catch(reason) {
  23635. failure(reason);
  23636. }
  23637. }
  23638. });
  23639. } catch(error) {
  23640. failure(err);
  23641. }
  23642. // success
  23643. }
  23644. });
  23645. ```
  23646. Promise Example;
  23647. ```javascript
  23648. findAuthor().
  23649. then(findBooksByAuthor).
  23650. then(function(books){
  23651. // found books
  23652. }).catch(function(reason){
  23653. // something went wrong
  23654. });
  23655. ```
  23656. @method then
  23657. @param {Function} onFulfilled
  23658. @param {Function} onRejected
  23659. Useful for tooling.
  23660. @return {Promise}
  23661. */
  23662. /**
  23663. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  23664. as the catch block of a try/catch statement.
  23665. ```js
  23666. function findAuthor(){
  23667. throw new Error('couldn't find that author');
  23668. }
  23669. // synchronous
  23670. try {
  23671. findAuthor();
  23672. } catch(reason) {
  23673. // something went wrong
  23674. }
  23675. // async with promises
  23676. findAuthor().catch(function(reason){
  23677. // something went wrong
  23678. });
  23679. ```
  23680. @method catch
  23681. @param {Function} onRejection
  23682. Useful for tooling.
  23683. @return {Promise}
  23684. */
  23685. Promise.prototype.catch = function _catch(onRejection) {
  23686. return this.then(null, onRejection);
  23687. };
  23688. /**
  23689. `finally` will be invoked regardless of the promise's fate just as native
  23690. try/catch/finally behaves
  23691. Synchronous example:
  23692. ```js
  23693. findAuthor() {
  23694. if (Math.random() > 0.5) {
  23695. throw new Error();
  23696. }
  23697. return new Author();
  23698. }
  23699. try {
  23700. return findAuthor(); // succeed or fail
  23701. } catch(error) {
  23702. return findOtherAuther();
  23703. } finally {
  23704. // always runs
  23705. // doesn't affect the return value
  23706. }
  23707. ```
  23708. Asynchronous example:
  23709. ```js
  23710. findAuthor().catch(function(reason){
  23711. return findOtherAuther();
  23712. }).finally(function(){
  23713. // author was either found, or not
  23714. });
  23715. ```
  23716. @method finally
  23717. @param {Function} callback
  23718. @return {Promise}
  23719. */
  23720. Promise.prototype.finally = function _finally(callback) {
  23721. var promise = this;
  23722. var constructor = promise.constructor;
  23723. if (isFunction(callback)) {
  23724. return promise.then(function (value) {
  23725. return constructor.resolve(callback()).then(function () {
  23726. return value;
  23727. });
  23728. }, function (reason) {
  23729. return constructor.resolve(callback()).then(function () {
  23730. throw reason;
  23731. });
  23732. });
  23733. }
  23734. return promise.then(callback, callback);
  23735. };
  23736. return Promise;
  23737. }();
  23738. Promise$1.prototype.then = then;
  23739. Promise$1.all = all;
  23740. Promise$1.race = race;
  23741. Promise$1.resolve = resolve$1;
  23742. Promise$1.reject = reject$1;
  23743. Promise$1._setScheduler = setScheduler;
  23744. Promise$1._setAsap = setAsap;
  23745. Promise$1._asap = asap;
  23746. /*global self*/
  23747. function polyfill() {
  23748. var local = void 0;
  23749. if (typeof global !== 'undefined') {
  23750. local = global;
  23751. } else if (typeof self !== 'undefined') {
  23752. local = self;
  23753. } else {
  23754. try {
  23755. local = Function('return this')();
  23756. } catch (e) {
  23757. throw new Error('polyfill failed because global object is unavailable in this environment');
  23758. }
  23759. }
  23760. var P = local.Promise;
  23761. if (P) {
  23762. var promiseToString = null;
  23763. try {
  23764. promiseToString = Object.prototype.toString.call(P.resolve());
  23765. } catch (e) {
  23766. // silently ignored
  23767. }
  23768. if (promiseToString === '[object Promise]' && !P.cast) {
  23769. return;
  23770. }
  23771. }
  23772. local.Promise = Promise$1;
  23773. }
  23774. // Strange compat..
  23775. Promise$1.polyfill = polyfill;
  23776. Promise$1.Promise = Promise$1;
  23777. return Promise$1;
  23778. })));
  23779. //# sourceMappingURL=es6-promise.map
  23780. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(23), __webpack_require__(24)))
  23781. /***/ }),
  23782. /* 23 */
  23783. /***/ (function(module, exports) {
  23784. // shim for using process in browser
  23785. var process = module.exports = {};
  23786. // cached from whatever global is present so that test runners that stub it
  23787. // don't break things. But we need to wrap it in a try catch in case it is
  23788. // wrapped in strict mode code which doesn't define any globals. It's inside a
  23789. // function because try/catches deoptimize in certain engines.
  23790. var cachedSetTimeout;
  23791. var cachedClearTimeout;
  23792. function defaultSetTimout() {
  23793. throw new Error('setTimeout has not been defined');
  23794. }
  23795. function defaultClearTimeout () {
  23796. throw new Error('clearTimeout has not been defined');
  23797. }
  23798. (function () {
  23799. try {
  23800. if (typeof setTimeout === 'function') {
  23801. cachedSetTimeout = setTimeout;
  23802. } else {
  23803. cachedSetTimeout = defaultSetTimout;
  23804. }
  23805. } catch (e) {
  23806. cachedSetTimeout = defaultSetTimout;
  23807. }
  23808. try {
  23809. if (typeof clearTimeout === 'function') {
  23810. cachedClearTimeout = clearTimeout;
  23811. } else {
  23812. cachedClearTimeout = defaultClearTimeout;
  23813. }
  23814. } catch (e) {
  23815. cachedClearTimeout = defaultClearTimeout;
  23816. }
  23817. } ())
  23818. function runTimeout(fun) {
  23819. if (cachedSetTimeout === setTimeout) {
  23820. //normal enviroments in sane situations
  23821. return setTimeout(fun, 0);
  23822. }
  23823. // if setTimeout wasn't available but was latter defined
  23824. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  23825. cachedSetTimeout = setTimeout;
  23826. return setTimeout(fun, 0);
  23827. }
  23828. try {
  23829. // when when somebody has screwed with setTimeout but no I.E. maddness
  23830. return cachedSetTimeout(fun, 0);
  23831. } catch(e){
  23832. try {
  23833. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  23834. return cachedSetTimeout.call(null, fun, 0);
  23835. } catch(e){
  23836. // 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
  23837. return cachedSetTimeout.call(this, fun, 0);
  23838. }
  23839. }
  23840. }
  23841. function runClearTimeout(marker) {
  23842. if (cachedClearTimeout === clearTimeout) {
  23843. //normal enviroments in sane situations
  23844. return clearTimeout(marker);
  23845. }
  23846. // if clearTimeout wasn't available but was latter defined
  23847. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  23848. cachedClearTimeout = clearTimeout;
  23849. return clearTimeout(marker);
  23850. }
  23851. try {
  23852. // when when somebody has screwed with setTimeout but no I.E. maddness
  23853. return cachedClearTimeout(marker);
  23854. } catch (e){
  23855. try {
  23856. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  23857. return cachedClearTimeout.call(null, marker);
  23858. } catch (e){
  23859. // 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.
  23860. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  23861. return cachedClearTimeout.call(this, marker);
  23862. }
  23863. }
  23864. }
  23865. var queue = [];
  23866. var draining = false;
  23867. var currentQueue;
  23868. var queueIndex = -1;
  23869. function cleanUpNextTick() {
  23870. if (!draining || !currentQueue) {
  23871. return;
  23872. }
  23873. draining = false;
  23874. if (currentQueue.length) {
  23875. queue = currentQueue.concat(queue);
  23876. } else {
  23877. queueIndex = -1;
  23878. }
  23879. if (queue.length) {
  23880. drainQueue();
  23881. }
  23882. }
  23883. function drainQueue() {
  23884. if (draining) {
  23885. return;
  23886. }
  23887. var timeout = runTimeout(cleanUpNextTick);
  23888. draining = true;
  23889. var len = queue.length;
  23890. while(len) {
  23891. currentQueue = queue;
  23892. queue = [];
  23893. while (++queueIndex < len) {
  23894. if (currentQueue) {
  23895. currentQueue[queueIndex].run();
  23896. }
  23897. }
  23898. queueIndex = -1;
  23899. len = queue.length;
  23900. }
  23901. currentQueue = null;
  23902. draining = false;
  23903. runClearTimeout(timeout);
  23904. }
  23905. process.nextTick = function (fun) {
  23906. var args = new Array(arguments.length - 1);
  23907. if (arguments.length > 1) {
  23908. for (var i = 1; i < arguments.length; i++) {
  23909. args[i - 1] = arguments[i];
  23910. }
  23911. }
  23912. queue.push(new Item(fun, args));
  23913. if (queue.length === 1 && !draining) {
  23914. runTimeout(drainQueue);
  23915. }
  23916. };
  23917. // v8 likes predictible objects
  23918. function Item(fun, array) {
  23919. this.fun = fun;
  23920. this.array = array;
  23921. }
  23922. Item.prototype.run = function () {
  23923. this.fun.apply(null, this.array);
  23924. };
  23925. process.title = 'browser';
  23926. process.browser = true;
  23927. process.env = {};
  23928. process.argv = [];
  23929. process.version = ''; // empty string to avoid regexp issues
  23930. process.versions = {};
  23931. function noop() {}
  23932. process.on = noop;
  23933. process.addListener = noop;
  23934. process.once = noop;
  23935. process.off = noop;
  23936. process.removeListener = noop;
  23937. process.removeAllListeners = noop;
  23938. process.emit = noop;
  23939. process.prependListener = noop;
  23940. process.prependOnceListener = noop;
  23941. process.listeners = function (name) { return [] }
  23942. process.binding = function (name) {
  23943. throw new Error('process.binding is not supported');
  23944. };
  23945. process.cwd = function () { return '/' };
  23946. process.chdir = function (dir) {
  23947. throw new Error('process.chdir is not supported');
  23948. };
  23949. process.umask = function() { return 0; };
  23950. /***/ }),
  23951. /* 24 */
  23952. /***/ (function(module, exports) {
  23953. var g;
  23954. // This works in non-strict mode
  23955. g = (function() {
  23956. return this;
  23957. })();
  23958. try {
  23959. // This works if eval is allowed (see CSP)
  23960. g = g || new Function("return this")();
  23961. } catch (e) {
  23962. // This works if the window reference is available
  23963. if (typeof window === "object") g = window;
  23964. }
  23965. // g can still be undefined, but nothing to do about it...
  23966. // We return undefined, instead of nothing here, so it's
  23967. // easier to handle this case. if(!global) { ...}
  23968. module.exports = g;
  23969. /***/ }),
  23970. /* 25 */
  23971. /***/ (function(module, exports, __webpack_require__) {
  23972. "use strict";
  23973. Object.defineProperty(exports, "__esModule", {
  23974. value: true
  23975. });
  23976. 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; }; }(); /*
  23977. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  23978. *
  23979. * @author zheng qian <xqq@xqq.im>
  23980. *
  23981. * Licensed under the Apache License, Version 2.0 (the "License");
  23982. * you may not use this file except in compliance with the License.
  23983. * You may obtain a copy of the License at
  23984. *
  23985. * http://www.apache.org/licenses/LICENSE-2.0
  23986. *
  23987. * Unless required by applicable law or agreed to in writing, software
  23988. * distributed under the License is distributed on an "AS IS" BASIS,
  23989. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23990. * See the License for the specific language governing permissions and
  23991. * limitations under the License.
  23992. */
  23993. var _ioController = __webpack_require__(12);
  23994. var _ioController2 = _interopRequireDefault(_ioController);
  23995. var _config = __webpack_require__(6);
  23996. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  23997. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  23998. var Features = function () {
  23999. function Features() {
  24000. _classCallCheck(this, Features);
  24001. }
  24002. _createClass(Features, null, [{
  24003. key: 'supportMSEH264Playback',
  24004. value: function supportMSEH264Playback() {
  24005. return window.MediaSource && window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
  24006. }
  24007. }, {
  24008. key: 'supportNetworkStreamIO',
  24009. value: function supportNetworkStreamIO() {
  24010. var ioctl = new _ioController2.default({}, (0, _config.createDefaultConfig)());
  24011. var loaderType = ioctl.loaderType;
  24012. ioctl.destroy();
  24013. return loaderType == 'fetch-stream-loader' || loaderType == 'xhr-moz-chunked-loader';
  24014. }
  24015. }, {
  24016. key: 'getNetworkLoaderTypeName',
  24017. value: function getNetworkLoaderTypeName() {
  24018. var ioctl = new _ioController2.default({}, (0, _config.createDefaultConfig)());
  24019. var loaderType = ioctl.loaderType;
  24020. ioctl.destroy();
  24021. return loaderType;
  24022. }
  24023. }, {
  24024. key: 'supportNativeMediaPlayback',
  24025. value: function supportNativeMediaPlayback(mimeType) {
  24026. if (Features.videoElement == undefined) {
  24027. Features.videoElement = window.document.createElement('video');
  24028. }
  24029. var canPlay = Features.videoElement.canPlayType(mimeType);
  24030. return canPlay === 'probably' || canPlay == 'maybe';
  24031. }
  24032. }, {
  24033. key: 'getFeatureList',
  24034. value: function getFeatureList() {
  24035. var features = {
  24036. mseFlvPlayback: false,
  24037. mseLiveFlvPlayback: false,
  24038. networkStreamIO: false,
  24039. networkLoaderName: '',
  24040. nativeMP4H264Playback: false,
  24041. nativeWebmVP8Playback: false,
  24042. nativeWebmVP9Playback: false
  24043. };
  24044. features.mseFlvPlayback = Features.supportMSEH264Playback();
  24045. features.networkStreamIO = Features.supportNetworkStreamIO();
  24046. features.networkLoaderName = Features.getNetworkLoaderTypeName();
  24047. features.mseLiveFlvPlayback = features.mseFlvPlayback && features.networkStreamIO;
  24048. features.nativeMP4H264Playback = Features.supportNativeMediaPlayback('video/mp4; codecs="avc1.42001E, mp4a.40.2"');
  24049. features.nativeWebmVP8Playback = Features.supportNativeMediaPlayback('video/webm; codecs="vp8.0, vorbis"');
  24050. features.nativeWebmVP9Playback = Features.supportNativeMediaPlayback('video/webm; codecs="vp9"');
  24051. return features;
  24052. }
  24053. }]);
  24054. return Features;
  24055. }();
  24056. exports.default = Features;
  24057. module.exports = exports['default'];
  24058. /***/ }),
  24059. /* 26 */
  24060. /***/ (function(module, exports, __webpack_require__) {
  24061. "use strict";
  24062. Object.defineProperty(exports, "__esModule", {
  24063. value: true
  24064. });
  24065. 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; };
  24066. 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); } };
  24067. 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; }; }();
  24068. var _logger = __webpack_require__(0);
  24069. var _logger2 = _interopRequireDefault(_logger);
  24070. var _browser = __webpack_require__(4);
  24071. var _browser2 = _interopRequireDefault(_browser);
  24072. var _loader = __webpack_require__(3);
  24073. var _exception = __webpack_require__(1);
  24074. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24075. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  24076. 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; }
  24077. 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; } /*
  24078. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  24079. *
  24080. * @author zheng qian <xqq@xqq.im>
  24081. *
  24082. * Licensed under the Apache License, Version 2.0 (the "License");
  24083. * you may not use this file except in compliance with the License.
  24084. * You may obtain a copy of the License at
  24085. *
  24086. * http://www.apache.org/licenses/LICENSE-2.0
  24087. *
  24088. * Unless required by applicable law or agreed to in writing, software
  24089. * distributed under the License is distributed on an "AS IS" BASIS,
  24090. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24091. * See the License for the specific language governing permissions and
  24092. * limitations under the License.
  24093. */
  24094. /* fetch + stream IO loader. Currently working on chrome 43+.
  24095. * fetch provides a better alternative http API to XMLHttpRequest
  24096. *
  24097. * fetch spec https://fetch.spec.whatwg.org/
  24098. * stream spec https://streams.spec.whatwg.org/
  24099. */
  24100. var FetchStreamLoader = function (_BaseLoader) {
  24101. _inherits(FetchStreamLoader, _BaseLoader);
  24102. _createClass(FetchStreamLoader, null, [{
  24103. key: 'isSupported',
  24104. value: function isSupported() {
  24105. try {
  24106. // fetch + stream is broken on Microsoft Edge. Disable before build 15048.
  24107. // see https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8196907/
  24108. // Fixed in Jan 10, 2017. Build 15048+ removed from blacklist.
  24109. var isWorkWellEdge = _browser2.default.msedge && _browser2.default.version.minor >= 15048;
  24110. var browserNotBlacklisted = _browser2.default.msedge ? isWorkWellEdge : true;
  24111. return self.fetch && self.ReadableStream && browserNotBlacklisted;
  24112. } catch (e) {
  24113. return false;
  24114. }
  24115. }
  24116. }]);
  24117. function FetchStreamLoader(seekHandler, config) {
  24118. _classCallCheck(this, FetchStreamLoader);
  24119. var _this = _possibleConstructorReturn(this, (FetchStreamLoader.__proto__ || Object.getPrototypeOf(FetchStreamLoader)).call(this, 'fetch-stream-loader'));
  24120. _this.TAG = 'FetchStreamLoader';
  24121. _this._seekHandler = seekHandler;
  24122. _this._config = config;
  24123. _this._needStash = true;
  24124. _this._requestAbort = false;
  24125. _this._contentLength = null;
  24126. _this._receivedLength = 0;
  24127. return _this;
  24128. }
  24129. _createClass(FetchStreamLoader, [{
  24130. key: 'destroy',
  24131. value: function destroy() {
  24132. if (this.isWorking()) {
  24133. this.abort();
  24134. }
  24135. _get(FetchStreamLoader.prototype.__proto__ || Object.getPrototypeOf(FetchStreamLoader.prototype), 'destroy', this).call(this);
  24136. }
  24137. }, {
  24138. key: 'open',
  24139. value: function open(dataSource, range) {
  24140. var _this2 = this;
  24141. this._dataSource = dataSource;
  24142. this._range = range;
  24143. var sourceURL = dataSource.url;
  24144. if (this._config.reuseRedirectedURL && dataSource.redirectedURL != undefined) {
  24145. sourceURL = dataSource.redirectedURL;
  24146. }
  24147. var seekConfig = this._seekHandler.getConfig(sourceURL, range);
  24148. var headers = new self.Headers();
  24149. if (_typeof(seekConfig.headers) === 'object') {
  24150. var configHeaders = seekConfig.headers;
  24151. for (var key in configHeaders) {
  24152. if (configHeaders.hasOwnProperty(key)) {
  24153. headers.append(key, configHeaders[key]);
  24154. }
  24155. }
  24156. }
  24157. var params = {
  24158. method: 'GET',
  24159. headers: headers,
  24160. mode: 'cors',
  24161. cache: 'default',
  24162. // The default policy of Fetch API in the whatwg standard
  24163. // Safari incorrectly indicates 'no-referrer' as default policy, fuck it
  24164. referrerPolicy: 'no-referrer-when-downgrade'
  24165. };
  24166. // cors is enabled by default
  24167. if (dataSource.cors === false) {
  24168. // no-cors means 'disregard cors policy', which can only be used in ServiceWorker
  24169. params.mode = 'same-origin';
  24170. }
  24171. // withCredentials is disabled by default
  24172. if (dataSource.withCredentials) {
  24173. params.credentials = 'include';
  24174. }
  24175. // referrerPolicy from config
  24176. if (dataSource.referrerPolicy) {
  24177. params.referrerPolicy = dataSource.referrerPolicy;
  24178. }
  24179. this._status = _loader.LoaderStatus.kConnecting;
  24180. self.fetch(seekConfig.url, params).then(function (res) {
  24181. if (_this2._requestAbort) {
  24182. _this2._requestAbort = false;
  24183. _this2._status = _loader.LoaderStatus.kIdle;
  24184. return;
  24185. }
  24186. if (res.ok && res.status >= 200 && res.status <= 299) {
  24187. if (res.url !== seekConfig.url) {
  24188. if (_this2._onURLRedirect) {
  24189. var redirectedURL = _this2._seekHandler.removeURLParameters(res.url);
  24190. _this2._onURLRedirect(redirectedURL);
  24191. }
  24192. }
  24193. var lengthHeader = res.headers.get('Content-Length');
  24194. if (lengthHeader != null) {
  24195. _this2._contentLength = parseInt(lengthHeader);
  24196. if (_this2._contentLength !== 0) {
  24197. if (_this2._onContentLengthKnown) {
  24198. _this2._onContentLengthKnown(_this2._contentLength);
  24199. }
  24200. }
  24201. }
  24202. return _this2._pump.call(_this2, res.body.getReader());
  24203. } else {
  24204. _this2._status = _loader.LoaderStatus.kError;
  24205. if (_this2._onError) {
  24206. _this2._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: res.status, msg: res.statusText });
  24207. } else {
  24208. throw new _exception.RuntimeException('FetchStreamLoader: Http code invalid, ' + res.status + ' ' + res.statusText);
  24209. }
  24210. }
  24211. }).catch(function (e) {
  24212. _this2._status = _loader.LoaderStatus.kError;
  24213. if (_this2._onError) {
  24214. _this2._onError(_loader.LoaderErrors.EXCEPTION, { code: -1, msg: e.message });
  24215. } else {
  24216. throw e;
  24217. }
  24218. });
  24219. }
  24220. }, {
  24221. key: 'abort',
  24222. value: function abort() {
  24223. this._requestAbort = true;
  24224. }
  24225. }, {
  24226. key: '_pump',
  24227. value: function _pump(reader) {
  24228. var _this3 = this;
  24229. // ReadableStreamReader
  24230. return reader.read().then(function (result) {
  24231. if (result.done) {
  24232. // First check received length
  24233. if (_this3._contentLength !== null && _this3._receivedLength < _this3._contentLength) {
  24234. // Report Early-EOF
  24235. _this3._status = _loader.LoaderStatus.kError;
  24236. var type = _loader.LoaderErrors.EARLY_EOF;
  24237. var info = { code: -1, msg: 'Fetch stream meet Early-EOF' };
  24238. if (_this3._onError) {
  24239. _this3._onError(type, info);
  24240. } else {
  24241. throw new _exception.RuntimeException(info.msg);
  24242. }
  24243. } else {
  24244. // OK. Download complete
  24245. _this3._status = _loader.LoaderStatus.kComplete;
  24246. if (_this3._onComplete) {
  24247. _this3._onComplete(_this3._range.from, _this3._range.from + _this3._receivedLength - 1);
  24248. }
  24249. }
  24250. } else {
  24251. if (_this3._requestAbort === true) {
  24252. _this3._requestAbort = false;
  24253. _this3._status = _loader.LoaderStatus.kComplete;
  24254. return reader.cancel();
  24255. }
  24256. _this3._status = _loader.LoaderStatus.kBuffering;
  24257. var chunk = result.value.buffer;
  24258. var byteStart = _this3._range.from + _this3._receivedLength;
  24259. _this3._receivedLength += chunk.byteLength;
  24260. if (_this3._onDataArrival) {
  24261. _this3._onDataArrival(chunk, byteStart, _this3._receivedLength);
  24262. }
  24263. _this3._pump(reader);
  24264. }
  24265. }).catch(function (e) {
  24266. if (e.code === 11 && _browser2.default.msedge) {
  24267. // InvalidStateError on Microsoft Edge
  24268. // Workaround: Edge may throw InvalidStateError after ReadableStreamReader.cancel() call
  24269. // Ignore the unknown exception.
  24270. // Related issue: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/11265202/
  24271. return;
  24272. }
  24273. _this3._status = _loader.LoaderStatus.kError;
  24274. var type = 0;
  24275. var info = null;
  24276. if ((e.code === 19 || e.message === 'network error') && ( // NETWORK_ERR
  24277. _this3._contentLength === null || _this3._contentLength !== null && _this3._receivedLength < _this3._contentLength)) {
  24278. type = _loader.LoaderErrors.EARLY_EOF;
  24279. info = { code: e.code, msg: 'Fetch stream meet Early-EOF' };
  24280. } else {
  24281. type = _loader.LoaderErrors.EXCEPTION;
  24282. info = { code: e.code, msg: e.message };
  24283. }
  24284. if (_this3._onError) {
  24285. _this3._onError(type, info);
  24286. } else {
  24287. throw new _exception.RuntimeException(info.msg);
  24288. }
  24289. });
  24290. }
  24291. }]);
  24292. return FetchStreamLoader;
  24293. }(_loader.BaseLoader);
  24294. exports.default = FetchStreamLoader;
  24295. module.exports = exports['default'];
  24296. /***/ }),
  24297. /* 27 */
  24298. /***/ (function(module, exports, __webpack_require__) {
  24299. "use strict";
  24300. Object.defineProperty(exports, "__esModule", {
  24301. value: true
  24302. });
  24303. 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; };
  24304. 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); } };
  24305. 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; }; }();
  24306. var _logger = __webpack_require__(0);
  24307. var _logger2 = _interopRequireDefault(_logger);
  24308. var _loader = __webpack_require__(3);
  24309. var _exception = __webpack_require__(1);
  24310. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24311. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  24312. 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; }
  24313. 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; } /*
  24314. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  24315. *
  24316. * @author zheng qian <xqq@xqq.im>
  24317. *
  24318. * Licensed under the Apache License, Version 2.0 (the "License");
  24319. * you may not use this file except in compliance with the License.
  24320. * You may obtain a copy of the License at
  24321. *
  24322. * http://www.apache.org/licenses/LICENSE-2.0
  24323. *
  24324. * Unless required by applicable law or agreed to in writing, software
  24325. * distributed under the License is distributed on an "AS IS" BASIS,
  24326. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24327. * See the License for the specific language governing permissions and
  24328. * limitations under the License.
  24329. */
  24330. // For FireFox browser which supports `xhr.responseType = 'moz-chunked-arraybuffer'`
  24331. var MozChunkedLoader = function (_BaseLoader) {
  24332. _inherits(MozChunkedLoader, _BaseLoader);
  24333. _createClass(MozChunkedLoader, null, [{
  24334. key: 'isSupported',
  24335. value: function isSupported() {
  24336. try {
  24337. var xhr = new XMLHttpRequest();
  24338. // Firefox 37- requires .open() to be called before setting responseType
  24339. xhr.open('GET', 'https://example.com', true);
  24340. xhr.responseType = 'moz-chunked-arraybuffer';
  24341. return xhr.responseType === 'moz-chunked-arraybuffer';
  24342. } catch (e) {
  24343. _logger2.default.w('MozChunkedLoader', e.message);
  24344. return false;
  24345. }
  24346. }
  24347. }]);
  24348. function MozChunkedLoader(seekHandler, config) {
  24349. _classCallCheck(this, MozChunkedLoader);
  24350. var _this = _possibleConstructorReturn(this, (MozChunkedLoader.__proto__ || Object.getPrototypeOf(MozChunkedLoader)).call(this, 'xhr-moz-chunked-loader'));
  24351. _this.TAG = 'MozChunkedLoader';
  24352. _this._seekHandler = seekHandler;
  24353. _this._config = config;
  24354. _this._needStash = true;
  24355. _this._xhr = null;
  24356. _this._requestAbort = false;
  24357. _this._contentLength = null;
  24358. _this._receivedLength = 0;
  24359. return _this;
  24360. }
  24361. _createClass(MozChunkedLoader, [{
  24362. key: 'destroy',
  24363. value: function destroy() {
  24364. if (this.isWorking()) {
  24365. this.abort();
  24366. }
  24367. if (this._xhr) {
  24368. this._xhr.onreadystatechange = null;
  24369. this._xhr.onprogress = null;
  24370. this._xhr.onloadend = null;
  24371. this._xhr.onerror = null;
  24372. this._xhr = null;
  24373. }
  24374. _get(MozChunkedLoader.prototype.__proto__ || Object.getPrototypeOf(MozChunkedLoader.prototype), 'destroy', this).call(this);
  24375. }
  24376. }, {
  24377. key: 'open',
  24378. value: function open(dataSource, range) {
  24379. this._dataSource = dataSource;
  24380. this._range = range;
  24381. var sourceURL = dataSource.url;
  24382. if (this._config.reuseRedirectedURL && dataSource.redirectedURL != undefined) {
  24383. sourceURL = dataSource.redirectedURL;
  24384. }
  24385. var seekConfig = this._seekHandler.getConfig(sourceURL, range);
  24386. this._requestURL = seekConfig.url;
  24387. var xhr = this._xhr = new XMLHttpRequest();
  24388. xhr.open('GET', seekConfig.url, true);
  24389. xhr.responseType = 'moz-chunked-arraybuffer';
  24390. xhr.onreadystatechange = this._onReadyStateChange.bind(this);
  24391. xhr.onprogress = this._onProgress.bind(this);
  24392. xhr.onloadend = this._onLoadEnd.bind(this);
  24393. xhr.onerror = this._onXhrError.bind(this);
  24394. // cors is auto detected and enabled by xhr
  24395. // withCredentials is disabled by default
  24396. if (dataSource.withCredentials) {
  24397. xhr.withCredentials = true;
  24398. }
  24399. if (_typeof(seekConfig.headers) === 'object') {
  24400. var headers = seekConfig.headers;
  24401. for (var key in headers) {
  24402. if (headers.hasOwnProperty(key)) {
  24403. xhr.setRequestHeader(key, headers[key]);
  24404. }
  24405. }
  24406. }
  24407. this._status = _loader.LoaderStatus.kConnecting;
  24408. xhr.send();
  24409. }
  24410. }, {
  24411. key: 'abort',
  24412. value: function abort() {
  24413. this._requestAbort = true;
  24414. if (this._xhr) {
  24415. this._xhr.abort();
  24416. }
  24417. this._status = _loader.LoaderStatus.kComplete;
  24418. }
  24419. }, {
  24420. key: '_onReadyStateChange',
  24421. value: function _onReadyStateChange(e) {
  24422. var xhr = e.target;
  24423. if (xhr.readyState === 2) {
  24424. // HEADERS_RECEIVED
  24425. if (xhr.responseURL != undefined && xhr.responseURL !== this._requestURL) {
  24426. if (this._onURLRedirect) {
  24427. var redirectedURL = this._seekHandler.removeURLParameters(xhr.responseURL);
  24428. this._onURLRedirect(redirectedURL);
  24429. }
  24430. }
  24431. if (xhr.status !== 0 && (xhr.status < 200 || xhr.status > 299)) {
  24432. this._status = _loader.LoaderStatus.kError;
  24433. if (this._onError) {
  24434. this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: xhr.status, msg: xhr.statusText });
  24435. } else {
  24436. throw new _exception.RuntimeException('MozChunkedLoader: Http code invalid, ' + xhr.status + ' ' + xhr.statusText);
  24437. }
  24438. } else {
  24439. this._status = _loader.LoaderStatus.kBuffering;
  24440. }
  24441. }
  24442. }
  24443. }, {
  24444. key: '_onProgress',
  24445. value: function _onProgress(e) {
  24446. if (this._status === _loader.LoaderStatus.kError) {
  24447. // Ignore error response
  24448. return;
  24449. }
  24450. if (this._contentLength === null) {
  24451. if (e.total !== null && e.total !== 0) {
  24452. this._contentLength = e.total;
  24453. if (this._onContentLengthKnown) {
  24454. this._onContentLengthKnown(this._contentLength);
  24455. }
  24456. }
  24457. }
  24458. var chunk = e.target.response;
  24459. var byteStart = this._range.from + this._receivedLength;
  24460. this._receivedLength += chunk.byteLength;
  24461. if (this._onDataArrival) {
  24462. this._onDataArrival(chunk, byteStart, this._receivedLength);
  24463. }
  24464. }
  24465. }, {
  24466. key: '_onLoadEnd',
  24467. value: function _onLoadEnd(e) {
  24468. if (this._requestAbort === true) {
  24469. this._requestAbort = false;
  24470. return;
  24471. } else if (this._status === _loader.LoaderStatus.kError) {
  24472. return;
  24473. }
  24474. this._status = _loader.LoaderStatus.kComplete;
  24475. if (this._onComplete) {
  24476. this._onComplete(this._range.from, this._range.from + this._receivedLength - 1);
  24477. }
  24478. }
  24479. }, {
  24480. key: '_onXhrError',
  24481. value: function _onXhrError(e) {
  24482. this._status = _loader.LoaderStatus.kError;
  24483. var type = 0;
  24484. var info = null;
  24485. if (this._contentLength && e.loaded < this._contentLength) {
  24486. type = _loader.LoaderErrors.EARLY_EOF;
  24487. info = { code: -1, msg: 'Moz-Chunked stream meet Early-Eof' };
  24488. } else {
  24489. type = _loader.LoaderErrors.EXCEPTION;
  24490. info = { code: -1, msg: e.constructor.name + ' ' + e.type };
  24491. }
  24492. if (this._onError) {
  24493. this._onError(type, info);
  24494. } else {
  24495. throw new _exception.RuntimeException(info.msg);
  24496. }
  24497. }
  24498. }]);
  24499. return MozChunkedLoader;
  24500. }(_loader.BaseLoader);
  24501. exports.default = MozChunkedLoader;
  24502. module.exports = exports['default'];
  24503. /***/ }),
  24504. /* 28 */
  24505. /***/ (function(module, exports, __webpack_require__) {
  24506. "use strict";
  24507. Object.defineProperty(exports, "__esModule", {
  24508. value: true
  24509. });
  24510. 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; };
  24511. 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); } };
  24512. 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; }; }();
  24513. var _logger = __webpack_require__(0);
  24514. var _logger2 = _interopRequireDefault(_logger);
  24515. var _loader = __webpack_require__(3);
  24516. var _exception = __webpack_require__(1);
  24517. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24518. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  24519. 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; }
  24520. 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; } /*
  24521. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  24522. *
  24523. * @author zheng qian <xqq@xqq.im>
  24524. *
  24525. * Licensed under the Apache License, Version 2.0 (the "License");
  24526. * you may not use this file except in compliance with the License.
  24527. * You may obtain a copy of the License at
  24528. *
  24529. * http://www.apache.org/licenses/LICENSE-2.0
  24530. *
  24531. * Unless required by applicable law or agreed to in writing, software
  24532. * distributed under the License is distributed on an "AS IS" BASIS,
  24533. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24534. * See the License for the specific language governing permissions and
  24535. * limitations under the License.
  24536. */
  24537. /* Notice: ms-stream may cause IE/Edge browser crash if seek too frequently!!!
  24538. * The browser may crash in wininet.dll. Disable for now.
  24539. *
  24540. * For IE11/Edge browser by microsoft which supports `xhr.responseType = 'ms-stream'`
  24541. * Notice that ms-stream API sucks. The buffer is always expanding along with downloading.
  24542. *
  24543. * We need to abort the xhr if buffer size exceeded limit size (e.g. 16 MiB), then do reconnect.
  24544. * in order to release previous ArrayBuffer to avoid memory leak
  24545. *
  24546. * Otherwise, the ArrayBuffer will increase to a terrible size that equals final file size.
  24547. */
  24548. var MSStreamLoader = function (_BaseLoader) {
  24549. _inherits(MSStreamLoader, _BaseLoader);
  24550. _createClass(MSStreamLoader, null, [{
  24551. key: 'isSupported',
  24552. value: function isSupported() {
  24553. try {
  24554. if (typeof self.MSStream === 'undefined' || typeof self.MSStreamReader === 'undefined') {
  24555. return false;
  24556. }
  24557. var xhr = new XMLHttpRequest();
  24558. xhr.open('GET', 'https://example.com', true);
  24559. xhr.responseType = 'ms-stream';
  24560. return xhr.responseType === 'ms-stream';
  24561. } catch (e) {
  24562. _logger2.default.w('MSStreamLoader', e.message);
  24563. return false;
  24564. }
  24565. }
  24566. }]);
  24567. function MSStreamLoader(seekHandler, config) {
  24568. _classCallCheck(this, MSStreamLoader);
  24569. var _this = _possibleConstructorReturn(this, (MSStreamLoader.__proto__ || Object.getPrototypeOf(MSStreamLoader)).call(this, 'xhr-msstream-loader'));
  24570. _this.TAG = 'MSStreamLoader';
  24571. _this._seekHandler = seekHandler;
  24572. _this._config = config;
  24573. _this._needStash = true;
  24574. _this._xhr = null;
  24575. _this._reader = null; // MSStreamReader
  24576. _this._totalRange = null;
  24577. _this._currentRange = null;
  24578. _this._currentRequestURL = null;
  24579. _this._currentRedirectedURL = null;
  24580. _this._contentLength = null;
  24581. _this._receivedLength = 0;
  24582. _this._bufferLimit = 16 * 1024 * 1024; // 16MB
  24583. _this._lastTimeBufferSize = 0;
  24584. _this._isReconnecting = false;
  24585. return _this;
  24586. }
  24587. _createClass(MSStreamLoader, [{
  24588. key: 'destroy',
  24589. value: function destroy() {
  24590. if (this.isWorking()) {
  24591. this.abort();
  24592. }
  24593. if (this._reader) {
  24594. this._reader.onprogress = null;
  24595. this._reader.onload = null;
  24596. this._reader.onerror = null;
  24597. this._reader = null;
  24598. }
  24599. if (this._xhr) {
  24600. this._xhr.onreadystatechange = null;
  24601. this._xhr = null;
  24602. }
  24603. _get(MSStreamLoader.prototype.__proto__ || Object.getPrototypeOf(MSStreamLoader.prototype), 'destroy', this).call(this);
  24604. }
  24605. }, {
  24606. key: 'open',
  24607. value: function open(dataSource, range) {
  24608. this._internalOpen(dataSource, range, false);
  24609. }
  24610. }, {
  24611. key: '_internalOpen',
  24612. value: function _internalOpen(dataSource, range, isSubrange) {
  24613. this._dataSource = dataSource;
  24614. if (!isSubrange) {
  24615. this._totalRange = range;
  24616. } else {
  24617. this._currentRange = range;
  24618. }
  24619. var sourceURL = dataSource.url;
  24620. if (this._config.reuseRedirectedURL) {
  24621. if (this._currentRedirectedURL != undefined) {
  24622. sourceURL = this._currentRedirectedURL;
  24623. } else if (dataSource.redirectedURL != undefined) {
  24624. sourceURL = dataSource.redirectedURL;
  24625. }
  24626. }
  24627. var seekConfig = this._seekHandler.getConfig(sourceURL, range);
  24628. this._currentRequestURL = seekConfig.url;
  24629. var reader = this._reader = new self.MSStreamReader();
  24630. reader.onprogress = this._msrOnProgress.bind(this);
  24631. reader.onload = this._msrOnLoad.bind(this);
  24632. reader.onerror = this._msrOnError.bind(this);
  24633. var xhr = this._xhr = new XMLHttpRequest();
  24634. xhr.open('GET', seekConfig.url, true);
  24635. xhr.responseType = 'ms-stream';
  24636. xhr.onreadystatechange = this._xhrOnReadyStateChange.bind(this);
  24637. xhr.onerror = this._xhrOnError.bind(this);
  24638. if (dataSource.withCredentials) {
  24639. xhr.withCredentials = true;
  24640. }
  24641. if (_typeof(seekConfig.headers) === 'object') {
  24642. var headers = seekConfig.headers;
  24643. for (var key in headers) {
  24644. if (headers.hasOwnProperty(key)) {
  24645. xhr.setRequestHeader(key, headers[key]);
  24646. }
  24647. }
  24648. }
  24649. if (this._isReconnecting) {
  24650. this._isReconnecting = false;
  24651. } else {
  24652. this._status = _loader.LoaderStatus.kConnecting;
  24653. }
  24654. xhr.send();
  24655. }
  24656. }, {
  24657. key: 'abort',
  24658. value: function abort() {
  24659. this._internalAbort();
  24660. this._status = _loader.LoaderStatus.kComplete;
  24661. }
  24662. }, {
  24663. key: '_internalAbort',
  24664. value: function _internalAbort() {
  24665. if (this._reader) {
  24666. if (this._reader.readyState === 1) {
  24667. // LOADING
  24668. this._reader.abort();
  24669. }
  24670. this._reader.onprogress = null;
  24671. this._reader.onload = null;
  24672. this._reader.onerror = null;
  24673. this._reader = null;
  24674. }
  24675. if (this._xhr) {
  24676. this._xhr.abort();
  24677. this._xhr.onreadystatechange = null;
  24678. this._xhr = null;
  24679. }
  24680. }
  24681. }, {
  24682. key: '_xhrOnReadyStateChange',
  24683. value: function _xhrOnReadyStateChange(e) {
  24684. var xhr = e.target;
  24685. if (xhr.readyState === 2) {
  24686. // HEADERS_RECEIVED
  24687. if (xhr.status >= 200 && xhr.status <= 299) {
  24688. this._status = _loader.LoaderStatus.kBuffering;
  24689. if (xhr.responseURL != undefined) {
  24690. var redirectedURL = this._seekHandler.removeURLParameters(xhr.responseURL);
  24691. if (xhr.responseURL !== this._currentRequestURL && redirectedURL !== this._currentRedirectedURL) {
  24692. this._currentRedirectedURL = redirectedURL;
  24693. if (this._onURLRedirect) {
  24694. this._onURLRedirect(redirectedURL);
  24695. }
  24696. }
  24697. }
  24698. var lengthHeader = xhr.getResponseHeader('Content-Length');
  24699. if (lengthHeader != null && this._contentLength == null) {
  24700. var length = parseInt(lengthHeader);
  24701. if (length > 0) {
  24702. this._contentLength = length;
  24703. if (this._onContentLengthKnown) {
  24704. this._onContentLengthKnown(this._contentLength);
  24705. }
  24706. }
  24707. }
  24708. } else {
  24709. this._status = _loader.LoaderStatus.kError;
  24710. if (this._onError) {
  24711. this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: xhr.status, msg: xhr.statusText });
  24712. } else {
  24713. throw new _exception.RuntimeException('MSStreamLoader: Http code invalid, ' + xhr.status + ' ' + xhr.statusText);
  24714. }
  24715. }
  24716. } else if (xhr.readyState === 3) {
  24717. // LOADING
  24718. if (xhr.status >= 200 && xhr.status <= 299) {
  24719. this._status = _loader.LoaderStatus.kBuffering;
  24720. var msstream = xhr.response;
  24721. this._reader.readAsArrayBuffer(msstream);
  24722. }
  24723. }
  24724. }
  24725. }, {
  24726. key: '_xhrOnError',
  24727. value: function _xhrOnError(e) {
  24728. this._status = _loader.LoaderStatus.kError;
  24729. var type = _loader.LoaderErrors.EXCEPTION;
  24730. var info = { code: -1, msg: e.constructor.name + ' ' + e.type };
  24731. if (this._onError) {
  24732. this._onError(type, info);
  24733. } else {
  24734. throw new _exception.RuntimeException(info.msg);
  24735. }
  24736. }
  24737. }, {
  24738. key: '_msrOnProgress',
  24739. value: function _msrOnProgress(e) {
  24740. var reader = e.target;
  24741. var bigbuffer = reader.result;
  24742. if (bigbuffer == null) {
  24743. // result may be null, workaround for buggy M$
  24744. this._doReconnectIfNeeded();
  24745. return;
  24746. }
  24747. var slice = bigbuffer.slice(this._lastTimeBufferSize);
  24748. this._lastTimeBufferSize = bigbuffer.byteLength;
  24749. var byteStart = this._totalRange.from + this._receivedLength;
  24750. this._receivedLength += slice.byteLength;
  24751. if (this._onDataArrival) {
  24752. this._onDataArrival(slice, byteStart, this._receivedLength);
  24753. }
  24754. if (bigbuffer.byteLength >= this._bufferLimit) {
  24755. _logger2.default.v(this.TAG, 'MSStream buffer exceeded max size near ' + (byteStart + slice.byteLength) + ', reconnecting...');
  24756. this._doReconnectIfNeeded();
  24757. }
  24758. }
  24759. }, {
  24760. key: '_doReconnectIfNeeded',
  24761. value: function _doReconnectIfNeeded() {
  24762. if (this._contentLength == null || this._receivedLength < this._contentLength) {
  24763. this._isReconnecting = true;
  24764. this._lastTimeBufferSize = 0;
  24765. this._internalAbort();
  24766. var range = {
  24767. from: this._totalRange.from + this._receivedLength,
  24768. to: -1
  24769. };
  24770. this._internalOpen(this._dataSource, range, true);
  24771. }
  24772. }
  24773. }, {
  24774. key: '_msrOnLoad',
  24775. value: function _msrOnLoad(e) {
  24776. // actually it is onComplete event
  24777. this._status = _loader.LoaderStatus.kComplete;
  24778. if (this._onComplete) {
  24779. this._onComplete(this._totalRange.from, this._totalRange.from + this._receivedLength - 1);
  24780. }
  24781. }
  24782. }, {
  24783. key: '_msrOnError',
  24784. value: function _msrOnError(e) {
  24785. this._status = _loader.LoaderStatus.kError;
  24786. var type = 0;
  24787. var info = null;
  24788. if (this._contentLength && this._receivedLength < this._contentLength) {
  24789. type = _loader.LoaderErrors.EARLY_EOF;
  24790. info = { code: -1, msg: 'MSStream meet Early-Eof' };
  24791. } else {
  24792. type = _loader.LoaderErrors.EARLY_EOF;
  24793. info = { code: -1, msg: e.constructor.name + ' ' + e.type };
  24794. }
  24795. if (this._onError) {
  24796. this._onError(type, info);
  24797. } else {
  24798. throw new _exception.RuntimeException(info.msg);
  24799. }
  24800. }
  24801. }]);
  24802. return MSStreamLoader;
  24803. }(_loader.BaseLoader);
  24804. exports.default = MSStreamLoader;
  24805. module.exports = exports['default'];
  24806. /***/ }),
  24807. /* 29 */
  24808. /***/ (function(module, exports, __webpack_require__) {
  24809. "use strict";
  24810. Object.defineProperty(exports, "__esModule", {
  24811. value: true
  24812. });
  24813. 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; };
  24814. 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); } };
  24815. 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; }; }();
  24816. var _logger = __webpack_require__(0);
  24817. var _logger2 = _interopRequireDefault(_logger);
  24818. var _speedSampler = __webpack_require__(13);
  24819. var _speedSampler2 = _interopRequireDefault(_speedSampler);
  24820. var _loader = __webpack_require__(3);
  24821. var _exception = __webpack_require__(1);
  24822. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24823. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  24824. 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; }
  24825. 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; } /*
  24826. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  24827. *
  24828. * @author zheng qian <xqq@xqq.im>
  24829. *
  24830. * Licensed under the Apache License, Version 2.0 (the "License");
  24831. * you may not use this file except in compliance with the License.
  24832. * You may obtain a copy of the License at
  24833. *
  24834. * http://www.apache.org/licenses/LICENSE-2.0
  24835. *
  24836. * Unless required by applicable law or agreed to in writing, software
  24837. * distributed under the License is distributed on an "AS IS" BASIS,
  24838. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24839. * See the License for the specific language governing permissions and
  24840. * limitations under the License.
  24841. */
  24842. // Universal IO Loader, implemented by adding Range header in xhr's request header
  24843. var RangeLoader = function (_BaseLoader) {
  24844. _inherits(RangeLoader, _BaseLoader);
  24845. _createClass(RangeLoader, null, [{
  24846. key: 'isSupported',
  24847. value: function isSupported() {
  24848. try {
  24849. var xhr = new XMLHttpRequest();
  24850. xhr.open('GET', 'https://example.com', true);
  24851. xhr.responseType = 'arraybuffer';
  24852. return xhr.responseType === 'arraybuffer';
  24853. } catch (e) {
  24854. _logger2.default.w('RangeLoader', e.message);
  24855. return false;
  24856. }
  24857. }
  24858. }]);
  24859. function RangeLoader(seekHandler, config) {
  24860. _classCallCheck(this, RangeLoader);
  24861. var _this = _possibleConstructorReturn(this, (RangeLoader.__proto__ || Object.getPrototypeOf(RangeLoader)).call(this, 'xhr-range-loader'));
  24862. _this.TAG = 'RangeLoader';
  24863. _this._seekHandler = seekHandler;
  24864. _this._config = config;
  24865. _this._needStash = false;
  24866. _this._chunkSizeKBList = [128, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 5120, 6144, 7168, 8192];
  24867. _this._currentChunkSizeKB = 384;
  24868. _this._currentSpeedNormalized = 0;
  24869. _this._zeroSpeedChunkCount = 0;
  24870. _this._xhr = null;
  24871. _this._speedSampler = new _speedSampler2.default();
  24872. _this._requestAbort = false;
  24873. _this._waitForTotalLength = false;
  24874. _this._totalLengthReceived = false;
  24875. _this._currentRequestURL = null;
  24876. _this._currentRedirectedURL = null;
  24877. _this._currentRequestRange = null;
  24878. _this._totalLength = null; // size of the entire file
  24879. _this._contentLength = null; // Content-Length of entire request range
  24880. _this._receivedLength = 0; // total received bytes
  24881. _this._lastTimeLoaded = 0; // received bytes of current request sub-range
  24882. return _this;
  24883. }
  24884. _createClass(RangeLoader, [{
  24885. key: 'destroy',
  24886. value: function destroy() {
  24887. if (this.isWorking()) {
  24888. this.abort();
  24889. }
  24890. if (this._xhr) {
  24891. this._xhr.onreadystatechange = null;
  24892. this._xhr.onprogress = null;
  24893. this._xhr.onload = null;
  24894. this._xhr.onerror = null;
  24895. this._xhr = null;
  24896. }
  24897. _get(RangeLoader.prototype.__proto__ || Object.getPrototypeOf(RangeLoader.prototype), 'destroy', this).call(this);
  24898. }
  24899. }, {
  24900. key: 'open',
  24901. value: function open(dataSource, range) {
  24902. this._dataSource = dataSource;
  24903. this._range = range;
  24904. this._status = _loader.LoaderStatus.kConnecting;
  24905. var useRefTotalLength = false;
  24906. if (this._dataSource.filesize != undefined && this._dataSource.filesize !== 0) {
  24907. useRefTotalLength = true;
  24908. this._totalLength = this._dataSource.filesize;
  24909. }
  24910. if (!this._totalLengthReceived && !useRefTotalLength) {
  24911. // We need total filesize
  24912. this._waitForTotalLength = true;
  24913. this._internalOpen(this._dataSource, { from: 0, to: -1 });
  24914. } else {
  24915. // We have filesize, start loading
  24916. this._openSubRange();
  24917. }
  24918. }
  24919. }, {
  24920. key: '_openSubRange',
  24921. value: function _openSubRange() {
  24922. var chunkSize = this._currentChunkSizeKB * 1024;
  24923. var from = this._range.from + this._receivedLength;
  24924. var to = from + chunkSize;
  24925. if (this._contentLength != null) {
  24926. if (to - this._range.from >= this._contentLength) {
  24927. to = this._range.from + this._contentLength - 1;
  24928. }
  24929. }
  24930. this._currentRequestRange = { from: from, to: to };
  24931. this._internalOpen(this._dataSource, this._currentRequestRange);
  24932. }
  24933. }, {
  24934. key: '_internalOpen',
  24935. value: function _internalOpen(dataSource, range) {
  24936. this._lastTimeLoaded = 0;
  24937. var sourceURL = dataSource.url;
  24938. if (this._config.reuseRedirectedURL) {
  24939. if (this._currentRedirectedURL != undefined) {
  24940. sourceURL = this._currentRedirectedURL;
  24941. } else if (dataSource.redirectedURL != undefined) {
  24942. sourceURL = dataSource.redirectedURL;
  24943. }
  24944. }
  24945. var seekConfig = this._seekHandler.getConfig(sourceURL, range);
  24946. this._currentRequestURL = seekConfig.url;
  24947. var xhr = this._xhr = new XMLHttpRequest();
  24948. xhr.open('GET', seekConfig.url, true);
  24949. xhr.responseType = 'arraybuffer';
  24950. xhr.onreadystatechange = this._onReadyStateChange.bind(this);
  24951. xhr.onprogress = this._onProgress.bind(this);
  24952. xhr.onload = this._onLoad.bind(this);
  24953. xhr.onerror = this._onXhrError.bind(this);
  24954. if (dataSource.withCredentials) {
  24955. xhr.withCredentials = true;
  24956. }
  24957. if (_typeof(seekConfig.headers) === 'object') {
  24958. var headers = seekConfig.headers;
  24959. for (var key in headers) {
  24960. if (headers.hasOwnProperty(key)) {
  24961. xhr.setRequestHeader(key, headers[key]);
  24962. }
  24963. }
  24964. }
  24965. xhr.send();
  24966. }
  24967. }, {
  24968. key: 'abort',
  24969. value: function abort() {
  24970. this._requestAbort = true;
  24971. this._internalAbort();
  24972. this._status = _loader.LoaderStatus.kComplete;
  24973. }
  24974. }, {
  24975. key: '_internalAbort',
  24976. value: function _internalAbort() {
  24977. if (this._xhr) {
  24978. this._xhr.onreadystatechange = null;
  24979. this._xhr.onprogress = null;
  24980. this._xhr.onload = null;
  24981. this._xhr.onerror = null;
  24982. this._xhr.abort();
  24983. this._xhr = null;
  24984. }
  24985. }
  24986. }, {
  24987. key: '_onReadyStateChange',
  24988. value: function _onReadyStateChange(e) {
  24989. var xhr = e.target;
  24990. if (xhr.readyState === 2) {
  24991. // HEADERS_RECEIVED
  24992. if (xhr.responseURL != undefined) {
  24993. // if the browser support this property
  24994. var redirectedURL = this._seekHandler.removeURLParameters(xhr.responseURL);
  24995. if (xhr.responseURL !== this._currentRequestURL && redirectedURL !== this._currentRedirectedURL) {
  24996. this._currentRedirectedURL = redirectedURL;
  24997. if (this._onURLRedirect) {
  24998. this._onURLRedirect(redirectedURL);
  24999. }
  25000. }
  25001. }
  25002. if (xhr.status >= 200 && xhr.status <= 299) {
  25003. if (this._waitForTotalLength) {
  25004. return;
  25005. }
  25006. this._status = _loader.LoaderStatus.kBuffering;
  25007. } else {
  25008. this._status = _loader.LoaderStatus.kError;
  25009. if (this._onError) {
  25010. this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: xhr.status, msg: xhr.statusText });
  25011. } else {
  25012. throw new _exception.RuntimeException('RangeLoader: Http code invalid, ' + xhr.status + ' ' + xhr.statusText);
  25013. }
  25014. }
  25015. }
  25016. }
  25017. }, {
  25018. key: '_onProgress',
  25019. value: function _onProgress(e) {
  25020. if (this._status === _loader.LoaderStatus.kError) {
  25021. // Ignore error response
  25022. return;
  25023. }
  25024. if (this._contentLength === null) {
  25025. var openNextRange = false;
  25026. if (this._waitForTotalLength) {
  25027. this._waitForTotalLength = false;
  25028. this._totalLengthReceived = true;
  25029. openNextRange = true;
  25030. var total = e.total;
  25031. this._internalAbort();
  25032. if (total != null & total !== 0) {
  25033. this._totalLength = total;
  25034. }
  25035. }
  25036. // calculate currrent request range's contentLength
  25037. if (this._range.to === -1) {
  25038. this._contentLength = this._totalLength - this._range.from;
  25039. } else {
  25040. // to !== -1
  25041. this._contentLength = this._range.to - this._range.from + 1;
  25042. }
  25043. if (openNextRange) {
  25044. this._openSubRange();
  25045. return;
  25046. }
  25047. if (this._onContentLengthKnown) {
  25048. this._onContentLengthKnown(this._contentLength);
  25049. }
  25050. }
  25051. var delta = e.loaded - this._lastTimeLoaded;
  25052. this._lastTimeLoaded = e.loaded;
  25053. this._speedSampler.addBytes(delta);
  25054. }
  25055. }, {
  25056. key: '_normalizeSpeed',
  25057. value: function _normalizeSpeed(input) {
  25058. var list = this._chunkSizeKBList;
  25059. var last = list.length - 1;
  25060. var mid = 0;
  25061. var lbound = 0;
  25062. var ubound = last;
  25063. if (input < list[0]) {
  25064. return list[0];
  25065. }
  25066. while (lbound <= ubound) {
  25067. mid = lbound + Math.floor((ubound - lbound) / 2);
  25068. if (mid === last || input >= list[mid] && input < list[mid + 1]) {
  25069. return list[mid];
  25070. } else if (list[mid] < input) {
  25071. lbound = mid + 1;
  25072. } else {
  25073. ubound = mid - 1;
  25074. }
  25075. }
  25076. }
  25077. }, {
  25078. key: '_onLoad',
  25079. value: function _onLoad(e) {
  25080. if (this._status === _loader.LoaderStatus.kError) {
  25081. // Ignore error response
  25082. return;
  25083. }
  25084. if (this._waitForTotalLength) {
  25085. this._waitForTotalLength = false;
  25086. return;
  25087. }
  25088. this._lastTimeLoaded = 0;
  25089. var KBps = this._speedSampler.lastSecondKBps;
  25090. if (KBps === 0) {
  25091. this._zeroSpeedChunkCount++;
  25092. if (this._zeroSpeedChunkCount >= 3) {
  25093. // Try get currentKBps after 3 chunks
  25094. KBps = this._speedSampler.currentKBps;
  25095. }
  25096. }
  25097. if (KBps !== 0) {
  25098. var normalized = this._normalizeSpeed(KBps);
  25099. if (this._currentSpeedNormalized !== normalized) {
  25100. this._currentSpeedNormalized = normalized;
  25101. this._currentChunkSizeKB = normalized;
  25102. }
  25103. }
  25104. var chunk = e.target.response;
  25105. var byteStart = this._range.from + this._receivedLength;
  25106. this._receivedLength += chunk.byteLength;
  25107. var reportComplete = false;
  25108. if (this._contentLength != null && this._receivedLength < this._contentLength) {
  25109. // continue load next chunk
  25110. this._openSubRange();
  25111. } else {
  25112. reportComplete = true;
  25113. }
  25114. // dispatch received chunk
  25115. if (this._onDataArrival) {
  25116. this._onDataArrival(chunk, byteStart, this._receivedLength);
  25117. }
  25118. if (reportComplete) {
  25119. this._status = _loader.LoaderStatus.kComplete;
  25120. if (this._onComplete) {
  25121. this._onComplete(this._range.from, this._range.from + this._receivedLength - 1);
  25122. }
  25123. }
  25124. }
  25125. }, {
  25126. key: '_onXhrError',
  25127. value: function _onXhrError(e) {
  25128. this._status = _loader.LoaderStatus.kError;
  25129. var type = 0;
  25130. var info = null;
  25131. if (this._contentLength && this._receivedLength > 0 && this._receivedLength < this._contentLength) {
  25132. type = _loader.LoaderErrors.EARLY_EOF;
  25133. info = { code: -1, msg: 'RangeLoader meet Early-Eof' };
  25134. } else {
  25135. type = _loader.LoaderErrors.EXCEPTION;
  25136. info = { code: -1, msg: e.constructor.name + ' ' + e.type };
  25137. }
  25138. if (this._onError) {
  25139. this._onError(type, info);
  25140. } else {
  25141. throw new _exception.RuntimeException(info.msg);
  25142. }
  25143. }
  25144. }, {
  25145. key: 'currentSpeed',
  25146. get: function get() {
  25147. return this._speedSampler.lastSecondKBps;
  25148. }
  25149. }]);
  25150. return RangeLoader;
  25151. }(_loader.BaseLoader);
  25152. exports.default = RangeLoader;
  25153. module.exports = exports['default'];
  25154. /***/ }),
  25155. /* 30 */
  25156. /***/ (function(module, exports, __webpack_require__) {
  25157. "use strict";
  25158. Object.defineProperty(exports, "__esModule", {
  25159. value: true
  25160. });
  25161. 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); } };
  25162. 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; }; }();
  25163. var _logger = __webpack_require__(0);
  25164. var _logger2 = _interopRequireDefault(_logger);
  25165. var _loader = __webpack_require__(3);
  25166. var _exception = __webpack_require__(1);
  25167. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25168. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  25169. 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; }
  25170. 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; } /*
  25171. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  25172. *
  25173. * @author zheng qian <xqq@xqq.im>
  25174. *
  25175. * Licensed under the Apache License, Version 2.0 (the "License");
  25176. * you may not use this file except in compliance with the License.
  25177. * You may obtain a copy of the License at
  25178. *
  25179. * http://www.apache.org/licenses/LICENSE-2.0
  25180. *
  25181. * Unless required by applicable law or agreed to in writing, software
  25182. * distributed under the License is distributed on an "AS IS" BASIS,
  25183. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25184. * See the License for the specific language governing permissions and
  25185. * limitations under the License.
  25186. */
  25187. // For FLV over WebSocket live stream
  25188. var WebSocketLoader = function (_BaseLoader) {
  25189. _inherits(WebSocketLoader, _BaseLoader);
  25190. _createClass(WebSocketLoader, null, [{
  25191. key: 'isSupported',
  25192. value: function isSupported() {
  25193. try {
  25194. return typeof self.WebSocket !== 'undefined';
  25195. } catch (e) {
  25196. return false;
  25197. }
  25198. }
  25199. }]);
  25200. function WebSocketLoader() {
  25201. _classCallCheck(this, WebSocketLoader);
  25202. var _this = _possibleConstructorReturn(this, (WebSocketLoader.__proto__ || Object.getPrototypeOf(WebSocketLoader)).call(this, 'websocket-loader'));
  25203. _this.TAG = 'WebSocketLoader';
  25204. _this._needStash = true;
  25205. _this._ws = null;
  25206. _this._requestAbort = false;
  25207. _this._receivedLength = 0;
  25208. return _this;
  25209. }
  25210. _createClass(WebSocketLoader, [{
  25211. key: 'destroy',
  25212. value: function destroy() {
  25213. if (this._ws) {
  25214. this.abort();
  25215. }
  25216. _get(WebSocketLoader.prototype.__proto__ || Object.getPrototypeOf(WebSocketLoader.prototype), 'destroy', this).call(this);
  25217. }
  25218. }, {
  25219. key: 'open',
  25220. value: function open(dataSource) {
  25221. try {
  25222. var ws = this._ws = new self.WebSocket(dataSource.url);
  25223. ws.binaryType = 'arraybuffer';
  25224. ws.onopen = this._onWebSocketOpen.bind(this);
  25225. ws.onclose = this._onWebSocketClose.bind(this);
  25226. ws.onmessage = this._onWebSocketMessage.bind(this);
  25227. ws.onerror = this._onWebSocketError.bind(this);
  25228. this._status = _loader.LoaderStatus.kConnecting;
  25229. } catch (e) {
  25230. this._status = _loader.LoaderStatus.kError;
  25231. var info = { code: e.code, msg: e.message };
  25232. if (this._onError) {
  25233. this._onError(_loader.LoaderErrors.EXCEPTION, info);
  25234. } else {
  25235. throw new _exception.RuntimeException(info.msg);
  25236. }
  25237. }
  25238. }
  25239. }, {
  25240. key: 'abort',
  25241. value: function abort() {
  25242. var ws = this._ws;
  25243. if (ws && (ws.readyState === 0 || ws.readyState === 1)) {
  25244. // CONNECTING || OPEN
  25245. this._requestAbort = true;
  25246. ws.close();
  25247. }
  25248. this._ws = null;
  25249. this._status = _loader.LoaderStatus.kComplete;
  25250. }
  25251. }, {
  25252. key: '_onWebSocketOpen',
  25253. value: function _onWebSocketOpen(e) {
  25254. this._status = _loader.LoaderStatus.kBuffering;
  25255. }
  25256. }, {
  25257. key: '_onWebSocketClose',
  25258. value: function _onWebSocketClose(e) {
  25259. if (this._requestAbort === true) {
  25260. this._requestAbort = false;
  25261. return;
  25262. }
  25263. this._status = _loader.LoaderStatus.kComplete;
  25264. if (this._onComplete) {
  25265. this._onComplete(0, this._receivedLength - 1);
  25266. }
  25267. }
  25268. }, {
  25269. key: '_onWebSocketMessage',
  25270. value: function _onWebSocketMessage(e) {
  25271. var _this2 = this;
  25272. if (e.data instanceof ArrayBuffer) {
  25273. this._dispatchArrayBuffer(e.data);
  25274. } else if (e.data instanceof Blob) {
  25275. var reader = new FileReader();
  25276. reader.onload = function () {
  25277. _this2._dispatchArrayBuffer(reader.result);
  25278. };
  25279. reader.readAsArrayBuffer(e.data);
  25280. } else {
  25281. this._status = _loader.LoaderStatus.kError;
  25282. var info = { code: -1, msg: 'Unsupported WebSocket message type: ' + e.data.constructor.name };
  25283. if (this._onError) {
  25284. this._onError(_loader.LoaderErrors.EXCEPTION, info);
  25285. } else {
  25286. throw new _exception.RuntimeException(info.msg);
  25287. }
  25288. }
  25289. }
  25290. }, {
  25291. key: '_dispatchArrayBuffer',
  25292. value: function _dispatchArrayBuffer(arraybuffer) {
  25293. var chunk = arraybuffer;
  25294. var byteStart = this._receivedLength;
  25295. this._receivedLength += chunk.byteLength;
  25296. if (this._onDataArrival) {
  25297. this._onDataArrival(chunk, byteStart, this._receivedLength);
  25298. }
  25299. }
  25300. }, {
  25301. key: '_onWebSocketError',
  25302. value: function _onWebSocketError(e) {
  25303. this._status = _loader.LoaderStatus.kError;
  25304. var info = {
  25305. code: e.code,
  25306. msg: e.message
  25307. };
  25308. if (this._onError) {
  25309. this._onError(_loader.LoaderErrors.EXCEPTION, info);
  25310. } else {
  25311. throw new _exception.RuntimeException(info.msg);
  25312. }
  25313. }
  25314. }]);
  25315. return WebSocketLoader;
  25316. }(_loader.BaseLoader);
  25317. exports.default = WebSocketLoader;
  25318. module.exports = exports['default'];
  25319. /***/ }),
  25320. /* 31 */
  25321. /***/ (function(module, exports, __webpack_require__) {
  25322. "use strict";
  25323. Object.defineProperty(exports, "__esModule", {
  25324. value: true
  25325. });
  25326. 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; }; }();
  25327. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  25328. /*
  25329. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  25330. *
  25331. * @author zheng qian <xqq@xqq.im>
  25332. *
  25333. * Licensed under the Apache License, Version 2.0 (the "License");
  25334. * you may not use this file except in compliance with the License.
  25335. * You may obtain a copy of the License at
  25336. *
  25337. * http://www.apache.org/licenses/LICENSE-2.0
  25338. *
  25339. * Unless required by applicable law or agreed to in writing, software
  25340. * distributed under the License is distributed on an "AS IS" BASIS,
  25341. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25342. * See the License for the specific language governing permissions and
  25343. * limitations under the License.
  25344. */
  25345. var RangeSeekHandler = function () {
  25346. function RangeSeekHandler(zeroStart) {
  25347. _classCallCheck(this, RangeSeekHandler);
  25348. this._zeroStart = zeroStart || false;
  25349. }
  25350. _createClass(RangeSeekHandler, [{
  25351. key: 'getConfig',
  25352. value: function getConfig(url, range) {
  25353. var headers = {};
  25354. if (range.from !== 0 || range.to !== -1) {
  25355. var param = void 0;
  25356. if (range.to !== -1) {
  25357. param = 'bytes=' + range.from.toString() + '-' + range.to.toString();
  25358. } else {
  25359. param = 'bytes=' + range.from.toString() + '-';
  25360. }
  25361. headers['Range'] = param;
  25362. } else if (this._zeroStart) {
  25363. headers['Range'] = 'bytes=0-';
  25364. }
  25365. return {
  25366. url: url,
  25367. headers: headers
  25368. };
  25369. }
  25370. }, {
  25371. key: 'removeURLParameters',
  25372. value: function removeURLParameters(seekedURL) {
  25373. return seekedURL;
  25374. }
  25375. }]);
  25376. return RangeSeekHandler;
  25377. }();
  25378. exports.default = RangeSeekHandler;
  25379. module.exports = exports['default'];
  25380. /***/ }),
  25381. /* 32 */
  25382. /***/ (function(module, exports, __webpack_require__) {
  25383. "use strict";
  25384. Object.defineProperty(exports, "__esModule", {
  25385. value: true
  25386. });
  25387. 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; }; }();
  25388. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  25389. /*
  25390. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  25391. *
  25392. * @author zheng qian <xqq@xqq.im>
  25393. *
  25394. * Licensed under the Apache License, Version 2.0 (the "License");
  25395. * you may not use this file except in compliance with the License.
  25396. * You may obtain a copy of the License at
  25397. *
  25398. * http://www.apache.org/licenses/LICENSE-2.0
  25399. *
  25400. * Unless required by applicable law or agreed to in writing, software
  25401. * distributed under the License is distributed on an "AS IS" BASIS,
  25402. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25403. * See the License for the specific language governing permissions and
  25404. * limitations under the License.
  25405. */
  25406. var ParamSeekHandler = function () {
  25407. function ParamSeekHandler(paramStart, paramEnd) {
  25408. _classCallCheck(this, ParamSeekHandler);
  25409. this._startName = paramStart;
  25410. this._endName = paramEnd;
  25411. }
  25412. _createClass(ParamSeekHandler, [{
  25413. key: 'getConfig',
  25414. value: function getConfig(baseUrl, range) {
  25415. var url = baseUrl;
  25416. if (range.from !== 0 || range.to !== -1) {
  25417. var needAnd = true;
  25418. if (url.indexOf('?') === -1) {
  25419. url += '?';
  25420. needAnd = false;
  25421. }
  25422. if (needAnd) {
  25423. url += '&';
  25424. }
  25425. url += this._startName + '=' + range.from.toString();
  25426. if (range.to !== -1) {
  25427. url += '&' + this._endName + '=' + range.to.toString();
  25428. }
  25429. }
  25430. return {
  25431. url: url,
  25432. headers: {}
  25433. };
  25434. }
  25435. }, {
  25436. key: 'removeURLParameters',
  25437. value: function removeURLParameters(seekedURL) {
  25438. var baseURL = seekedURL.split('?')[0];
  25439. var params = undefined;
  25440. var queryIndex = seekedURL.indexOf('?');
  25441. if (queryIndex !== -1) {
  25442. params = seekedURL.substring(queryIndex + 1);
  25443. }
  25444. var resultParams = '';
  25445. if (params != undefined && params.length > 0) {
  25446. var pairs = params.split('&');
  25447. for (var i = 0; i < pairs.length; i++) {
  25448. var pair = pairs[i].split('=');
  25449. var requireAnd = i > 0;
  25450. if (pair[0] !== this._startName && pair[0] !== this._endName) {
  25451. if (requireAnd) {
  25452. resultParams += '&';
  25453. }
  25454. resultParams += pairs[i];
  25455. }
  25456. }
  25457. }
  25458. return resultParams.length === 0 ? baseURL : baseURL + '?' + resultParams;
  25459. }
  25460. }]);
  25461. return ParamSeekHandler;
  25462. }();
  25463. exports.default = ParamSeekHandler;
  25464. module.exports = exports['default'];
  25465. /***/ }),
  25466. /* 33 */
  25467. /***/ (function(module, exports, __webpack_require__) {
  25468. "use strict";
  25469. Object.defineProperty(exports, "__esModule", {
  25470. value: true
  25471. });
  25472. 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; };
  25473. 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; }; }(); /*
  25474. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  25475. *
  25476. * @author zheng qian <xqq@xqq.im>
  25477. *
  25478. * Licensed under the Apache License, Version 2.0 (the "License");
  25479. * you may not use this file except in compliance with the License.
  25480. * You may obtain a copy of the License at
  25481. *
  25482. * http://www.apache.org/licenses/LICENSE-2.0
  25483. *
  25484. * Unless required by applicable law or agreed to in writing, software
  25485. * distributed under the License is distributed on an "AS IS" BASIS,
  25486. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25487. * See the License for the specific language governing permissions and
  25488. * limitations under the License.
  25489. */
  25490. var _events = __webpack_require__(2);
  25491. var _events2 = _interopRequireDefault(_events);
  25492. var _logger = __webpack_require__(0);
  25493. var _logger2 = _interopRequireDefault(_logger);
  25494. var _browser = __webpack_require__(4);
  25495. var _browser2 = _interopRequireDefault(_browser);
  25496. var _playerEvents = __webpack_require__(7);
  25497. var _playerEvents2 = _interopRequireDefault(_playerEvents);
  25498. var _transmuxer = __webpack_require__(34);
  25499. var _transmuxer2 = _interopRequireDefault(_transmuxer);
  25500. var _transmuxingEvents = __webpack_require__(5);
  25501. var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
  25502. var _mseController = __webpack_require__(45);
  25503. var _mseController2 = _interopRequireDefault(_mseController);
  25504. var _mseEvents = __webpack_require__(16);
  25505. var _mseEvents2 = _interopRequireDefault(_mseEvents);
  25506. var _playerErrors = __webpack_require__(17);
  25507. var _config = __webpack_require__(6);
  25508. var _exception = __webpack_require__(1);
  25509. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25510. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  25511. var FlvPlayer = function () {
  25512. function FlvPlayer(mediaDataSource, config) {
  25513. _classCallCheck(this, FlvPlayer);
  25514. this.TAG = 'FlvPlayer';
  25515. this._type = 'FlvPlayer';
  25516. this._emitter = new _events2.default();
  25517. this._config = (0, _config.createDefaultConfig)();
  25518. if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object') {
  25519. Object.assign(this._config, config);
  25520. }
  25521. if (mediaDataSource.type.toLowerCase() !== 'flv') {
  25522. throw new _exception.InvalidArgumentException('FlvPlayer requires an flv MediaDataSource input!');
  25523. }
  25524. if (mediaDataSource.isLive === true) {
  25525. this._config.isLive = true;
  25526. }
  25527. this.e = {
  25528. onvLoadedMetadata: this._onvLoadedMetadata.bind(this),
  25529. onvSeeking: this._onvSeeking.bind(this),
  25530. onvCanPlay: this._onvCanPlay.bind(this),
  25531. onvStalled: this._onvStalled.bind(this),
  25532. onvProgress: this._onvProgress.bind(this)
  25533. };
  25534. if (self.performance && self.performance.now) {
  25535. this._now = self.performance.now.bind(self.performance);
  25536. } else {
  25537. this._now = Date.now;
  25538. }
  25539. this._pendingSeekTime = null; // in seconds
  25540. this._requestSetTime = false;
  25541. this._seekpointRecord = null;
  25542. this._progressChecker = null;
  25543. this._mediaDataSource = mediaDataSource;
  25544. this._mediaElement = null;
  25545. this._msectl = null;
  25546. this._transmuxer = null;
  25547. this._mseSourceOpened = false;
  25548. this._hasPendingLoad = false;
  25549. this._receivedCanPlay = false;
  25550. this._mediaInfo = null;
  25551. this._statisticsInfo = null;
  25552. var chromeNeedIDRFix = _browser2.default.chrome && (_browser2.default.version.major < 50 || _browser2.default.version.major === 50 && _browser2.default.version.build < 2661);
  25553. this._alwaysSeekKeyframe = chromeNeedIDRFix || _browser2.default.msedge || _browser2.default.msie ? true : false;
  25554. if (this._alwaysSeekKeyframe) {
  25555. this._config.accurateSeek = false;
  25556. }
  25557. }
  25558. _createClass(FlvPlayer, [{
  25559. key: 'destroy',
  25560. value: function destroy() {
  25561. if (this._progressChecker != null) {
  25562. window.clearInterval(this._progressChecker);
  25563. this._progressChecker = null;
  25564. }
  25565. if (this._transmuxer) {
  25566. this.unload();
  25567. }
  25568. if (this._mediaElement) {
  25569. this.detachMediaElement();
  25570. }
  25571. this.e = null;
  25572. this._mediaDataSource = null;
  25573. this._emitter.removeAllListeners();
  25574. this._emitter = null;
  25575. }
  25576. }, {
  25577. key: 'on',
  25578. value: function on(event, listener) {
  25579. var _this = this;
  25580. if (event === _playerEvents2.default.MEDIA_INFO) {
  25581. if (this._mediaInfo != null) {
  25582. Promise.resolve().then(function () {
  25583. _this._emitter.emit(_playerEvents2.default.MEDIA_INFO, _this.mediaInfo);
  25584. });
  25585. }
  25586. } else if (event === _playerEvents2.default.STATISTICS_INFO) {
  25587. if (this._statisticsInfo != null) {
  25588. Promise.resolve().then(function () {
  25589. _this._emitter.emit(_playerEvents2.default.STATISTICS_INFO, _this.statisticsInfo);
  25590. });
  25591. }
  25592. }
  25593. this._emitter.addListener(event, listener);
  25594. }
  25595. }, {
  25596. key: 'off',
  25597. value: function off(event, listener) {
  25598. this._emitter.removeListener(event, listener);
  25599. }
  25600. }, {
  25601. key: 'attachMediaElement',
  25602. value: function attachMediaElement(mediaElement) {
  25603. var _this2 = this;
  25604. this._mediaElement = mediaElement;
  25605. mediaElement.addEventListener('loadedmetadata', this.e.onvLoadedMetadata);
  25606. mediaElement.addEventListener('seeking', this.e.onvSeeking);
  25607. mediaElement.addEventListener('canplay', this.e.onvCanPlay);
  25608. mediaElement.addEventListener('stalled', this.e.onvStalled);
  25609. mediaElement.addEventListener('progress', this.e.onvProgress);
  25610. this._msectl = new _mseController2.default(this._config);
  25611. this._msectl.on(_mseEvents2.default.UPDATE_END, this._onmseUpdateEnd.bind(this));
  25612. this._msectl.on(_mseEvents2.default.BUFFER_FULL, this._onmseBufferFull.bind(this));
  25613. this._msectl.on(_mseEvents2.default.SOURCE_OPEN, function () {
  25614. _this2._mseSourceOpened = true;
  25615. if (_this2._hasPendingLoad) {
  25616. _this2._hasPendingLoad = false;
  25617. _this2.load();
  25618. }
  25619. });
  25620. this._msectl.on(_mseEvents2.default.ERROR, function (info) {
  25621. _this2._emitter.emit(_playerEvents2.default.ERROR, _playerErrors.ErrorTypes.MEDIA_ERROR, _playerErrors.ErrorDetails.MEDIA_MSE_ERROR, info);
  25622. });
  25623. this._msectl.attachMediaElement(mediaElement);
  25624. if (this._pendingSeekTime != null) {
  25625. try {
  25626. mediaElement.currentTime = this._pendingSeekTime;
  25627. this._pendingSeekTime = null;
  25628. } catch (e) {
  25629. // IE11 may throw InvalidStateError if readyState === 0
  25630. // We can defer set currentTime operation after loadedmetadata
  25631. }
  25632. }
  25633. }
  25634. }, {
  25635. key: 'detachMediaElement',
  25636. value: function detachMediaElement() {
  25637. if (this._mediaElement) {
  25638. this._msectl.detachMediaElement();
  25639. this._mediaElement.removeEventListener('loadedmetadata', this.e.onvLoadedMetadata);
  25640. this._mediaElement.removeEventListener('seeking', this.e.onvSeeking);
  25641. this._mediaElement.removeEventListener('canplay', this.e.onvCanPlay);
  25642. this._mediaElement.removeEventListener('stalled', this.e.onvStalled);
  25643. this._mediaElement.removeEventListener('progress', this.e.onvProgress);
  25644. this._mediaElement = null;
  25645. }
  25646. if (this._msectl) {
  25647. this._msectl.destroy();
  25648. this._msectl = null;
  25649. }
  25650. }
  25651. }, {
  25652. key: 'load',
  25653. value: function load() {
  25654. var _this3 = this;
  25655. if (!this._mediaElement) {
  25656. throw new _exception.IllegalStateException('HTMLMediaElement must be attached before load()!');
  25657. }
  25658. if (this._transmuxer) {
  25659. throw new _exception.IllegalStateException('FlvPlayer.load() has been called, please call unload() first!');
  25660. }
  25661. if (this._hasPendingLoad) {
  25662. return;
  25663. }
  25664. if (this._config.deferLoadAfterSourceOpen && this._mseSourceOpened === false) {
  25665. this._hasPendingLoad = true;
  25666. return;
  25667. }
  25668. if (this._mediaElement.readyState > 0) {
  25669. this._requestSetTime = true;
  25670. // IE11 may throw InvalidStateError if readyState === 0
  25671. this._mediaElement.currentTime = 0;
  25672. }
  25673. this._transmuxer = new _transmuxer2.default(this._mediaDataSource, this._config);
  25674. this._transmuxer.on(_transmuxingEvents2.default.INIT_SEGMENT, function (type, is) {
  25675. _this3._msectl.appendInitSegment(is);
  25676. });
  25677. this._transmuxer.on(_transmuxingEvents2.default.MEDIA_SEGMENT, function (type, ms) {
  25678. _this3._msectl.appendMediaSegment(ms);
  25679. // lazyLoad check
  25680. if (_this3._config.lazyLoad && !_this3._config.isLive) {
  25681. var currentTime = _this3._mediaElement.currentTime;
  25682. if (ms.info.endDts >= (currentTime + _this3._config.lazyLoadMaxDuration) * 1000) {
  25683. if (_this3._progressChecker == null) {
  25684. _logger2.default.v(_this3.TAG, 'Maximum buffering duration exceeded, suspend transmuxing task');
  25685. _this3._suspendTransmuxer();
  25686. }
  25687. }
  25688. }
  25689. });
  25690. this._transmuxer.on(_transmuxingEvents2.default.LOADING_COMPLETE, function () {
  25691. _this3._msectl.endOfStream();
  25692. _this3._emitter.emit(_playerEvents2.default.LOADING_COMPLETE);
  25693. });
  25694. this._transmuxer.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF, function () {
  25695. _this3._emitter.emit(_playerEvents2.default.RECOVERED_EARLY_EOF);
  25696. });
  25697. this._transmuxer.on(_transmuxingEvents2.default.IO_ERROR, function (detail, info) {
  25698. _this3._emitter.emit(_playerEvents2.default.ERROR, _playerErrors.ErrorTypes.NETWORK_ERROR, detail, info);
  25699. });
  25700. this._transmuxer.on(_transmuxingEvents2.default.DEMUX_ERROR, function (detail, info) {
  25701. _this3._emitter.emit(_playerEvents2.default.ERROR, _playerErrors.ErrorTypes.MEDIA_ERROR, detail, { code: -1, msg: info });
  25702. });
  25703. this._transmuxer.on(_transmuxingEvents2.default.MEDIA_INFO, function (mediaInfo) {
  25704. _this3._mediaInfo = mediaInfo;
  25705. _this3._emitter.emit(_playerEvents2.default.MEDIA_INFO, Object.assign({}, mediaInfo));
  25706. });
  25707. this._transmuxer.on(_transmuxingEvents2.default.STATISTICS_INFO, function (statInfo) {
  25708. _this3._statisticsInfo = _this3._fillStatisticsInfo(statInfo);
  25709. _this3._emitter.emit(_playerEvents2.default.STATISTICS_INFO, Object.assign({}, _this3._statisticsInfo));
  25710. });
  25711. this._transmuxer.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, function (milliseconds) {
  25712. if (_this3._mediaElement && !_this3._config.accurateSeek) {
  25713. _this3._requestSetTime = true;
  25714. _this3._mediaElement.currentTime = milliseconds / 1000;
  25715. }
  25716. });
  25717. this._transmuxer.on(_transmuxingEvents2.default.LOADED_SEI, function (timestamp, data) {
  25718. _this3._emitter.emit(_playerEvents2.default.LOADED_SEI, timestamp, data);
  25719. });
  25720. this._transmuxer.open();
  25721. }
  25722. }, {
  25723. key: 'unload',
  25724. value: function unload() {
  25725. if (this._mediaElement) {
  25726. this._mediaElement.pause();
  25727. }
  25728. if (this._msectl) {
  25729. this._msectl.seek(0);
  25730. }
  25731. if (this._transmuxer) {
  25732. this._transmuxer.close();
  25733. this._transmuxer.destroy();
  25734. this._transmuxer = null;
  25735. }
  25736. }
  25737. }, {
  25738. key: 'play',
  25739. value: function play() {
  25740. var playPromise = this._mediaElement.play();
  25741. if (playPromise !== undefined && playPromise) {
  25742. return playPromise.catch(function () {});
  25743. } else return undefined;
  25744. }
  25745. }, {
  25746. key: 'pause',
  25747. value: function pause() {
  25748. this._mediaElement.pause();
  25749. }
  25750. }, {
  25751. key: '_fillStatisticsInfo',
  25752. value: function _fillStatisticsInfo(statInfo) {
  25753. statInfo.playerType = this._type;
  25754. if (!(this._mediaElement instanceof HTMLVideoElement)) {
  25755. return statInfo;
  25756. }
  25757. var hasQualityInfo = true;
  25758. var decoded = 0;
  25759. var dropped = 0;
  25760. if (this._mediaElement.getVideoPlaybackQuality) {
  25761. var quality = this._mediaElement.getVideoPlaybackQuality();
  25762. decoded = quality.totalVideoFrames;
  25763. dropped = quality.droppedVideoFrames;
  25764. } else if (this._mediaElement.webkitDecodedFrameCount != undefined) {
  25765. decoded = this._mediaElement.webkitDecodedFrameCount;
  25766. dropped = this._mediaElement.webkitDroppedFrameCount;
  25767. } else {
  25768. hasQualityInfo = false;
  25769. }
  25770. if (hasQualityInfo) {
  25771. statInfo.decodedFrames = decoded;
  25772. statInfo.droppedFrames = dropped;
  25773. }
  25774. return statInfo;
  25775. }
  25776. }, {
  25777. key: '_onmseUpdateEnd',
  25778. value: function _onmseUpdateEnd() {
  25779. if (!this._config.lazyLoad || this._config.isLive) {
  25780. return;
  25781. }
  25782. var buffered = this._mediaElement.buffered;
  25783. var currentTime = this._mediaElement.currentTime;
  25784. var currentRangeStart = 0;
  25785. var currentRangeEnd = 0;
  25786. for (var i = 0; i < buffered.length; i++) {
  25787. var start = buffered.start(i);
  25788. var end = buffered.end(i);
  25789. if (start <= currentTime && currentTime < end) {
  25790. currentRangeStart = start;
  25791. currentRangeEnd = end;
  25792. break;
  25793. }
  25794. }
  25795. if (currentRangeEnd >= currentTime + this._config.lazyLoadMaxDuration && this._progressChecker == null) {
  25796. _logger2.default.v(this.TAG, 'Maximum buffering duration exceeded, suspend transmuxing task');
  25797. this._suspendTransmuxer();
  25798. }
  25799. }
  25800. }, {
  25801. key: '_onmseBufferFull',
  25802. value: function _onmseBufferFull() {
  25803. _logger2.default.v(this.TAG, 'MSE SourceBuffer is full, suspend transmuxing task');
  25804. if (this._progressChecker == null) {
  25805. this._suspendTransmuxer();
  25806. }
  25807. }
  25808. }, {
  25809. key: '_suspendTransmuxer',
  25810. value: function _suspendTransmuxer() {
  25811. if (this._transmuxer) {
  25812. this._transmuxer.pause();
  25813. if (this._progressChecker == null) {
  25814. this._progressChecker = window.setInterval(this._checkProgressAndResume.bind(this), 1000);
  25815. }
  25816. }
  25817. }
  25818. }, {
  25819. key: '_checkProgressAndResume',
  25820. value: function _checkProgressAndResume() {
  25821. var currentTime = this._mediaElement.currentTime;
  25822. var buffered = this._mediaElement.buffered;
  25823. var needResume = false;
  25824. for (var i = 0; i < buffered.length; i++) {
  25825. var from = buffered.start(i);
  25826. var to = buffered.end(i);
  25827. if (currentTime >= from && currentTime < to) {
  25828. if (currentTime >= to - this._config.lazyLoadRecoverDuration) {
  25829. needResume = true;
  25830. }
  25831. break;
  25832. }
  25833. }
  25834. if (needResume) {
  25835. window.clearInterval(this._progressChecker);
  25836. this._progressChecker = null;
  25837. if (needResume) {
  25838. _logger2.default.v(this.TAG, 'Continue loading from paused position');
  25839. this._transmuxer.resume();
  25840. }
  25841. }
  25842. }
  25843. }, {
  25844. key: '_isTimepointBuffered',
  25845. value: function _isTimepointBuffered(seconds) {
  25846. var buffered = this._mediaElement.buffered;
  25847. for (var i = 0; i < buffered.length; i++) {
  25848. var from = buffered.start(i);
  25849. var to = buffered.end(i);
  25850. if (seconds >= from && seconds < to) {
  25851. return true;
  25852. }
  25853. }
  25854. return false;
  25855. }
  25856. }, {
  25857. key: '_internalSeek',
  25858. value: function _internalSeek(seconds) {
  25859. var directSeek = this._isTimepointBuffered(seconds);
  25860. var directSeekBegin = false;
  25861. var directSeekBeginTime = 0;
  25862. if (seconds < 1.0 && this._mediaElement.buffered.length > 0) {
  25863. var videoBeginTime = this._mediaElement.buffered.start(0);
  25864. if (videoBeginTime < 1.0 && seconds < videoBeginTime || _browser2.default.safari) {
  25865. directSeekBegin = true;
  25866. // also workaround for Safari: Seek to 0 may cause video stuck, use 0.1 to avoid
  25867. directSeekBeginTime = _browser2.default.safari ? 0.1 : videoBeginTime;
  25868. }
  25869. }
  25870. if (directSeekBegin) {
  25871. // seek to video begin, set currentTime directly if beginPTS buffered
  25872. this._requestSetTime = true;
  25873. this._mediaElement.currentTime = directSeekBeginTime;
  25874. } else if (directSeek) {
  25875. // buffered position
  25876. if (!this._alwaysSeekKeyframe) {
  25877. this._requestSetTime = true;
  25878. this._mediaElement.currentTime = seconds;
  25879. } else {
  25880. var idr = this._msectl.getNearestKeyframe(Math.floor(seconds * 1000));
  25881. this._requestSetTime = true;
  25882. if (idr != null) {
  25883. this._mediaElement.currentTime = idr.dts / 1000;
  25884. } else {
  25885. this._mediaElement.currentTime = seconds;
  25886. }
  25887. }
  25888. if (this._progressChecker != null) {
  25889. this._checkProgressAndResume();
  25890. }
  25891. } else {
  25892. if (this._progressChecker != null) {
  25893. window.clearInterval(this._progressChecker);
  25894. this._progressChecker = null;
  25895. }
  25896. this._msectl.seek(seconds);
  25897. this._transmuxer.seek(Math.floor(seconds * 1000)); // in milliseconds
  25898. // no need to set mediaElement.currentTime if non-accurateSeek,
  25899. // just wait for the recommend_seekpoint callback
  25900. if (this._config.accurateSeek) {
  25901. this._requestSetTime = true;
  25902. this._mediaElement.currentTime = seconds;
  25903. }
  25904. }
  25905. }
  25906. }, {
  25907. key: '_checkAndApplyUnbufferedSeekpoint',
  25908. value: function _checkAndApplyUnbufferedSeekpoint() {
  25909. if (this._seekpointRecord) {
  25910. if (this._seekpointRecord.recordTime <= this._now() - 100) {
  25911. var target = this._mediaElement.currentTime;
  25912. this._seekpointRecord = null;
  25913. if (!this._isTimepointBuffered(target)) {
  25914. if (this._progressChecker != null) {
  25915. window.clearTimeout(this._progressChecker);
  25916. this._progressChecker = null;
  25917. }
  25918. // .currentTime is consists with .buffered timestamp
  25919. // Chrome/Edge use DTS, while FireFox/Safari use PTS
  25920. this._msectl.seek(target);
  25921. this._transmuxer.seek(Math.floor(target * 1000));
  25922. // set currentTime if accurateSeek, or wait for recommend_seekpoint callback
  25923. if (this._config.accurateSeek) {
  25924. this._requestSetTime = true;
  25925. this._mediaElement.currentTime = target;
  25926. }
  25927. }
  25928. } else {
  25929. window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this), 50);
  25930. }
  25931. }
  25932. }
  25933. }, {
  25934. key: '_checkAndResumeStuckPlayback',
  25935. value: function _checkAndResumeStuckPlayback(stalled) {
  25936. var media = this._mediaElement;
  25937. if (stalled || !this._receivedCanPlay || media.readyState < 2) {
  25938. // HAVE_CURRENT_DATA
  25939. var buffered = media.buffered;
  25940. if (buffered.length > 0 && media.currentTime < buffered.start(0)) {
  25941. _logger2.default.w(this.TAG, 'Playback seems stuck at ' + media.currentTime + ', seek to ' + buffered.start(0));
  25942. this._requestSetTime = true;
  25943. this._mediaElement.currentTime = buffered.start(0);
  25944. this._mediaElement.removeEventListener('progress', this.e.onvProgress);
  25945. }
  25946. } else {
  25947. // Playback didn't stuck, remove progress event listener
  25948. this._mediaElement.removeEventListener('progress', this.e.onvProgress);
  25949. }
  25950. }
  25951. }, {
  25952. key: '_onvLoadedMetadata',
  25953. value: function _onvLoadedMetadata(e) {
  25954. if (this._pendingSeekTime != null) {
  25955. this._mediaElement.currentTime = this._pendingSeekTime;
  25956. this._pendingSeekTime = null;
  25957. }
  25958. }
  25959. }, {
  25960. key: '_onvSeeking',
  25961. value: function _onvSeeking(e) {
  25962. // handle seeking request from browser's progress bar
  25963. var target = this._mediaElement.currentTime;
  25964. var buffered = this._mediaElement.buffered;
  25965. if (this._requestSetTime) {
  25966. this._requestSetTime = false;
  25967. return;
  25968. }
  25969. if (target < 1.0 && buffered.length > 0) {
  25970. // seek to video begin, set currentTime directly if beginPTS buffered
  25971. var videoBeginTime = buffered.start(0);
  25972. if (videoBeginTime < 1.0 && target < videoBeginTime || _browser2.default.safari) {
  25973. this._requestSetTime = true;
  25974. // also workaround for Safari: Seek to 0 may cause video stuck, use 0.1 to avoid
  25975. this._mediaElement.currentTime = _browser2.default.safari ? 0.1 : videoBeginTime;
  25976. return;
  25977. }
  25978. }
  25979. if (this._isTimepointBuffered(target)) {
  25980. if (this._alwaysSeekKeyframe) {
  25981. var idr = this._msectl.getNearestKeyframe(Math.floor(target * 1000));
  25982. if (idr != null) {
  25983. this._requestSetTime = true;
  25984. this._mediaElement.currentTime = idr.dts / 1000;
  25985. }
  25986. }
  25987. if (this._progressChecker != null) {
  25988. this._checkProgressAndResume();
  25989. }
  25990. return;
  25991. }
  25992. this._seekpointRecord = {
  25993. seekPoint: target,
  25994. recordTime: this._now()
  25995. };
  25996. window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this), 50);
  25997. }
  25998. }, {
  25999. key: '_onvCanPlay',
  26000. value: function _onvCanPlay(e) {
  26001. this._receivedCanPlay = true;
  26002. this._mediaElement.removeEventListener('canplay', this.e.onvCanPlay);
  26003. }
  26004. }, {
  26005. key: '_onvStalled',
  26006. value: function _onvStalled(e) {
  26007. this._checkAndResumeStuckPlayback(true);
  26008. }
  26009. }, {
  26010. key: '_onvProgress',
  26011. value: function _onvProgress(e) {
  26012. this._checkAndResumeStuckPlayback();
  26013. }
  26014. }, {
  26015. key: 'type',
  26016. get: function get() {
  26017. return this._type;
  26018. }
  26019. }, {
  26020. key: 'buffered',
  26021. get: function get() {
  26022. return this._mediaElement.buffered;
  26023. }
  26024. }, {
  26025. key: 'duration',
  26026. get: function get() {
  26027. return this._mediaElement.duration;
  26028. }
  26029. }, {
  26030. key: 'volume',
  26031. get: function get() {
  26032. return this._mediaElement.volume;
  26033. },
  26034. set: function set(value) {
  26035. this._mediaElement.volume = value;
  26036. }
  26037. }, {
  26038. key: 'muted',
  26039. get: function get() {
  26040. return this._mediaElement.muted;
  26041. },
  26042. set: function set(muted) {
  26043. this._mediaElement.muted = muted;
  26044. }
  26045. }, {
  26046. key: 'currentTime',
  26047. get: function get() {
  26048. if (this._mediaElement) {
  26049. return this._mediaElement.currentTime;
  26050. }
  26051. return 0;
  26052. },
  26053. set: function set(seconds) {
  26054. if (this._mediaElement) {
  26055. this._internalSeek(seconds);
  26056. } else {
  26057. this._pendingSeekTime = seconds;
  26058. }
  26059. }
  26060. }, {
  26061. key: 'mediaInfo',
  26062. get: function get() {
  26063. return Object.assign({}, this._mediaInfo);
  26064. }
  26065. }, {
  26066. key: 'statisticsInfo',
  26067. get: function get() {
  26068. if (this._statisticsInfo == null) {
  26069. this._statisticsInfo = {};
  26070. }
  26071. this._statisticsInfo = this._fillStatisticsInfo(this._statisticsInfo);
  26072. return Object.assign({}, this._statisticsInfo);
  26073. }
  26074. }]);
  26075. return FlvPlayer;
  26076. }();
  26077. exports.default = FlvPlayer;
  26078. module.exports = exports['default'];
  26079. /***/ }),
  26080. /* 34 */
  26081. /***/ (function(module, exports, __webpack_require__) {
  26082. "use strict";
  26083. Object.defineProperty(exports, "__esModule", {
  26084. value: true
  26085. });
  26086. 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; }; }(); /*
  26087. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  26088. *
  26089. * @author zheng qian <xqq@xqq.im>
  26090. *
  26091. * Licensed under the Apache License, Version 2.0 (the "License");
  26092. * you may not use this file except in compliance with the License.
  26093. * You may obtain a copy of the License at
  26094. *
  26095. * http://www.apache.org/licenses/LICENSE-2.0
  26096. *
  26097. * Unless required by applicable law or agreed to in writing, software
  26098. * distributed under the License is distributed on an "AS IS" BASIS,
  26099. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26100. * See the License for the specific language governing permissions and
  26101. * limitations under the License.
  26102. */
  26103. var _events = __webpack_require__(2);
  26104. var _events2 = _interopRequireDefault(_events);
  26105. var _logger = __webpack_require__(0);
  26106. var _logger2 = _interopRequireDefault(_logger);
  26107. var _loggingControl = __webpack_require__(8);
  26108. var _loggingControl2 = _interopRequireDefault(_loggingControl);
  26109. var _transmuxingController = __webpack_require__(14);
  26110. var _transmuxingController2 = _interopRequireDefault(_transmuxingController);
  26111. var _transmuxingEvents = __webpack_require__(5);
  26112. var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
  26113. var _transmuxingWorker = __webpack_require__(43);
  26114. var _transmuxingWorker2 = _interopRequireDefault(_transmuxingWorker);
  26115. var _mediaInfo = __webpack_require__(9);
  26116. var _mediaInfo2 = _interopRequireDefault(_mediaInfo);
  26117. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26118. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  26119. var Transmuxer = function () {
  26120. function Transmuxer(mediaDataSource, config) {
  26121. _classCallCheck(this, Transmuxer);
  26122. this.TAG = 'Transmuxer';
  26123. this._emitter = new _events2.default();
  26124. if (config.enableWorker && typeof Worker !== 'undefined') {
  26125. try {
  26126. var work = __webpack_require__(44);
  26127. this._worker = work(_transmuxingWorker2.default);
  26128. this._workerDestroying = false;
  26129. this._worker.addEventListener('message', this._onWorkerMessage.bind(this));
  26130. this._worker.postMessage({ cmd: 'init', param: [mediaDataSource, config] });
  26131. this.e = {
  26132. onLoggingConfigChanged: this._onLoggingConfigChanged.bind(this)
  26133. };
  26134. _loggingControl2.default.registerListener(this.e.onLoggingConfigChanged);
  26135. this._worker.postMessage({ cmd: 'logging_config', param: _loggingControl2.default.getConfig() });
  26136. } catch (error) {
  26137. _logger2.default.e(this.TAG, 'Error while initialize transmuxing worker, fallback to inline transmuxing');
  26138. this._worker = null;
  26139. this._controller = new _transmuxingController2.default(mediaDataSource, config);
  26140. }
  26141. } else {
  26142. this._controller = new _transmuxingController2.default(mediaDataSource, config);
  26143. }
  26144. if (this._controller) {
  26145. var ctl = this._controller;
  26146. ctl.on(_transmuxingEvents2.default.IO_ERROR, this._onIOError.bind(this));
  26147. ctl.on(_transmuxingEvents2.default.DEMUX_ERROR, this._onDemuxError.bind(this));
  26148. ctl.on(_transmuxingEvents2.default.INIT_SEGMENT, this._onInitSegment.bind(this));
  26149. ctl.on(_transmuxingEvents2.default.MEDIA_SEGMENT, this._onMediaSegment.bind(this));
  26150. ctl.on(_transmuxingEvents2.default.LOADING_COMPLETE, this._onLoadingComplete.bind(this));
  26151. ctl.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF, this._onRecoveredEarlyEof.bind(this));
  26152. ctl.on(_transmuxingEvents2.default.MEDIA_INFO, this._onMediaInfo.bind(this));
  26153. ctl.on(_transmuxingEvents2.default.STATISTICS_INFO, this._onStatisticsInfo.bind(this));
  26154. ctl.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, this._onRecommendSeekpoint.bind(this));
  26155. ctl.on(_transmuxingEvents2.default.LOADED_SEI, this._onLoadedSei.bind(this));
  26156. }
  26157. }
  26158. _createClass(Transmuxer, [{
  26159. key: 'destroy',
  26160. value: function destroy() {
  26161. if (this._worker) {
  26162. if (!this._workerDestroying) {
  26163. this._workerDestroying = true;
  26164. this._worker.postMessage({ cmd: 'destroy' });
  26165. _loggingControl2.default.removeListener(this.e.onLoggingConfigChanged);
  26166. this.e = null;
  26167. }
  26168. } else {
  26169. this._controller.destroy();
  26170. this._controller = null;
  26171. }
  26172. this._emitter.removeAllListeners();
  26173. this._emitter = null;
  26174. }
  26175. }, {
  26176. key: 'on',
  26177. value: function on(event, listener) {
  26178. this._emitter.addListener(event, listener);
  26179. }
  26180. }, {
  26181. key: 'off',
  26182. value: function off(event, listener) {
  26183. this._emitter.removeListener(event, listener);
  26184. }
  26185. }, {
  26186. key: 'hasWorker',
  26187. value: function hasWorker() {
  26188. return this._worker != null;
  26189. }
  26190. }, {
  26191. key: 'open',
  26192. value: function open() {
  26193. if (this._worker) {
  26194. this._worker.postMessage({ cmd: 'start' });
  26195. } else {
  26196. this._controller.start();
  26197. }
  26198. }
  26199. }, {
  26200. key: 'close',
  26201. value: function close() {
  26202. if (this._worker) {
  26203. this._worker.postMessage({ cmd: 'stop' });
  26204. } else {
  26205. this._controller.stop();
  26206. }
  26207. }
  26208. }, {
  26209. key: 'seek',
  26210. value: function seek(milliseconds) {
  26211. if (this._worker) {
  26212. this._worker.postMessage({ cmd: 'seek', param: milliseconds });
  26213. } else {
  26214. this._controller.seek(milliseconds);
  26215. }
  26216. }
  26217. }, {
  26218. key: 'pause',
  26219. value: function pause() {
  26220. if (this._worker) {
  26221. this._worker.postMessage({ cmd: 'pause' });
  26222. } else {
  26223. this._controller.pause();
  26224. }
  26225. }
  26226. }, {
  26227. key: 'resume',
  26228. value: function resume() {
  26229. if (this._worker) {
  26230. this._worker.postMessage({ cmd: 'resume' });
  26231. } else {
  26232. this._controller.resume();
  26233. }
  26234. }
  26235. }, {
  26236. key: '_onInitSegment',
  26237. value: function _onInitSegment(type, initSegment) {
  26238. var _this = this;
  26239. // do async invoke
  26240. Promise.resolve().then(function () {
  26241. _this._emitter.emit(_transmuxingEvents2.default.INIT_SEGMENT, type, initSegment);
  26242. });
  26243. }
  26244. }, {
  26245. key: '_onMediaSegment',
  26246. value: function _onMediaSegment(type, mediaSegment) {
  26247. var _this2 = this;
  26248. Promise.resolve().then(function () {
  26249. _this2._emitter.emit(_transmuxingEvents2.default.MEDIA_SEGMENT, type, mediaSegment);
  26250. });
  26251. }
  26252. }, {
  26253. key: '_onLoadingComplete',
  26254. value: function _onLoadingComplete() {
  26255. var _this3 = this;
  26256. Promise.resolve().then(function () {
  26257. _this3._emitter.emit(_transmuxingEvents2.default.LOADING_COMPLETE);
  26258. });
  26259. }
  26260. }, {
  26261. key: '_onRecoveredEarlyEof',
  26262. value: function _onRecoveredEarlyEof() {
  26263. var _this4 = this;
  26264. Promise.resolve().then(function () {
  26265. _this4._emitter.emit(_transmuxingEvents2.default.RECOVERED_EARLY_EOF);
  26266. });
  26267. }
  26268. }, {
  26269. key: '_onMediaInfo',
  26270. value: function _onMediaInfo(mediaInfo) {
  26271. var _this5 = this;
  26272. Promise.resolve().then(function () {
  26273. _this5._emitter.emit(_transmuxingEvents2.default.MEDIA_INFO, mediaInfo);
  26274. });
  26275. }
  26276. }, {
  26277. key: '_onStatisticsInfo',
  26278. value: function _onStatisticsInfo(statisticsInfo) {
  26279. var _this6 = this;
  26280. Promise.resolve().then(function () {
  26281. _this6._emitter.emit(_transmuxingEvents2.default.STATISTICS_INFO, statisticsInfo);
  26282. });
  26283. }
  26284. }, {
  26285. key: '_onIOError',
  26286. value: function _onIOError(type, info) {
  26287. var _this7 = this;
  26288. Promise.resolve().then(function () {
  26289. _this7._emitter.emit(_transmuxingEvents2.default.IO_ERROR, type, info);
  26290. });
  26291. }
  26292. }, {
  26293. key: '_onDemuxError',
  26294. value: function _onDemuxError(type, info) {
  26295. var _this8 = this;
  26296. Promise.resolve().then(function () {
  26297. _this8._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR, type, info);
  26298. });
  26299. }
  26300. }, {
  26301. key: '_onRecommendSeekpoint',
  26302. value: function _onRecommendSeekpoint(milliseconds) {
  26303. var _this9 = this;
  26304. Promise.resolve().then(function () {
  26305. _this9._emitter.emit(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, milliseconds);
  26306. });
  26307. }
  26308. }, {
  26309. key: '_onLoadedSei',
  26310. value: function _onLoadedSei(timestamp, data) {
  26311. var _this10 = this;
  26312. Promise.resolve().then(function () {
  26313. _this10._emitter.emit(_transmuxingEvents2.default.LOADED_SEI, timestamp, data);
  26314. });
  26315. }
  26316. }, {
  26317. key: '_onLoggingConfigChanged',
  26318. value: function _onLoggingConfigChanged(config) {
  26319. if (this._worker) {
  26320. this._worker.postMessage({ cmd: 'logging_config', param: config });
  26321. }
  26322. }
  26323. }, {
  26324. key: '_onWorkerMessage',
  26325. value: function _onWorkerMessage(e) {
  26326. var message = e.data;
  26327. var data = message.data;
  26328. if (message.msg === 'destroyed' || this._workerDestroying) {
  26329. this._workerDestroying = false;
  26330. this._worker.terminate();
  26331. this._worker = null;
  26332. return;
  26333. }
  26334. switch (message.msg) {
  26335. case _transmuxingEvents2.default.INIT_SEGMENT:
  26336. case _transmuxingEvents2.default.MEDIA_SEGMENT:
  26337. this._emitter.emit(message.msg, data.type, data.data);
  26338. break;
  26339. case _transmuxingEvents2.default.LOADING_COMPLETE:
  26340. case _transmuxingEvents2.default.RECOVERED_EARLY_EOF:
  26341. this._emitter.emit(message.msg);
  26342. break;
  26343. case _transmuxingEvents2.default.MEDIA_INFO:
  26344. Object.setPrototypeOf(data, _mediaInfo2.default.prototype);
  26345. this._emitter.emit(message.msg, data);
  26346. break;
  26347. case _transmuxingEvents2.default.STATISTICS_INFO:
  26348. this._emitter.emit(message.msg, data);
  26349. break;
  26350. case _transmuxingEvents2.default.IO_ERROR:
  26351. case _transmuxingEvents2.default.DEMUX_ERROR:
  26352. this._emitter.emit(message.msg, data.type, data.info);
  26353. break;
  26354. case _transmuxingEvents2.default.RECOMMEND_SEEKPOINT:
  26355. this._emitter.emit(message.msg, data);
  26356. break;
  26357. case 'logcat_callback':
  26358. _logger2.default.emitter.emit('log', data.type, data.logcat);
  26359. break;
  26360. default:
  26361. break;
  26362. }
  26363. }
  26364. }]);
  26365. return Transmuxer;
  26366. }();
  26367. exports.default = Transmuxer;
  26368. module.exports = exports['default'];
  26369. /***/ }),
  26370. /* 35 */
  26371. /***/ (function(module, exports, __webpack_require__) {
  26372. "use strict";
  26373. Object.defineProperty(exports, "__esModule", {
  26374. value: true
  26375. });
  26376. 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; };
  26377. 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; }; }(); /*
  26378. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  26379. *
  26380. * @author zheng qian <xqq@xqq.im>
  26381. *
  26382. * Licensed under the Apache License, Version 2.0 (the "License");
  26383. * you may not use this file except in compliance with the License.
  26384. * You may obtain a copy of the License at
  26385. *
  26386. * http://www.apache.org/licenses/LICENSE-2.0
  26387. *
  26388. * Unless required by applicable law or agreed to in writing, software
  26389. * distributed under the License is distributed on an "AS IS" BASIS,
  26390. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26391. * See the License for the specific language governing permissions and
  26392. * limitations under the License.
  26393. */
  26394. var _logger = __webpack_require__(0);
  26395. var _logger2 = _interopRequireDefault(_logger);
  26396. var _amfParser = __webpack_require__(36);
  26397. var _amfParser2 = _interopRequireDefault(_amfParser);
  26398. var _spsParser = __webpack_require__(38);
  26399. var _spsParser2 = _interopRequireDefault(_spsParser);
  26400. var _demuxErrors = __webpack_require__(10);
  26401. var _demuxErrors2 = _interopRequireDefault(_demuxErrors);
  26402. var _mediaInfo = __webpack_require__(9);
  26403. var _mediaInfo2 = _interopRequireDefault(_mediaInfo);
  26404. var _exception = __webpack_require__(1);
  26405. var _events = __webpack_require__(2);
  26406. var _events2 = _interopRequireDefault(_events);
  26407. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26408. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  26409. function Swap16(src) {
  26410. return src >>> 8 & 0xFF | (src & 0xFF) << 8;
  26411. }
  26412. function Swap32(src) {
  26413. return (src & 0xFF000000) >>> 24 | (src & 0x00FF0000) >>> 8 | (src & 0x0000FF00) << 8 | (src & 0x000000FF) << 24;
  26414. }
  26415. function ReadBig32(array, index) {
  26416. return array[index] << 24 | array[index + 1] << 16 | array[index + 2] << 8 | array[index + 3];
  26417. }
  26418. var FLVDemuxer = function () {
  26419. function FLVDemuxer(probeData, config) {
  26420. _classCallCheck(this, FLVDemuxer);
  26421. this.TAG = 'FLVDemuxer';
  26422. this._emitter = new _events2.default();
  26423. this._config = config;
  26424. this._onError = null;
  26425. this._onMediaInfo = null;
  26426. this._onTrackMetadata = null;
  26427. this._onDataAvailable = null;
  26428. this._dataOffset = probeData.dataOffset;
  26429. this._firstParse = true;
  26430. this._dispatch = false;
  26431. this._hasAudio = probeData.hasAudioTrack;
  26432. this._hasVideo = probeData.hasVideoTrack;
  26433. this._hasAudioFlagOverrided = false;
  26434. this._hasVideoFlagOverrided = false;
  26435. this._audioInitialMetadataDispatched = false;
  26436. this._videoInitialMetadataDispatched = false;
  26437. this._mediaInfo = new _mediaInfo2.default();
  26438. this._mediaInfo.hasAudio = this._hasAudio;
  26439. this._mediaInfo.hasVideo = this._hasVideo;
  26440. this._metadata = null;
  26441. this._audioMetadata = null;
  26442. this._videoMetadata = null;
  26443. this._naluLengthSize = 4;
  26444. this._timestampBase = 0; // int32, in milliseconds
  26445. this._timescale = 1000;
  26446. this._duration = 0; // int32, in milliseconds
  26447. this._durationOverrided = false;
  26448. this._referenceFrameRate = {
  26449. fixed: true,
  26450. fps: 23.976,
  26451. fps_num: 23976,
  26452. fps_den: 1000
  26453. };
  26454. this._flvSoundRateTable = [5500, 11025, 22050, 44100, 48000];
  26455. this._mpegSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  26456. this._mpegAudioV10SampleRateTable = [44100, 48000, 32000, 0];
  26457. this._mpegAudioV20SampleRateTable = [22050, 24000, 16000, 0];
  26458. this._mpegAudioV25SampleRateTable = [11025, 12000, 8000, 0];
  26459. this._mpegAudioL1BitRateTable = [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, -1];
  26460. this._mpegAudioL2BitRateTable = [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, -1];
  26461. this._mpegAudioL3BitRateTable = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1];
  26462. this._videoTrack = { type: 'video', id: 1, sequenceNumber: 0, samples: [], length: 0 };
  26463. this._audioTrack = { type: 'audio', id: 2, sequenceNumber: 0, samples: [], length: 0 };
  26464. this._littleEndian = function () {
  26465. var buf = new ArrayBuffer(2);
  26466. new DataView(buf).setInt16(0, 256, true); // little-endian write
  26467. return new Int16Array(buf)[0] === 256; // platform-spec read, if equal then LE
  26468. }();
  26469. }
  26470. _createClass(FLVDemuxer, [{
  26471. key: 'destroy',
  26472. value: function destroy() {
  26473. this._mediaInfo = null;
  26474. this._metadata = null;
  26475. this._audioMetadata = null;
  26476. this._videoMetadata = null;
  26477. this._videoTrack = null;
  26478. this._audioTrack = null;
  26479. this._onError = null;
  26480. this._onMediaInfo = null;
  26481. this._onTrackMetadata = null;
  26482. this._onDataAvailable = null;
  26483. this._emitter.removeAllListeners();
  26484. this._emitter = null;
  26485. }
  26486. }, {
  26487. key: 'bindDataSource',
  26488. value: function bindDataSource(loader) {
  26489. loader.onDataArrival = this.parseChunks.bind(this);
  26490. return this;
  26491. }
  26492. // prototype: function(type: string, metadata: any): void
  26493. }, {
  26494. key: 'resetMediaInfo',
  26495. value: function resetMediaInfo() {
  26496. this._mediaInfo = new _mediaInfo2.default();
  26497. }
  26498. }, {
  26499. key: '_isInitialMetadataDispatched',
  26500. value: function _isInitialMetadataDispatched() {
  26501. if (this._hasAudio && this._hasVideo) {
  26502. // both audio & video
  26503. return this._audioInitialMetadataDispatched && this._videoInitialMetadataDispatched;
  26504. }
  26505. if (this._hasAudio && !this._hasVideo) {
  26506. // audio only
  26507. return this._audioInitialMetadataDispatched;
  26508. }
  26509. if (!this._hasAudio && this._hasVideo) {
  26510. // video only
  26511. return this._videoInitialMetadataDispatched;
  26512. }
  26513. return false;
  26514. }
  26515. // function parseChunks(chunk: ArrayBuffer, byteStart: number): number;
  26516. }, {
  26517. key: 'parseChunks',
  26518. value: function parseChunks(chunk, byteStart) {
  26519. if (!this._onError || !this._onMediaInfo || !this._onTrackMetadata || !this._onDataAvailable) {
  26520. throw new _exception.IllegalStateException('Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified');
  26521. }
  26522. var offset = 0;
  26523. var le = this._littleEndian;
  26524. if (byteStart === 0) {
  26525. // buffer with FLV header
  26526. if (chunk.byteLength > 13) {
  26527. var probeData = FLVDemuxer.probe(chunk);
  26528. offset = probeData.dataOffset;
  26529. } else {
  26530. return 0;
  26531. }
  26532. }
  26533. if (this._firstParse) {
  26534. // handle PreviousTagSize0 before Tag1
  26535. this._firstParse = false;
  26536. if (byteStart + offset !== this._dataOffset) {
  26537. _logger2.default.w(this.TAG, 'First time parsing but chunk byteStart invalid!');
  26538. }
  26539. var v = new DataView(chunk, offset);
  26540. var prevTagSize0 = v.getUint32(0, !le);
  26541. if (prevTagSize0 !== 0) {
  26542. _logger2.default.w(this.TAG, 'PrevTagSize0 !== 0 !!!');
  26543. }
  26544. offset += 4;
  26545. }
  26546. while (offset < chunk.byteLength) {
  26547. this._dispatch = true;
  26548. var _v = new DataView(chunk, offset);
  26549. if (offset + 11 + 4 > chunk.byteLength) {
  26550. // data not enough for parsing an flv tag
  26551. break;
  26552. }
  26553. var tagType = _v.getUint8(0);
  26554. var dataSize = _v.getUint32(0, !le) & 0x00FFFFFF;
  26555. if (offset + 11 + dataSize + 4 > chunk.byteLength) {
  26556. // data not enough for parsing actual data body
  26557. break;
  26558. }
  26559. if (tagType !== 8 && tagType !== 9 && tagType !== 18) {
  26560. _logger2.default.w(this.TAG, 'Unsupported tag type ' + tagType + ', skipped');
  26561. // consume the whole tag (skip it)
  26562. offset += 11 + dataSize + 4;
  26563. continue;
  26564. }
  26565. var ts2 = _v.getUint8(4);
  26566. var ts1 = _v.getUint8(5);
  26567. var ts0 = _v.getUint8(6);
  26568. var ts3 = _v.getUint8(7);
  26569. var timestamp = ts0 | ts1 << 8 | ts2 << 16 | ts3 << 24;
  26570. var streamId = _v.getUint32(7, !le) & 0x00FFFFFF;
  26571. if (streamId !== 0) {
  26572. _logger2.default.w(this.TAG, 'Meet tag which has StreamID != 0!');
  26573. }
  26574. var dataOffset = offset + 11;
  26575. switch (tagType) {
  26576. case 8:
  26577. // Audio
  26578. this._parseAudioData(chunk, dataOffset, dataSize, timestamp);
  26579. break;
  26580. case 9:
  26581. // Video
  26582. this._parseVideoData(chunk, dataOffset, dataSize, timestamp, byteStart + offset);
  26583. break;
  26584. case 18:
  26585. // ScriptDataObject
  26586. this._parseScriptData(chunk, dataOffset, dataSize);
  26587. break;
  26588. }
  26589. var prevTagSize = _v.getUint32(11 + dataSize, !le);
  26590. if (prevTagSize !== 11 + dataSize) {
  26591. _logger2.default.w(this.TAG, 'Invalid PrevTagSize ' + prevTagSize);
  26592. }
  26593. offset += 11 + dataSize + 4; // tagBody + dataSize + prevTagSize
  26594. }
  26595. // dispatch parsed frames to consumer (typically, the remuxer)
  26596. if (this._isInitialMetadataDispatched()) {
  26597. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  26598. this._onDataAvailable(this._audioTrack, this._videoTrack);
  26599. }
  26600. }
  26601. return offset; // consumed bytes, just equals latest offset index
  26602. }
  26603. }, {
  26604. key: '_parseScriptData',
  26605. value: function _parseScriptData(arrayBuffer, dataOffset, dataSize) {
  26606. var scriptData = _amfParser2.default.parseScriptData(arrayBuffer, dataOffset, dataSize);
  26607. if (scriptData.hasOwnProperty('onMetaData')) {
  26608. if (scriptData.onMetaData == null || _typeof(scriptData.onMetaData) !== 'object') {
  26609. _logger2.default.w(this.TAG, 'Invalid onMetaData structure!');
  26610. return;
  26611. }
  26612. if (this._metadata) {
  26613. _logger2.default.w(this.TAG, 'Found another onMetaData tag!');
  26614. }
  26615. this._metadata = scriptData;
  26616. var onMetaData = this._metadata.onMetaData;
  26617. this._emitter.emit('metadata_arrived', onMetaData);
  26618. if (typeof onMetaData.hasAudio === 'boolean') {
  26619. // hasAudio
  26620. if (this._hasAudioFlagOverrided === false) {
  26621. this._hasAudio = onMetaData.hasAudio;
  26622. this._mediaInfo.hasAudio = this._hasAudio;
  26623. }
  26624. }
  26625. if (typeof onMetaData.hasVideo === 'boolean') {
  26626. // hasVideo
  26627. if (this._hasVideoFlagOverrided === false) {
  26628. this._hasVideo = onMetaData.hasVideo;
  26629. this._mediaInfo.hasVideo = this._hasVideo;
  26630. }
  26631. }
  26632. if (typeof onMetaData.audiodatarate === 'number') {
  26633. // audiodatarate
  26634. this._mediaInfo.audioDataRate = onMetaData.audiodatarate;
  26635. }
  26636. if (typeof onMetaData.videodatarate === 'number') {
  26637. // videodatarate
  26638. this._mediaInfo.videoDataRate = onMetaData.videodatarate;
  26639. }
  26640. if (typeof onMetaData.width === 'number') {
  26641. // width
  26642. this._mediaInfo.width = onMetaData.width;
  26643. }
  26644. if (typeof onMetaData.height === 'number') {
  26645. // height
  26646. this._mediaInfo.height = onMetaData.height;
  26647. }
  26648. if (typeof onMetaData.duration === 'number') {
  26649. // duration
  26650. if (!this._durationOverrided) {
  26651. var duration = Math.floor(onMetaData.duration * this._timescale);
  26652. this._duration = duration;
  26653. this._mediaInfo.duration = duration;
  26654. }
  26655. } else {
  26656. this._mediaInfo.duration = 0;
  26657. }
  26658. if (typeof onMetaData.framerate === 'number') {
  26659. // framerate
  26660. var fps_num = Math.floor(onMetaData.framerate * 1000);
  26661. if (fps_num > 0) {
  26662. var fps = fps_num / 1000;
  26663. this._referenceFrameRate.fixed = true;
  26664. this._referenceFrameRate.fps = fps;
  26665. this._referenceFrameRate.fps_num = fps_num;
  26666. this._referenceFrameRate.fps_den = 1000;
  26667. this._mediaInfo.fps = fps;
  26668. }
  26669. }
  26670. if (_typeof(onMetaData.keyframes) === 'object') {
  26671. // keyframes
  26672. this._mediaInfo.hasKeyframesIndex = true;
  26673. var keyframes = onMetaData.keyframes;
  26674. this._mediaInfo.keyframesIndex = this._parseKeyframesIndex(keyframes);
  26675. onMetaData.keyframes = null; // keyframes has been extracted, remove it
  26676. } else {
  26677. this._mediaInfo.hasKeyframesIndex = false;
  26678. }
  26679. this._dispatch = false;
  26680. this._mediaInfo.metadata = onMetaData;
  26681. _logger2.default.v(this.TAG, 'Parsed onMetaData');
  26682. if (this._mediaInfo.isComplete()) {
  26683. this._onMediaInfo(this._mediaInfo);
  26684. }
  26685. }
  26686. }
  26687. }, {
  26688. key: '_parseKeyframesIndex',
  26689. value: function _parseKeyframesIndex(keyframes) {
  26690. var times = [];
  26691. var filepositions = [];
  26692. // ignore first keyframe which is actually AVC Sequence Header (AVCDecoderConfigurationRecord)
  26693. for (var i = 1; i < keyframes.times.length; i++) {
  26694. var time = this._timestampBase + Math.floor(keyframes.times[i] * 1000);
  26695. times.push(time);
  26696. filepositions.push(keyframes.filepositions[i]);
  26697. }
  26698. return {
  26699. times: times,
  26700. filepositions: filepositions
  26701. };
  26702. }
  26703. }, {
  26704. key: '_parseAudioData',
  26705. value: function _parseAudioData(arrayBuffer, dataOffset, dataSize, tagTimestamp) {
  26706. if (dataSize <= 1) {
  26707. _logger2.default.w(this.TAG, 'Flv: Invalid audio packet, missing SoundData payload!');
  26708. return;
  26709. }
  26710. if (this._hasAudioFlagOverrided === true && this._hasAudio === false) {
  26711. // If hasAudio: false indicated explicitly in MediaDataSource,
  26712. // Ignore all the audio packets
  26713. return;
  26714. }
  26715. var le = this._littleEndian;
  26716. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  26717. var soundSpec = v.getUint8(0);
  26718. var soundFormat = soundSpec >>> 4;
  26719. if (soundFormat !== 2 && soundFormat !== 10) {
  26720. // MP3 or AAC
  26721. this._onError(_demuxErrors2.default.CODEC_UNSUPPORTED, 'Flv: Unsupported audio codec idx: ' + soundFormat);
  26722. return;
  26723. }
  26724. var soundRate = 0;
  26725. var soundRateIndex = (soundSpec & 12) >>> 2;
  26726. if (soundRateIndex >= 0 && soundRateIndex <= 4) {
  26727. soundRate = this._flvSoundRateTable[soundRateIndex];
  26728. } else {
  26729. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid audio sample rate idx: ' + soundRateIndex);
  26730. return;
  26731. }
  26732. var soundSize = (soundSpec & 2) >>> 1; // unused
  26733. var soundType = soundSpec & 1;
  26734. var meta = this._audioMetadata;
  26735. var track = this._audioTrack;
  26736. if (!meta) {
  26737. if (this._hasAudio === false && this._hasAudioFlagOverrided === false) {
  26738. this._hasAudio = true;
  26739. this._mediaInfo.hasAudio = true;
  26740. }
  26741. // initial metadata
  26742. meta = this._audioMetadata = {};
  26743. meta.type = 'audio';
  26744. meta.id = track.id;
  26745. meta.timescale = this._timescale;
  26746. meta.duration = this._duration;
  26747. meta.audioSampleRate = soundRate;
  26748. meta.channelCount = soundType === 0 ? 1 : 2;
  26749. }
  26750. if (soundFormat === 10) {
  26751. // AAC
  26752. var aacData = this._parseAACAudioData(arrayBuffer, dataOffset + 1, dataSize - 1);
  26753. if (aacData == undefined) {
  26754. return;
  26755. }
  26756. if (aacData.packetType === 0) {
  26757. // AAC sequence header (AudioSpecificConfig)
  26758. if (meta.config) {
  26759. _logger2.default.w(this.TAG, 'Found another AudioSpecificConfig!');
  26760. }
  26761. var misc = aacData.data;
  26762. meta.audioSampleRate = misc.samplingRate;
  26763. meta.channelCount = misc.channelCount;
  26764. meta.codec = misc.codec;
  26765. meta.originalCodec = misc.originalCodec;
  26766. meta.config = misc.config;
  26767. // The decode result of an aac sample is 1024 PCM samples
  26768. meta.refSampleDuration = 1024 / meta.audioSampleRate * meta.timescale;
  26769. _logger2.default.v(this.TAG, 'Parsed AudioSpecificConfig');
  26770. if (this._isInitialMetadataDispatched()) {
  26771. // Non-initial metadata, force dispatch (or flush) parsed frames to remuxer
  26772. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  26773. this._onDataAvailable(this._audioTrack, this._videoTrack);
  26774. }
  26775. } else {
  26776. this._audioInitialMetadataDispatched = true;
  26777. }
  26778. // then notify new metadata
  26779. this._dispatch = false;
  26780. this._onTrackMetadata('audio', meta);
  26781. var mi = this._mediaInfo;
  26782. mi.audioCodec = meta.originalCodec;
  26783. mi.audioSampleRate = meta.audioSampleRate;
  26784. mi.audioChannelCount = meta.channelCount;
  26785. if (mi.hasVideo) {
  26786. if (mi.videoCodec != null) {
  26787. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
  26788. }
  26789. } else {
  26790. mi.mimeType = 'video/x-flv; codecs="' + mi.audioCodec + '"';
  26791. }
  26792. if (mi.isComplete()) {
  26793. this._onMediaInfo(mi);
  26794. }
  26795. } else if (aacData.packetType === 1) {
  26796. // AAC raw frame data
  26797. var dts = this._timestampBase + tagTimestamp;
  26798. var aacSample = { unit: aacData.data, length: aacData.data.byteLength, dts: dts, pts: dts };
  26799. track.samples.push(aacSample);
  26800. track.length += aacData.data.length;
  26801. } else {
  26802. _logger2.default.e(this.TAG, 'Flv: Unsupported AAC data type ' + aacData.packetType);
  26803. }
  26804. } else if (soundFormat === 2) {
  26805. // MP3
  26806. if (!meta.codec) {
  26807. // We need metadata for mp3 audio track, extract info from frame header
  26808. var _misc = this._parseMP3AudioData(arrayBuffer, dataOffset + 1, dataSize - 1, true);
  26809. if (_misc == undefined) {
  26810. return;
  26811. }
  26812. meta.audioSampleRate = _misc.samplingRate;
  26813. meta.channelCount = _misc.channelCount;
  26814. meta.codec = _misc.codec;
  26815. meta.originalCodec = _misc.originalCodec;
  26816. // The decode result of an mp3 sample is 1152 PCM samples
  26817. meta.refSampleDuration = 1152 / meta.audioSampleRate * meta.timescale;
  26818. _logger2.default.v(this.TAG, 'Parsed MPEG Audio Frame Header');
  26819. this._audioInitialMetadataDispatched = true;
  26820. this._onTrackMetadata('audio', meta);
  26821. var _mi = this._mediaInfo;
  26822. _mi.audioCodec = meta.codec;
  26823. _mi.audioSampleRate = meta.audioSampleRate;
  26824. _mi.audioChannelCount = meta.channelCount;
  26825. _mi.audioDataRate = _misc.bitRate;
  26826. if (_mi.hasVideo) {
  26827. if (_mi.videoCodec != null) {
  26828. _mi.mimeType = 'video/x-flv; codecs="' + _mi.videoCodec + ',' + _mi.audioCodec + '"';
  26829. }
  26830. } else {
  26831. _mi.mimeType = 'video/x-flv; codecs="' + _mi.audioCodec + '"';
  26832. }
  26833. if (_mi.isComplete()) {
  26834. this._onMediaInfo(_mi);
  26835. }
  26836. }
  26837. // This packet is always a valid audio packet, extract it
  26838. var data = this._parseMP3AudioData(arrayBuffer, dataOffset + 1, dataSize - 1, false);
  26839. if (data == undefined) {
  26840. return;
  26841. }
  26842. var _dts = this._timestampBase + tagTimestamp;
  26843. var mp3Sample = { unit: data, length: data.byteLength, dts: _dts, pts: _dts };
  26844. track.samples.push(mp3Sample);
  26845. track.length += data.length;
  26846. }
  26847. }
  26848. }, {
  26849. key: '_parseAACAudioData',
  26850. value: function _parseAACAudioData(arrayBuffer, dataOffset, dataSize) {
  26851. if (dataSize <= 1) {
  26852. _logger2.default.w(this.TAG, 'Flv: Invalid AAC packet, missing AACPacketType or/and Data!');
  26853. return;
  26854. }
  26855. var result = {};
  26856. var array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  26857. result.packetType = array[0];
  26858. if (array[0] === 0) {
  26859. result.data = this._parseAACAudioSpecificConfig(arrayBuffer, dataOffset + 1, dataSize - 1);
  26860. } else {
  26861. result.data = array.subarray(1);
  26862. }
  26863. return result;
  26864. }
  26865. }, {
  26866. key: '_parseAACAudioSpecificConfig',
  26867. value: function _parseAACAudioSpecificConfig(arrayBuffer, dataOffset, dataSize) {
  26868. var array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  26869. var config = null;
  26870. /* Audio Object Type:
  26871. 0: Null
  26872. 1: AAC Main
  26873. 2: AAC LC
  26874. 3: AAC SSR (Scalable Sample Rate)
  26875. 4: AAC LTP (Long Term Prediction)
  26876. 5: HE-AAC / SBR (Spectral Band Replication)
  26877. 6: AAC Scalable
  26878. */
  26879. var audioObjectType = 0;
  26880. var originalAudioObjectType = 0;
  26881. var audioExtensionObjectType = null;
  26882. var samplingIndex = 0;
  26883. var extensionSamplingIndex = null;
  26884. // 5 bits
  26885. audioObjectType = originalAudioObjectType = array[0] >>> 3;
  26886. // 4 bits
  26887. samplingIndex = (array[0] & 0x07) << 1 | array[1] >>> 7;
  26888. if (samplingIndex < 0 || samplingIndex >= this._mpegSamplingRates.length) {
  26889. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: AAC invalid sampling frequency index!');
  26890. return;
  26891. }
  26892. var samplingFrequence = this._mpegSamplingRates[samplingIndex];
  26893. // 4 bits
  26894. var channelConfig = (array[1] & 0x78) >>> 3;
  26895. if (channelConfig < 0 || channelConfig >= 8) {
  26896. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: AAC invalid channel configuration');
  26897. return;
  26898. }
  26899. if (audioObjectType === 5) {
  26900. // HE-AAC?
  26901. // 4 bits
  26902. extensionSamplingIndex = (array[1] & 0x07) << 1 | array[2] >>> 7;
  26903. // 5 bits
  26904. audioExtensionObjectType = (array[2] & 0x7C) >>> 2;
  26905. }
  26906. // workarounds for various browsers
  26907. var userAgent = self.navigator.userAgent.toLowerCase();
  26908. if (userAgent.indexOf('firefox') !== -1) {
  26909. // firefox: use SBR (HE-AAC) if freq less than 24kHz
  26910. if (samplingIndex >= 6) {
  26911. audioObjectType = 5;
  26912. config = new Array(4);
  26913. extensionSamplingIndex = samplingIndex - 3;
  26914. } else {
  26915. // use LC-AAC
  26916. audioObjectType = 2;
  26917. config = new Array(2);
  26918. extensionSamplingIndex = samplingIndex;
  26919. }
  26920. } else if (userAgent.indexOf('android') !== -1) {
  26921. // android: always use LC-AAC
  26922. audioObjectType = 2;
  26923. config = new Array(2);
  26924. extensionSamplingIndex = samplingIndex;
  26925. } else {
  26926. // for other browsers, e.g. chrome...
  26927. // Always use HE-AAC to make it easier to switch aac codec profile
  26928. audioObjectType = 5;
  26929. extensionSamplingIndex = samplingIndex;
  26930. config = new Array(4);
  26931. if (samplingIndex >= 6) {
  26932. extensionSamplingIndex = samplingIndex - 3;
  26933. } else if (channelConfig === 1) {
  26934. // Mono channel
  26935. audioObjectType = 2;
  26936. config = new Array(2);
  26937. extensionSamplingIndex = samplingIndex;
  26938. }
  26939. }
  26940. config[0] = audioObjectType << 3;
  26941. config[0] |= (samplingIndex & 0x0F) >>> 1;
  26942. config[1] = (samplingIndex & 0x0F) << 7;
  26943. config[1] |= (channelConfig & 0x0F) << 3;
  26944. if (audioObjectType === 5) {
  26945. config[1] |= (extensionSamplingIndex & 0x0F) >>> 1;
  26946. config[2] = (extensionSamplingIndex & 0x01) << 7;
  26947. // extended audio object type: force to 2 (LC-AAC)
  26948. config[2] |= 2 << 2;
  26949. config[3] = 0;
  26950. }
  26951. return {
  26952. config: config,
  26953. samplingRate: samplingFrequence,
  26954. channelCount: channelConfig,
  26955. codec: 'mp4a.40.' + audioObjectType,
  26956. originalCodec: 'mp4a.40.' + originalAudioObjectType
  26957. };
  26958. }
  26959. }, {
  26960. key: '_parseMP3AudioData',
  26961. value: function _parseMP3AudioData(arrayBuffer, dataOffset, dataSize, requestHeader) {
  26962. if (dataSize < 4) {
  26963. _logger2.default.w(this.TAG, 'Flv: Invalid MP3 packet, header missing!');
  26964. return;
  26965. }
  26966. var le = this._littleEndian;
  26967. var array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  26968. var result = null;
  26969. if (requestHeader) {
  26970. if (array[0] !== 0xFF) {
  26971. return;
  26972. }
  26973. var ver = array[1] >>> 3 & 0x03;
  26974. var layer = (array[1] & 0x06) >> 1;
  26975. var bitrate_index = (array[2] & 0xF0) >>> 4;
  26976. var sampling_freq_index = (array[2] & 0x0C) >>> 2;
  26977. var channel_mode = array[3] >>> 6 & 0x03;
  26978. var channel_count = channel_mode !== 3 ? 2 : 1;
  26979. var sample_rate = 0;
  26980. var bit_rate = 0;
  26981. var object_type = 34; // Layer-3, listed in MPEG-4 Audio Object Types
  26982. var codec = 'mp3';
  26983. switch (ver) {
  26984. case 0:
  26985. // MPEG 2.5
  26986. sample_rate = this._mpegAudioV25SampleRateTable[sampling_freq_index];
  26987. break;
  26988. case 2:
  26989. // MPEG 2
  26990. sample_rate = this._mpegAudioV20SampleRateTable[sampling_freq_index];
  26991. break;
  26992. case 3:
  26993. // MPEG 1
  26994. sample_rate = this._mpegAudioV10SampleRateTable[sampling_freq_index];
  26995. break;
  26996. }
  26997. switch (layer) {
  26998. case 1:
  26999. // Layer 3
  27000. object_type = 34;
  27001. if (bitrate_index < this._mpegAudioL3BitRateTable.length) {
  27002. bit_rate = this._mpegAudioL3BitRateTable[bitrate_index];
  27003. }
  27004. break;
  27005. case 2:
  27006. // Layer 2
  27007. object_type = 33;
  27008. if (bitrate_index < this._mpegAudioL2BitRateTable.length) {
  27009. bit_rate = this._mpegAudioL2BitRateTable[bitrate_index];
  27010. }
  27011. break;
  27012. case 3:
  27013. // Layer 1
  27014. object_type = 32;
  27015. if (bitrate_index < this._mpegAudioL1BitRateTable.length) {
  27016. bit_rate = this._mpegAudioL1BitRateTable[bitrate_index];
  27017. }
  27018. break;
  27019. }
  27020. result = {
  27021. bitRate: bit_rate,
  27022. samplingRate: sample_rate,
  27023. channelCount: channel_count,
  27024. codec: codec,
  27025. originalCodec: codec
  27026. };
  27027. } else {
  27028. result = array;
  27029. }
  27030. return result;
  27031. }
  27032. }, {
  27033. key: '_parseVideoData',
  27034. value: function _parseVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition) {
  27035. if (dataSize <= 1) {
  27036. _logger2.default.w(this.TAG, 'Flv: Invalid video packet, missing VideoData payload!');
  27037. return;
  27038. }
  27039. if (this._hasVideoFlagOverrided === true && this._hasVideo === false) {
  27040. // If hasVideo: false indicated explicitly in MediaDataSource,
  27041. // Ignore all the video packets
  27042. return;
  27043. }
  27044. var spec = new Uint8Array(arrayBuffer, dataOffset, dataSize)[0];
  27045. var frameType = (spec & 240) >>> 4;
  27046. var codecId = spec & 15;
  27047. if (codecId !== 7) {
  27048. this._onError(_demuxErrors2.default.CODEC_UNSUPPORTED, 'Flv: Unsupported codec in video frame: ' + codecId);
  27049. return;
  27050. }
  27051. this._parseAVCVideoPacket(arrayBuffer, dataOffset + 1, dataSize - 1, tagTimestamp, tagPosition, frameType);
  27052. }
  27053. }, {
  27054. key: '_parseAVCVideoPacket',
  27055. value: function _parseAVCVideoPacket(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType) {
  27056. if (dataSize < 4) {
  27057. _logger2.default.w(this.TAG, 'Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime');
  27058. return;
  27059. }
  27060. var le = this._littleEndian;
  27061. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  27062. var packetType = v.getUint8(0);
  27063. var cts_unsigned = v.getUint32(0, !le) & 0x00FFFFFF;
  27064. var cts = cts_unsigned << 8 >> 8; // convert to 24-bit signed int
  27065. if (packetType === 0) {
  27066. // AVCDecoderConfigurationRecord
  27067. this._parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset + 4, dataSize - 4);
  27068. } else if (packetType === 1) {
  27069. // One or more Nalus
  27070. this._parseAVCVideoData(arrayBuffer, dataOffset + 4, dataSize - 4, tagTimestamp, tagPosition, frameType, cts);
  27071. } else if (packetType === 2) {
  27072. // empty, AVC end of sequence
  27073. } else {
  27074. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid video packet type ' + packetType);
  27075. return;
  27076. }
  27077. }
  27078. }, {
  27079. key: '_parseAVCDecoderConfigurationRecord',
  27080. value: function _parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset, dataSize) {
  27081. if (dataSize < 7) {
  27082. _logger2.default.w(this.TAG, 'Flv: Invalid AVCDecoderConfigurationRecord, lack of data!');
  27083. return;
  27084. }
  27085. var meta = this._videoMetadata;
  27086. var track = this._videoTrack;
  27087. var le = this._littleEndian;
  27088. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  27089. if (!meta) {
  27090. if (this._hasVideo === false && this._hasVideoFlagOverrided === false) {
  27091. this._hasVideo = true;
  27092. this._mediaInfo.hasVideo = true;
  27093. }
  27094. meta = this._videoMetadata = {};
  27095. meta.type = 'video';
  27096. meta.id = track.id;
  27097. meta.timescale = this._timescale;
  27098. meta.duration = this._duration;
  27099. } else {
  27100. if (typeof meta.avcc !== 'undefined') {
  27101. _logger2.default.w(this.TAG, 'Found another AVCDecoderConfigurationRecord!');
  27102. }
  27103. }
  27104. var version = v.getUint8(0); // configurationVersion
  27105. var avcProfile = v.getUint8(1); // avcProfileIndication
  27106. var profileCompatibility = v.getUint8(2); // profile_compatibility
  27107. var avcLevel = v.getUint8(3); // AVCLevelIndication
  27108. if (version !== 1 || avcProfile === 0) {
  27109. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord');
  27110. return;
  27111. }
  27112. this._naluLengthSize = (v.getUint8(4) & 3) + 1; // lengthSizeMinusOne
  27113. if (this._naluLengthSize !== 3 && this._naluLengthSize !== 4) {
  27114. // holy shit!!!
  27115. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Strange NaluLengthSizeMinusOne: ' + (this._naluLengthSize - 1));
  27116. return;
  27117. }
  27118. var spsCount = v.getUint8(5) & 31; // numOfSequenceParameterSets
  27119. if (spsCount === 0) {
  27120. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord: No SPS');
  27121. return;
  27122. } else if (spsCount > 1) {
  27123. _logger2.default.w(this.TAG, 'Flv: Strange AVCDecoderConfigurationRecord: SPS Count = ' + spsCount);
  27124. }
  27125. var offset = 6;
  27126. for (var i = 0; i < spsCount; i++) {
  27127. var len = v.getUint16(offset, !le); // sequenceParameterSetLength
  27128. offset += 2;
  27129. if (len === 0) {
  27130. continue;
  27131. }
  27132. // Notice: Nalu without startcode header (00 00 00 01)
  27133. var sps = new Uint8Array(arrayBuffer, dataOffset + offset, len);
  27134. offset += len;
  27135. var config = _spsParser2.default.parseSPS(sps);
  27136. if (i !== 0) {
  27137. // ignore other sps's config
  27138. continue;
  27139. }
  27140. meta.codecWidth = config.codec_size.width;
  27141. meta.codecHeight = config.codec_size.height;
  27142. meta.presentWidth = config.present_size.width;
  27143. meta.presentHeight = config.present_size.height;
  27144. meta.profile = config.profile_string;
  27145. meta.level = config.level_string;
  27146. meta.bitDepth = config.bit_depth;
  27147. meta.chromaFormat = config.chroma_format;
  27148. meta.sarRatio = config.par_ratio;
  27149. meta.frameRate = config.frame_rate;
  27150. if (config.frame_rate.fixed === false || config.frame_rate.fps_num === 0 || config.frame_rate.fps_den === 0) {
  27151. meta.frameRate = this._referenceFrameRate;
  27152. }
  27153. var fps_den = meta.frameRate.fps_den;
  27154. var fps_num = meta.frameRate.fps_num;
  27155. meta.refSampleDuration = meta.timescale * (fps_den / fps_num);
  27156. var codecArray = sps.subarray(1, 4);
  27157. var codecString = 'avc1.';
  27158. for (var j = 0; j < 3; j++) {
  27159. var h = codecArray[j].toString(16);
  27160. if (h.length < 2) {
  27161. h = '0' + h;
  27162. }
  27163. codecString += h;
  27164. }
  27165. meta.codec = codecString;
  27166. var mi = this._mediaInfo;
  27167. mi.width = meta.codecWidth;
  27168. mi.height = meta.codecHeight;
  27169. mi.fps = meta.frameRate.fps;
  27170. mi.profile = meta.profile;
  27171. mi.level = meta.level;
  27172. mi.refFrames = config.ref_frames;
  27173. mi.chromaFormat = config.chroma_format_string;
  27174. mi.sarNum = meta.sarRatio.width;
  27175. mi.sarDen = meta.sarRatio.height;
  27176. mi.videoCodec = codecString;
  27177. if (mi.hasAudio) {
  27178. if (mi.audioCodec != null) {
  27179. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
  27180. }
  27181. } else {
  27182. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + '"';
  27183. }
  27184. if (mi.isComplete()) {
  27185. this._onMediaInfo(mi);
  27186. }
  27187. }
  27188. var ppsCount = v.getUint8(offset); // numOfPictureParameterSets
  27189. if (ppsCount === 0) {
  27190. this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord: No PPS');
  27191. return;
  27192. } else if (ppsCount > 1) {
  27193. _logger2.default.w(this.TAG, 'Flv: Strange AVCDecoderConfigurationRecord: PPS Count = ' + ppsCount);
  27194. }
  27195. offset++;
  27196. for (var _i = 0; _i < ppsCount; _i++) {
  27197. var _len = v.getUint16(offset, !le); // pictureParameterSetLength
  27198. offset += 2;
  27199. if (_len === 0) {
  27200. continue;
  27201. }
  27202. // pps is useless for extracting video information
  27203. offset += _len;
  27204. }
  27205. meta.avcc = new Uint8Array(dataSize);
  27206. meta.avcc.set(new Uint8Array(arrayBuffer, dataOffset, dataSize), 0);
  27207. _logger2.default.v(this.TAG, 'Parsed AVCDecoderConfigurationRecord');
  27208. if (this._isInitialMetadataDispatched()) {
  27209. // flush parsed frames
  27210. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  27211. this._onDataAvailable(this._audioTrack, this._videoTrack);
  27212. }
  27213. } else {
  27214. this._videoInitialMetadataDispatched = true;
  27215. }
  27216. // notify new metadata
  27217. this._dispatch = false;
  27218. this._onTrackMetadata('video', meta);
  27219. }
  27220. }, {
  27221. key: '_parseAVCVideoData',
  27222. value: function _parseAVCVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType, cts) {
  27223. var le = this._littleEndian;
  27224. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  27225. var units = [],
  27226. length = 0;
  27227. var offset = 0;
  27228. var lengthSize = this._naluLengthSize;
  27229. var dts = this._timestampBase + tagTimestamp;
  27230. var keyframe = frameType === 1; // from FLV Frame Type constants
  27231. while (offset < dataSize) {
  27232. if (offset + 4 >= dataSize) {
  27233. _logger2.default.w(this.TAG, 'Malformed Nalu near timestamp ' + dts + ', offset = ' + offset + ', dataSize = ' + dataSize);
  27234. break; // data not enough for next Nalu
  27235. }
  27236. // Nalu with length-header (AVC1)
  27237. var naluSize = v.getUint32(offset, !le); // Big-Endian read
  27238. if (lengthSize === 3) {
  27239. naluSize >>>= 8;
  27240. }
  27241. if (naluSize > dataSize - lengthSize) {
  27242. _logger2.default.w(this.TAG, 'Malformed Nalus near timestamp ' + dts + ', NaluSize > DataSize!');
  27243. return;
  27244. }
  27245. var unitType = v.getUint8(offset + lengthSize) & 0x1F;
  27246. if (unitType === 5) {
  27247. // IDR
  27248. keyframe = true;
  27249. }
  27250. var data = new Uint8Array(arrayBuffer, dataOffset + offset, lengthSize + naluSize);
  27251. var unit = { type: unitType, data: data };
  27252. units.push(unit);
  27253. length += data.byteLength;
  27254. offset += lengthSize + naluSize;
  27255. }
  27256. if (units.length) {
  27257. var track = this._videoTrack;
  27258. var avcSample = {
  27259. units: units,
  27260. length: length,
  27261. isKeyframe: keyframe,
  27262. dts: dts,
  27263. cts: cts,
  27264. pts: dts + cts
  27265. };
  27266. if (keyframe) {
  27267. avcSample.fileposition = tagPosition;
  27268. }
  27269. track.samples.push(avcSample);
  27270. track.length += length;
  27271. }
  27272. }
  27273. }, {
  27274. key: 'onTrackMetadata',
  27275. get: function get() {
  27276. return this._onTrackMetadata;
  27277. },
  27278. set: function set(callback) {
  27279. this._onTrackMetadata = callback;
  27280. }
  27281. // prototype: function(mediaInfo: MediaInfo): void
  27282. }, {
  27283. key: 'onMediaInfo',
  27284. get: function get() {
  27285. return this._onMediaInfo;
  27286. },
  27287. set: function set(callback) {
  27288. this._onMediaInfo = callback;
  27289. }
  27290. // prototype: function(type: number, info: string): void
  27291. }, {
  27292. key: 'onError',
  27293. get: function get() {
  27294. return this._onError;
  27295. },
  27296. set: function set(callback) {
  27297. this._onError = callback;
  27298. }
  27299. // prototype: function(videoTrack: any, audioTrack: any): void
  27300. }, {
  27301. key: 'onDataAvailable',
  27302. get: function get() {
  27303. return this._onDataAvailable;
  27304. },
  27305. set: function set(callback) {
  27306. this._onDataAvailable = callback;
  27307. }
  27308. // timestamp base for output samples, must be in milliseconds
  27309. }, {
  27310. key: 'timestampBase',
  27311. get: function get() {
  27312. return this._timestampBase;
  27313. },
  27314. set: function set(base) {
  27315. this._timestampBase = base;
  27316. }
  27317. }, {
  27318. key: 'overridedDuration',
  27319. get: function get() {
  27320. return this._duration;
  27321. }
  27322. // Force-override media duration. Must be in milliseconds, int32
  27323. ,
  27324. set: function set(duration) {
  27325. this._durationOverrided = true;
  27326. this._duration = duration;
  27327. this._mediaInfo.duration = duration;
  27328. }
  27329. // Force-override audio track present flag, boolean
  27330. }, {
  27331. key: 'overridedHasAudio',
  27332. set: function set(hasAudio) {
  27333. this._hasAudioFlagOverrided = true;
  27334. this._hasAudio = hasAudio;
  27335. this._mediaInfo.hasAudio = hasAudio;
  27336. }
  27337. // Force-override video track present flag, boolean
  27338. }, {
  27339. key: 'overridedHasVideo',
  27340. set: function set(hasVideo) {
  27341. this._hasVideoFlagOverrided = true;
  27342. this._hasVideo = hasVideo;
  27343. this._mediaInfo.hasVideo = hasVideo;
  27344. }
  27345. }], [{
  27346. key: 'probe',
  27347. value: function probe(buffer) {
  27348. var data = new Uint8Array(buffer);
  27349. var mismatch = { match: false };
  27350. if (data[0] !== 0x46 || data[1] !== 0x4C || data[2] !== 0x56 || data[3] !== 0x01) {
  27351. return mismatch;
  27352. }
  27353. var hasAudio = (data[4] & 4) >>> 2 !== 0;
  27354. var hasVideo = (data[4] & 1) !== 0;
  27355. var offset = ReadBig32(data, 5);
  27356. if (offset < 9) {
  27357. return mismatch;
  27358. }
  27359. return {
  27360. match: true,
  27361. consumed: offset,
  27362. dataOffset: offset,
  27363. hasAudioTrack: hasAudio,
  27364. hasVideoTrack: hasVideo
  27365. };
  27366. }
  27367. }]);
  27368. return FLVDemuxer;
  27369. }();
  27370. exports.default = FLVDemuxer;
  27371. module.exports = exports['default'];
  27372. /***/ }),
  27373. /* 36 */
  27374. /***/ (function(module, exports, __webpack_require__) {
  27375. "use strict";
  27376. Object.defineProperty(exports, "__esModule", {
  27377. value: true
  27378. });
  27379. 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; }; }(); /*
  27380. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  27381. *
  27382. * @author zheng qian <xqq@xqq.im>
  27383. *
  27384. * Licensed under the Apache License, Version 2.0 (the "License");
  27385. * you may not use this file except in compliance with the License.
  27386. * You may obtain a copy of the License at
  27387. *
  27388. * http://www.apache.org/licenses/LICENSE-2.0
  27389. *
  27390. * Unless required by applicable law or agreed to in writing, software
  27391. * distributed under the License is distributed on an "AS IS" BASIS,
  27392. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  27393. * See the License for the specific language governing permissions and
  27394. * limitations under the License.
  27395. */
  27396. var _logger = __webpack_require__(0);
  27397. var _logger2 = _interopRequireDefault(_logger);
  27398. var _utf8Conv = __webpack_require__(37);
  27399. var _utf8Conv2 = _interopRequireDefault(_utf8Conv);
  27400. var _exception = __webpack_require__(1);
  27401. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27402. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27403. var le = function () {
  27404. var buf = new ArrayBuffer(2);
  27405. new DataView(buf).setInt16(0, 256, true); // little-endian write
  27406. return new Int16Array(buf)[0] === 256; // platform-spec read, if equal then LE
  27407. }();
  27408. var AMF = function () {
  27409. function AMF() {
  27410. _classCallCheck(this, AMF);
  27411. }
  27412. _createClass(AMF, null, [{
  27413. key: 'parseScriptData',
  27414. value: function parseScriptData(arrayBuffer, dataOffset, dataSize) {
  27415. var data = {};
  27416. try {
  27417. var name = AMF.parseValue(arrayBuffer, dataOffset, dataSize);
  27418. var value = AMF.parseValue(arrayBuffer, dataOffset + name.size, dataSize - name.size);
  27419. data[name.data] = value.data;
  27420. } catch (e) {
  27421. _logger2.default.e('AMF', e.toString());
  27422. }
  27423. return data;
  27424. }
  27425. }, {
  27426. key: 'parseObject',
  27427. value: function parseObject(arrayBuffer, dataOffset, dataSize) {
  27428. if (dataSize < 3) {
  27429. throw new _exception.IllegalStateException('Data not enough when parse ScriptDataObject');
  27430. }
  27431. var name = AMF.parseString(arrayBuffer, dataOffset, dataSize);
  27432. var value = AMF.parseValue(arrayBuffer, dataOffset + name.size, dataSize - name.size);
  27433. var isObjectEnd = value.objectEnd;
  27434. return {
  27435. data: {
  27436. name: name.data,
  27437. value: value.data
  27438. },
  27439. size: name.size + value.size,
  27440. objectEnd: isObjectEnd
  27441. };
  27442. }
  27443. }, {
  27444. key: 'parseVariable',
  27445. value: function parseVariable(arrayBuffer, dataOffset, dataSize) {
  27446. return AMF.parseObject(arrayBuffer, dataOffset, dataSize);
  27447. }
  27448. }, {
  27449. key: 'parseString',
  27450. value: function parseString(arrayBuffer, dataOffset, dataSize) {
  27451. if (dataSize < 2) {
  27452. throw new _exception.IllegalStateException('Data not enough when parse String');
  27453. }
  27454. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  27455. var length = v.getUint16(0, !le);
  27456. var str = void 0;
  27457. if (length > 0) {
  27458. str = (0, _utf8Conv2.default)(new Uint8Array(arrayBuffer, dataOffset + 2, length));
  27459. } else {
  27460. str = '';
  27461. }
  27462. return {
  27463. data: str,
  27464. size: 2 + length
  27465. };
  27466. }
  27467. }, {
  27468. key: 'parseLongString',
  27469. value: function parseLongString(arrayBuffer, dataOffset, dataSize) {
  27470. if (dataSize < 4) {
  27471. throw new _exception.IllegalStateException('Data not enough when parse LongString');
  27472. }
  27473. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  27474. var length = v.getUint32(0, !le);
  27475. var str = void 0;
  27476. if (length > 0) {
  27477. str = (0, _utf8Conv2.default)(new Uint8Array(arrayBuffer, dataOffset + 4, length));
  27478. } else {
  27479. str = '';
  27480. }
  27481. return {
  27482. data: str,
  27483. size: 4 + length
  27484. };
  27485. }
  27486. }, {
  27487. key: 'parseDate',
  27488. value: function parseDate(arrayBuffer, dataOffset, dataSize) {
  27489. if (dataSize < 10) {
  27490. throw new _exception.IllegalStateException('Data size invalid when parse Date');
  27491. }
  27492. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  27493. var timestamp = v.getFloat64(0, !le);
  27494. var localTimeOffset = v.getInt16(8, !le);
  27495. timestamp += localTimeOffset * 60 * 1000; // get UTC time
  27496. return {
  27497. data: new Date(timestamp),
  27498. size: 8 + 2
  27499. };
  27500. }
  27501. }, {
  27502. key: 'parseValue',
  27503. value: function parseValue(arrayBuffer, dataOffset, dataSize) {
  27504. if (dataSize < 1) {
  27505. throw new _exception.IllegalStateException('Data not enough when parse Value');
  27506. }
  27507. var v = new DataView(arrayBuffer, dataOffset, dataSize);
  27508. var offset = 1;
  27509. var type = v.getUint8(0);
  27510. var value = void 0;
  27511. var objectEnd = false;
  27512. try {
  27513. switch (type) {
  27514. case 0:
  27515. // Number(Double) type
  27516. value = v.getFloat64(1, !le);
  27517. offset += 8;
  27518. break;
  27519. case 1:
  27520. {
  27521. // Boolean type
  27522. var b = v.getUint8(1);
  27523. value = b ? true : false;
  27524. offset += 1;
  27525. break;
  27526. }
  27527. case 2:
  27528. {
  27529. // String type
  27530. var amfstr = AMF.parseString(arrayBuffer, dataOffset + 1, dataSize - 1);
  27531. value = amfstr.data;
  27532. offset += amfstr.size;
  27533. break;
  27534. }
  27535. case 3:
  27536. {
  27537. // Object(s) type
  27538. value = {};
  27539. var terminal = 0; // workaround for malformed Objects which has missing ScriptDataObjectEnd
  27540. if ((v.getUint32(dataSize - 4, !le) & 0x00FFFFFF) === 9) {
  27541. terminal = 3;
  27542. }
  27543. var maxLoop = 10000;
  27544. while (offset < dataSize - 4 && maxLoop-- > 0) {
  27545. // 4 === type(UI8) + ScriptDataObjectEnd(UI24)
  27546. var amfobj = AMF.parseObject(arrayBuffer, dataOffset + offset, dataSize - offset - terminal);
  27547. if (amfobj.objectEnd) break;
  27548. value[amfobj.data.name] = amfobj.data.value;
  27549. offset += amfobj.size;
  27550. }
  27551. if (offset <= dataSize - 3) {
  27552. var marker = v.getUint32(offset - 1, !le) & 0x00FFFFFF;
  27553. if (marker === 9) {
  27554. offset += 3;
  27555. }
  27556. }
  27557. break;
  27558. }
  27559. case 8:
  27560. {
  27561. // ECMA array type (Mixed array)
  27562. value = {};
  27563. offset += 4; // ECMAArrayLength(UI32)
  27564. var _terminal = 0; // workaround for malformed MixedArrays which has missing ScriptDataObjectEnd
  27565. if ((v.getUint32(dataSize - 4, !le) & 0x00FFFFFF) === 9) {
  27566. _terminal = 3;
  27567. }
  27568. var _maxLoop = 10000;
  27569. while (offset < dataSize - 8 && _maxLoop-- > 0) {
  27570. // 8 === type(UI8) + ECMAArrayLength(UI32) + ScriptDataVariableEnd(UI24)
  27571. var amfvar = AMF.parseVariable(arrayBuffer, dataOffset + offset, dataSize - offset - _terminal);
  27572. if (amfvar.objectEnd) break;
  27573. value[amfvar.data.name] = amfvar.data.value;
  27574. offset += amfvar.size;
  27575. }
  27576. if (offset <= dataSize - 3) {
  27577. var _marker = v.getUint32(offset - 1, !le) & 0x00FFFFFF;
  27578. if (_marker === 9) {
  27579. offset += 3;
  27580. }
  27581. }
  27582. break;
  27583. }
  27584. case 9:
  27585. // ScriptDataObjectEnd
  27586. value = undefined;
  27587. offset = 1;
  27588. objectEnd = true;
  27589. break;
  27590. case 10:
  27591. {
  27592. // Strict array type
  27593. // ScriptDataValue[n]. NOTE: according to video_file_format_spec_v10_1.pdf
  27594. value = [];
  27595. var strictArrayLength = v.getUint32(1, !le);
  27596. offset += 4;
  27597. for (var i = 0; i < strictArrayLength; i++) {
  27598. var val = AMF.parseValue(arrayBuffer, dataOffset + offset, dataSize - offset);
  27599. value.push(val.data);
  27600. offset += val.size;
  27601. }
  27602. break;
  27603. }
  27604. case 11:
  27605. {
  27606. // Date type
  27607. var date = AMF.parseDate(arrayBuffer, dataOffset + 1, dataSize - 1);
  27608. value = date.data;
  27609. offset += date.size;
  27610. break;
  27611. }
  27612. case 12:
  27613. {
  27614. // Long string type
  27615. var amfLongStr = AMF.parseString(arrayBuffer, dataOffset + 1, dataSize - 1);
  27616. value = amfLongStr.data;
  27617. offset += amfLongStr.size;
  27618. break;
  27619. }
  27620. default:
  27621. // ignore and skip
  27622. offset = dataSize;
  27623. _logger2.default.w('AMF', 'Unsupported AMF value type ' + type);
  27624. }
  27625. } catch (e) {
  27626. _logger2.default.e('AMF', e.toString());
  27627. }
  27628. return {
  27629. data: value,
  27630. size: offset,
  27631. objectEnd: objectEnd
  27632. };
  27633. }
  27634. }]);
  27635. return AMF;
  27636. }();
  27637. exports.default = AMF;
  27638. module.exports = exports['default'];
  27639. /***/ }),
  27640. /* 37 */
  27641. /***/ (function(module, exports, __webpack_require__) {
  27642. "use strict";
  27643. Object.defineProperty(exports, "__esModule", {
  27644. value: true
  27645. });
  27646. /*
  27647. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  27648. *
  27649. * This file is derived from C++ project libWinTF8 (https://github.com/m13253/libWinTF8)
  27650. * @author zheng qian <xqq@xqq.im>
  27651. *
  27652. * Licensed under the Apache License, Version 2.0 (the "License");
  27653. * you may not use this file except in compliance with the License.
  27654. * You may obtain a copy of the License at
  27655. *
  27656. * http://www.apache.org/licenses/LICENSE-2.0
  27657. *
  27658. * Unless required by applicable law or agreed to in writing, software
  27659. * distributed under the License is distributed on an "AS IS" BASIS,
  27660. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  27661. * See the License for the specific language governing permissions and
  27662. * limitations under the License.
  27663. */
  27664. function checkContinuation(uint8array, start, checkLength) {
  27665. var array = uint8array;
  27666. if (start + checkLength < array.length) {
  27667. while (checkLength--) {
  27668. if ((array[++start] & 0xC0) !== 0x80) return false;
  27669. }
  27670. return true;
  27671. } else {
  27672. return false;
  27673. }
  27674. }
  27675. function decodeUTF8(uint8array) {
  27676. var out = [];
  27677. var input = uint8array;
  27678. var i = 0;
  27679. var length = uint8array.length;
  27680. while (i < length) {
  27681. if (input[i] < 0x80) {
  27682. out.push(String.fromCharCode(input[i]));
  27683. ++i;
  27684. continue;
  27685. } else if (input[i] < 0xC0) {
  27686. // fallthrough
  27687. } else if (input[i] < 0xE0) {
  27688. if (checkContinuation(input, i, 1)) {
  27689. var ucs4 = (input[i] & 0x1F) << 6 | input[i + 1] & 0x3F;
  27690. if (ucs4 >= 0x80) {
  27691. out.push(String.fromCharCode(ucs4 & 0xFFFF));
  27692. i += 2;
  27693. continue;
  27694. }
  27695. }
  27696. } else if (input[i] < 0xF0) {
  27697. if (checkContinuation(input, i, 2)) {
  27698. var _ucs = (input[i] & 0xF) << 12 | (input[i + 1] & 0x3F) << 6 | input[i + 2] & 0x3F;
  27699. if (_ucs >= 0x800 && (_ucs & 0xF800) !== 0xD800) {
  27700. out.push(String.fromCharCode(_ucs & 0xFFFF));
  27701. i += 3;
  27702. continue;
  27703. }
  27704. }
  27705. } else if (input[i] < 0xF8) {
  27706. if (checkContinuation(input, i, 3)) {
  27707. var _ucs2 = (input[i] & 0x7) << 18 | (input[i + 1] & 0x3F) << 12 | (input[i + 2] & 0x3F) << 6 | input[i + 3] & 0x3F;
  27708. if (_ucs2 > 0x10000 && _ucs2 < 0x110000) {
  27709. _ucs2 -= 0x10000;
  27710. out.push(String.fromCharCode(_ucs2 >>> 10 | 0xD800));
  27711. out.push(String.fromCharCode(_ucs2 & 0x3FF | 0xDC00));
  27712. i += 4;
  27713. continue;
  27714. }
  27715. }
  27716. }
  27717. out.push(String.fromCharCode(0xFFFD));
  27718. ++i;
  27719. }
  27720. return out.join('');
  27721. }
  27722. exports.default = decodeUTF8;
  27723. module.exports = exports['default'];
  27724. /***/ }),
  27725. /* 38 */
  27726. /***/ (function(module, exports, __webpack_require__) {
  27727. "use strict";
  27728. Object.defineProperty(exports, "__esModule", {
  27729. value: true
  27730. });
  27731. 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; }; }(); /*
  27732. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  27733. *
  27734. * @author zheng qian <xqq@xqq.im>
  27735. *
  27736. * Licensed under the Apache License, Version 2.0 (the "License");
  27737. * you may not use this file except in compliance with the License.
  27738. * You may obtain a copy of the License at
  27739. *
  27740. * http://www.apache.org/licenses/LICENSE-2.0
  27741. *
  27742. * Unless required by applicable law or agreed to in writing, software
  27743. * distributed under the License is distributed on an "AS IS" BASIS,
  27744. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  27745. * See the License for the specific language governing permissions and
  27746. * limitations under the License.
  27747. */
  27748. var _expGolomb = __webpack_require__(39);
  27749. var _expGolomb2 = _interopRequireDefault(_expGolomb);
  27750. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27751. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27752. var SPSParser = function () {
  27753. function SPSParser() {
  27754. _classCallCheck(this, SPSParser);
  27755. }
  27756. _createClass(SPSParser, null, [{
  27757. key: '_ebsp2rbsp',
  27758. value: function _ebsp2rbsp(uint8array) {
  27759. var src = uint8array;
  27760. var src_length = src.byteLength;
  27761. var dst = new Uint8Array(src_length);
  27762. var dst_idx = 0;
  27763. for (var i = 0; i < src_length; i++) {
  27764. if (i >= 2) {
  27765. // Unescape: Skip 0x03 after 00 00
  27766. if (src[i] === 0x03 && src[i - 1] === 0x00 && src[i - 2] === 0x00) {
  27767. continue;
  27768. }
  27769. }
  27770. dst[dst_idx] = src[i];
  27771. dst_idx++;
  27772. }
  27773. return new Uint8Array(dst.buffer, 0, dst_idx);
  27774. }
  27775. }, {
  27776. key: 'parseSPS',
  27777. value: function parseSPS(uint8array) {
  27778. var rbsp = SPSParser._ebsp2rbsp(uint8array);
  27779. var gb = new _expGolomb2.default(rbsp);
  27780. gb.readByte();
  27781. var profile_idc = gb.readByte(); // profile_idc
  27782. gb.readByte(); // constraint_set_flags[5] + reserved_zero[3]
  27783. var level_idc = gb.readByte(); // level_idc
  27784. gb.readUEG(); // seq_parameter_set_id
  27785. var profile_string = SPSParser.getProfileString(profile_idc);
  27786. var level_string = SPSParser.getLevelString(level_idc);
  27787. var chroma_format_idc = 1;
  27788. var chroma_format = 420;
  27789. var chroma_format_table = [0, 420, 422, 444];
  27790. var bit_depth = 8;
  27791. 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) {
  27792. chroma_format_idc = gb.readUEG();
  27793. if (chroma_format_idc === 3) {
  27794. gb.readBits(1); // separate_colour_plane_flag
  27795. }
  27796. if (chroma_format_idc <= 3) {
  27797. chroma_format = chroma_format_table[chroma_format_idc];
  27798. }
  27799. bit_depth = gb.readUEG() + 8; // bit_depth_luma_minus8
  27800. gb.readUEG(); // bit_depth_chroma_minus8
  27801. gb.readBits(1); // qpprime_y_zero_transform_bypass_flag
  27802. if (gb.readBool()) {
  27803. // seq_scaling_matrix_present_flag
  27804. var scaling_list_count = chroma_format_idc !== 3 ? 8 : 12;
  27805. for (var i = 0; i < scaling_list_count; i++) {
  27806. if (gb.readBool()) {
  27807. // seq_scaling_list_present_flag
  27808. if (i < 6) {
  27809. SPSParser._skipScalingList(gb, 16);
  27810. } else {
  27811. SPSParser._skipScalingList(gb, 64);
  27812. }
  27813. }
  27814. }
  27815. }
  27816. }
  27817. gb.readUEG(); // log2_max_frame_num_minus4
  27818. var pic_order_cnt_type = gb.readUEG();
  27819. if (pic_order_cnt_type === 0) {
  27820. gb.readUEG(); // log2_max_pic_order_cnt_lsb_minus_4
  27821. } else if (pic_order_cnt_type === 1) {
  27822. gb.readBits(1); // delta_pic_order_always_zero_flag
  27823. gb.readSEG(); // offset_for_non_ref_pic
  27824. gb.readSEG(); // offset_for_top_to_bottom_field
  27825. var num_ref_frames_in_pic_order_cnt_cycle = gb.readUEG();
  27826. for (var _i = 0; _i < num_ref_frames_in_pic_order_cnt_cycle; _i++) {
  27827. gb.readSEG(); // offset_for_ref_frame
  27828. }
  27829. }
  27830. var ref_frames = gb.readUEG(); // max_num_ref_frames
  27831. gb.readBits(1); // gaps_in_frame_num_value_allowed_flag
  27832. var pic_width_in_mbs_minus1 = gb.readUEG();
  27833. var pic_height_in_map_units_minus1 = gb.readUEG();
  27834. var frame_mbs_only_flag = gb.readBits(1);
  27835. if (frame_mbs_only_flag === 0) {
  27836. gb.readBits(1); // mb_adaptive_frame_field_flag
  27837. }
  27838. gb.readBits(1); // direct_8x8_inference_flag
  27839. var frame_crop_left_offset = 0;
  27840. var frame_crop_right_offset = 0;
  27841. var frame_crop_top_offset = 0;
  27842. var frame_crop_bottom_offset = 0;
  27843. var frame_cropping_flag = gb.readBool();
  27844. if (frame_cropping_flag) {
  27845. frame_crop_left_offset = gb.readUEG();
  27846. frame_crop_right_offset = gb.readUEG();
  27847. frame_crop_top_offset = gb.readUEG();
  27848. frame_crop_bottom_offset = gb.readUEG();
  27849. }
  27850. var sar_width = 1,
  27851. sar_height = 1;
  27852. var fps = 0,
  27853. fps_fixed = true,
  27854. fps_num = 0,
  27855. fps_den = 0;
  27856. var vui_parameters_present_flag = gb.readBool();
  27857. if (vui_parameters_present_flag) {
  27858. if (gb.readBool()) {
  27859. // aspect_ratio_info_present_flag
  27860. var aspect_ratio_idc = gb.readByte();
  27861. var sar_w_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2];
  27862. var sar_h_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
  27863. if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) {
  27864. sar_width = sar_w_table[aspect_ratio_idc - 1];
  27865. sar_height = sar_h_table[aspect_ratio_idc - 1];
  27866. } else if (aspect_ratio_idc === 255) {
  27867. sar_width = gb.readByte() << 8 | gb.readByte();
  27868. sar_height = gb.readByte() << 8 | gb.readByte();
  27869. }
  27870. }
  27871. if (gb.readBool()) {
  27872. // overscan_info_present_flag
  27873. gb.readBool(); // overscan_appropriate_flag
  27874. }
  27875. if (gb.readBool()) {
  27876. // video_signal_type_present_flag
  27877. gb.readBits(4); // video_format & video_full_range_flag
  27878. if (gb.readBool()) {
  27879. // colour_description_present_flag
  27880. gb.readBits(24); // colour_primaries & transfer_characteristics & matrix_coefficients
  27881. }
  27882. }
  27883. if (gb.readBool()) {
  27884. // chroma_loc_info_present_flag
  27885. gb.readUEG(); // chroma_sample_loc_type_top_field
  27886. gb.readUEG(); // chroma_sample_loc_type_bottom_field
  27887. }
  27888. if (gb.readBool()) {
  27889. // timing_info_present_flag
  27890. var num_units_in_tick = gb.readBits(32);
  27891. var time_scale = gb.readBits(32);
  27892. fps_fixed = gb.readBool(); // fixed_frame_rate_flag
  27893. fps_num = time_scale;
  27894. fps_den = num_units_in_tick * 2;
  27895. fps = fps_num / fps_den;
  27896. }
  27897. }
  27898. var sarScale = 1;
  27899. if (sar_width !== 1 || sar_height !== 1) {
  27900. sarScale = sar_width / sar_height;
  27901. }
  27902. var crop_unit_x = 0,
  27903. crop_unit_y = 0;
  27904. if (chroma_format_idc === 0) {
  27905. crop_unit_x = 1;
  27906. crop_unit_y = 2 - frame_mbs_only_flag;
  27907. } else {
  27908. var sub_wc = chroma_format_idc === 3 ? 1 : 2;
  27909. var sub_hc = chroma_format_idc === 1 ? 2 : 1;
  27910. crop_unit_x = sub_wc;
  27911. crop_unit_y = sub_hc * (2 - frame_mbs_only_flag);
  27912. }
  27913. var codec_width = (pic_width_in_mbs_minus1 + 1) * 16;
  27914. var codec_height = (2 - frame_mbs_only_flag) * ((pic_height_in_map_units_minus1 + 1) * 16);
  27915. codec_width -= (frame_crop_left_offset + frame_crop_right_offset) * crop_unit_x;
  27916. codec_height -= (frame_crop_top_offset + frame_crop_bottom_offset) * crop_unit_y;
  27917. var present_width = Math.ceil(codec_width * sarScale);
  27918. gb.destroy();
  27919. gb = null;
  27920. return {
  27921. profile_string: profile_string, // baseline, high, high10, ...
  27922. level_string: level_string, // 3, 3.1, 4, 4.1, 5, 5.1, ...
  27923. bit_depth: bit_depth, // 8bit, 10bit, ...
  27924. ref_frames: ref_frames,
  27925. chroma_format: chroma_format, // 4:2:0, 4:2:2, ...
  27926. chroma_format_string: SPSParser.getChromaFormatString(chroma_format),
  27927. frame_rate: {
  27928. fixed: fps_fixed,
  27929. fps: fps,
  27930. fps_den: fps_den,
  27931. fps_num: fps_num
  27932. },
  27933. par_ratio: {
  27934. width: sar_width,
  27935. height: sar_height
  27936. },
  27937. codec_size: {
  27938. width: codec_width,
  27939. height: codec_height
  27940. },
  27941. present_size: {
  27942. width: present_width,
  27943. height: codec_height
  27944. }
  27945. };
  27946. }
  27947. }, {
  27948. key: '_skipScalingList',
  27949. value: function _skipScalingList(gb, count) {
  27950. var last_scale = 8,
  27951. next_scale = 8;
  27952. var delta_scale = 0;
  27953. for (var i = 0; i < count; i++) {
  27954. if (next_scale !== 0) {
  27955. delta_scale = gb.readSEG();
  27956. next_scale = (last_scale + delta_scale + 256) % 256;
  27957. }
  27958. last_scale = next_scale === 0 ? last_scale : next_scale;
  27959. }
  27960. }
  27961. }, {
  27962. key: 'getProfileString',
  27963. value: function getProfileString(profile_idc) {
  27964. switch (profile_idc) {
  27965. case 66:
  27966. return 'Baseline';
  27967. case 77:
  27968. return 'Main';
  27969. case 88:
  27970. return 'Extended';
  27971. case 100:
  27972. return 'High';
  27973. case 110:
  27974. return 'High10';
  27975. case 122:
  27976. return 'High422';
  27977. case 244:
  27978. return 'High444';
  27979. default:
  27980. return 'Unknown';
  27981. }
  27982. }
  27983. }, {
  27984. key: 'getLevelString',
  27985. value: function getLevelString(level_idc) {
  27986. return (level_idc / 10).toFixed(1);
  27987. }
  27988. }, {
  27989. key: 'getChromaFormatString',
  27990. value: function getChromaFormatString(chroma) {
  27991. switch (chroma) {
  27992. case 420:
  27993. return '4:2:0';
  27994. case 422:
  27995. return '4:2:2';
  27996. case 444:
  27997. return '4:4:4';
  27998. default:
  27999. return 'Unknown';
  28000. }
  28001. }
  28002. }]);
  28003. return SPSParser;
  28004. }();
  28005. exports.default = SPSParser;
  28006. module.exports = exports['default'];
  28007. /***/ }),
  28008. /* 39 */
  28009. /***/ (function(module, exports, __webpack_require__) {
  28010. "use strict";
  28011. Object.defineProperty(exports, "__esModule", {
  28012. value: true
  28013. });
  28014. 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; }; }(); /*
  28015. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  28016. *
  28017. * @author zheng qian <xqq@xqq.im>
  28018. *
  28019. * Licensed under the Apache License, Version 2.0 (the "License");
  28020. * you may not use this file except in compliance with the License.
  28021. * You may obtain a copy of the License at
  28022. *
  28023. * http://www.apache.org/licenses/LICENSE-2.0
  28024. *
  28025. * Unless required by applicable law or agreed to in writing, software
  28026. * distributed under the License is distributed on an "AS IS" BASIS,
  28027. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  28028. * See the License for the specific language governing permissions and
  28029. * limitations under the License.
  28030. */
  28031. var _exception = __webpack_require__(1);
  28032. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  28033. // Exponential-Golomb buffer decoder
  28034. var ExpGolomb = function () {
  28035. function ExpGolomb(uint8array) {
  28036. _classCallCheck(this, ExpGolomb);
  28037. this.TAG = 'ExpGolomb';
  28038. this._buffer = uint8array;
  28039. this._buffer_index = 0;
  28040. this._total_bytes = uint8array.byteLength;
  28041. this._total_bits = uint8array.byteLength * 8;
  28042. this._current_word = 0;
  28043. this._current_word_bits_left = 0;
  28044. }
  28045. _createClass(ExpGolomb, [{
  28046. key: 'destroy',
  28047. value: function destroy() {
  28048. this._buffer = null;
  28049. }
  28050. }, {
  28051. key: '_fillCurrentWord',
  28052. value: function _fillCurrentWord() {
  28053. var buffer_bytes_left = this._total_bytes - this._buffer_index;
  28054. if (buffer_bytes_left <= 0) throw new _exception.IllegalStateException('ExpGolomb: _fillCurrentWord() but no bytes available');
  28055. var bytes_read = Math.min(4, buffer_bytes_left);
  28056. var word = new Uint8Array(4);
  28057. word.set(this._buffer.subarray(this._buffer_index, this._buffer_index + bytes_read));
  28058. this._current_word = new DataView(word.buffer).getUint32(0, false);
  28059. this._buffer_index += bytes_read;
  28060. this._current_word_bits_left = bytes_read * 8;
  28061. }
  28062. }, {
  28063. key: 'readBits',
  28064. value: function readBits(bits) {
  28065. if (bits > 32) throw new _exception.InvalidArgumentException('ExpGolomb: readBits() bits exceeded max 32bits!');
  28066. if (bits <= this._current_word_bits_left) {
  28067. var _result = this._current_word >>> 32 - bits;
  28068. this._current_word <<= bits;
  28069. this._current_word_bits_left -= bits;
  28070. return _result;
  28071. }
  28072. var result = this._current_word_bits_left ? this._current_word : 0;
  28073. result = result >>> 32 - this._current_word_bits_left;
  28074. var bits_need_left = bits - this._current_word_bits_left;
  28075. this._fillCurrentWord();
  28076. var bits_read_next = Math.min(bits_need_left, this._current_word_bits_left);
  28077. var result2 = this._current_word >>> 32 - bits_read_next;
  28078. this._current_word <<= bits_read_next;
  28079. this._current_word_bits_left -= bits_read_next;
  28080. result = result << bits_read_next | result2;
  28081. return result;
  28082. }
  28083. }, {
  28084. key: 'readBool',
  28085. value: function readBool() {
  28086. return this.readBits(1) === 1;
  28087. }
  28088. }, {
  28089. key: 'readByte',
  28090. value: function readByte() {
  28091. return this.readBits(8);
  28092. }
  28093. }, {
  28094. key: '_skipLeadingZero',
  28095. value: function _skipLeadingZero() {
  28096. var zero_count = void 0;
  28097. for (zero_count = 0; zero_count < this._current_word_bits_left; zero_count++) {
  28098. if (0 !== (this._current_word & 0x80000000 >>> zero_count)) {
  28099. this._current_word <<= zero_count;
  28100. this._current_word_bits_left -= zero_count;
  28101. return zero_count;
  28102. }
  28103. }
  28104. this._fillCurrentWord();
  28105. return zero_count + this._skipLeadingZero();
  28106. }
  28107. }, {
  28108. key: 'readUEG',
  28109. value: function readUEG() {
  28110. // unsigned exponential golomb
  28111. var leading_zeros = this._skipLeadingZero();
  28112. return this.readBits(leading_zeros + 1) - 1;
  28113. }
  28114. }, {
  28115. key: 'readSEG',
  28116. value: function readSEG() {
  28117. // signed exponential golomb
  28118. var value = this.readUEG();
  28119. if (value & 0x01) {
  28120. return value + 1 >>> 1;
  28121. } else {
  28122. return -1 * (value >>> 1);
  28123. }
  28124. }
  28125. }]);
  28126. return ExpGolomb;
  28127. }();
  28128. exports.default = ExpGolomb;
  28129. module.exports = exports['default'];
  28130. /***/ }),
  28131. /* 40 */
  28132. /***/ (function(module, exports, __webpack_require__) {
  28133. "use strict";
  28134. Object.defineProperty(exports, "__esModule", {
  28135. value: true
  28136. });
  28137. 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; }; }(); /*
  28138. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  28139. *
  28140. * @author zheng qian <xqq@xqq.im>
  28141. *
  28142. * Licensed under the Apache License, Version 2.0 (the "License");
  28143. * you may not use this file except in compliance with the License.
  28144. * You may obtain a copy of the License at
  28145. *
  28146. * http://www.apache.org/licenses/LICENSE-2.0
  28147. *
  28148. * Unless required by applicable law or agreed to in writing, software
  28149. * distributed under the License is distributed on an "AS IS" BASIS,
  28150. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  28151. * See the License for the specific language governing permissions and
  28152. * limitations under the License.
  28153. */
  28154. var _logger = __webpack_require__(0);
  28155. var _logger2 = _interopRequireDefault(_logger);
  28156. var _mp4Generator = __webpack_require__(41);
  28157. var _mp4Generator2 = _interopRequireDefault(_mp4Generator);
  28158. var _aacSilent = __webpack_require__(42);
  28159. var _aacSilent2 = _interopRequireDefault(_aacSilent);
  28160. var _browser = __webpack_require__(4);
  28161. var _browser2 = _interopRequireDefault(_browser);
  28162. var _mediaSegmentInfo = __webpack_require__(15);
  28163. var _exception = __webpack_require__(1);
  28164. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  28165. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  28166. // Fragmented mp4 remuxer
  28167. var MP4Remuxer = function () {
  28168. function MP4Remuxer(config) {
  28169. _classCallCheck(this, MP4Remuxer);
  28170. this.TAG = 'MP4Remuxer';
  28171. this._config = config;
  28172. this._isLive = config.isLive === true ? true : false;
  28173. this._dtsBase = -1;
  28174. this._dtsBaseInited = false;
  28175. this._audioDtsBase = Infinity;
  28176. this._videoDtsBase = Infinity;
  28177. this._audioNextDts = undefined;
  28178. this._videoNextDts = undefined;
  28179. this._audioStashedLastSample = null;
  28180. this._videoStashedLastSample = null;
  28181. this._audioMeta = null;
  28182. this._videoMeta = null;
  28183. this._audioSegmentInfoList = new _mediaSegmentInfo.MediaSegmentInfoList('audio');
  28184. this._videoSegmentInfoList = new _mediaSegmentInfo.MediaSegmentInfoList('video');
  28185. this._onInitSegment = null;
  28186. this._onMediaSegment = null;
  28187. // Workaround for chrome < 50: Always force first sample as a Random Access Point in media segment
  28188. // see https://bugs.chromium.org/p/chromium/issues/detail?id=229412
  28189. this._forceFirstIDR = _browser2.default.chrome && (_browser2.default.version.major < 50 || _browser2.default.version.major === 50 && _browser2.default.version.build < 2661) ? true : false;
  28190. // Workaround for IE11/Edge: Fill silent aac frame after keyframe-seeking
  28191. // Make audio beginDts equals with video beginDts, in order to fix seek freeze
  28192. this._fillSilentAfterSeek = _browser2.default.msedge || _browser2.default.msie;
  28193. // While only FireFox supports 'audio/mp4, codecs="mp3"', use 'audio/mpeg' for chrome, safari, ...
  28194. this._mp3UseMpegAudio = !_browser2.default.firefox;
  28195. this._fillAudioTimestampGap = this._config.fixAudioTimestampGap;
  28196. }
  28197. _createClass(MP4Remuxer, [{
  28198. key: 'destroy',
  28199. value: function destroy() {
  28200. this._dtsBase = -1;
  28201. this._dtsBaseInited = false;
  28202. this._audioMeta = null;
  28203. this._videoMeta = null;
  28204. this._audioSegmentInfoList.clear();
  28205. this._audioSegmentInfoList = null;
  28206. this._videoSegmentInfoList.clear();
  28207. this._videoSegmentInfoList = null;
  28208. this._onInitSegment = null;
  28209. this._onMediaSegment = null;
  28210. }
  28211. }, {
  28212. key: 'bindDataSource',
  28213. value: function bindDataSource(producer) {
  28214. producer.onDataAvailable = this.remux.bind(this);
  28215. producer.onTrackMetadata = this._onTrackMetadataReceived.bind(this);
  28216. return this;
  28217. }
  28218. /* prototype: function onInitSegment(type: string, initSegment: ArrayBuffer): void
  28219. InitSegment: {
  28220. type: string,
  28221. data: ArrayBuffer,
  28222. codec: string,
  28223. container: string
  28224. }
  28225. */
  28226. }, {
  28227. key: 'insertDiscontinuity',
  28228. value: function insertDiscontinuity() {
  28229. this._audioNextDts = this._videoNextDts = undefined;
  28230. }
  28231. }, {
  28232. key: 'seek',
  28233. value: function seek(originalDts) {
  28234. this._audioStashedLastSample = null;
  28235. this._videoStashedLastSample = null;
  28236. this._videoSegmentInfoList.clear();
  28237. this._audioSegmentInfoList.clear();
  28238. }
  28239. }, {
  28240. key: 'remux',
  28241. value: function remux(audioTrack, videoTrack) {
  28242. if (!this._onMediaSegment) {
  28243. throw new _exception.IllegalStateException('MP4Remuxer: onMediaSegment callback must be specificed!');
  28244. }
  28245. if (!this._dtsBaseInited) {
  28246. this._calculateDtsBase(audioTrack, videoTrack);
  28247. }
  28248. this._remuxVideo(videoTrack);
  28249. this._remuxAudio(audioTrack);
  28250. }
  28251. }, {
  28252. key: '_onTrackMetadataReceived',
  28253. value: function _onTrackMetadataReceived(type, metadata) {
  28254. var metabox = null;
  28255. var container = 'mp4';
  28256. var codec = metadata.codec;
  28257. if (type === 'audio') {
  28258. this._audioMeta = metadata;
  28259. if (metadata.codec === 'mp3' && this._mp3UseMpegAudio) {
  28260. // 'audio/mpeg' for MP3 audio track
  28261. container = 'mpeg';
  28262. codec = '';
  28263. metabox = new Uint8Array();
  28264. } else {
  28265. // 'audio/mp4, codecs="codec"'
  28266. metabox = _mp4Generator2.default.generateInitSegment(metadata);
  28267. }
  28268. } else if (type === 'video') {
  28269. this._videoMeta = metadata;
  28270. metabox = _mp4Generator2.default.generateInitSegment(metadata);
  28271. } else {
  28272. return;
  28273. }
  28274. // dispatch metabox (Initialization Segment)
  28275. if (!this._onInitSegment) {
  28276. throw new _exception.IllegalStateException('MP4Remuxer: onInitSegment callback must be specified!');
  28277. }
  28278. this._onInitSegment(type, {
  28279. type: type,
  28280. data: metabox.buffer,
  28281. codec: codec,
  28282. container: type + '/' + container,
  28283. mediaDuration: metadata.duration // in timescale 1000 (milliseconds)
  28284. });
  28285. }
  28286. }, {
  28287. key: '_calculateDtsBase',
  28288. value: function _calculateDtsBase(audioTrack, videoTrack) {
  28289. if (this._dtsBaseInited) {
  28290. return;
  28291. }
  28292. if (audioTrack.samples && audioTrack.samples.length) {
  28293. this._audioDtsBase = audioTrack.samples[0].dts;
  28294. }
  28295. if (videoTrack.samples && videoTrack.samples.length) {
  28296. this._videoDtsBase = videoTrack.samples[0].dts;
  28297. }
  28298. this._dtsBase = Math.min(this._audioDtsBase, this._videoDtsBase);
  28299. this._dtsBaseInited = true;
  28300. }
  28301. }, {
  28302. key: 'flushStashedSamples',
  28303. value: function flushStashedSamples() {
  28304. var videoSample = this._videoStashedLastSample;
  28305. var audioSample = this._audioStashedLastSample;
  28306. var videoTrack = {
  28307. type: 'video',
  28308. id: 1,
  28309. sequenceNumber: 0,
  28310. samples: [],
  28311. length: 0
  28312. };
  28313. if (videoSample != null) {
  28314. videoTrack.samples.push(videoSample);
  28315. videoTrack.length = videoSample.length;
  28316. }
  28317. var audioTrack = {
  28318. type: 'audio',
  28319. id: 2,
  28320. sequenceNumber: 0,
  28321. samples: [],
  28322. length: 0
  28323. };
  28324. if (audioSample != null) {
  28325. audioTrack.samples.push(audioSample);
  28326. audioTrack.length = audioSample.length;
  28327. }
  28328. this._videoStashedLastSample = null;
  28329. this._audioStashedLastSample = null;
  28330. this._remuxVideo(videoTrack, true);
  28331. this._remuxAudio(audioTrack, true);
  28332. }
  28333. }, {
  28334. key: '_remuxAudio',
  28335. value: function _remuxAudio(audioTrack, force) {
  28336. if (this._audioMeta == null) {
  28337. return;
  28338. }
  28339. var track = audioTrack;
  28340. var samples = track.samples;
  28341. var dtsCorrection = undefined;
  28342. var firstDts = -1,
  28343. lastDts = -1,
  28344. lastPts = -1;
  28345. var refSampleDuration = this._audioMeta.refSampleDuration;
  28346. var mpegRawTrack = this._audioMeta.codec === 'mp3' && this._mp3UseMpegAudio;
  28347. var firstSegmentAfterSeek = this._dtsBaseInited && this._audioNextDts === undefined;
  28348. var insertPrefixSilentFrame = false;
  28349. if (!samples || samples.length === 0) {
  28350. return;
  28351. }
  28352. if (samples.length === 1 && !force) {
  28353. // If [sample count in current batch] === 1 && (force != true)
  28354. // Ignore and keep in demuxer's queue
  28355. return;
  28356. } // else if (force === true) do remux
  28357. var offset = 0;
  28358. var mdatbox = null;
  28359. var mdatBytes = 0;
  28360. // calculate initial mdat size
  28361. if (mpegRawTrack) {
  28362. // for raw mpeg buffer
  28363. offset = 0;
  28364. mdatBytes = track.length;
  28365. } else {
  28366. // for fmp4 mdat box
  28367. offset = 8; // size + type
  28368. mdatBytes = 8 + track.length;
  28369. }
  28370. var lastSample = null;
  28371. // Pop the lastSample and waiting for stash
  28372. if (samples.length > 1) {
  28373. lastSample = samples.pop();
  28374. mdatBytes -= lastSample.length;
  28375. }
  28376. // Insert [stashed lastSample in the previous batch] to the front
  28377. if (this._audioStashedLastSample != null) {
  28378. var sample = this._audioStashedLastSample;
  28379. this._audioStashedLastSample = null;
  28380. samples.unshift(sample);
  28381. mdatBytes += sample.length;
  28382. }
  28383. // Stash the lastSample of current batch, waiting for next batch
  28384. if (lastSample != null) {
  28385. this._audioStashedLastSample = lastSample;
  28386. }
  28387. var firstSampleOriginalDts = samples[0].dts - this._dtsBase;
  28388. // calculate dtsCorrection
  28389. if (this._audioNextDts) {
  28390. dtsCorrection = firstSampleOriginalDts - this._audioNextDts;
  28391. } else {
  28392. // this._audioNextDts == undefined
  28393. if (this._audioSegmentInfoList.isEmpty()) {
  28394. dtsCorrection = 0;
  28395. if (this._fillSilentAfterSeek && !this._videoSegmentInfoList.isEmpty()) {
  28396. if (this._audioMeta.originalCodec !== 'mp3') {
  28397. insertPrefixSilentFrame = true;
  28398. }
  28399. }
  28400. } else {
  28401. var _lastSample = this._audioSegmentInfoList.getLastSampleBefore(firstSampleOriginalDts);
  28402. if (_lastSample != null) {
  28403. var distance = firstSampleOriginalDts - (_lastSample.originalDts + _lastSample.duration);
  28404. if (distance <= 3) {
  28405. distance = 0;
  28406. }
  28407. var expectedDts = _lastSample.dts + _lastSample.duration + distance;
  28408. dtsCorrection = firstSampleOriginalDts - expectedDts;
  28409. } else {
  28410. // lastSample == null, cannot found
  28411. dtsCorrection = 0;
  28412. }
  28413. }
  28414. }
  28415. if (insertPrefixSilentFrame) {
  28416. // align audio segment beginDts to match with current video segment's beginDts
  28417. var firstSampleDts = firstSampleOriginalDts - dtsCorrection;
  28418. var videoSegment = this._videoSegmentInfoList.getLastSegmentBefore(firstSampleOriginalDts);
  28419. if (videoSegment != null && videoSegment.beginDts < firstSampleDts) {
  28420. var silentUnit = _aacSilent2.default.getSilentFrame(this._audioMeta.originalCodec, this._audioMeta.channelCount);
  28421. if (silentUnit) {
  28422. var dts = videoSegment.beginDts;
  28423. var silentFrameDuration = firstSampleDts - videoSegment.beginDts;
  28424. _logger2.default.v(this.TAG, 'InsertPrefixSilentAudio: dts: ' + dts + ', duration: ' + silentFrameDuration);
  28425. samples.unshift({ unit: silentUnit, dts: dts, pts: dts });
  28426. mdatBytes += silentUnit.byteLength;
  28427. } // silentUnit == null: Cannot generate, skip
  28428. } else {
  28429. insertPrefixSilentFrame = false;
  28430. }
  28431. }
  28432. var mp4Samples = [];
  28433. // Correct dts for each sample, and calculate sample duration. Then output to mp4Samples
  28434. for (var i = 0; i < samples.length; i++) {
  28435. var _sample = samples[i];
  28436. var unit = _sample.unit;
  28437. var originalDts = _sample.dts - this._dtsBase;
  28438. var _dts = originalDts;
  28439. var needFillSilentFrames = false;
  28440. var silentFrames = null;
  28441. var sampleDuration = 0;
  28442. if (originalDts < -0.001) {
  28443. continue; //pass the first sample with the invalid dts
  28444. }
  28445. if (this._audioMeta.codec !== 'mp3') {
  28446. // for AAC codec, we need to keep dts increase based on refSampleDuration
  28447. var curRefDts = originalDts;
  28448. var maxAudioFramesDrift = 3;
  28449. if (this._audioNextDts) {
  28450. curRefDts = this._audioNextDts;
  28451. }
  28452. dtsCorrection = originalDts - curRefDts;
  28453. if (dtsCorrection <= -maxAudioFramesDrift * refSampleDuration) {
  28454. // If we're overlapping by more than maxAudioFramesDrift number of frame, drop this sample
  28455. _logger2.default.w(this.TAG, 'Dropping 1 audio frame (originalDts: ' + originalDts + ' ms ,curRefDts: ' + curRefDts + ' ms) due to dtsCorrection: ' + dtsCorrection + ' ms overlap.');
  28456. continue;
  28457. } else if (dtsCorrection >= maxAudioFramesDrift * refSampleDuration && this._fillAudioTimestampGap && !_browser2.default.safari) {
  28458. // Silent frame generation, if large timestamp gap detected && config.fixAudioTimestampGap
  28459. needFillSilentFrames = true;
  28460. // We need to insert silent frames to fill timestamp gap
  28461. var frameCount = Math.floor(dtsCorrection / refSampleDuration);
  28462. _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'));
  28463. _dts = Math.floor(curRefDts);
  28464. sampleDuration = Math.floor(curRefDts + refSampleDuration) - _dts;
  28465. var _silentUnit = _aacSilent2.default.getSilentFrame(this._audioMeta.originalCodec, this._audioMeta.channelCount);
  28466. if (_silentUnit == null) {
  28467. _logger2.default.w(this.TAG, 'Unable to generate silent frame for ' + (this._audioMeta.originalCodec + ' with ' + this._audioMeta.channelCount + ' channels, repeat last frame'));
  28468. // Repeat last frame
  28469. _silentUnit = unit;
  28470. }
  28471. silentFrames = [];
  28472. for (var j = 0; j < frameCount; j++) {
  28473. curRefDts = curRefDts + refSampleDuration;
  28474. var intDts = Math.floor(curRefDts); // change to integer
  28475. var intDuration = Math.floor(curRefDts + refSampleDuration) - intDts;
  28476. var frame = {
  28477. dts: intDts,
  28478. pts: intDts,
  28479. cts: 0,
  28480. unit: _silentUnit,
  28481. size: _silentUnit.byteLength,
  28482. duration: intDuration, // wait for next sample
  28483. originalDts: originalDts,
  28484. flags: {
  28485. isLeading: 0,
  28486. dependsOn: 1,
  28487. isDependedOn: 0,
  28488. hasRedundancy: 0
  28489. }
  28490. };
  28491. silentFrames.push(frame);
  28492. mdatBytes += unit.byteLength;
  28493. }
  28494. this._audioNextDts = curRefDts + refSampleDuration;
  28495. } else {
  28496. _dts = Math.floor(curRefDts);
  28497. sampleDuration = Math.floor(curRefDts + refSampleDuration) - _dts;
  28498. this._audioNextDts = curRefDts + refSampleDuration;
  28499. }
  28500. } else {
  28501. // keep the original dts calculate algorithm for mp3
  28502. _dts = originalDts - dtsCorrection;
  28503. if (i !== samples.length - 1) {
  28504. var nextDts = samples[i + 1].dts - this._dtsBase - dtsCorrection;
  28505. sampleDuration = nextDts - _dts;
  28506. } else {
  28507. // the last sample
  28508. if (lastSample != null) {
  28509. // use stashed sample's dts to calculate sample duration
  28510. var _nextDts = lastSample.dts - this._dtsBase - dtsCorrection;
  28511. sampleDuration = _nextDts - _dts;
  28512. } else if (mp4Samples.length >= 1) {
  28513. // use second last sample duration
  28514. sampleDuration = mp4Samples[mp4Samples.length - 1].duration;
  28515. } else {
  28516. // the only one sample, use reference sample duration
  28517. sampleDuration = Math.floor(refSampleDuration);
  28518. }
  28519. }
  28520. this._audioNextDts = _dts + sampleDuration;
  28521. }
  28522. if (firstDts === -1) {
  28523. firstDts = _dts;
  28524. }
  28525. mp4Samples.push({
  28526. dts: _dts,
  28527. pts: _dts,
  28528. cts: 0,
  28529. unit: _sample.unit,
  28530. size: _sample.unit.byteLength,
  28531. duration: sampleDuration,
  28532. originalDts: originalDts,
  28533. flags: {
  28534. isLeading: 0,
  28535. dependsOn: 1,
  28536. isDependedOn: 0,
  28537. hasRedundancy: 0
  28538. }
  28539. });
  28540. if (needFillSilentFrames) {
  28541. // Silent frames should be inserted after wrong-duration frame
  28542. mp4Samples.push.apply(mp4Samples, silentFrames);
  28543. }
  28544. }
  28545. if (mp4Samples.length === 0) {
  28546. //no samples need to remux
  28547. track.samples = [];
  28548. track.length = 0;
  28549. return;
  28550. }
  28551. // allocate mdatbox
  28552. if (mpegRawTrack) {
  28553. // allocate for raw mpeg buffer
  28554. mdatbox = new Uint8Array(mdatBytes);
  28555. } else {
  28556. // allocate for fmp4 mdat box
  28557. mdatbox = new Uint8Array(mdatBytes);
  28558. // size field
  28559. mdatbox[0] = mdatBytes >>> 24 & 0xFF;
  28560. mdatbox[1] = mdatBytes >>> 16 & 0xFF;
  28561. mdatbox[2] = mdatBytes >>> 8 & 0xFF;
  28562. mdatbox[3] = mdatBytes & 0xFF;
  28563. // type field (fourCC)
  28564. mdatbox.set(_mp4Generator2.default.types.mdat, 4);
  28565. }
  28566. // Write samples into mdatbox
  28567. for (var _i = 0; _i < mp4Samples.length; _i++) {
  28568. var _unit = mp4Samples[_i].unit;
  28569. mdatbox.set(_unit, offset);
  28570. offset += _unit.byteLength;
  28571. }
  28572. var latest = mp4Samples[mp4Samples.length - 1];
  28573. lastDts = latest.dts + latest.duration;
  28574. //this._audioNextDts = lastDts;
  28575. // fill media segment info & add to info list
  28576. var info = new _mediaSegmentInfo.MediaSegmentInfo();
  28577. info.beginDts = firstDts;
  28578. info.endDts = lastDts;
  28579. info.beginPts = firstDts;
  28580. info.endPts = lastDts;
  28581. info.originalBeginDts = mp4Samples[0].originalDts;
  28582. info.originalEndDts = latest.originalDts + latest.duration;
  28583. info.firstSample = new _mediaSegmentInfo.SampleInfo(mp4Samples[0].dts, mp4Samples[0].pts, mp4Samples[0].duration, mp4Samples[0].originalDts, false);
  28584. info.lastSample = new _mediaSegmentInfo.SampleInfo(latest.dts, latest.pts, latest.duration, latest.originalDts, false);
  28585. if (!this._isLive) {
  28586. this._audioSegmentInfoList.append(info);
  28587. }
  28588. track.samples = mp4Samples;
  28589. track.sequenceNumber++;
  28590. var moofbox = null;
  28591. if (mpegRawTrack) {
  28592. // Generate empty buffer, because useless for raw mpeg
  28593. moofbox = new Uint8Array();
  28594. } else {
  28595. // Generate moof for fmp4 segment
  28596. moofbox = _mp4Generator2.default.moof(track, firstDts);
  28597. }
  28598. track.samples = [];
  28599. track.length = 0;
  28600. var segment = {
  28601. type: 'audio',
  28602. data: this._mergeBoxes(moofbox, mdatbox).buffer,
  28603. sampleCount: mp4Samples.length,
  28604. info: info
  28605. };
  28606. if (mpegRawTrack && firstSegmentAfterSeek) {
  28607. // For MPEG audio stream in MSE, if seeking occurred, before appending new buffer
  28608. // We need explicitly set timestampOffset to the desired point in timeline for mpeg SourceBuffer.
  28609. segment.timestampOffset = firstDts;
  28610. }
  28611. this._onMediaSegment('audio', segment);
  28612. }
  28613. }, {
  28614. key: '_remuxVideo',
  28615. value: function _remuxVideo(videoTrack, force) {
  28616. if (this._videoMeta == null) {
  28617. return;
  28618. }
  28619. var track = videoTrack;
  28620. var samples = track.samples;
  28621. var dtsCorrection = undefined;
  28622. var firstDts = -1,
  28623. lastDts = -1;
  28624. var firstPts = -1,
  28625. lastPts = -1;
  28626. if (!samples || samples.length === 0) {
  28627. return;
  28628. }
  28629. if (samples.length === 1 && !force) {
  28630. // If [sample count in current batch] === 1 && (force != true)
  28631. // Ignore and keep in demuxer's queue
  28632. return;
  28633. } // else if (force === true) do remux
  28634. var offset = 8;
  28635. var mdatbox = null;
  28636. var mdatBytes = 8 + videoTrack.length;
  28637. var lastSample = null;
  28638. // Pop the lastSample and waiting for stash
  28639. if (samples.length > 1) {
  28640. lastSample = samples.pop();
  28641. mdatBytes -= lastSample.length;
  28642. }
  28643. // Insert [stashed lastSample in the previous batch] to the front
  28644. if (this._videoStashedLastSample != null) {
  28645. var sample = this._videoStashedLastSample;
  28646. this._videoStashedLastSample = null;
  28647. samples.unshift(sample);
  28648. mdatBytes += sample.length;
  28649. }
  28650. // Stash the lastSample of current batch, waiting for next batch
  28651. if (lastSample != null) {
  28652. this._videoStashedLastSample = lastSample;
  28653. }
  28654. var firstSampleOriginalDts = samples[0].dts - this._dtsBase;
  28655. // calculate dtsCorrection
  28656. if (this._videoNextDts) {
  28657. dtsCorrection = firstSampleOriginalDts - this._videoNextDts;
  28658. } else {
  28659. // this._videoNextDts == undefined
  28660. if (this._videoSegmentInfoList.isEmpty()) {
  28661. dtsCorrection = 0;
  28662. } else {
  28663. var _lastSample2 = this._videoSegmentInfoList.getLastSampleBefore(firstSampleOriginalDts);
  28664. if (_lastSample2 != null) {
  28665. var distance = firstSampleOriginalDts - (_lastSample2.originalDts + _lastSample2.duration);
  28666. if (distance <= 3) {
  28667. distance = 0;
  28668. }
  28669. var expectedDts = _lastSample2.dts + _lastSample2.duration + distance;
  28670. dtsCorrection = firstSampleOriginalDts - expectedDts;
  28671. } else {
  28672. // lastSample == null, cannot found
  28673. dtsCorrection = 0;
  28674. }
  28675. }
  28676. }
  28677. var info = new _mediaSegmentInfo.MediaSegmentInfo();
  28678. var mp4Samples = [];
  28679. // Correct dts for each sample, and calculate sample duration. Then output to mp4Samples
  28680. for (var i = 0; i < samples.length; i++) {
  28681. var _sample2 = samples[i];
  28682. var originalDts = _sample2.dts - this._dtsBase;
  28683. var isKeyframe = _sample2.isKeyframe;
  28684. var dts = originalDts - dtsCorrection;
  28685. var cts = _sample2.cts;
  28686. var pts = dts + cts;
  28687. if (firstDts === -1) {
  28688. firstDts = dts;
  28689. firstPts = pts;
  28690. }
  28691. var sampleDuration = 0;
  28692. if (i !== samples.length - 1) {
  28693. var nextDts = samples[i + 1].dts - this._dtsBase - dtsCorrection;
  28694. sampleDuration = nextDts - dts;
  28695. } else {
  28696. // the last sample
  28697. if (lastSample != null) {
  28698. // use stashed sample's dts to calculate sample duration
  28699. var _nextDts2 = lastSample.dts - this._dtsBase - dtsCorrection;
  28700. sampleDuration = _nextDts2 - dts;
  28701. } else if (mp4Samples.length >= 1) {
  28702. // use second last sample duration
  28703. sampleDuration = mp4Samples[mp4Samples.length - 1].duration;
  28704. } else {
  28705. // the only one sample, use reference sample duration
  28706. sampleDuration = Math.floor(this._videoMeta.refSampleDuration);
  28707. }
  28708. }
  28709. if (isKeyframe) {
  28710. var syncPoint = new _mediaSegmentInfo.SampleInfo(dts, pts, sampleDuration, _sample2.dts, true);
  28711. syncPoint.fileposition = _sample2.fileposition;
  28712. info.appendSyncPoint(syncPoint);
  28713. }
  28714. mp4Samples.push({
  28715. dts: dts,
  28716. pts: pts,
  28717. cts: cts,
  28718. units: _sample2.units,
  28719. size: _sample2.length,
  28720. isKeyframe: isKeyframe,
  28721. duration: sampleDuration,
  28722. originalDts: originalDts,
  28723. flags: {
  28724. isLeading: 0,
  28725. dependsOn: isKeyframe ? 2 : 1,
  28726. isDependedOn: isKeyframe ? 1 : 0,
  28727. hasRedundancy: 0,
  28728. isNonSync: isKeyframe ? 0 : 1
  28729. }
  28730. });
  28731. }
  28732. // allocate mdatbox
  28733. mdatbox = new Uint8Array(mdatBytes);
  28734. mdatbox[0] = mdatBytes >>> 24 & 0xFF;
  28735. mdatbox[1] = mdatBytes >>> 16 & 0xFF;
  28736. mdatbox[2] = mdatBytes >>> 8 & 0xFF;
  28737. mdatbox[3] = mdatBytes & 0xFF;
  28738. mdatbox.set(_mp4Generator2.default.types.mdat, 4);
  28739. // Write samples into mdatbox
  28740. for (var _i2 = 0; _i2 < mp4Samples.length; _i2++) {
  28741. var units = mp4Samples[_i2].units;
  28742. while (units.length) {
  28743. var unit = units.shift();
  28744. var data = unit.data;
  28745. mdatbox.set(data, offset);
  28746. offset += data.byteLength;
  28747. }
  28748. }
  28749. var latest = mp4Samples[mp4Samples.length - 1];
  28750. lastDts = latest.dts + latest.duration;
  28751. lastPts = latest.pts + latest.duration;
  28752. this._videoNextDts = lastDts;
  28753. // fill media segment info & add to info list
  28754. info.beginDts = firstDts;
  28755. info.endDts = lastDts;
  28756. info.beginPts = firstPts;
  28757. info.endPts = lastPts;
  28758. info.originalBeginDts = mp4Samples[0].originalDts;
  28759. info.originalEndDts = latest.originalDts + latest.duration;
  28760. info.firstSample = new _mediaSegmentInfo.SampleInfo(mp4Samples[0].dts, mp4Samples[0].pts, mp4Samples[0].duration, mp4Samples[0].originalDts, mp4Samples[0].isKeyframe);
  28761. info.lastSample = new _mediaSegmentInfo.SampleInfo(latest.dts, latest.pts, latest.duration, latest.originalDts, latest.isKeyframe);
  28762. if (!this._isLive) {
  28763. this._videoSegmentInfoList.append(info);
  28764. }
  28765. track.samples = mp4Samples;
  28766. track.sequenceNumber++;
  28767. // workaround for chrome < 50: force first sample as a random access point
  28768. // see https://bugs.chromium.org/p/chromium/issues/detail?id=229412
  28769. if (this._forceFirstIDR) {
  28770. var flags = mp4Samples[0].flags;
  28771. flags.dependsOn = 2;
  28772. flags.isNonSync = 0;
  28773. }
  28774. var moofbox = _mp4Generator2.default.moof(track, firstDts);
  28775. track.samples = [];
  28776. track.length = 0;
  28777. this._onMediaSegment('video', {
  28778. type: 'video',
  28779. data: this._mergeBoxes(moofbox, mdatbox).buffer,
  28780. sampleCount: mp4Samples.length,
  28781. info: info
  28782. });
  28783. }
  28784. }, {
  28785. key: '_mergeBoxes',
  28786. value: function _mergeBoxes(moof, mdat) {
  28787. var result = new Uint8Array(moof.byteLength + mdat.byteLength);
  28788. result.set(moof, 0);
  28789. result.set(mdat, moof.byteLength);
  28790. return result;
  28791. }
  28792. }, {
  28793. key: 'onInitSegment',
  28794. get: function get() {
  28795. return this._onInitSegment;
  28796. },
  28797. set: function set(callback) {
  28798. this._onInitSegment = callback;
  28799. }
  28800. /* prototype: function onMediaSegment(type: string, mediaSegment: MediaSegment): void
  28801. MediaSegment: {
  28802. type: string,
  28803. data: ArrayBuffer,
  28804. sampleCount: int32
  28805. info: MediaSegmentInfo
  28806. }
  28807. */
  28808. }, {
  28809. key: 'onMediaSegment',
  28810. get: function get() {
  28811. return this._onMediaSegment;
  28812. },
  28813. set: function set(callback) {
  28814. this._onMediaSegment = callback;
  28815. }
  28816. }]);
  28817. return MP4Remuxer;
  28818. }();
  28819. exports.default = MP4Remuxer;
  28820. module.exports = exports['default'];
  28821. /***/ }),
  28822. /* 41 */
  28823. /***/ (function(module, exports, __webpack_require__) {
  28824. "use strict";
  28825. Object.defineProperty(exports, "__esModule", {
  28826. value: true
  28827. });
  28828. 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; }; }();
  28829. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  28830. /*
  28831. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  28832. *
  28833. * This file is derived from dailymotion's hls.js library (hls.js/src/remux/mp4-generator.js)
  28834. * @author zheng qian <xqq@xqq.im>
  28835. *
  28836. * Licensed under the Apache License, Version 2.0 (the "License");
  28837. * you may not use this file except in compliance with the License.
  28838. * You may obtain a copy of the License at
  28839. *
  28840. * http://www.apache.org/licenses/LICENSE-2.0
  28841. *
  28842. * Unless required by applicable law or agreed to in writing, software
  28843. * distributed under the License is distributed on an "AS IS" BASIS,
  28844. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  28845. * See the License for the specific language governing permissions and
  28846. * limitations under the License.
  28847. */
  28848. // MP4 boxes generator for ISO BMFF (ISO Base Media File Format, defined in ISO/IEC 14496-12)
  28849. var MP4 = function () {
  28850. function MP4() {
  28851. _classCallCheck(this, MP4);
  28852. }
  28853. _createClass(MP4, null, [{
  28854. key: 'init',
  28855. value: function init() {
  28856. MP4.types = {
  28857. avc1: [],
  28858. avcC: [],
  28859. btrt: [],
  28860. dinf: [],
  28861. dref: [],
  28862. esds: [],
  28863. ftyp: [],
  28864. hdlr: [],
  28865. mdat: [],
  28866. mdhd: [],
  28867. mdia: [],
  28868. mfhd: [],
  28869. minf: [],
  28870. moof: [],
  28871. moov: [],
  28872. mp4a: [],
  28873. mvex: [],
  28874. mvhd: [],
  28875. sdtp: [],
  28876. stbl: [],
  28877. stco: [],
  28878. stsc: [],
  28879. stsd: [],
  28880. stsz: [],
  28881. stts: [],
  28882. tfdt: [],
  28883. tfhd: [],
  28884. traf: [],
  28885. trak: [],
  28886. trun: [],
  28887. trex: [],
  28888. tkhd: [],
  28889. vmhd: [],
  28890. smhd: [],
  28891. '.mp3': []
  28892. };
  28893. for (var name in MP4.types) {
  28894. if (MP4.types.hasOwnProperty(name)) {
  28895. MP4.types[name] = [name.charCodeAt(0), name.charCodeAt(1), name.charCodeAt(2), name.charCodeAt(3)];
  28896. }
  28897. }
  28898. var constants = MP4.constants = {};
  28899. constants.FTYP = new Uint8Array([0x69, 0x73, 0x6F, 0x6D, // major_brand: isom
  28900. 0x0, 0x0, 0x0, 0x1, // minor_version: 0x01
  28901. 0x69, 0x73, 0x6F, 0x6D, // isom
  28902. 0x61, 0x76, 0x63, 0x31 // avc1
  28903. ]);
  28904. constants.STSD_PREFIX = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  28905. 0x00, 0x00, 0x00, 0x01 // entry_count
  28906. ]);
  28907. constants.STTS = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  28908. 0x00, 0x00, 0x00, 0x00 // entry_count
  28909. ]);
  28910. constants.STSC = constants.STCO = constants.STTS;
  28911. constants.STSZ = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  28912. 0x00, 0x00, 0x00, 0x00, // sample_size
  28913. 0x00, 0x00, 0x00, 0x00 // sample_count
  28914. ]);
  28915. constants.HDLR_VIDEO = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  28916. 0x00, 0x00, 0x00, 0x00, // pre_defined
  28917. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  28918. 0x00, 0x00, 0x00, 0x00, // reserved: 3 * 4 bytes
  28919. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x69, 0x64, 0x65, 0x6F, 0x48, 0x61, 0x6E, 0x64, 0x6C, 0x65, 0x72, 0x00 // name: VideoHandler
  28920. ]);
  28921. constants.HDLR_AUDIO = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  28922. 0x00, 0x00, 0x00, 0x00, // pre_defined
  28923. 0x73, 0x6F, 0x75, 0x6E, // handler_type: 'soun'
  28924. 0x00, 0x00, 0x00, 0x00, // reserved: 3 * 4 bytes
  28925. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x6F, 0x75, 0x6E, 0x64, 0x48, 0x61, 0x6E, 0x64, 0x6C, 0x65, 0x72, 0x00 // name: SoundHandler
  28926. ]);
  28927. constants.DREF = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  28928. 0x00, 0x00, 0x00, 0x01, // entry_count
  28929. 0x00, 0x00, 0x00, 0x0C, // entry_size
  28930. 0x75, 0x72, 0x6C, 0x20, // type 'url '
  28931. 0x00, 0x00, 0x00, 0x01 // version(0) + flags
  28932. ]);
  28933. // Sound media header
  28934. constants.SMHD = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  28935. 0x00, 0x00, 0x00, 0x00 // balance(2) + reserved(2)
  28936. ]);
  28937. // video media header
  28938. constants.VMHD = new Uint8Array([0x00, 0x00, 0x00, 0x01, // version(0) + flags
  28939. 0x00, 0x00, // graphicsmode: 2 bytes
  28940. 0x00, 0x00, 0x00, 0x00, // opcolor: 3 * 2 bytes
  28941. 0x00, 0x00]);
  28942. }
  28943. // Generate a box
  28944. }, {
  28945. key: 'box',
  28946. value: function box(type) {
  28947. var size = 8;
  28948. var result = null;
  28949. var datas = Array.prototype.slice.call(arguments, 1);
  28950. var arrayCount = datas.length;
  28951. for (var i = 0; i < arrayCount; i++) {
  28952. size += datas[i].byteLength;
  28953. }
  28954. result = new Uint8Array(size);
  28955. result[0] = size >>> 24 & 0xFF; // size
  28956. result[1] = size >>> 16 & 0xFF;
  28957. result[2] = size >>> 8 & 0xFF;
  28958. result[3] = size & 0xFF;
  28959. result.set(type, 4); // type
  28960. var offset = 8;
  28961. for (var _i = 0; _i < arrayCount; _i++) {
  28962. // data body
  28963. result.set(datas[_i], offset);
  28964. offset += datas[_i].byteLength;
  28965. }
  28966. return result;
  28967. }
  28968. // emit ftyp & moov
  28969. }, {
  28970. key: 'generateInitSegment',
  28971. value: function generateInitSegment(meta) {
  28972. var ftyp = MP4.box(MP4.types.ftyp, MP4.constants.FTYP);
  28973. var moov = MP4.moov(meta);
  28974. var result = new Uint8Array(ftyp.byteLength + moov.byteLength);
  28975. result.set(ftyp, 0);
  28976. result.set(moov, ftyp.byteLength);
  28977. return result;
  28978. }
  28979. // Movie metadata box
  28980. }, {
  28981. key: 'moov',
  28982. value: function moov(meta) {
  28983. var mvhd = MP4.mvhd(meta.timescale, meta.duration);
  28984. var trak = MP4.trak(meta);
  28985. var mvex = MP4.mvex(meta);
  28986. return MP4.box(MP4.types.moov, mvhd, trak, mvex);
  28987. }
  28988. // Movie header box
  28989. }, {
  28990. key: 'mvhd',
  28991. value: function mvhd(timescale, duration) {
  28992. return MP4.box(MP4.types.mvhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  28993. 0x00, 0x00, 0x00, 0x00, // creation_time
  28994. 0x00, 0x00, 0x00, 0x00, // modification_time
  28995. timescale >>> 24 & 0xFF, // timescale: 4 bytes
  28996. timescale >>> 16 & 0xFF, timescale >>> 8 & 0xFF, timescale & 0xFF, duration >>> 24 & 0xFF, // duration: 4 bytes
  28997. duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x00, 0x01, 0x00, 0x00, // Preferred rate: 1.0
  28998. 0x01, 0x00, 0x00, 0x00, // PreferredVolume(1.0, 2bytes) + reserved(2bytes)
  28999. 0x00, 0x00, 0x00, 0x00, // reserved: 4 + 4 bytes
  29000. 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, // ----begin composition matrix----
  29001. 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----
  29002. 0x00, 0x00, 0x00, 0x00, // ----begin pre_defined 6 * 4 bytes----
  29003. 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----
  29004. 0xFF, 0xFF, 0xFF, 0xFF // next_track_ID
  29005. ]));
  29006. }
  29007. // Track box
  29008. }, {
  29009. key: 'trak',
  29010. value: function trak(meta) {
  29011. return MP4.box(MP4.types.trak, MP4.tkhd(meta), MP4.mdia(meta));
  29012. }
  29013. // Track header box
  29014. }, {
  29015. key: 'tkhd',
  29016. value: function tkhd(meta) {
  29017. var trackId = meta.id,
  29018. duration = meta.duration;
  29019. var width = meta.presentWidth,
  29020. height = meta.presentHeight;
  29021. return MP4.box(MP4.types.tkhd, new Uint8Array([0x00, 0x00, 0x00, 0x07, // version(0) + flags
  29022. 0x00, 0x00, 0x00, 0x00, // creation_time
  29023. 0x00, 0x00, 0x00, 0x00, // modification_time
  29024. trackId >>> 24 & 0xFF, // track_ID: 4 bytes
  29025. trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF, 0x00, 0x00, 0x00, 0x00, // reserved: 4 bytes
  29026. duration >>> 24 & 0xFF, // duration: 4 bytes
  29027. duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes
  29028. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // layer(2bytes) + alternate_group(2bytes)
  29029. 0x00, 0x00, 0x00, 0x00, // volume(2bytes) + reserved(2bytes)
  29030. 0x00, 0x01, 0x00, 0x00, // ----begin composition matrix----
  29031. 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----
  29032. width >>> 8 & 0xFF, // width and height
  29033. width & 0xFF, 0x00, 0x00, height >>> 8 & 0xFF, height & 0xFF, 0x00, 0x00]));
  29034. }
  29035. // Media Box
  29036. }, {
  29037. key: 'mdia',
  29038. value: function mdia(meta) {
  29039. return MP4.box(MP4.types.mdia, MP4.mdhd(meta), MP4.hdlr(meta), MP4.minf(meta));
  29040. }
  29041. // Media header box
  29042. }, {
  29043. key: 'mdhd',
  29044. value: function mdhd(meta) {
  29045. var timescale = meta.timescale;
  29046. var duration = meta.duration;
  29047. return MP4.box(MP4.types.mdhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  29048. 0x00, 0x00, 0x00, 0x00, // creation_time
  29049. 0x00, 0x00, 0x00, 0x00, // modification_time
  29050. timescale >>> 24 & 0xFF, // timescale: 4 bytes
  29051. timescale >>> 16 & 0xFF, timescale >>> 8 & 0xFF, timescale & 0xFF, duration >>> 24 & 0xFF, // duration: 4 bytes
  29052. duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x55, 0xC4, // language: und (undetermined)
  29053. 0x00, 0x00 // pre_defined = 0
  29054. ]));
  29055. }
  29056. // Media handler reference box
  29057. }, {
  29058. key: 'hdlr',
  29059. value: function hdlr(meta) {
  29060. var data = null;
  29061. if (meta.type === 'audio') {
  29062. data = MP4.constants.HDLR_AUDIO;
  29063. } else {
  29064. data = MP4.constants.HDLR_VIDEO;
  29065. }
  29066. return MP4.box(MP4.types.hdlr, data);
  29067. }
  29068. // Media infomation box
  29069. }, {
  29070. key: 'minf',
  29071. value: function minf(meta) {
  29072. var xmhd = null;
  29073. if (meta.type === 'audio') {
  29074. xmhd = MP4.box(MP4.types.smhd, MP4.constants.SMHD);
  29075. } else {
  29076. xmhd = MP4.box(MP4.types.vmhd, MP4.constants.VMHD);
  29077. }
  29078. return MP4.box(MP4.types.minf, xmhd, MP4.dinf(), MP4.stbl(meta));
  29079. }
  29080. // Data infomation box
  29081. }, {
  29082. key: 'dinf',
  29083. value: function dinf() {
  29084. var result = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, MP4.constants.DREF));
  29085. return result;
  29086. }
  29087. // Sample table box
  29088. }, {
  29089. key: 'stbl',
  29090. value: function stbl(meta) {
  29091. var result = MP4.box(MP4.types.stbl, // type: stbl
  29092. MP4.stsd(meta), // Sample Description Table
  29093. MP4.box(MP4.types.stts, MP4.constants.STTS), // Time-To-Sample
  29094. MP4.box(MP4.types.stsc, MP4.constants.STSC), // Sample-To-Chunk
  29095. MP4.box(MP4.types.stsz, MP4.constants.STSZ), // Sample size
  29096. MP4.box(MP4.types.stco, MP4.constants.STCO) // Chunk offset
  29097. );
  29098. return result;
  29099. }
  29100. // Sample description box
  29101. }, {
  29102. key: 'stsd',
  29103. value: function stsd(meta) {
  29104. if (meta.type === 'audio') {
  29105. if (meta.codec === 'mp3') {
  29106. return MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.mp3(meta));
  29107. }
  29108. // else: aac -> mp4a
  29109. return MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.mp4a(meta));
  29110. } else {
  29111. return MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.avc1(meta));
  29112. }
  29113. }
  29114. }, {
  29115. key: 'mp3',
  29116. value: function mp3(meta) {
  29117. var channelCount = meta.channelCount;
  29118. var sampleRate = meta.audioSampleRate;
  29119. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // reserved(4)
  29120. 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2)
  29121. 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes
  29122. 0x00, 0x00, 0x00, 0x00, 0x00, channelCount, // channelCount(2)
  29123. 0x00, 0x10, // sampleSize(2)
  29124. 0x00, 0x00, 0x00, 0x00, // reserved(4)
  29125. sampleRate >>> 8 & 0xFF, // Audio sample rate
  29126. sampleRate & 0xFF, 0x00, 0x00]);
  29127. return MP4.box(MP4.types['.mp3'], data);
  29128. }
  29129. }, {
  29130. key: 'mp4a',
  29131. value: function mp4a(meta) {
  29132. var channelCount = meta.channelCount;
  29133. var sampleRate = meta.audioSampleRate;
  29134. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // reserved(4)
  29135. 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2)
  29136. 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes
  29137. 0x00, 0x00, 0x00, 0x00, 0x00, channelCount, // channelCount(2)
  29138. 0x00, 0x10, // sampleSize(2)
  29139. 0x00, 0x00, 0x00, 0x00, // reserved(4)
  29140. sampleRate >>> 8 & 0xFF, // Audio sample rate
  29141. sampleRate & 0xFF, 0x00, 0x00]);
  29142. return MP4.box(MP4.types.mp4a, data, MP4.esds(meta));
  29143. }
  29144. }, {
  29145. key: 'esds',
  29146. value: function esds(meta) {
  29147. var config = meta.config || [];
  29148. var configSize = config.length;
  29149. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version 0 + flags
  29150. 0x03, // descriptor_type
  29151. 0x17 + configSize, // length3
  29152. 0x00, 0x01, // es_id
  29153. 0x00, // stream_priority
  29154. 0x04, // descriptor_type
  29155. 0x0F + configSize, // length
  29156. 0x40, // codec: mpeg4_audio
  29157. 0x15, // stream_type: Audio
  29158. 0x00, 0x00, 0x00, // buffer_size
  29159. 0x00, 0x00, 0x00, 0x00, // maxBitrate
  29160. 0x00, 0x00, 0x00, 0x00, // avgBitrate
  29161. 0x05 // descriptor_type
  29162. ].concat([configSize]).concat(config).concat([0x06, 0x01, 0x02 // GASpecificConfig
  29163. ]));
  29164. return MP4.box(MP4.types.esds, data);
  29165. }
  29166. }, {
  29167. key: 'avc1',
  29168. value: function avc1(meta) {
  29169. var avcc = meta.avcc;
  29170. var width = meta.codecWidth,
  29171. height = meta.codecHeight;
  29172. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // reserved(4)
  29173. 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2)
  29174. 0x00, 0x00, 0x00, 0x00, // pre_defined(2) + reserved(2)
  29175. 0x00, 0x00, 0x00, 0x00, // pre_defined: 3 * 4 bytes
  29176. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, width >>> 8 & 0xFF, // width: 2 bytes
  29177. width & 0xFF, height >>> 8 & 0xFF, // height: 2 bytes
  29178. height & 0xFF, 0x00, 0x48, 0x00, 0x00, // horizresolution: 4 bytes
  29179. 0x00, 0x48, 0x00, 0x00, // vertresolution: 4 bytes
  29180. 0x00, 0x00, 0x00, 0x00, // reserved: 4 bytes
  29181. 0x00, 0x01, // frame_count
  29182. 0x0A, // strlen
  29183. 0x78, 0x71, 0x71, 0x2F, // compressorname: 32 bytes
  29184. 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
  29185. 0xFF, 0xFF // pre_defined = -1
  29186. ]);
  29187. return MP4.box(MP4.types.avc1, data, MP4.box(MP4.types.avcC, avcc));
  29188. }
  29189. // Movie Extends box
  29190. }, {
  29191. key: 'mvex',
  29192. value: function mvex(meta) {
  29193. return MP4.box(MP4.types.mvex, MP4.trex(meta));
  29194. }
  29195. // Track Extends box
  29196. }, {
  29197. key: 'trex',
  29198. value: function trex(meta) {
  29199. var trackId = meta.id;
  29200. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
  29201. trackId >>> 24 & 0xFF, // track_ID
  29202. trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF, 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  29203. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  29204. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  29205. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  29206. ]);
  29207. return MP4.box(MP4.types.trex, data);
  29208. }
  29209. // Movie fragment box
  29210. }, {
  29211. key: 'moof',
  29212. value: function moof(track, baseMediaDecodeTime) {
  29213. return MP4.box(MP4.types.moof, MP4.mfhd(track.sequenceNumber), MP4.traf(track, baseMediaDecodeTime));
  29214. }
  29215. }, {
  29216. key: 'mfhd',
  29217. value: function mfhd(sequenceNumber) {
  29218. var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, sequenceNumber >>> 24 & 0xFF, // sequence_number: int32
  29219. sequenceNumber >>> 16 & 0xFF, sequenceNumber >>> 8 & 0xFF, sequenceNumber & 0xFF]);
  29220. return MP4.box(MP4.types.mfhd, data);
  29221. }
  29222. // Track fragment box
  29223. }, {
  29224. key: 'traf',
  29225. value: function traf(track, baseMediaDecodeTime) {
  29226. var trackId = track.id;
  29227. // Track fragment header box
  29228. var tfhd = MP4.box(MP4.types.tfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) & flags
  29229. trackId >>> 24 & 0xFF, // track_ID
  29230. trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF]));
  29231. // Track Fragment Decode Time
  29232. var tfdt = MP4.box(MP4.types.tfdt, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) & flags
  29233. baseMediaDecodeTime >>> 24 & 0xFF, // baseMediaDecodeTime: int32
  29234. baseMediaDecodeTime >>> 16 & 0xFF, baseMediaDecodeTime >>> 8 & 0xFF, baseMediaDecodeTime & 0xFF]));
  29235. var sdtp = MP4.sdtp(track);
  29236. var trun = MP4.trun(track, sdtp.byteLength + 16 + 16 + 8 + 16 + 8 + 8);
  29237. if (trackId === 1) {
  29238. // console.log(trun)
  29239. }
  29240. return MP4.box(MP4.types.traf, tfhd, tfdt, trun, sdtp);
  29241. }
  29242. // Sample Dependency Type box
  29243. }, {
  29244. key: 'sdtp',
  29245. value: function sdtp(track) {
  29246. var samples = track.samples || [];
  29247. var sampleCount = samples.length;
  29248. var data = new Uint8Array(4 + sampleCount);
  29249. // 0~4 bytes: version(0) & flags
  29250. for (var i = 0; i < sampleCount; i++) {
  29251. var flags = samples[i].flags;
  29252. data[i + 4] = flags.isLeading << 6 | // is_leading: 2 (bit)
  29253. flags.dependsOn << 4 | // sample_depends_on
  29254. flags.isDependedOn << 2 | // sample_is_depended_on
  29255. flags.hasRedundancy; // sample_has_redundancy
  29256. }
  29257. return MP4.box(MP4.types.sdtp, data);
  29258. }
  29259. // Track fragment run box
  29260. }, {
  29261. key: 'trun',
  29262. value: function trun(track, offset) {
  29263. var samples = track.samples || [];
  29264. var sampleCount = samples.length;
  29265. var dataSize = 12 + 16 * sampleCount;
  29266. var data = new Uint8Array(dataSize);
  29267. offset += 8 + dataSize;
  29268. data.set([0x00, 0x00, 0x0F, 0x01, // version(0) & flags
  29269. sampleCount >>> 24 & 0xFF, // sample_count
  29270. sampleCount >>> 16 & 0xFF, sampleCount >>> 8 & 0xFF, sampleCount & 0xFF, offset >>> 24 & 0xFF, // data_offset
  29271. offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF], 0);
  29272. for (var i = 0; i < sampleCount; i++) {
  29273. // console.log(samples[i].duration)
  29274. var duration = samples[i].duration;
  29275. var size = samples[i].size;
  29276. var flags = samples[i].flags;
  29277. var cts = samples[i].cts;
  29278. data.set([duration >>> 24 & 0xFF, // sample_duration
  29279. duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, size >>> 24 & 0xFF, // sample_size
  29280. size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, flags.isLeading << 2 | flags.dependsOn, // sample_flags
  29281. flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.isNonSync, 0x00, 0x00, // sample_degradation_priority
  29282. cts >>> 24 & 0xFF, // sample_composition_time_offset
  29283. cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF], 12 + 16 * i);
  29284. }
  29285. return MP4.box(MP4.types.trun, data);
  29286. }
  29287. }, {
  29288. key: 'mdat',
  29289. value: function mdat(data) {
  29290. return MP4.box(MP4.types.mdat, data);
  29291. }
  29292. }]);
  29293. return MP4;
  29294. }();
  29295. MP4.init();
  29296. exports.default = MP4;
  29297. module.exports = exports['default'];
  29298. /***/ }),
  29299. /* 42 */
  29300. /***/ (function(module, exports, __webpack_require__) {
  29301. "use strict";
  29302. Object.defineProperty(exports, "__esModule", {
  29303. value: true
  29304. });
  29305. 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; }; }();
  29306. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  29307. /*
  29308. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  29309. *
  29310. * This file is modified from dailymotion's hls.js library (hls.js/src/helper/aac.js)
  29311. * @author zheng qian <xqq@xqq.im>
  29312. *
  29313. * Licensed under the Apache License, Version 2.0 (the "License");
  29314. * you may not use this file except in compliance with the License.
  29315. * You may obtain a copy of the License at
  29316. *
  29317. * http://www.apache.org/licenses/LICENSE-2.0
  29318. *
  29319. * Unless required by applicable law or agreed to in writing, software
  29320. * distributed under the License is distributed on an "AS IS" BASIS,
  29321. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  29322. * See the License for the specific language governing permissions and
  29323. * limitations under the License.
  29324. */
  29325. var AAC = function () {
  29326. function AAC() {
  29327. _classCallCheck(this, AAC);
  29328. }
  29329. _createClass(AAC, null, [{
  29330. key: 'getSilentFrame',
  29331. value: function getSilentFrame(codec, channelCount) {
  29332. if (codec === 'mp4a.40.2') {
  29333. // handle LC-AAC
  29334. if (channelCount === 1) {
  29335. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  29336. } else if (channelCount === 2) {
  29337. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  29338. } else if (channelCount === 3) {
  29339. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  29340. } else if (channelCount === 4) {
  29341. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  29342. } else if (channelCount === 5) {
  29343. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  29344. } else if (channelCount === 6) {
  29345. 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]);
  29346. }
  29347. } else {
  29348. // handle HE-AAC (mp4a.40.5 / mp4a.40.29)
  29349. if (channelCount === 1) {
  29350. // 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
  29351. 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]);
  29352. } else if (channelCount === 2) {
  29353. // 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
  29354. 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]);
  29355. } else if (channelCount === 3) {
  29356. // 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
  29357. 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]);
  29358. }
  29359. }
  29360. return null;
  29361. }
  29362. }]);
  29363. return AAC;
  29364. }();
  29365. exports.default = AAC;
  29366. module.exports = exports['default'];
  29367. /***/ }),
  29368. /* 43 */
  29369. /***/ (function(module, exports, __webpack_require__) {
  29370. "use strict";
  29371. Object.defineProperty(exports, "__esModule", {
  29372. value: true
  29373. });
  29374. var _logger = __webpack_require__(0);
  29375. var _logger2 = _interopRequireDefault(_logger);
  29376. var _loggingControl = __webpack_require__(8);
  29377. var _loggingControl2 = _interopRequireDefault(_loggingControl);
  29378. var _polyfill = __webpack_require__(11);
  29379. var _polyfill2 = _interopRequireDefault(_polyfill);
  29380. var _transmuxingController = __webpack_require__(14);
  29381. var _transmuxingController2 = _interopRequireDefault(_transmuxingController);
  29382. var _transmuxingEvents = __webpack_require__(5);
  29383. var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
  29384. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  29385. /* post message to worker:
  29386. data: {
  29387. cmd: string
  29388. param: any
  29389. }
  29390. receive message from worker:
  29391. data: {
  29392. msg: string,
  29393. data: any
  29394. }
  29395. */
  29396. var TransmuxingWorker = function TransmuxingWorker(self) {
  29397. var TAG = 'TransmuxingWorker';
  29398. var controller = null;
  29399. var logcatListener = onLogcatCallback.bind(this);
  29400. _polyfill2.default.install();
  29401. self.addEventListener('message', function (e) {
  29402. switch (e.data.cmd) {
  29403. case 'init':
  29404. controller = new _transmuxingController2.default(e.data.param[0], e.data.param[1]);
  29405. controller.on(_transmuxingEvents2.default.IO_ERROR, onIOError.bind(this));
  29406. controller.on(_transmuxingEvents2.default.DEMUX_ERROR, onDemuxError.bind(this));
  29407. controller.on(_transmuxingEvents2.default.INIT_SEGMENT, onInitSegment.bind(this));
  29408. controller.on(_transmuxingEvents2.default.MEDIA_SEGMENT, onMediaSegment.bind(this));
  29409. controller.on(_transmuxingEvents2.default.LOADING_COMPLETE, onLoadingComplete.bind(this));
  29410. controller.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF, onRecoveredEarlyEof.bind(this));
  29411. controller.on(_transmuxingEvents2.default.MEDIA_INFO, onMediaInfo.bind(this));
  29412. controller.on(_transmuxingEvents2.default.STATISTICS_INFO, onStatisticsInfo.bind(this));
  29413. controller.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, onRecommendSeekpoint.bind(this));
  29414. break;
  29415. case 'destroy':
  29416. if (controller) {
  29417. controller.destroy();
  29418. controller = null;
  29419. }
  29420. self.postMessage({ msg: 'destroyed' });
  29421. break;
  29422. case 'start':
  29423. controller.start();
  29424. break;
  29425. case 'stop':
  29426. controller.stop();
  29427. break;
  29428. case 'seek':
  29429. controller.seek(e.data.param);
  29430. break;
  29431. case 'pause':
  29432. controller.pause();
  29433. break;
  29434. case 'resume':
  29435. controller.resume();
  29436. break;
  29437. case 'logging_config':
  29438. {
  29439. var config = e.data.param;
  29440. _loggingControl2.default.applyConfig(config);
  29441. if (config.enableCallback === true) {
  29442. _loggingControl2.default.addLogListener(logcatListener);
  29443. } else {
  29444. _loggingControl2.default.removeLogListener(logcatListener);
  29445. }
  29446. break;
  29447. }
  29448. }
  29449. });
  29450. function onInitSegment(type, initSegment) {
  29451. var obj = {
  29452. msg: _transmuxingEvents2.default.INIT_SEGMENT,
  29453. data: {
  29454. type: type,
  29455. data: initSegment
  29456. }
  29457. };
  29458. self.postMessage(obj, [initSegment.data]); // data: ArrayBuffer
  29459. }
  29460. function onMediaSegment(type, mediaSegment) {
  29461. var obj = {
  29462. msg: _transmuxingEvents2.default.MEDIA_SEGMENT,
  29463. data: {
  29464. type: type,
  29465. data: mediaSegment
  29466. }
  29467. };
  29468. self.postMessage(obj, [mediaSegment.data]); // data: ArrayBuffer
  29469. }
  29470. function onLoadingComplete() {
  29471. var obj = {
  29472. msg: _transmuxingEvents2.default.LOADING_COMPLETE
  29473. };
  29474. self.postMessage(obj);
  29475. }
  29476. function onRecoveredEarlyEof() {
  29477. var obj = {
  29478. msg: _transmuxingEvents2.default.RECOVERED_EARLY_EOF
  29479. };
  29480. self.postMessage(obj);
  29481. }
  29482. function onMediaInfo(mediaInfo) {
  29483. var obj = {
  29484. msg: _transmuxingEvents2.default.MEDIA_INFO,
  29485. data: mediaInfo
  29486. };
  29487. self.postMessage(obj);
  29488. }
  29489. function onStatisticsInfo(statInfo) {
  29490. var obj = {
  29491. msg: _transmuxingEvents2.default.STATISTICS_INFO,
  29492. data: statInfo
  29493. };
  29494. self.postMessage(obj);
  29495. }
  29496. function onIOError(type, info) {
  29497. self.postMessage({
  29498. msg: _transmuxingEvents2.default.IO_ERROR,
  29499. data: {
  29500. type: type,
  29501. info: info
  29502. }
  29503. });
  29504. }
  29505. function onDemuxError(type, info) {
  29506. self.postMessage({
  29507. msg: _transmuxingEvents2.default.DEMUX_ERROR,
  29508. data: {
  29509. type: type,
  29510. info: info
  29511. }
  29512. });
  29513. }
  29514. function onRecommendSeekpoint(milliseconds) {
  29515. self.postMessage({
  29516. msg: _transmuxingEvents2.default.RECOMMEND_SEEKPOINT,
  29517. data: milliseconds
  29518. });
  29519. }
  29520. function onLogcatCallback(type, str) {
  29521. self.postMessage({
  29522. msg: 'logcat_callback',
  29523. data: {
  29524. type: type,
  29525. logcat: str
  29526. }
  29527. });
  29528. }
  29529. }; /*
  29530. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  29531. *
  29532. * @author zheng qian <xqq@xqq.im>
  29533. *
  29534. * Licensed under the Apache License, Version 2.0 (the "License");
  29535. * you may not use this file except in compliance with the License.
  29536. * You may obtain a copy of the License at
  29537. *
  29538. * http://www.apache.org/licenses/LICENSE-2.0
  29539. *
  29540. * Unless required by applicable law or agreed to in writing, software
  29541. * distributed under the License is distributed on an "AS IS" BASIS,
  29542. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  29543. * See the License for the specific language governing permissions and
  29544. * limitations under the License.
  29545. */
  29546. exports.default = TransmuxingWorker;
  29547. module.exports = exports['default'];
  29548. /***/ }),
  29549. /* 44 */
  29550. /***/ (function(module, exports) {
  29551. var bundleFn = arguments[3];
  29552. var sources = arguments[4];
  29553. var cache = arguments[5];
  29554. var stringify = JSON.stringify;
  29555. module.exports = function (fn, options) {
  29556. var wkey;
  29557. var cacheKeys = Object.keys(cache);
  29558. for (var i = 0, l = cacheKeys.length; i < l; i++) {
  29559. var key = cacheKeys[i];
  29560. var exp = cache[key].exports;
  29561. // Using babel as a transpiler to use esmodule, the export will always
  29562. // be an object with the default export as a property of it. To ensure
  29563. // the existing api and babel esmodule exports are both supported we
  29564. // check for both
  29565. if (exp === fn || exp && exp.default === fn) {
  29566. wkey = key;
  29567. break;
  29568. }
  29569. }
  29570. if (!wkey) {
  29571. wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
  29572. var wcache = {};
  29573. for (var i = 0, l = cacheKeys.length; i < l; i++) {
  29574. var key = cacheKeys[i];
  29575. wcache[key] = key;
  29576. }
  29577. sources[wkey] = [
  29578. 'function(require,module,exports){' + fn + '(self); }',
  29579. wcache
  29580. ];
  29581. }
  29582. var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
  29583. var scache = {}; scache[wkey] = wkey;
  29584. sources[skey] = [
  29585. 'function(require,module,exports){' +
  29586. // try to call default if defined to also support babel esmodule exports
  29587. 'var f = require(' + stringify(wkey) + ');' +
  29588. '(f.default ? f.default : f)(self);' +
  29589. '}',
  29590. scache
  29591. ];
  29592. var workerSources = {};
  29593. resolveSources(skey);
  29594. function resolveSources(key) {
  29595. workerSources[key] = true;
  29596. for (var depPath in sources[key][1]) {
  29597. var depKey = sources[key][1][depPath];
  29598. if (!workerSources[depKey]) {
  29599. resolveSources(depKey);
  29600. }
  29601. }
  29602. }
  29603. var src = '(' + bundleFn + ')({'
  29604. + Object.keys(workerSources).map(function (key) {
  29605. return stringify(key) + ':['
  29606. + sources[key][0]
  29607. + ',' + stringify(sources[key][1]) + ']'
  29608. ;
  29609. }).join(',')
  29610. + '},{},[' + stringify(skey) + '])'
  29611. ;
  29612. var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  29613. var blob = new Blob([src], { type: 'text/javascript' });
  29614. if (options && options.bare) { return blob; }
  29615. var workerUrl = URL.createObjectURL(blob);
  29616. var worker = new Worker(workerUrl);
  29617. worker.objectURL = workerUrl;
  29618. return worker;
  29619. };
  29620. /***/ }),
  29621. /* 45 */
  29622. /***/ (function(module, exports, __webpack_require__) {
  29623. "use strict";
  29624. Object.defineProperty(exports, "__esModule", {
  29625. value: true
  29626. });
  29627. 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; }; }(); /*
  29628. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  29629. *
  29630. * @author zheng qian <xqq@xqq.im>
  29631. *
  29632. * Licensed under the Apache License, Version 2.0 (the "License");
  29633. * you may not use this file except in compliance with the License.
  29634. * You may obtain a copy of the License at
  29635. *
  29636. * http://www.apache.org/licenses/LICENSE-2.0
  29637. *
  29638. * Unless required by applicable law or agreed to in writing, software
  29639. * distributed under the License is distributed on an "AS IS" BASIS,
  29640. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  29641. * See the License for the specific language governing permissions and
  29642. * limitations under the License.
  29643. */
  29644. var _events = __webpack_require__(2);
  29645. var _events2 = _interopRequireDefault(_events);
  29646. var _logger = __webpack_require__(0);
  29647. var _logger2 = _interopRequireDefault(_logger);
  29648. var _browser = __webpack_require__(4);
  29649. var _browser2 = _interopRequireDefault(_browser);
  29650. var _mseEvents = __webpack_require__(16);
  29651. var _mseEvents2 = _interopRequireDefault(_mseEvents);
  29652. var _mediaSegmentInfo = __webpack_require__(15);
  29653. var _exception = __webpack_require__(1);
  29654. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  29655. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  29656. // Media Source Extensions controller
  29657. var MSEController = function () {
  29658. function MSEController(config) {
  29659. _classCallCheck(this, MSEController);
  29660. this.TAG = 'MSEController';
  29661. this._config = config;
  29662. this._emitter = new _events2.default();
  29663. if (this._config.isLive && this._config.autoCleanupSourceBuffer == undefined) {
  29664. // For live stream, do auto cleanup by default
  29665. this._config.autoCleanupSourceBuffer = true;
  29666. }
  29667. this.e = {
  29668. onSourceOpen: this._onSourceOpen.bind(this),
  29669. onSourceEnded: this._onSourceEnded.bind(this),
  29670. onSourceClose: this._onSourceClose.bind(this),
  29671. onSourceBufferError: this._onSourceBufferError.bind(this),
  29672. onSourceBufferUpdateEnd: this._onSourceBufferUpdateEnd.bind(this)
  29673. };
  29674. this._mediaSource = null;
  29675. this._mediaSourceObjectURL = null;
  29676. this._mediaElement = null;
  29677. this._isBufferFull = false;
  29678. this._hasPendingEos = false;
  29679. this._requireSetMediaDuration = false;
  29680. this._pendingMediaDuration = 0;
  29681. this._pendingSourceBufferInit = [];
  29682. this._mimeTypes = {
  29683. video: null,
  29684. audio: null
  29685. };
  29686. this._sourceBuffers = {
  29687. video: null,
  29688. audio: null
  29689. };
  29690. this._lastInitSegments = {
  29691. video: null,
  29692. audio: null
  29693. };
  29694. this._pendingSegments = {
  29695. video: [],
  29696. audio: []
  29697. };
  29698. this._pendingRemoveRanges = {
  29699. video: [],
  29700. audio: []
  29701. };
  29702. this._idrList = new _mediaSegmentInfo.IDRSampleList();
  29703. }
  29704. _createClass(MSEController, [{
  29705. key: 'destroy',
  29706. value: function destroy() {
  29707. if (this._mediaElement || this._mediaSource) {
  29708. this.detachMediaElement();
  29709. }
  29710. this.e = null;
  29711. this._emitter.removeAllListeners();
  29712. this._emitter = null;
  29713. }
  29714. }, {
  29715. key: 'on',
  29716. value: function on(event, listener) {
  29717. this._emitter.addListener(event, listener);
  29718. }
  29719. }, {
  29720. key: 'off',
  29721. value: function off(event, listener) {
  29722. this._emitter.removeListener(event, listener);
  29723. }
  29724. }, {
  29725. key: 'attachMediaElement',
  29726. value: function attachMediaElement(mediaElement) {
  29727. if (this._mediaSource) {
  29728. throw new _exception.IllegalStateException('MediaSource has been attached to an HTMLMediaElement!');
  29729. }
  29730. var ms = this._mediaSource = new window.MediaSource();
  29731. ms.addEventListener('sourceopen', this.e.onSourceOpen);
  29732. ms.addEventListener('sourceended', this.e.onSourceEnded);
  29733. ms.addEventListener('sourceclose', this.e.onSourceClose);
  29734. this._mediaElement = mediaElement;
  29735. this._mediaSourceObjectURL = window.URL.createObjectURL(this._mediaSource);
  29736. mediaElement.src = this._mediaSourceObjectURL;
  29737. }
  29738. }, {
  29739. key: 'detachMediaElement',
  29740. value: function detachMediaElement() {
  29741. if (this._mediaSource) {
  29742. var ms = this._mediaSource;
  29743. for (var type in this._sourceBuffers) {
  29744. // pending segments should be discard
  29745. var ps = this._pendingSegments[type];
  29746. ps.splice(0, ps.length);
  29747. this._pendingSegments[type] = null;
  29748. this._pendingRemoveRanges[type] = null;
  29749. this._lastInitSegments[type] = null;
  29750. // remove all sourcebuffers
  29751. var sb = this._sourceBuffers[type];
  29752. if (sb) {
  29753. if (ms.readyState !== 'closed') {
  29754. ms.removeSourceBuffer(sb);
  29755. sb.removeEventListener('error', this.e.onSourceBufferError);
  29756. sb.removeEventListener('updateend', this.e.onSourceBufferUpdateEnd);
  29757. }
  29758. this._mimeTypes[type] = null;
  29759. this._sourceBuffers[type] = null;
  29760. }
  29761. }
  29762. if (ms.readyState === 'open') {
  29763. try {
  29764. ms.endOfStream();
  29765. } catch (error) {
  29766. _logger2.default.e(this.TAG, error.message);
  29767. }
  29768. }
  29769. ms.removeEventListener('sourceopen', this.e.onSourceOpen);
  29770. ms.removeEventListener('sourceended', this.e.onSourceEnded);
  29771. ms.removeEventListener('sourceclose', this.e.onSourceClose);
  29772. this._pendingSourceBufferInit = [];
  29773. this._isBufferFull = false;
  29774. this._idrList.clear();
  29775. this._mediaSource = null;
  29776. }
  29777. if (this._mediaElement) {
  29778. this._mediaElement.src = '';
  29779. this._mediaElement.removeAttribute('src');
  29780. this._mediaElement = null;
  29781. }
  29782. if (this._mediaSourceObjectURL) {
  29783. window.URL.revokeObjectURL(this._mediaSourceObjectURL);
  29784. this._mediaSourceObjectURL = null;
  29785. }
  29786. }
  29787. }, {
  29788. key: 'appendInitSegment',
  29789. value: function appendInitSegment(initSegment, deferred) {
  29790. if (!this._mediaSource || this._mediaSource.readyState !== 'open') {
  29791. // sourcebuffer creation requires mediaSource.readyState === 'open'
  29792. // so we defer the sourcebuffer creation, until sourceopen event triggered
  29793. this._pendingSourceBufferInit.push(initSegment);
  29794. // make sure that this InitSegment is in the front of pending segments queue
  29795. this._pendingSegments[initSegment.type].push(initSegment);
  29796. // console.log(`${initSegment.type}`, initSegment)
  29797. return;
  29798. }
  29799. var is = initSegment;
  29800. var mimeType = '' + is.container;
  29801. if (is.codec && is.codec.length > 0) {
  29802. mimeType += ';codecs=' + is.codec;
  29803. }
  29804. var firstInitSegment = false;
  29805. _logger2.default.v(this.TAG, 'Received Initialization Segment, mimeType: ' + mimeType);
  29806. this._lastInitSegments[is.type] = is;
  29807. if (mimeType !== this._mimeTypes[is.type]) {
  29808. if (!this._mimeTypes[is.type]) {
  29809. // empty, first chance create sourcebuffer
  29810. firstInitSegment = true;
  29811. try {
  29812. var sb = this._sourceBuffers[is.type] = this._mediaSource.addSourceBuffer(mimeType);
  29813. sb.addEventListener('error', this.e.onSourceBufferError);
  29814. sb.addEventListener('updateend', this.e.onSourceBufferUpdateEnd);
  29815. } catch (error) {
  29816. _logger2.default.e(this.TAG, error.message);
  29817. this._emitter.emit(_mseEvents2.default.ERROR, { code: error.code, msg: error.message });
  29818. return;
  29819. }
  29820. } else {
  29821. _logger2.default.v(this.TAG, 'Notice: ' + is.type + ' mimeType changed, origin: ' + this._mimeTypes[is.type] + ', target: ' + mimeType);
  29822. }
  29823. this._mimeTypes[is.type] = mimeType;
  29824. }
  29825. if (!deferred) {
  29826. // deferred means this InitSegment has been pushed to pendingSegments queue
  29827. this._pendingSegments[is.type].push(is);
  29828. }
  29829. if (!firstInitSegment) {
  29830. // append immediately only if init segment in subsequence
  29831. if (this._sourceBuffers[is.type] && !this._sourceBuffers[is.type].updating) {
  29832. this._doAppendSegments();
  29833. }
  29834. }
  29835. if (_browser2.default.safari && is.container === 'audio/mpeg' && is.mediaDuration > 0) {
  29836. // 'audio/mpeg' track under Safari may cause MediaElement's duration to be NaN
  29837. // Manually correct MediaSource.duration to make progress bar seekable, and report right duration
  29838. this._requireSetMediaDuration = true;
  29839. this._pendingMediaDuration = is.mediaDuration / 1000; // in seconds
  29840. this._updateMediaSourceDuration();
  29841. }
  29842. }
  29843. }, {
  29844. key: 'appendMediaSegment',
  29845. value: function appendMediaSegment(mediaSegment) {
  29846. var ms = mediaSegment;
  29847. this._pendingSegments[ms.type].push(ms);
  29848. if (this._config.autoCleanupSourceBuffer && this._needCleanupSourceBuffer()) {
  29849. this._doCleanupSourceBuffer();
  29850. }
  29851. var sb = this._sourceBuffers[ms.type];
  29852. if (sb && !sb.updating && !this._hasPendingRemoveRanges()) {
  29853. this._doAppendSegments();
  29854. }
  29855. }
  29856. }, {
  29857. key: 'seek',
  29858. value: function seek(seconds) {
  29859. // remove all appended buffers
  29860. for (var type in this._sourceBuffers) {
  29861. if (!this._sourceBuffers[type]) {
  29862. continue;
  29863. }
  29864. // abort current buffer append algorithm
  29865. var sb = this._sourceBuffers[type];
  29866. if (this._mediaSource.readyState === 'open') {
  29867. try {
  29868. // If range removal algorithm is running, InvalidStateError will be throwed
  29869. // Ignore it.
  29870. sb.abort();
  29871. } catch (error) {
  29872. _logger2.default.e(this.TAG, error.message);
  29873. }
  29874. }
  29875. // IDRList should be clear
  29876. this._idrList.clear();
  29877. // pending segments should be discard
  29878. var ps = this._pendingSegments[type];
  29879. ps.splice(0, ps.length);
  29880. if (this._mediaSource.readyState === 'closed') {
  29881. // Parent MediaSource object has been detached from HTMLMediaElement
  29882. continue;
  29883. }
  29884. // record ranges to be remove from SourceBuffer
  29885. for (var i = 0; i < sb.buffered.length; i++) {
  29886. var start = sb.buffered.start(i);
  29887. var end = sb.buffered.end(i);
  29888. this._pendingRemoveRanges[type].push({ start: start, end: end });
  29889. }
  29890. // if sb is not updating, let's remove ranges now!
  29891. if (!sb.updating) {
  29892. this._doRemoveRanges();
  29893. }
  29894. // Safari 10 may get InvalidStateError in the later appendBuffer() after SourceBuffer.remove() call
  29895. // Internal parser's state may be invalid at this time. Re-append last InitSegment to workaround.
  29896. // Related issue: https://bugs.webkit.org/show_bug.cgi?id=159230
  29897. if (_browser2.default.safari) {
  29898. var lastInitSegment = this._lastInitSegments[type];
  29899. if (lastInitSegment) {
  29900. this._pendingSegments[type].push(lastInitSegment);
  29901. if (!sb.updating) {
  29902. this._doAppendSegments();
  29903. }
  29904. }
  29905. }
  29906. }
  29907. }
  29908. }, {
  29909. key: 'endOfStream',
  29910. value: function endOfStream() {
  29911. var ms = this._mediaSource;
  29912. var sb = this._sourceBuffers;
  29913. if (!ms || ms.readyState !== 'open') {
  29914. if (ms && ms.readyState === 'closed' && this._hasPendingSegments()) {
  29915. // If MediaSource hasn't turned into open state, and there're pending segments
  29916. // Mark pending endOfStream, defer call until all pending segments appended complete
  29917. this._hasPendingEos = true;
  29918. }
  29919. return;
  29920. }
  29921. if (sb.video && sb.video.updating || sb.audio && sb.audio.updating) {
  29922. // If any sourcebuffer is updating, defer endOfStream operation
  29923. // See _onSourceBufferUpdateEnd()
  29924. this._hasPendingEos = true;
  29925. } else {
  29926. this._hasPendingEos = false;
  29927. // Notify media data loading complete
  29928. // This is helpful for correcting total duration to match last media segment
  29929. // Otherwise MediaElement's ended event may not be triggered
  29930. ms.endOfStream();
  29931. }
  29932. }
  29933. }, {
  29934. key: 'getNearestKeyframe',
  29935. value: function getNearestKeyframe(dts) {
  29936. return this._idrList.getLastSyncPointBeforeDts(dts);
  29937. }
  29938. }, {
  29939. key: '_needCleanupSourceBuffer',
  29940. value: function _needCleanupSourceBuffer() {
  29941. if (!this._config.autoCleanupSourceBuffer) {
  29942. return false;
  29943. }
  29944. var currentTime = this._mediaElement.currentTime;
  29945. for (var type in this._sourceBuffers) {
  29946. var sb = this._sourceBuffers[type];
  29947. if (sb) {
  29948. var buffered = sb.buffered;
  29949. if (buffered.length >= 1) {
  29950. if (currentTime - buffered.start(0) >= this._config.autoCleanupMaxBackwardDuration) {
  29951. return true;
  29952. }
  29953. }
  29954. }
  29955. }
  29956. return false;
  29957. }
  29958. }, {
  29959. key: '_doCleanupSourceBuffer',
  29960. value: function _doCleanupSourceBuffer() {
  29961. var currentTime = this._mediaElement.currentTime;
  29962. for (var type in this._sourceBuffers) {
  29963. var sb = this._sourceBuffers[type];
  29964. if (sb) {
  29965. var buffered = sb.buffered;
  29966. var doRemove = false;
  29967. for (var i = 0; i < buffered.length; i++) {
  29968. var start = buffered.start(i);
  29969. var end = buffered.end(i);
  29970. if (start <= currentTime && currentTime < end + 3) {
  29971. // padding 3 seconds
  29972. if (currentTime - start >= this._config.autoCleanupMaxBackwardDuration) {
  29973. doRemove = true;
  29974. var removeEnd = currentTime - this._config.autoCleanupMinBackwardDuration;
  29975. this._pendingRemoveRanges[type].push({ start: start, end: removeEnd });
  29976. }
  29977. } else if (end < currentTime) {
  29978. doRemove = true;
  29979. this._pendingRemoveRanges[type].push({ start: start, end: end });
  29980. }
  29981. }
  29982. if (doRemove && !sb.updating) {
  29983. this._doRemoveRanges();
  29984. }
  29985. }
  29986. }
  29987. }
  29988. }, {
  29989. key: '_updateMediaSourceDuration',
  29990. value: function _updateMediaSourceDuration() {
  29991. var sb = this._sourceBuffers;
  29992. if (this._mediaElement.readyState === 0 || this._mediaSource.readyState !== 'open') {
  29993. return;
  29994. }
  29995. if (sb.video && sb.video.updating || sb.audio && sb.audio.updating) {
  29996. return;
  29997. }
  29998. var current = this._mediaSource.duration;
  29999. var target = this._pendingMediaDuration;
  30000. if (target > 0 && (isNaN(current) || target > current)) {
  30001. _logger2.default.v(this.TAG, 'Update MediaSource duration from ' + current + ' to ' + target);
  30002. this._mediaSource.duration = target;
  30003. }
  30004. this._requireSetMediaDuration = false;
  30005. this._pendingMediaDuration = 0;
  30006. }
  30007. }, {
  30008. key: '_doRemoveRanges',
  30009. value: function _doRemoveRanges() {
  30010. for (var type in this._pendingRemoveRanges) {
  30011. if (!this._sourceBuffers[type] || this._sourceBuffers[type].updating) {
  30012. continue;
  30013. }
  30014. var sb = this._sourceBuffers[type];
  30015. var ranges = this._pendingRemoveRanges[type];
  30016. while (ranges.length && !sb.updating) {
  30017. var range = ranges.shift();
  30018. sb.remove(range.start, range.end);
  30019. }
  30020. }
  30021. }
  30022. }, {
  30023. key: '_doAppendSegments',
  30024. value: function _doAppendSegments() {
  30025. var pendingSegments = this._pendingSegments;
  30026. for (var type in pendingSegments) {
  30027. if (!this._sourceBuffers[type] || this._sourceBuffers[type].updating) {
  30028. continue;
  30029. }
  30030. if (pendingSegments[type].length > 0) {
  30031. var segment = pendingSegments[type].shift();
  30032. if (segment.timestampOffset) {
  30033. // For MPEG audio stream in MSE, if unbuffered-seeking occurred
  30034. // We need explicitly set timestampOffset to the desired point in timeline for mpeg SourceBuffer.
  30035. var currentOffset = this._sourceBuffers[type].timestampOffset;
  30036. var targetOffset = segment.timestampOffset / 1000; // in seconds
  30037. var delta = Math.abs(currentOffset - targetOffset);
  30038. if (delta > 0.1) {
  30039. // If time delta > 100ms
  30040. _logger2.default.v(this.TAG, 'Update MPEG audio timestampOffset from ' + currentOffset + ' to ' + targetOffset);
  30041. this._sourceBuffers[type].timestampOffset = targetOffset;
  30042. }
  30043. delete segment.timestampOffset;
  30044. }
  30045. if (!segment.data || segment.data.byteLength === 0) {
  30046. // Ignore empty buffer
  30047. continue;
  30048. }
  30049. try {
  30050. this._sourceBuffers[type].appendBuffer(segment.data);
  30051. this._isBufferFull = false;
  30052. if (type === 'video' && segment.hasOwnProperty('info')) {
  30053. this._idrList.appendArray(segment.info.syncPoints);
  30054. }
  30055. } catch (error) {
  30056. this._pendingSegments[type].unshift(segment);
  30057. if (error.code === 22) {
  30058. // QuotaExceededError
  30059. /* Notice that FireFox may not throw QuotaExceededError if SourceBuffer is full
  30060. * Currently we can only do lazy-load to avoid SourceBuffer become scattered.
  30061. * SourceBuffer eviction policy may be changed in future version of FireFox.
  30062. *
  30063. * Related issues:
  30064. * https://bugzilla.mozilla.org/show_bug.cgi?id=1279885
  30065. * https://bugzilla.mozilla.org/show_bug.cgi?id=1280023
  30066. */
  30067. // report buffer full, abort network IO
  30068. if (!this._isBufferFull) {
  30069. this._emitter.emit(_mseEvents2.default.BUFFER_FULL);
  30070. }
  30071. this._isBufferFull = true;
  30072. } else {
  30073. _logger2.default.e(this.TAG, error.message);
  30074. this._emitter.emit(_mseEvents2.default.ERROR, { code: error.code, msg: error.message });
  30075. }
  30076. }
  30077. }
  30078. }
  30079. }
  30080. }, {
  30081. key: '_onSourceOpen',
  30082. value: function _onSourceOpen() {
  30083. _logger2.default.v(this.TAG, 'MediaSource onSourceOpen');
  30084. this._mediaSource.removeEventListener('sourceopen', this.e.onSourceOpen);
  30085. // deferred sourcebuffer creation / initialization
  30086. if (this._pendingSourceBufferInit.length > 0) {
  30087. var pendings = this._pendingSourceBufferInit;
  30088. while (pendings.length) {
  30089. var segment = pendings.shift();
  30090. this.appendInitSegment(segment, true);
  30091. }
  30092. }
  30093. // there may be some pending media segments, append them
  30094. if (this._hasPendingSegments()) {
  30095. this._doAppendSegments();
  30096. }
  30097. this._emitter.emit(_mseEvents2.default.SOURCE_OPEN);
  30098. }
  30099. }, {
  30100. key: '_onSourceEnded',
  30101. value: function _onSourceEnded() {
  30102. // fired on endOfStream
  30103. _logger2.default.v(this.TAG, 'MediaSource onSourceEnded');
  30104. }
  30105. }, {
  30106. key: '_onSourceClose',
  30107. value: function _onSourceClose() {
  30108. // fired on detaching from media element
  30109. _logger2.default.v(this.TAG, 'MediaSource onSourceClose');
  30110. if (this._mediaSource && this.e != null) {
  30111. this._mediaSource.removeEventListener('sourceopen', this.e.onSourceOpen);
  30112. this._mediaSource.removeEventListener('sourceended', this.e.onSourceEnded);
  30113. this._mediaSource.removeEventListener('sourceclose', this.e.onSourceClose);
  30114. }
  30115. }
  30116. }, {
  30117. key: '_hasPendingSegments',
  30118. value: function _hasPendingSegments() {
  30119. var ps = this._pendingSegments;
  30120. return ps.video.length > 0 || ps.audio.length > 0;
  30121. }
  30122. }, {
  30123. key: '_hasPendingRemoveRanges',
  30124. value: function _hasPendingRemoveRanges() {
  30125. var prr = this._pendingRemoveRanges;
  30126. return prr.video.length > 0 || prr.audio.length > 0;
  30127. }
  30128. }, {
  30129. key: '_onSourceBufferUpdateEnd',
  30130. value: function _onSourceBufferUpdateEnd() {
  30131. if (this._requireSetMediaDuration) {
  30132. this._updateMediaSourceDuration();
  30133. } else if (this._hasPendingRemoveRanges()) {
  30134. this._doRemoveRanges();
  30135. } else if (this._hasPendingSegments()) {
  30136. this._doAppendSegments();
  30137. } else if (this._hasPendingEos) {
  30138. this.endOfStream();
  30139. }
  30140. this._emitter.emit(_mseEvents2.default.UPDATE_END);
  30141. }
  30142. }, {
  30143. key: '_onSourceBufferError',
  30144. value: function _onSourceBufferError(e) {
  30145. _logger2.default.e(this.TAG, 'SourceBuffer Error: ' + e);
  30146. // this error might not always be fatal, just ignore it
  30147. }
  30148. }]);
  30149. return MSEController;
  30150. }();
  30151. exports.default = MSEController;
  30152. module.exports = exports['default'];
  30153. /***/ }),
  30154. /* 46 */
  30155. /***/ (function(module, exports, __webpack_require__) {
  30156. "use strict";
  30157. Object.defineProperty(exports, "__esModule", {
  30158. value: true
  30159. });
  30160. 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; };
  30161. 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; }; }(); /*
  30162. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  30163. *
  30164. * @author zheng qian <xqq@xqq.im>
  30165. *
  30166. * Licensed under the Apache License, Version 2.0 (the "License");
  30167. * you may not use this file except in compliance with the License.
  30168. * You may obtain a copy of the License at
  30169. *
  30170. * http://www.apache.org/licenses/LICENSE-2.0
  30171. *
  30172. * Unless required by applicable law or agreed to in writing, software
  30173. * distributed under the License is distributed on an "AS IS" BASIS,
  30174. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  30175. * See the License for the specific language governing permissions and
  30176. * limitations under the License.
  30177. */
  30178. var _events = __webpack_require__(2);
  30179. var _events2 = _interopRequireDefault(_events);
  30180. var _playerEvents = __webpack_require__(7);
  30181. var _playerEvents2 = _interopRequireDefault(_playerEvents);
  30182. var _config = __webpack_require__(6);
  30183. var _exception = __webpack_require__(1);
  30184. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  30185. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  30186. // Player wrapper for browser's native player (HTMLVideoElement) without MediaSource src.
  30187. var NativePlayer = function () {
  30188. function NativePlayer(mediaDataSource, config) {
  30189. _classCallCheck(this, NativePlayer);
  30190. this.TAG = 'NativePlayer';
  30191. this._type = 'NativePlayer';
  30192. this._emitter = new _events2.default();
  30193. this._config = (0, _config.createDefaultConfig)();
  30194. if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object') {
  30195. Object.assign(this._config, config);
  30196. }
  30197. if (mediaDataSource.type.toLowerCase() === 'flv') {
  30198. throw new _exception.InvalidArgumentException('NativePlayer does\'t support flv MediaDataSource input!');
  30199. }
  30200. if (mediaDataSource.hasOwnProperty('segments')) {
  30201. throw new _exception.InvalidArgumentException('NativePlayer(' + mediaDataSource.type + ') doesn\'t support multipart playback!');
  30202. }
  30203. this.e = {
  30204. onvLoadedMetadata: this._onvLoadedMetadata.bind(this)
  30205. };
  30206. this._pendingSeekTime = null;
  30207. this._statisticsReporter = null;
  30208. this._mediaDataSource = mediaDataSource;
  30209. this._mediaElement = null;
  30210. }
  30211. _createClass(NativePlayer, [{
  30212. key: 'destroy',
  30213. value: function destroy() {
  30214. if (this._mediaElement) {
  30215. this.unload();
  30216. this.detachMediaElement();
  30217. }
  30218. this.e = null;
  30219. this._mediaDataSource = null;
  30220. this._emitter.removeAllListeners();
  30221. this._emitter = null;
  30222. }
  30223. }, {
  30224. key: 'on',
  30225. value: function on(event, listener) {
  30226. var _this = this;
  30227. if (event === _playerEvents2.default.MEDIA_INFO) {
  30228. if (this._mediaElement != null && this._mediaElement.readyState !== 0) {
  30229. // HAVE_NOTHING
  30230. Promise.resolve().then(function () {
  30231. _this._emitter.emit(_playerEvents2.default.MEDIA_INFO, _this.mediaInfo);
  30232. });
  30233. }
  30234. } else if (event === _playerEvents2.default.STATISTICS_INFO) {
  30235. if (this._mediaElement != null && this._mediaElement.readyState !== 0) {
  30236. Promise.resolve().then(function () {
  30237. _this._emitter.emit(_playerEvents2.default.STATISTICS_INFO, _this.statisticsInfo);
  30238. });
  30239. }
  30240. }
  30241. this._emitter.addListener(event, listener);
  30242. }
  30243. }, {
  30244. key: 'off',
  30245. value: function off(event, listener) {
  30246. this._emitter.removeListener(event, listener);
  30247. }
  30248. }, {
  30249. key: 'attachMediaElement',
  30250. value: function attachMediaElement(mediaElement) {
  30251. this._mediaElement = mediaElement;
  30252. mediaElement.addEventListener('loadedmetadata', this.e.onvLoadedMetadata);
  30253. if (this._pendingSeekTime != null) {
  30254. try {
  30255. mediaElement.currentTime = this._pendingSeekTime;
  30256. this._pendingSeekTime = null;
  30257. } catch (e) {
  30258. // IE11 may throw InvalidStateError if readyState === 0
  30259. // Defer set currentTime operation after loadedmetadata
  30260. }
  30261. }
  30262. }
  30263. }, {
  30264. key: 'detachMediaElement',
  30265. value: function detachMediaElement() {
  30266. if (this._mediaElement) {
  30267. this._mediaElement.src = '';
  30268. this._mediaElement.removeAttribute('src');
  30269. this._mediaElement.removeEventListener('loadedmetadata', this.e.onvLoadedMetadata);
  30270. this._mediaElement = null;
  30271. }
  30272. if (this._statisticsReporter != null) {
  30273. window.clearInterval(this._statisticsReporter);
  30274. this._statisticsReporter = null;
  30275. }
  30276. }
  30277. }, {
  30278. key: 'load',
  30279. value: function load() {
  30280. if (!this._mediaElement) {
  30281. throw new _exception.IllegalStateException('HTMLMediaElement must be attached before load()!');
  30282. }
  30283. this._mediaElement.src = this._mediaDataSource.url;
  30284. if (this._mediaElement.readyState > 0) {
  30285. this._mediaElement.currentTime = 0;
  30286. }
  30287. this._mediaElement.preload = 'auto';
  30288. this._mediaElement.load();
  30289. this._statisticsReporter = window.setInterval(this._reportStatisticsInfo.bind(this), this._config.statisticsInfoReportInterval);
  30290. }
  30291. }, {
  30292. key: 'unload',
  30293. value: function unload() {
  30294. if (this._mediaElement) {
  30295. this._mediaElement.src = '';
  30296. this._mediaElement.removeAttribute('src');
  30297. }
  30298. if (this._statisticsReporter != null) {
  30299. window.clearInterval(this._statisticsReporter);
  30300. this._statisticsReporter = null;
  30301. }
  30302. }
  30303. }, {
  30304. key: 'play',
  30305. value: function play() {
  30306. var playPromise = this._mediaElement.play();
  30307. if (playPromise !== undefined && playPromise) {
  30308. return playPromise.catch(function () {});
  30309. } else return undefined;
  30310. }
  30311. }, {
  30312. key: 'pause',
  30313. value: function pause() {
  30314. this._mediaElement.pause();
  30315. }
  30316. }, {
  30317. key: '_onvLoadedMetadata',
  30318. value: function _onvLoadedMetadata(e) {
  30319. if (this._pendingSeekTime != null) {
  30320. this._mediaElement.currentTime = this._pendingSeekTime;
  30321. this._pendingSeekTime = null;
  30322. }
  30323. this._emitter.emit(_playerEvents2.default.MEDIA_INFO, this.mediaInfo);
  30324. }
  30325. }, {
  30326. key: '_reportStatisticsInfo',
  30327. value: function _reportStatisticsInfo() {
  30328. this._emitter.emit(_playerEvents2.default.STATISTICS_INFO, this.statisticsInfo);
  30329. }
  30330. }, {
  30331. key: 'type',
  30332. get: function get() {
  30333. return this._type;
  30334. }
  30335. }, {
  30336. key: 'buffered',
  30337. get: function get() {
  30338. return this._mediaElement.buffered;
  30339. }
  30340. }, {
  30341. key: 'duration',
  30342. get: function get() {
  30343. return this._mediaElement.duration;
  30344. }
  30345. }, {
  30346. key: 'volume',
  30347. get: function get() {
  30348. return this._mediaElement.volume;
  30349. },
  30350. set: function set(value) {
  30351. this._mediaElement.volume = value;
  30352. }
  30353. }, {
  30354. key: 'muted',
  30355. get: function get() {
  30356. return this._mediaElement.muted;
  30357. },
  30358. set: function set(muted) {
  30359. this._mediaElement.muted = muted;
  30360. }
  30361. }, {
  30362. key: 'currentTime',
  30363. get: function get() {
  30364. if (this._mediaElement) {
  30365. return this._mediaElement.currentTime;
  30366. }
  30367. return 0;
  30368. },
  30369. set: function set(seconds) {
  30370. if (this._mediaElement) {
  30371. this._mediaElement.currentTime = seconds;
  30372. } else {
  30373. this._pendingSeekTime = seconds;
  30374. }
  30375. }
  30376. }, {
  30377. key: 'mediaInfo',
  30378. get: function get() {
  30379. var mediaPrefix = this._mediaElement instanceof HTMLAudioElement ? 'audio/' : 'video/';
  30380. var info = {
  30381. mimeType: mediaPrefix + this._mediaDataSource.type
  30382. };
  30383. if (this._mediaElement) {
  30384. info.duration = Math.floor(this._mediaElement.duration * 1000);
  30385. if (this._mediaElement instanceof HTMLVideoElement) {
  30386. info.width = this._mediaElement.videoWidth;
  30387. info.height = this._mediaElement.videoHeight;
  30388. }
  30389. }
  30390. return info;
  30391. }
  30392. }, {
  30393. key: 'statisticsInfo',
  30394. get: function get() {
  30395. var info = {
  30396. playerType: this._type,
  30397. url: this._mediaDataSource.url
  30398. };
  30399. if (!(this._mediaElement instanceof HTMLVideoElement)) {
  30400. return info;
  30401. }
  30402. var hasQualityInfo = true;
  30403. var decoded = 0;
  30404. var dropped = 0;
  30405. if (this._mediaElement.getVideoPlaybackQuality) {
  30406. var quality = this._mediaElement.getVideoPlaybackQuality();
  30407. decoded = quality.totalVideoFrames;
  30408. dropped = quality.droppedVideoFrames;
  30409. } else if (this._mediaElement.webkitDecodedFrameCount != undefined) {
  30410. decoded = this._mediaElement.webkitDecodedFrameCount;
  30411. dropped = this._mediaElement.webkitDroppedFrameCount;
  30412. } else {
  30413. hasQualityInfo = false;
  30414. }
  30415. if (hasQualityInfo) {
  30416. info.decodedFrames = decoded;
  30417. info.droppedFrames = dropped;
  30418. }
  30419. return info;
  30420. }
  30421. }]);
  30422. return NativePlayer;
  30423. }();
  30424. exports.default = NativePlayer;
  30425. module.exports = exports['default'];
  30426. /***/ })
  30427. /******/ ]);
  30428. });
  30429. /***/ }),
  30430. /***/ "c04e":
  30431. /***/ (function(module, exports, __webpack_require__) {
  30432. var isObject = __webpack_require__("861d");
  30433. // `ToPrimitive` abstract operation
  30434. // https://tc39.github.io/ecma262/#sec-toprimitive
  30435. // instead of the ES6 spec version, we didn't implement @@toPrimitive case
  30436. // and the second argument - flag - preferred type is a string
  30437. module.exports = function (input, PREFERRED_STRING) {
  30438. if (!isObject(input)) return input;
  30439. var fn, val;
  30440. if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
  30441. if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;
  30442. if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
  30443. throw TypeError("Can't convert object to primitive value");
  30444. };
  30445. /***/ }),
  30446. /***/ "c430":
  30447. /***/ (function(module, exports) {
  30448. module.exports = false;
  30449. /***/ }),
  30450. /***/ "c6b6":
  30451. /***/ (function(module, exports) {
  30452. var toString = {}.toString;
  30453. module.exports = function (it) {
  30454. return toString.call(it).slice(8, -1);
  30455. };
  30456. /***/ }),
  30457. /***/ "c6cd":
  30458. /***/ (function(module, exports, __webpack_require__) {
  30459. var global = __webpack_require__("da84");
  30460. var setGlobal = __webpack_require__("ce4e");
  30461. var SHARED = '__core-js_shared__';
  30462. var store = global[SHARED] || setGlobal(SHARED, {});
  30463. module.exports = store;
  30464. /***/ }),
  30465. /***/ "c8ba":
  30466. /***/ (function(module, exports) {
  30467. var g;
  30468. // This works in non-strict mode
  30469. g = (function() {
  30470. return this;
  30471. })();
  30472. try {
  30473. // This works if eval is allowed (see CSP)
  30474. g = g || new Function("return this")();
  30475. } catch (e) {
  30476. // This works if the window reference is available
  30477. if (typeof window === "object") g = window;
  30478. }
  30479. // g can still be undefined, but nothing to do about it...
  30480. // We return undefined, instead of nothing here, so it's
  30481. // easier to handle this case. if(!global) { ...}
  30482. module.exports = g;
  30483. /***/ }),
  30484. /***/ "ca84":
  30485. /***/ (function(module, exports, __webpack_require__) {
  30486. var has = __webpack_require__("5135");
  30487. var toIndexedObject = __webpack_require__("fc6a");
  30488. var indexOf = __webpack_require__("4d64").indexOf;
  30489. var hiddenKeys = __webpack_require__("d012");
  30490. module.exports = function (object, names) {
  30491. var O = toIndexedObject(object);
  30492. var i = 0;
  30493. var result = [];
  30494. var key;
  30495. for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key);
  30496. // Don't enum bug & hidden keys
  30497. while (names.length > i) if (has(O, key = names[i++])) {
  30498. ~indexOf(result, key) || result.push(key);
  30499. }
  30500. return result;
  30501. };
  30502. /***/ }),
  30503. /***/ "cc12":
  30504. /***/ (function(module, exports, __webpack_require__) {
  30505. var global = __webpack_require__("da84");
  30506. var isObject = __webpack_require__("861d");
  30507. var document = global.document;
  30508. // typeof document.createElement is 'object' in old IE
  30509. var EXISTS = isObject(document) && isObject(document.createElement);
  30510. module.exports = function (it) {
  30511. return EXISTS ? document.createElement(it) : {};
  30512. };
  30513. /***/ }),
  30514. /***/ "cca6":
  30515. /***/ (function(module, exports, __webpack_require__) {
  30516. var $ = __webpack_require__("23e7");
  30517. var assign = __webpack_require__("60da");
  30518. // `Object.assign` method
  30519. // https://tc39.github.io/ecma262/#sec-object.assign
  30520. $({ target: 'Object', stat: true, forced: Object.assign !== assign }, {
  30521. assign: assign
  30522. });
  30523. /***/ }),
  30524. /***/ "ce4e":
  30525. /***/ (function(module, exports, __webpack_require__) {
  30526. var global = __webpack_require__("da84");
  30527. var createNonEnumerableProperty = __webpack_require__("9112");
  30528. module.exports = function (key, value) {
  30529. try {
  30530. createNonEnumerableProperty(global, key, value);
  30531. } catch (error) {
  30532. global[key] = value;
  30533. } return value;
  30534. };
  30535. /***/ }),
  30536. /***/ "d012":
  30537. /***/ (function(module, exports) {
  30538. module.exports = {};
  30539. /***/ }),
  30540. /***/ "d039":
  30541. /***/ (function(module, exports) {
  30542. module.exports = function (exec) {
  30543. try {
  30544. return !!exec();
  30545. } catch (error) {
  30546. return true;
  30547. }
  30548. };
  30549. /***/ }),
  30550. /***/ "d066":
  30551. /***/ (function(module, exports, __webpack_require__) {
  30552. var path = __webpack_require__("428f");
  30553. var global = __webpack_require__("da84");
  30554. var aFunction = function (variable) {
  30555. return typeof variable == 'function' ? variable : undefined;
  30556. };
  30557. module.exports = function (namespace, method) {
  30558. return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global[namespace])
  30559. : path[namespace] && path[namespace][method] || global[namespace] && global[namespace][method];
  30560. };
  30561. /***/ }),
  30562. /***/ "d1e7":
  30563. /***/ (function(module, exports, __webpack_require__) {
  30564. "use strict";
  30565. var nativePropertyIsEnumerable = {}.propertyIsEnumerable;
  30566. var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  30567. // Nashorn ~ JDK8 bug
  30568. var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1);
  30569. // `Object.prototype.propertyIsEnumerable` method implementation
  30570. // https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable
  30571. exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
  30572. var descriptor = getOwnPropertyDescriptor(this, V);
  30573. return !!descriptor && descriptor.enumerable;
  30574. } : nativePropertyIsEnumerable;
  30575. /***/ }),
  30576. /***/ "da84":
  30577. /***/ (function(module, exports, __webpack_require__) {
  30578. /* WEBPACK VAR INJECTION */(function(global) {var check = function (it) {
  30579. return it && it.Math == Math && it;
  30580. };
  30581. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  30582. module.exports =
  30583. // eslint-disable-next-line no-undef
  30584. check(typeof globalThis == 'object' && globalThis) ||
  30585. check(typeof window == 'object' && window) ||
  30586. check(typeof self == 'object' && self) ||
  30587. check(typeof global == 'object' && global) ||
  30588. // eslint-disable-next-line no-new-func
  30589. Function('return this')();
  30590. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__("c8ba")))
  30591. /***/ }),
  30592. /***/ "df75":
  30593. /***/ (function(module, exports, __webpack_require__) {
  30594. var internalObjectKeys = __webpack_require__("ca84");
  30595. var enumBugKeys = __webpack_require__("7839");
  30596. // `Object.keys` method
  30597. // https://tc39.github.io/ecma262/#sec-object.keys
  30598. module.exports = Object.keys || function keys(O) {
  30599. return internalObjectKeys(O, enumBugKeys);
  30600. };
  30601. /***/ }),
  30602. /***/ "e893":
  30603. /***/ (function(module, exports, __webpack_require__) {
  30604. var has = __webpack_require__("5135");
  30605. var ownKeys = __webpack_require__("56ef");
  30606. var getOwnPropertyDescriptorModule = __webpack_require__("06cf");
  30607. var definePropertyModule = __webpack_require__("9bf2");
  30608. module.exports = function (target, source) {
  30609. var keys = ownKeys(source);
  30610. var defineProperty = definePropertyModule.f;
  30611. var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
  30612. for (var i = 0; i < keys.length; i++) {
  30613. var key = keys[i];
  30614. if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
  30615. }
  30616. };
  30617. /***/ }),
  30618. /***/ "f772":
  30619. /***/ (function(module, exports, __webpack_require__) {
  30620. var shared = __webpack_require__("5692");
  30621. var uid = __webpack_require__("90e3");
  30622. var keys = shared('keys');
  30623. module.exports = function (key) {
  30624. return keys[key] || (keys[key] = uid(key));
  30625. };
  30626. /***/ }),
  30627. /***/ "fae3":
  30628. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  30629. "use strict";
  30630. // ESM COMPAT FLAG
  30631. __webpack_require__.r(__webpack_exports__);
  30632. // EXPORTS
  30633. __webpack_require__.d(__webpack_exports__, "Mp4", function() { return /* reexport */ Mp4; });
  30634. __webpack_require__.d(__webpack_exports__, "Hls", function() { return /* reexport */ Hls; });
  30635. __webpack_require__.d(__webpack_exports__, "Flv", function() { return /* reexport */ Flv; });
  30636. // CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/setPublicPath.js
  30637. // This file is imported into lib/wc client bundles.
  30638. if (typeof window !== 'undefined') {
  30639. var currentScript = window.document.currentScript
  30640. if (true) {
  30641. var getCurrentScript = __webpack_require__("8875")
  30642. currentScript = getCurrentScript()
  30643. // for backward compatibility, because previously we directly included the polyfill
  30644. if (!('currentScript' in document)) {
  30645. Object.defineProperty(document, 'currentScript', { get: getCurrentScript })
  30646. }
  30647. }
  30648. var src = currentScript && currentScript.src.match(/(.+\/)[^/]+\.js(\?.*)?$/)
  30649. if (src) {
  30650. __webpack_require__.p = src[1] // eslint-disable-line
  30651. }
  30652. }
  30653. // Indicate to webpack that this file can be concatenated
  30654. /* harmony default export */ var setPublicPath = (null);
  30655. // 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&
  30656. 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}})}
  30657. var staticRenderFns = []
  30658. // CONCATENATED MODULE: ./src/components/Mp4.vue?vue&type=template&id=cedd472c&
  30659. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.object.assign.js
  30660. var es_object_assign = __webpack_require__("cca6");
  30661. // EXTERNAL MODULE: ./node_modules/xgplayer/dist/index.js
  30662. var dist = __webpack_require__("5392");
  30663. var dist_default = /*#__PURE__*/__webpack_require__.n(dist);
  30664. // 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&
  30665. //
  30666. //
  30667. //
  30668. //
  30669. /* harmony default export */ var Mp4vue_type_script_lang_js_ = ({
  30670. name: "Mp4",
  30671. props: {
  30672. config: {
  30673. type: Object,
  30674. default: function _default() {
  30675. return {
  30676. id: "mse",
  30677. url: ""
  30678. };
  30679. }
  30680. },
  30681. rootStyle: {
  30682. type: Object,
  30683. default: function _default() {
  30684. return {};
  30685. }
  30686. }
  30687. },
  30688. data: function data() {
  30689. return {
  30690. player: null,
  30691. finalConfig: {
  30692. volume: 0,
  30693. autoplayMuted: true,
  30694. //解决浏览器非静音阻止自动播放机制
  30695. autoplay: true,
  30696. //自动播放
  30697. loop: true,
  30698. //循环播放
  30699. fluid: true,
  30700. //流式布局
  30701. videoInit: true,
  30702. //加载首屏
  30703. playbackRate: [0.5, 0.75, 1, 1.5, 2],
  30704. //快进设置
  30705. pip: true,
  30706. //画中画
  30707. screenShot: true,
  30708. //开启截屏
  30709. lang: "zh-cn",
  30710. enterLogo: {
  30711. url: "",
  30712. width: 231,
  30713. height: 42
  30714. },
  30715. enterBg: {
  30716. color: "rgba(0,0,0,0.87)"
  30717. },
  30718. enterTips: {
  30719. background: "linear-gradient(to right, rgba(0,0,0,0.87), #3D96FD, rgba(86,195,248), #3D96FD, rgba(0,0,0,0.87))"
  30720. }
  30721. }
  30722. };
  30723. },
  30724. mounted: function mounted() {
  30725. this.init();
  30726. },
  30727. beforeUpdate: function beforeUpdate() {
  30728. this.init();
  30729. },
  30730. beforeDestroy: function beforeDestroy() {
  30731. this.player && typeof this.player.destroy === "function" && this.player.destroy();
  30732. },
  30733. methods: {
  30734. init: function init() {
  30735. this.finalConfig = Object.assign(this.finalConfig, this.config);
  30736. if (this.finalConfig.url && this.finalConfig.url !== "") {
  30737. this.player = new dist_default.a(this.finalConfig);
  30738. this.$emit("player", this.player);
  30739. }
  30740. }
  30741. }
  30742. });
  30743. // CONCATENATED MODULE: ./src/components/Mp4.vue?vue&type=script&lang=js&
  30744. /* harmony default export */ var components_Mp4vue_type_script_lang_js_ = (Mp4vue_type_script_lang_js_);
  30745. // CONCATENATED MODULE: ./node_modules/vue-loader/lib/runtime/componentNormalizer.js
  30746. /* globals __VUE_SSR_CONTEXT__ */
  30747. // IMPORTANT: Do NOT use ES2015 features in this file (except for modules).
  30748. // This module is a runtime utility for cleaner component module output and will
  30749. // be included in the final webpack user bundle.
  30750. function normalizeComponent (
  30751. scriptExports,
  30752. render,
  30753. staticRenderFns,
  30754. functionalTemplate,
  30755. injectStyles,
  30756. scopeId,
  30757. moduleIdentifier, /* server only */
  30758. shadowMode /* vue-cli only */
  30759. ) {
  30760. // Vue.extend constructor export interop
  30761. var options = typeof scriptExports === 'function'
  30762. ? scriptExports.options
  30763. : scriptExports
  30764. // render functions
  30765. if (render) {
  30766. options.render = render
  30767. options.staticRenderFns = staticRenderFns
  30768. options._compiled = true
  30769. }
  30770. // functional template
  30771. if (functionalTemplate) {
  30772. options.functional = true
  30773. }
  30774. // scopedId
  30775. if (scopeId) {
  30776. options._scopeId = 'data-v-' + scopeId
  30777. }
  30778. var hook
  30779. if (moduleIdentifier) { // server build
  30780. hook = function (context) {
  30781. // 2.3 injection
  30782. context =
  30783. context || // cached call
  30784. (this.$vnode && this.$vnode.ssrContext) || // stateful
  30785. (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
  30786. // 2.2 with runInNewContext: true
  30787. if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
  30788. context = __VUE_SSR_CONTEXT__
  30789. }
  30790. // inject component styles
  30791. if (injectStyles) {
  30792. injectStyles.call(this, context)
  30793. }
  30794. // register component module identifier for async chunk inferrence
  30795. if (context && context._registeredComponents) {
  30796. context._registeredComponents.add(moduleIdentifier)
  30797. }
  30798. }
  30799. // used by ssr in case component is cached and beforeCreate
  30800. // never gets called
  30801. options._ssrRegister = hook
  30802. } else if (injectStyles) {
  30803. hook = shadowMode
  30804. ? function () {
  30805. injectStyles.call(
  30806. this,
  30807. (options.functional ? this.parent : this).$root.$options.shadowRoot
  30808. )
  30809. }
  30810. : injectStyles
  30811. }
  30812. if (hook) {
  30813. if (options.functional) {
  30814. // for template-only hot-reload because in that case the render fn doesn't
  30815. // go through the normalizer
  30816. options._injectStyles = hook
  30817. // register for functional component in vue file
  30818. var originalRender = options.render
  30819. options.render = function renderWithStyleInjection (h, context) {
  30820. hook.call(context)
  30821. return originalRender(h, context)
  30822. }
  30823. } else {
  30824. // inject component registration as beforeCreate hook
  30825. var existing = options.beforeCreate
  30826. options.beforeCreate = existing
  30827. ? [].concat(existing, hook)
  30828. : [hook]
  30829. }
  30830. }
  30831. return {
  30832. exports: scriptExports,
  30833. options: options
  30834. }
  30835. }
  30836. // CONCATENATED MODULE: ./src/components/Mp4.vue
  30837. /* normalize component */
  30838. var component = normalizeComponent(
  30839. components_Mp4vue_type_script_lang_js_,
  30840. render,
  30841. staticRenderFns,
  30842. false,
  30843. null,
  30844. null,
  30845. null
  30846. )
  30847. /* harmony default export */ var Mp4 = (component.exports);
  30848. // 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&
  30849. 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}})}
  30850. var Hlsvue_type_template_id_5bef744a_staticRenderFns = []
  30851. // CONCATENATED MODULE: ./src/components/Hls.vue?vue&type=template&id=5bef744a&
  30852. // EXTERNAL MODULE: ./node_modules/xgplayer-hls.js/dist/index.js
  30853. var xgplayer_hls_js_dist = __webpack_require__("9000");
  30854. var xgplayer_hls_js_dist_default = /*#__PURE__*/__webpack_require__.n(xgplayer_hls_js_dist);
  30855. // 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&
  30856. //
  30857. //
  30858. //
  30859. //
  30860. /* harmony default export */ var Hlsvue_type_script_lang_js_ = ({
  30861. name: "Hls",
  30862. props: {
  30863. config: {
  30864. type: Object,
  30865. default: function _default() {
  30866. return {
  30867. id: "mse",
  30868. url: ""
  30869. };
  30870. }
  30871. },
  30872. rootStyle: {
  30873. type: Object,
  30874. default: function _default() {
  30875. return {};
  30876. }
  30877. }
  30878. },
  30879. data: function data() {
  30880. return {
  30881. player: null,
  30882. finalConfig: {
  30883. volume: 0,
  30884. autoplayMuted: true,
  30885. //解决浏览器非静音阻止自动播放机制
  30886. autoplay: true,
  30887. //自动播放
  30888. loop: true,
  30889. //循环播放
  30890. fluid: true,
  30891. //流式布局
  30892. videoInit: true,
  30893. //加载首屏
  30894. playbackRate: [0.5, 0.75, 1, 1.5, 2],
  30895. //快进设置
  30896. pip: true,
  30897. //画中画
  30898. screenShot: true,
  30899. //开启截屏
  30900. lang: "zh-cn",
  30901. enterLogo: {
  30902. url: "",
  30903. width: 231,
  30904. height: 42
  30905. },
  30906. enterBg: {
  30907. color: "rgba(0,0,0,0.87)"
  30908. },
  30909. enterTips: {
  30910. background: "linear-gradient(to right, rgba(0,0,0,0.87), #3D96FD, rgba(86,195,248), #3D96FD, rgba(0,0,0,0.87))"
  30911. }
  30912. }
  30913. };
  30914. },
  30915. mounted: function mounted() {
  30916. this.init();
  30917. },
  30918. beforeUpdate: function beforeUpdate() {
  30919. this.init();
  30920. },
  30921. beforeDestroy: function beforeDestroy() {
  30922. this.player && typeof this.player.destroy === "function" && this.player.destroy();
  30923. },
  30924. methods: {
  30925. init: function init() {
  30926. this.finalConfig = Object.assign(this.finalConfig, this.config);
  30927. if (this.finalConfig.url && this.finalConfig.url !== "") {
  30928. this.player = new xgplayer_hls_js_dist_default.a(this.finalConfig);
  30929. this.$emit("player", this.player);
  30930. }
  30931. }
  30932. }
  30933. });
  30934. // CONCATENATED MODULE: ./src/components/Hls.vue?vue&type=script&lang=js&
  30935. /* harmony default export */ var components_Hlsvue_type_script_lang_js_ = (Hlsvue_type_script_lang_js_);
  30936. // CONCATENATED MODULE: ./src/components/Hls.vue
  30937. /* normalize component */
  30938. var Hls_component = normalizeComponent(
  30939. components_Hlsvue_type_script_lang_js_,
  30940. Hlsvue_type_template_id_5bef744a_render,
  30941. Hlsvue_type_template_id_5bef744a_staticRenderFns,
  30942. false,
  30943. null,
  30944. null,
  30945. null
  30946. )
  30947. /* harmony default export */ var Hls = (Hls_component.exports);
  30948. // 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&
  30949. 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}})}
  30950. var Flvvue_type_template_id_e5412e0a_staticRenderFns = []
  30951. // CONCATENATED MODULE: ./src/components/Flv.vue?vue&type=template&id=e5412e0a&
  30952. // EXTERNAL MODULE: ./node_modules/xgplayer-flv.js/dist/index.js
  30953. var xgplayer_flv_js_dist = __webpack_require__("b402");
  30954. var xgplayer_flv_js_dist_default = /*#__PURE__*/__webpack_require__.n(xgplayer_flv_js_dist);
  30955. // 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&
  30956. //
  30957. //
  30958. //
  30959. //
  30960. /* harmony default export */ var Flvvue_type_script_lang_js_ = ({
  30961. name: "Flv",
  30962. props: {
  30963. config: {
  30964. type: Object,
  30965. default: function _default() {
  30966. return {
  30967. id: "mse",
  30968. url: ""
  30969. };
  30970. }
  30971. },
  30972. rootStyle: {
  30973. type: Object,
  30974. default: function _default() {
  30975. return {};
  30976. }
  30977. }
  30978. },
  30979. data: function data() {
  30980. return {
  30981. player: null,
  30982. finalConfig: {
  30983. volume: 0,
  30984. autoplayMuted: true,
  30985. //解决浏览器非静音阻止自动播放机制
  30986. autoplay: true,
  30987. //自动播放
  30988. loop: true,
  30989. //循环播放
  30990. fluid: true,
  30991. //流式布局
  30992. videoInit: true,
  30993. //加载首屏
  30994. playbackRate: [0.5, 0.75, 1, 1.5, 2],
  30995. //快进设置
  30996. pip: true,
  30997. //画中画
  30998. screenShot: true,
  30999. //开启截屏
  31000. lang: "zh-cn",
  31001. hasVideo: true,
  31002. hasAudio: true,
  31003. flvOptionalConfig: {
  31004. enableWorker: true
  31005. },
  31006. enterLogo: {
  31007. url: "",
  31008. width: 231,
  31009. height: 42
  31010. },
  31011. enterBg: {
  31012. color: "rgba(0,0,0,0.87)"
  31013. },
  31014. enterTips: {
  31015. background: "linear-gradient(to right, rgba(0,0,0,0.87), #3D96FD, rgba(86,195,248), #3D96FD, rgba(0,0,0,0.87))"
  31016. }
  31017. }
  31018. };
  31019. },
  31020. mounted: function mounted() {
  31021. this.init();
  31022. },
  31023. beforeUpdate: function beforeUpdate() {
  31024. this.init();
  31025. },
  31026. beforeDestroy: function beforeDestroy() {
  31027. this.player && typeof this.player.destroy === "function" && this.player.destroy();
  31028. },
  31029. methods: {
  31030. init: function init() {
  31031. this.finalConfig = Object.assign(this.finalConfig, this.config);
  31032. if (this.finalConfig.url && this.finalConfig.url !== "") {
  31033. this.player = new xgplayer_flv_js_dist_default.a(this.finalConfig);
  31034. this.$emit("player", this.player);
  31035. }
  31036. }
  31037. }
  31038. });
  31039. // CONCATENATED MODULE: ./src/components/Flv.vue?vue&type=script&lang=js&
  31040. /* harmony default export */ var components_Flvvue_type_script_lang_js_ = (Flvvue_type_script_lang_js_);
  31041. // CONCATENATED MODULE: ./src/components/Flv.vue
  31042. /* normalize component */
  31043. var Flv_component = normalizeComponent(
  31044. components_Flvvue_type_script_lang_js_,
  31045. Flvvue_type_template_id_e5412e0a_render,
  31046. Flvvue_type_template_id_e5412e0a_staticRenderFns,
  31047. false,
  31048. null,
  31049. null,
  31050. null
  31051. )
  31052. /* harmony default export */ var Flv = (Flv_component.exports);
  31053. // CONCATENATED MODULE: ./src/components/export.js
  31054. if (typeof window !== "undefined" && window.Vue) {
  31055. window.Vue.component("zx-player-mp4", Mp4);
  31056. window.Vue.component("zx-player-hls", Hls);
  31057. window.Vue.component("zx-player-flv", Flv);
  31058. }
  31059. // CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/entry-lib-no-default.js
  31060. /***/ }),
  31061. /***/ "fc6a":
  31062. /***/ (function(module, exports, __webpack_require__) {
  31063. // toObject with fallback for non-array-like ES3 strings
  31064. var IndexedObject = __webpack_require__("44ad");
  31065. var requireObjectCoercible = __webpack_require__("1d80");
  31066. module.exports = function (it) {
  31067. return IndexedObject(requireObjectCoercible(it));
  31068. };
  31069. /***/ })
  31070. /******/ });
  31071. });
  31072. //# sourceMappingURL=zx-player.umd.js.map