123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249 |
- module.exports =
- /******/ (function(modules) { // webpackBootstrap
- /******/ // The module cache
- /******/ var installedModules = {};
- /******/
- /******/ // The require function
- /******/ function __webpack_require__(moduleId) {
- /******/
- /******/ // Check if module is in cache
- /******/ if(installedModules[moduleId]) {
- /******/ return installedModules[moduleId].exports;
- /******/ }
- /******/ // Create a new module (and put it into the cache)
- /******/ var module = installedModules[moduleId] = {
- /******/ i: moduleId,
- /******/ l: false,
- /******/ exports: {}
- /******/ };
- /******/
- /******/ // Execute the module function
- /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
- /******/
- /******/ // Flag the module as loaded
- /******/ module.l = true;
- /******/
- /******/ // Return the exports of the module
- /******/ return module.exports;
- /******/ }
- /******/
- /******/
- /******/ // expose the modules object (__webpack_modules__)
- /******/ __webpack_require__.m = modules;
- /******/
- /******/ // expose the module cache
- /******/ __webpack_require__.c = installedModules;
- /******/
- /******/ // define getter function for harmony exports
- /******/ __webpack_require__.d = function(exports, name, getter) {
- /******/ if(!__webpack_require__.o(exports, name)) {
- /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
- /******/ }
- /******/ };
- /******/
- /******/ // define __esModule on exports
- /******/ __webpack_require__.r = function(exports) {
- /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
- /******/ }
- /******/ Object.defineProperty(exports, '__esModule', { value: true });
- /******/ };
- /******/
- /******/ // create a fake namespace object
- /******/ // mode & 1: value is a module id, require it
- /******/ // mode & 2: merge all properties of value into the ns
- /******/ // mode & 4: return value when already ns object
- /******/ // mode & 8|1: behave like require
- /******/ __webpack_require__.t = function(value, mode) {
- /******/ if(mode & 1) value = __webpack_require__(value);
- /******/ if(mode & 8) return value;
- /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
- /******/ var ns = Object.create(null);
- /******/ __webpack_require__.r(ns);
- /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
- /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
- /******/ return ns;
- /******/ };
- /******/
- /******/ // getDefaultExport function for compatibility with non-harmony modules
- /******/ __webpack_require__.n = function(module) {
- /******/ var getter = module && module.__esModule ?
- /******/ function getDefault() { return module['default']; } :
- /******/ function getModuleExports() { return module; };
- /******/ __webpack_require__.d(getter, 'a', getter);
- /******/ return getter;
- /******/ };
- /******/
- /******/ // Object.prototype.hasOwnProperty.call
- /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
- /******/
- /******/ // __webpack_public_path__
- /******/ __webpack_require__.p = "";
- /******/
- /******/
- /******/ // Load entry module and return exports
- /******/ return __webpack_require__(__webpack_require__.s = "fae3");
- /******/ })
- /************************************************************************/
- /******/ ({
- /***/ "06cf":
- /***/ (function(module, exports, __webpack_require__) {
- var DESCRIPTORS = __webpack_require__("83ab");
- var propertyIsEnumerableModule = __webpack_require__("d1e7");
- var createPropertyDescriptor = __webpack_require__("5c6c");
- var toIndexedObject = __webpack_require__("fc6a");
- var toPrimitive = __webpack_require__("c04e");
- var has = __webpack_require__("5135");
- var IE8_DOM_DEFINE = __webpack_require__("0cfb");
- var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
- // `Object.getOwnPropertyDescriptor` method
- // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
- exports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
- O = toIndexedObject(O);
- P = toPrimitive(P, true);
- if (IE8_DOM_DEFINE) try {
- return nativeGetOwnPropertyDescriptor(O, P);
- } catch (error) { /* empty */ }
- if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]);
- };
- /***/ }),
- /***/ "0cfb":
- /***/ (function(module, exports, __webpack_require__) {
- var DESCRIPTORS = __webpack_require__("83ab");
- var fails = __webpack_require__("d039");
- var createElement = __webpack_require__("cc12");
- // Thank's IE8 for his funny defineProperty
- module.exports = !DESCRIPTORS && !fails(function () {
- return Object.defineProperty(createElement('div'), 'a', {
- get: function () { return 7; }
- }).a != 7;
- });
- /***/ }),
- /***/ "1d80":
- /***/ (function(module, exports) {
- // `RequireObjectCoercible` abstract operation
- // https://tc39.github.io/ecma262/#sec-requireobjectcoercible
- module.exports = function (it) {
- if (it == undefined) throw TypeError("Can't call method on " + it);
- return it;
- };
- /***/ }),
- /***/ "23cb":
- /***/ (function(module, exports, __webpack_require__) {
- var toInteger = __webpack_require__("a691");
- var max = Math.max;
- var min = Math.min;
- // Helper for a popular repeating case of the spec:
- // Let integer be ? ToInteger(index).
- // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
- module.exports = function (index, length) {
- var integer = toInteger(index);
- return integer < 0 ? max(integer + length, 0) : min(integer, length);
- };
- /***/ }),
- /***/ "23e7":
- /***/ (function(module, exports, __webpack_require__) {
- var global = __webpack_require__("da84");
- var getOwnPropertyDescriptor = __webpack_require__("06cf").f;
- var createNonEnumerableProperty = __webpack_require__("9112");
- var redefine = __webpack_require__("6eeb");
- var setGlobal = __webpack_require__("ce4e");
- var copyConstructorProperties = __webpack_require__("e893");
- var isForced = __webpack_require__("94ca");
- /*
- options.target - name of the target object
- options.global - target is the global object
- options.stat - export as static methods of target
- options.proto - export as prototype methods of target
- options.real - real prototype method for the `pure` version
- options.forced - export even if the native feature is available
- options.bind - bind methods to the target, required for the `pure` version
- options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
- options.unsafe - use the simple assignment of property instead of delete + defineProperty
- options.sham - add a flag to not completely full polyfills
- options.enumerable - export as enumerable property
- options.noTargetGet - prevent calling a getter on target
- */
- module.exports = function (options, source) {
- var TARGET = options.target;
- var GLOBAL = options.global;
- var STATIC = options.stat;
- var FORCED, target, key, targetProperty, sourceProperty, descriptor;
- if (GLOBAL) {
- target = global;
- } else if (STATIC) {
- target = global[TARGET] || setGlobal(TARGET, {});
- } else {
- target = (global[TARGET] || {}).prototype;
- }
- if (target) for (key in source) {
- sourceProperty = source[key];
- if (options.noTargetGet) {
- descriptor = getOwnPropertyDescriptor(target, key);
- targetProperty = descriptor && descriptor.value;
- } else targetProperty = target[key];
- FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
- // contained in target
- if (!FORCED && targetProperty !== undefined) {
- if (typeof sourceProperty === typeof targetProperty) continue;
- copyConstructorProperties(sourceProperty, targetProperty);
- }
- // add a flag to not completely full polyfills
- if (options.sham || (targetProperty && targetProperty.sham)) {
- createNonEnumerableProperty(sourceProperty, 'sham', true);
- }
- // extend global
- redefine(target, key, sourceProperty, options);
- }
- };
- /***/ }),
- /***/ "241c":
- /***/ (function(module, exports, __webpack_require__) {
- var internalObjectKeys = __webpack_require__("ca84");
- var enumBugKeys = __webpack_require__("7839");
- var hiddenKeys = enumBugKeys.concat('length', 'prototype');
- // `Object.getOwnPropertyNames` method
- // https://tc39.github.io/ecma262/#sec-object.getownpropertynames
- exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
- return internalObjectKeys(O, hiddenKeys);
- };
- /***/ }),
- /***/ "428f":
- /***/ (function(module, exports, __webpack_require__) {
- var global = __webpack_require__("da84");
- module.exports = global;
- /***/ }),
- /***/ "44ad":
- /***/ (function(module, exports, __webpack_require__) {
- var fails = __webpack_require__("d039");
- var classof = __webpack_require__("c6b6");
- var split = ''.split;
- // fallback for non-array-like ES3 and non-enumerable old V8 strings
- module.exports = fails(function () {
- // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
- // eslint-disable-next-line no-prototype-builtins
- return !Object('z').propertyIsEnumerable(0);
- }) ? function (it) {
- return classof(it) == 'String' ? split.call(it, '') : Object(it);
- } : Object;
- /***/ }),
- /***/ "4d64":
- /***/ (function(module, exports, __webpack_require__) {
- var toIndexedObject = __webpack_require__("fc6a");
- var toLength = __webpack_require__("50c4");
- var toAbsoluteIndex = __webpack_require__("23cb");
- // `Array.prototype.{ indexOf, includes }` methods implementation
- var createMethod = function (IS_INCLUDES) {
- return function ($this, el, fromIndex) {
- var O = toIndexedObject($this);
- var length = toLength(O.length);
- var index = toAbsoluteIndex(fromIndex, length);
- var value;
- // Array#includes uses SameValueZero equality algorithm
- // eslint-disable-next-line no-self-compare
- if (IS_INCLUDES && el != el) while (length > index) {
- value = O[index++];
- // eslint-disable-next-line no-self-compare
- if (value != value) return true;
- // Array#indexOf ignores holes, Array#includes - not
- } else for (;length > index; index++) {
- if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
- } return !IS_INCLUDES && -1;
- };
- };
- module.exports = {
- // `Array.prototype.includes` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.includes
- includes: createMethod(true),
- // `Array.prototype.indexOf` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.indexof
- indexOf: createMethod(false)
- };
- /***/ }),
- /***/ "50c4":
- /***/ (function(module, exports, __webpack_require__) {
- var toInteger = __webpack_require__("a691");
- var min = Math.min;
- // `ToLength` abstract operation
- // https://tc39.github.io/ecma262/#sec-tolength
- module.exports = function (argument) {
- return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
- };
- /***/ }),
- /***/ "5135":
- /***/ (function(module, exports) {
- var hasOwnProperty = {}.hasOwnProperty;
- module.exports = function (it, key) {
- return hasOwnProperty.call(it, key);
- };
- /***/ }),
- /***/ "5392":
- /***/ (function(module, exports, __webpack_require__) {
- !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;
- /*!
- * Draggabilly v2.3.0
- * Make that shiz draggable
- * https://draggabilly.desandro.com
- * MIT license
- */
- !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;
- /*!
- * Unidragger v2.3.1
- * Draggable base class
- * MIT license
- */
- !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;
- /*!
- * Unipointer v2.3.0
- * base class for doing one thing with pointer event
- * MIT license
- */
- !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)}}))}])}));
- //# sourceMappingURL=index.js.map
- /***/ }),
- /***/ "5692":
- /***/ (function(module, exports, __webpack_require__) {
- var IS_PURE = __webpack_require__("c430");
- var store = __webpack_require__("c6cd");
- (module.exports = function (key, value) {
- return store[key] || (store[key] = value !== undefined ? value : {});
- })('versions', []).push({
- version: '3.6.5',
- mode: IS_PURE ? 'pure' : 'global',
- copyright: '© 2020 Denis Pushkarev (zloirock.ru)'
- });
- /***/ }),
- /***/ "56ef":
- /***/ (function(module, exports, __webpack_require__) {
- var getBuiltIn = __webpack_require__("d066");
- var getOwnPropertyNamesModule = __webpack_require__("241c");
- var getOwnPropertySymbolsModule = __webpack_require__("7418");
- var anObject = __webpack_require__("825a");
- // all object keys, includes non-enumerable and symbols
- module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
- var keys = getOwnPropertyNamesModule.f(anObject(it));
- var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
- return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;
- };
- /***/ }),
- /***/ "5c6c":
- /***/ (function(module, exports) {
- module.exports = function (bitmap, value) {
- return {
- enumerable: !(bitmap & 1),
- configurable: !(bitmap & 2),
- writable: !(bitmap & 4),
- value: value
- };
- };
- /***/ }),
- /***/ "60da":
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- var DESCRIPTORS = __webpack_require__("83ab");
- var fails = __webpack_require__("d039");
- var objectKeys = __webpack_require__("df75");
- var getOwnPropertySymbolsModule = __webpack_require__("7418");
- var propertyIsEnumerableModule = __webpack_require__("d1e7");
- var toObject = __webpack_require__("7b0b");
- var IndexedObject = __webpack_require__("44ad");
- var nativeAssign = Object.assign;
- var defineProperty = Object.defineProperty;
- // `Object.assign` method
- // https://tc39.github.io/ecma262/#sec-object.assign
- module.exports = !nativeAssign || fails(function () {
- // should have correct order of operations (Edge bug)
- if (DESCRIPTORS && nativeAssign({ b: 1 }, nativeAssign(defineProperty({}, 'a', {
- enumerable: true,
- get: function () {
- defineProperty(this, 'b', {
- value: 3,
- enumerable: false
- });
- }
- }), { b: 2 })).b !== 1) return true;
- // should work with symbols and should have deterministic property order (V8 bug)
- var A = {};
- var B = {};
- // eslint-disable-next-line no-undef
- var symbol = Symbol();
- var alphabet = 'abcdefghijklmnopqrst';
- A[symbol] = 7;
- alphabet.split('').forEach(function (chr) { B[chr] = chr; });
- return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet;
- }) ? function assign(target, source) { // eslint-disable-line no-unused-vars
- var T = toObject(target);
- var argumentsLength = arguments.length;
- var index = 1;
- var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
- var propertyIsEnumerable = propertyIsEnumerableModule.f;
- while (argumentsLength > index) {
- var S = IndexedObject(arguments[index++]);
- var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S);
- var length = keys.length;
- var j = 0;
- var key;
- while (length > j) {
- key = keys[j++];
- if (!DESCRIPTORS || propertyIsEnumerable.call(S, key)) T[key] = S[key];
- }
- } return T;
- } : nativeAssign;
- /***/ }),
- /***/ "69f3":
- /***/ (function(module, exports, __webpack_require__) {
- var NATIVE_WEAK_MAP = __webpack_require__("7f9a");
- var global = __webpack_require__("da84");
- var isObject = __webpack_require__("861d");
- var createNonEnumerableProperty = __webpack_require__("9112");
- var objectHas = __webpack_require__("5135");
- var sharedKey = __webpack_require__("f772");
- var hiddenKeys = __webpack_require__("d012");
- var WeakMap = global.WeakMap;
- var set, get, has;
- var enforce = function (it) {
- return has(it) ? get(it) : set(it, {});
- };
- var getterFor = function (TYPE) {
- return function (it) {
- var state;
- if (!isObject(it) || (state = get(it)).type !== TYPE) {
- throw TypeError('Incompatible receiver, ' + TYPE + ' required');
- } return state;
- };
- };
- if (NATIVE_WEAK_MAP) {
- var store = new WeakMap();
- var wmget = store.get;
- var wmhas = store.has;
- var wmset = store.set;
- set = function (it, metadata) {
- wmset.call(store, it, metadata);
- return metadata;
- };
- get = function (it) {
- return wmget.call(store, it) || {};
- };
- has = function (it) {
- return wmhas.call(store, it);
- };
- } else {
- var STATE = sharedKey('state');
- hiddenKeys[STATE] = true;
- set = function (it, metadata) {
- createNonEnumerableProperty(it, STATE, metadata);
- return metadata;
- };
- get = function (it) {
- return objectHas(it, STATE) ? it[STATE] : {};
- };
- has = function (it) {
- return objectHas(it, STATE);
- };
- }
- module.exports = {
- set: set,
- get: get,
- has: has,
- enforce: enforce,
- getterFor: getterFor
- };
- /***/ }),
- /***/ "6eeb":
- /***/ (function(module, exports, __webpack_require__) {
- var global = __webpack_require__("da84");
- var createNonEnumerableProperty = __webpack_require__("9112");
- var has = __webpack_require__("5135");
- var setGlobal = __webpack_require__("ce4e");
- var inspectSource = __webpack_require__("8925");
- var InternalStateModule = __webpack_require__("69f3");
- var getInternalState = InternalStateModule.get;
- var enforceInternalState = InternalStateModule.enforce;
- var TEMPLATE = String(String).split('String');
- (module.exports = function (O, key, value, options) {
- var unsafe = options ? !!options.unsafe : false;
- var simple = options ? !!options.enumerable : false;
- var noTargetGet = options ? !!options.noTargetGet : false;
- if (typeof value == 'function') {
- if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key);
- enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : '');
- }
- if (O === global) {
- if (simple) O[key] = value;
- else setGlobal(key, value);
- return;
- } else if (!unsafe) {
- delete O[key];
- } else if (!noTargetGet && O[key]) {
- simple = true;
- }
- if (simple) O[key] = value;
- else createNonEnumerableProperty(O, key, value);
- // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
- })(Function.prototype, 'toString', function toString() {
- return typeof this == 'function' && getInternalState(this).source || inspectSource(this);
- });
- /***/ }),
- /***/ "7418":
- /***/ (function(module, exports) {
- exports.f = Object.getOwnPropertySymbols;
- /***/ }),
- /***/ "7839":
- /***/ (function(module, exports) {
- // IE8- don't enum bug keys
- module.exports = [
- 'constructor',
- 'hasOwnProperty',
- 'isPrototypeOf',
- 'propertyIsEnumerable',
- 'toLocaleString',
- 'toString',
- 'valueOf'
- ];
- /***/ }),
- /***/ "7b0b":
- /***/ (function(module, exports, __webpack_require__) {
- var requireObjectCoercible = __webpack_require__("1d80");
- // `ToObject` abstract operation
- // https://tc39.github.io/ecma262/#sec-toobject
- module.exports = function (argument) {
- return Object(requireObjectCoercible(argument));
- };
- /***/ }),
- /***/ "7f9a":
- /***/ (function(module, exports, __webpack_require__) {
- var global = __webpack_require__("da84");
- var inspectSource = __webpack_require__("8925");
- var WeakMap = global.WeakMap;
- module.exports = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap));
- /***/ }),
- /***/ "825a":
- /***/ (function(module, exports, __webpack_require__) {
- var isObject = __webpack_require__("861d");
- module.exports = function (it) {
- if (!isObject(it)) {
- throw TypeError(String(it) + ' is not an object');
- } return it;
- };
- /***/ }),
- /***/ "83ab":
- /***/ (function(module, exports, __webpack_require__) {
- var fails = __webpack_require__("d039");
- // Thank's IE8 for his funny defineProperty
- module.exports = !fails(function () {
- return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;
- });
- /***/ }),
- /***/ "861d":
- /***/ (function(module, exports) {
- module.exports = function (it) {
- return typeof it === 'object' ? it !== null : typeof it === 'function';
- };
- /***/ }),
- /***/ "8875":
- /***/ (function(module, exports, __webpack_require__) {
- var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// addapted from the document.currentScript polyfill by Adam Miller
- // MIT license
- // source: https://github.com/amiller-gh/currentScript-polyfill
- // added support for Firefox https://bugzilla.mozilla.org/show_bug.cgi?id=1620505
- (function (root, factory) {
- if (true) {
- !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
- } else {}
- }(typeof self !== 'undefined' ? self : this, function () {
- function getCurrentScript () {
- var descriptor = Object.getOwnPropertyDescriptor(document, 'currentScript')
- // for chrome
- if (!descriptor && 'currentScript' in document && document.currentScript) {
- return document.currentScript
- }
- // for other browsers with native support for currentScript
- if (descriptor && descriptor.get !== getCurrentScript && document.currentScript) {
- return document.currentScript
- }
-
- // IE 8-10 support script readyState
- // IE 11+ & Firefox support stack trace
- try {
- throw new Error();
- }
- catch (err) {
- // Find the second match for the "at" string to get file src url from stack.
- var ieStackRegExp = /.*at [^(]*\((.*):(.+):(.+)\)$/ig,
- ffStackRegExp = /@([^@]*):(\d+):(\d+)\s*$/ig,
- stackDetails = ieStackRegExp.exec(err.stack) || ffStackRegExp.exec(err.stack),
- scriptLocation = (stackDetails && stackDetails[1]) || false,
- line = (stackDetails && stackDetails[2]) || false,
- currentLocation = document.location.href.replace(document.location.hash, ''),
- pageSource,
- inlineScriptSourceRegExp,
- inlineScriptSource,
- scripts = document.getElementsByTagName('script'); // Live NodeList collection
-
- if (scriptLocation === currentLocation) {
- pageSource = document.documentElement.outerHTML;
- inlineScriptSourceRegExp = new RegExp('(?:[^\\n]+?\\n){0,' + (line - 2) + '}[^<]*<script>([\\d\\D]*?)<\\/script>[\\d\\D]*', 'i');
- inlineScriptSource = pageSource.replace(inlineScriptSourceRegExp, '$1').trim();
- }
-
- for (var i = 0; i < scripts.length; i++) {
- // If ready state is interactive, return the script tag
- if (scripts[i].readyState === 'interactive') {
- return scripts[i];
- }
-
- // If src matches, return the script tag
- if (scripts[i].src === scriptLocation) {
- return scripts[i];
- }
-
- // If inline source matches, return the script tag
- if (
- scriptLocation === currentLocation &&
- scripts[i].innerHTML &&
- scripts[i].innerHTML.trim() === inlineScriptSource
- ) {
- return scripts[i];
- }
- }
-
- // If no match, return null
- return null;
- }
- };
- return getCurrentScript
- }));
- /***/ }),
- /***/ "8925":
- /***/ (function(module, exports, __webpack_require__) {
- var store = __webpack_require__("c6cd");
- var functionToString = Function.toString;
- // this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper
- if (typeof store.inspectSource != 'function') {
- store.inspectSource = function (it) {
- return functionToString.call(it);
- };
- }
- module.exports = store.inspectSource;
- /***/ }),
- /***/ "9000":
- /***/ (function(module, exports, __webpack_require__) {
- (function webpackUniversalModuleDefinition(root, factory) {
- if(true)
- module.exports = factory(__webpack_require__("5392"));
- else {}
- })(window, function(__WEBPACK_EXTERNAL_MODULE__33__) {
- return /******/ (function(modules) { // webpackBootstrap
- /******/ // The module cache
- /******/ var installedModules = {};
- /******/
- /******/ // The require function
- /******/ function __webpack_require__(moduleId) {
- /******/
- /******/ // Check if module is in cache
- /******/ if(installedModules[moduleId]) {
- /******/ return installedModules[moduleId].exports;
- /******/ }
- /******/ // Create a new module (and put it into the cache)
- /******/ var module = installedModules[moduleId] = {
- /******/ i: moduleId,
- /******/ l: false,
- /******/ exports: {}
- /******/ };
- /******/
- /******/ // Execute the module function
- /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
- /******/
- /******/ // Flag the module as loaded
- /******/ module.l = true;
- /******/
- /******/ // Return the exports of the module
- /******/ return module.exports;
- /******/ }
- /******/
- /******/
- /******/ // expose the modules object (__webpack_modules__)
- /******/ __webpack_require__.m = modules;
- /******/
- /******/ // expose the module cache
- /******/ __webpack_require__.c = installedModules;
- /******/
- /******/ // define getter function for harmony exports
- /******/ __webpack_require__.d = function(exports, name, getter) {
- /******/ if(!__webpack_require__.o(exports, name)) {
- /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
- /******/ }
- /******/ };
- /******/
- /******/ // define __esModule on exports
- /******/ __webpack_require__.r = function(exports) {
- /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
- /******/ }
- /******/ Object.defineProperty(exports, '__esModule', { value: true });
- /******/ };
- /******/
- /******/ // create a fake namespace object
- /******/ // mode & 1: value is a module id, require it
- /******/ // mode & 2: merge all properties of value into the ns
- /******/ // mode & 4: return value when already ns object
- /******/ // mode & 8|1: behave like require
- /******/ __webpack_require__.t = function(value, mode) {
- /******/ if(mode & 1) value = __webpack_require__(value);
- /******/ if(mode & 8) return value;
- /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
- /******/ var ns = Object.create(null);
- /******/ __webpack_require__.r(ns);
- /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
- /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
- /******/ return ns;
- /******/ };
- /******/
- /******/ // getDefaultExport function for compatibility with non-harmony modules
- /******/ __webpack_require__.n = function(module) {
- /******/ var getter = module && module.__esModule ?
- /******/ function getDefault() { return module['default']; } :
- /******/ function getModuleExports() { return module; };
- /******/ __webpack_require__.d(getter, 'a', getter);
- /******/ return getter;
- /******/ };
- /******/
- /******/ // Object.prototype.hasOwnProperty.call
- /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
- /******/
- /******/ // __webpack_public_path__
- /******/ __webpack_require__.p = "";
- /******/
- /******/
- /******/ // Load entry module and return exports
- /******/ return __webpack_require__(__webpack_require__.s = 31);
- /******/ })
- /************************************************************************/
- /******/ ([
- /* 0 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.logger = exports.enableLogs = undefined;
- 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; };
- var _getSelfScope = __webpack_require__(5);
- function noop() {}
- var fakeLogger = {
- trace: noop,
- debug: noop,
- log: noop,
- warn: noop,
- info: noop,
- error: noop
- };
- var exportedLogger = fakeLogger;
- // let lastCallTime;
- // function formatMsgWithTimeInfo(type, msg) {
- // const now = Date.now();
- // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
- // lastCallTime = now;
- // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
- // return msg;
- // }
- function formatMsg(type, msg) {
- msg = '[' + type + '] > ' + msg;
- return msg;
- }
- var global = (0, _getSelfScope.getSelfScope)();
- function consolePrintFn(type) {
- var func = global.console[type];
- if (func) {
- return function () {
- for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- if (args[0]) {
- args[0] = formatMsg(type, args[0]);
- }
- func.apply(global.console, args);
- };
- }
- return noop;
- }
- function exportLoggerFunctions(debugConfig) {
- for (var _len2 = arguments.length, functions = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
- functions[_key2 - 1] = arguments[_key2];
- }
- functions.forEach(function (type) {
- exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
- });
- }
- var enableLogs = exports.enableLogs = function enableLogs(debugConfig) {
- if (debugConfig === true || (typeof debugConfig === 'undefined' ? 'undefined' : _typeof(debugConfig)) === 'object') {
- exportLoggerFunctions(debugConfig,
- // Remove out from list here to hard-disable a log-level
- // 'trace',
- 'debug', 'log', 'info', 'warn', 'error');
- // Some browsers don't allow to use bind on console object anyway
- // fallback to default if needed
- try {
- exportedLogger.log();
- } catch (e) {
- exportedLogger = fakeLogger;
- }
- } else {
- exportedLogger = fakeLogger;
- }
- };
- var logger = exports.logger = exportedLogger;
- /***/ }),
- /* 1 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- /**
- * @readonly
- * @enum {string}
- */
- var HlsEvents = {
- // fired before MediaSource is attaching to media element - data: { media }
- MEDIA_ATTACHING: 'hlsMediaAttaching',
- // fired when MediaSource has been succesfully attached to media element - data: { }
- MEDIA_ATTACHED: 'hlsMediaAttached',
- // fired before detaching MediaSource from media element - data: { }
- MEDIA_DETACHING: 'hlsMediaDetaching',
- // fired when MediaSource has been detached from media element - data: { }
- MEDIA_DETACHED: 'hlsMediaDetached',
- // fired when we buffer is going to be reset - data: { }
- BUFFER_RESET: 'hlsBufferReset',
- // fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}
- BUFFER_CODECS: 'hlsBufferCodecs',
- // fired when sourcebuffers have been created - data: { tracks : tracks }
- BUFFER_CREATED: 'hlsBufferCreated',
- // fired when we append a segment to the buffer - data: { segment: segment object }
- BUFFER_APPENDING: 'hlsBufferAppending',
- // 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}
- BUFFER_APPENDED: 'hlsBufferAppended',
- // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }
- BUFFER_EOS: 'hlsBufferEos',
- // fired when the media buffer should be flushed - data { startOffset, endOffset }
- BUFFER_FLUSHING: 'hlsBufferFlushing',
- // fired when the media buffer has been flushed - data: { }
- BUFFER_FLUSHED: 'hlsBufferFlushed',
- // fired to signal that a manifest loading starts - data: { url : manifestURL}
- MANIFEST_LOADING: 'hlsManifestLoading',
- // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}}
- MANIFEST_LOADED: 'hlsManifestLoaded',
- // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}
- MANIFEST_PARSED: 'hlsManifestParsed',
- // fired when a level switch is requested - data: { level : id of new level }
- LEVEL_SWITCHING: 'hlsLevelSwitching',
- // fired when a level switch is effective - data: { level : id of new level }
- LEVEL_SWITCHED: 'hlsLevelSwitched',
- // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}
- LEVEL_LOADING: 'hlsLevelLoading',
- // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }
- LEVEL_LOADED: 'hlsLevelLoaded',
- // 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 }
- LEVEL_UPDATED: 'hlsLevelUpdated',
- // 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 }
- LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',
- // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }
- AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated',
- // fired when an audio track switching is requested - data: { id : audio track id }
- AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching',
- // fired when an audio track switch actually occurs - data: { id : audio track id }
- AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched',
- // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }
- AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading',
- // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } }
- AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded',
- // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }
- SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated',
- // fired when an subtitle track switch occurs - data: { id : subtitle track id }
- SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch',
- // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }
- SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading',
- // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } }
- SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded',
- // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }
- SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed',
- // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object }
- INIT_PTS_FOUND: 'hlsInitPtsFound',
- // fired when a fragment loading starts - data: { frag : fragment object }
- FRAG_LOADING: 'hlsFragLoading',
- // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }
- FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',
- // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }
- FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',
- // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } }
- FRAG_LOADED: 'hlsFragLoaded',
- // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }
- FRAG_DECRYPTED: 'hlsFragDecrypted',
- // 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 }
- FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',
- // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }
- FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',
- // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }
- FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',
- // 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}
- FRAG_PARSING_DATA: 'hlsFragParsingData',
- // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }
- FRAG_PARSED: 'hlsFragParsed',
- // 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 } }
- FRAG_BUFFERED: 'hlsFragBuffered',
- // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }
- FRAG_CHANGED: 'hlsFragChanged',
- // Identifier for a FPS drop event - data: { curentDropped, currentDecoded, totalDroppedFrames }
- FPS_DROP: 'hlsFpsDrop',
- // triggered when FPS drop triggers auto level capping - data: { level, droppedlevel }
- FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',
- // 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 }
- ERROR: 'hlsError',
- // 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: { }
- DESTROYING: 'hlsDestroying',
- // fired when a decrypt key loading starts - data: { frag : fragment object }
- KEY_LOADING: 'hlsKeyLoading',
- // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length } }
- KEY_LOADED: 'hlsKeyLoaded',
- // fired upon stream controller state transitions - data: { previousState, nextState }
- STREAM_STATE_TRANSITION: 'hlsStreamStateTransition'
- };
- exports.default = HlsEvents;
- module.exports = exports['default'];
- /***/ }),
- /* 2 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var ErrorTypes = exports.ErrorTypes = {
- // Identifier for a network error (loading error / timeout ...)
- NETWORK_ERROR: 'networkError',
- // Identifier for a media Error (video/parsing/mediasource error)
- MEDIA_ERROR: 'mediaError',
- // EME (encrypted media extensions) errors
- KEY_SYSTEM_ERROR: 'keySystemError',
- // Identifier for a mux Error (demuxing/remuxing)
- MUX_ERROR: 'muxError',
- // Identifier for all other errors
- OTHER_ERROR: 'otherError'
- };
- /**
- * @enum {ErrorDetails}
- * @typedef {string} ErrorDetail
- */
- var ErrorDetails = exports.ErrorDetails = {
- KEY_SYSTEM_NO_KEYS: 'keySystemNoKeys',
- KEY_SYSTEM_NO_ACCESS: 'keySystemNoAccess',
- KEY_SYSTEM_NO_SESSION: 'keySystemNoSession',
- KEY_SYSTEM_LICENSE_REQUEST_FAILED: 'keySystemLicenseRequestFailed',
- // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}
- MANIFEST_LOAD_ERROR: 'manifestLoadError',
- // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
- MANIFEST_LOAD_TIMEOUT: 'manifestLoadTimeOut',
- // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}
- MANIFEST_PARSING_ERROR: 'manifestParsingError',
- // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}
- MANIFEST_INCOMPATIBLE_CODECS_ERROR: 'manifestIncompatibleCodecsError',
- // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}
- LEVEL_LOAD_ERROR: 'levelLoadError',
- // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
- LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut',
- // Identifier for a level switch error - data: { level : faulty level Id, event : error description}
- LEVEL_SWITCH_ERROR: 'levelSwitchError',
- // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}
- AUDIO_TRACK_LOAD_ERROR: 'audioTrackLoadError',
- // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
- AUDIO_TRACK_LOAD_TIMEOUT: 'audioTrackLoadTimeOut',
- // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}
- FRAG_LOAD_ERROR: 'fragLoadError',
- // Identifier for fragment load timeout error - data: { frag : fragment object}
- FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut',
- // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }
- FRAG_DECRYPT_ERROR: 'fragDecryptError',
- // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }
- // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release
- FRAG_PARSING_ERROR: 'fragParsingError',
- // 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 }
- REMUX_ALLOC_ERROR: 'remuxAllocError',
- // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}
- KEY_LOAD_ERROR: 'keyLoadError',
- // Identifier for decrypt key load timeout error - data: { frag : fragment object}
- KEY_LOAD_TIMEOUT: 'keyLoadTimeOut',
- // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { err : exception , mimeType : mimeType }
- BUFFER_ADD_CODEC_ERROR: 'bufferAddCodecError',
- // Identifier for a buffer append error - data: append error description
- BUFFER_APPEND_ERROR: 'bufferAppendError',
- // Identifier for a buffer appending error event - data: appending error description
- BUFFER_APPENDING_ERROR: 'bufferAppendingError',
- // Identifier for a buffer stalled error event
- BUFFER_STALLED_ERROR: 'bufferStalledError',
- // Identifier for a buffer full event
- BUFFER_FULL_ERROR: 'bufferFullError',
- // Identifier for a buffer seek over hole event
- BUFFER_SEEK_OVER_HOLE: 'bufferSeekOverHole',
- // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)
- BUFFER_NUDGE_ON_STALL: 'bufferNudgeOnStall',
- // Identifier for an internal exception happening inside hls.js while handling an event
- INTERNAL_EXCEPTION: 'internalException'
- };
- /***/ }),
- /* 3 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; };
- 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; }; }(); /*
- *
- * All objects in the event handling chain should inherit from this class
- *
- */
- var _logger = __webpack_require__(0);
- var _errors = __webpack_require__(2);
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var FORBIDDEN_EVENT_NAMES = {
- 'hlsEventGeneric': true,
- 'hlsHandlerDestroying': true,
- 'hlsHandlerDestroyed': true
- };
- var EventHandler = function () {
- function EventHandler(hls) {
- _classCallCheck(this, EventHandler);
- this.hls = hls;
- this.onEvent = this.onEvent.bind(this);
- for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- events[_key - 1] = arguments[_key];
- }
- this.handledEvents = events;
- this.useGenericHandler = true;
- this.registerListeners();
- }
- _createClass(EventHandler, [{
- key: 'destroy',
- value: function destroy() {
- this.onHandlerDestroying();
- this.unregisterListeners();
- this.onHandlerDestroyed();
- }
- }, {
- key: 'onHandlerDestroying',
- value: function onHandlerDestroying() {}
- }, {
- key: 'onHandlerDestroyed',
- value: function onHandlerDestroyed() {}
- }, {
- key: 'isEventHandler',
- value: function isEventHandler() {
- return _typeof(this.handledEvents) === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';
- }
- }, {
- key: 'registerListeners',
- value: function registerListeners() {
- if (this.isEventHandler()) {
- this.handledEvents.forEach(function (event) {
- if (FORBIDDEN_EVENT_NAMES[event]) {
- throw new Error('Forbidden event-name: ' + event);
- }
- this.hls.on(event, this.onEvent);
- }, this);
- }
- }
- }, {
- key: 'unregisterListeners',
- value: function unregisterListeners() {
- if (this.isEventHandler()) {
- this.handledEvents.forEach(function (event) {
- this.hls.off(event, this.onEvent);
- }, this);
- }
- }
- /**
- * arguments: event (string), data (any)
- */
- }, {
- key: 'onEvent',
- value: function onEvent(event, data) {
- this.onEventGeneric(event, data);
- }
- }, {
- key: 'onEventGeneric',
- value: function onEventGeneric(event, data) {
- var eventToFunction = function eventToFunction(event, data) {
- var funcName = 'on' + event.replace('hls', '');
- if (typeof this[funcName] !== 'function') {
- throw new Error('Event ' + event + ' has no generic handler in this ' + this.constructor.name + ' class (tried ' + funcName + ')');
- }
- return this[funcName].bind(this, data);
- };
- try {
- eventToFunction.call(this, event, data).call();
- } catch (err) {
- _logger.logger.error('An internal error happened while handling event ' + event + '. Error message: "' + err.message + '". Here is a stacktrace:', err);
- this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.INTERNAL_EXCEPTION, fatal: false, event: event, err: err });
- }
- }
- }]);
- return EventHandler;
- }();
- exports.default = EventHandler;
- module.exports = exports['default'];
- /***/ }),
- /* 4 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /**
- * @module BufferHelper
- *
- * Providing methods dealing with buffer length retrieval for example.
- *
- * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
- *
- * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
- */
- var BufferHelper = exports.BufferHelper = function () {
- function BufferHelper() {
- _classCallCheck(this, BufferHelper);
- }
- _createClass(BufferHelper, null, [{
- key: "isBuffered",
- /**
- * Return true if `media`'s buffered include `position`
- * @param {HTMLMediaElement|SourceBuffer} media
- * @param {number} position
- * @returns {boolean}
- */
- value: function isBuffered(media, position) {
- try {
- if (media) {
- var buffered = media.buffered;
- for (var i = 0; i < buffered.length; i++) {
- if (position >= buffered.start(i) && position <= buffered.end(i)) {
- return true;
- }
- }
- }
- } catch (error) {
- // this is to catch
- // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
- // This SourceBuffer has been removed from the parent media source
- }
- return false;
- }
- }, {
- key: "bufferInfo",
- value: function bufferInfo(media, pos, maxHoleDuration) {
- try {
- if (media) {
- var vbuffered = media.buffered,
- buffered = [],
- i = void 0;
- for (i = 0; i < vbuffered.length; i++) {
- buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) });
- }
- return this.bufferedInfo(buffered, pos, maxHoleDuration);
- }
- } catch (error) {
- // this is to catch
- // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
- // This SourceBuffer has been removed from the parent media source
- }
- return { len: 0, start: pos, end: pos, nextStart: undefined };
- }
- }, {
- key: "bufferedInfo",
- value: function bufferedInfo(buffered, pos, maxHoleDuration) {
- var buffered2 = [],
- // bufferStart and bufferEnd are buffer boundaries around current video position
- bufferLen = void 0,
- bufferStart = void 0,
- bufferEnd = void 0,
- bufferStartNext = void 0,
- i = void 0;
- // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
- buffered.sort(function (a, b) {
- var diff = a.start - b.start;
- if (diff) {
- return diff;
- } else {
- return b.end - a.end;
- }
- });
- // there might be some small holes between buffer time range
- // consider that holes smaller than maxHoleDuration are irrelevant and build another
- // buffer time range representations that discards those holes
- for (i = 0; i < buffered.length; i++) {
- var buf2len = buffered2.length;
- if (buf2len) {
- var buf2end = buffered2[buf2len - 1].end;
- // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
- if (buffered[i].start - buf2end < maxHoleDuration) {
- // merge overlapping time ranges
- // update lastRange.end only if smaller than item.end
- // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
- // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
- if (buffered[i].end > buf2end) {
- buffered2[buf2len - 1].end = buffered[i].end;
- }
- } else {
- // big hole
- buffered2.push(buffered[i]);
- }
- } else {
- // first value
- buffered2.push(buffered[i]);
- }
- }
- for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) {
- var start = buffered2[i].start,
- end = buffered2[i].end;
- // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
- if (pos + maxHoleDuration >= start && pos < end) {
- // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
- bufferStart = start;
- bufferEnd = end;
- bufferLen = bufferEnd - pos;
- } else if (pos + maxHoleDuration < start) {
- bufferStartNext = start;
- break;
- }
- }
- return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext };
- }
- }]);
- return BufferHelper;
- }();
- /***/ }),
- /* 5 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getSelfScope = getSelfScope;
- function getSelfScope() {
- // see https://stackoverflow.com/a/11237259/589493
- if (typeof window === 'undefined') {
- /* eslint-disable-next-line no-undef */
- return self;
- } else {
- return window;
- }
- }
- /***/ }),
- /* 6 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.FragmentTracker = exports.FragmentState = undefined;
- 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; }; }();
- 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); } };
- var _eventHandler = __webpack_require__(3);
- var _eventHandler2 = _interopRequireDefault(_eventHandler);
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; }
- var FragmentState = exports.FragmentState = {
- NOT_LOADED: 'NOT_LOADED',
- APPENDING: 'APPENDING',
- PARTIAL: 'PARTIAL',
- OK: 'OK'
- };
- var FragmentTracker = exports.FragmentTracker = function (_EventHandler) {
- _inherits(FragmentTracker, _EventHandler);
- function FragmentTracker(hls) {
- _classCallCheck(this, FragmentTracker);
- var _this = _possibleConstructorReturn(this, (FragmentTracker.__proto__ || Object.getPrototypeOf(FragmentTracker)).call(this, hls, _events2.default.BUFFER_APPENDED, _events2.default.FRAG_BUFFERED, _events2.default.FRAG_LOADED));
- _this.bufferPadding = 0.2;
- _this.fragments = Object.create(null);
- _this.timeRanges = Object.create(null);
- _this.config = hls.config;
- return _this;
- }
- _createClass(FragmentTracker, [{
- key: 'destroy',
- value: function destroy() {
- this.fragments = Object.create(null);
- this.timeRanges = Object.create(null);
- this.config = null;
- _eventHandler2.default.prototype.destroy.call(this);
- _get(FragmentTracker.prototype.__proto__ || Object.getPrototypeOf(FragmentTracker.prototype), 'destroy', this).call(this);
- }
- /**
- * Return a Fragment that match the position and levelType.
- * If not found any Fragment, return null
- * @param {number} position
- * @param {LevelType} levelType
- * @returns {Fragment|null}
- */
- }, {
- key: 'getBufferedFrag',
- value: function getBufferedFrag(position, levelType) {
- var fragments = this.fragments;
- var bufferedFrags = Object.keys(fragments).filter(function (key) {
- var fragmentEntity = fragments[key];
- if (fragmentEntity.body.type !== levelType) {
- return false;
- }
- if (!fragmentEntity.buffered) {
- return false;
- }
- var frag = fragmentEntity.body;
- return frag.startPTS <= position && position <= frag.endPTS;
- });
- if (bufferedFrags.length === 0) {
- return null;
- } else {
- // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566
- var bufferedFragKey = bufferedFrags.pop();
- return fragments[bufferedFragKey].body;
- }
- }
- /**
- * Partial fragments effected by coded frame eviction will be removed
- * The browser will unload parts of the buffer to free up memory for new buffer data
- * 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)
- * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)
- * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer
- */
- }, {
- key: 'detectEvictedFragments',
- value: function detectEvictedFragments(elementaryStream, timeRange) {
- var _this2 = this;
- var fragmentTimes = void 0,
- time = void 0;
- // Check if any flagged fragments have been unloaded
- Object.keys(this.fragments).forEach(function (key) {
- var fragmentEntity = _this2.fragments[key];
- if (fragmentEntity.buffered === true) {
- var esData = fragmentEntity.range[elementaryStream];
- if (esData) {
- fragmentTimes = esData.time;
- for (var i = 0; i < fragmentTimes.length; i++) {
- time = fragmentTimes[i];
- if (_this2.isTimeBuffered(time.startPTS, time.endPTS, timeRange) === false) {
- // Unregister partial fragment as it needs to load again to be reused
- _this2.removeFragment(fragmentEntity.body);
- break;
- }
- }
- }
- }
- });
- }
- /**
- * Checks if the fragment passed in is loaded in the buffer properly
- * Partially loaded fragments will be registered as a partial fragment
- * @param {Object} fragment Check the fragment against all sourceBuffers loaded
- */
- }, {
- key: 'detectPartialFragments',
- value: function detectPartialFragments(fragment) {
- var _this3 = this;
- var fragKey = this.getFragmentKey(fragment);
- var fragmentEntity = this.fragments[fragKey];
- if (fragmentEntity) {
- fragmentEntity.buffered = true;
- Object.keys(this.timeRanges).forEach(function (elementaryStream) {
- if (fragment.hasElementaryStream(elementaryStream)) {
- var timeRange = _this3.timeRanges[elementaryStream];
- // Check for malformed fragments
- // Gaps need to be calculated for each elementaryStream
- fragmentEntity.range[elementaryStream] = _this3.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);
- }
- });
- }
- }
- }, {
- key: 'getBufferedTimes',
- value: function getBufferedTimes(startPTS, endPTS, timeRange) {
- var fragmentTimes = [];
- var startTime = void 0,
- endTime = void 0;
- var fragmentPartial = false;
- for (var i = 0; i < timeRange.length; i++) {
- startTime = timeRange.start(i) - this.bufferPadding;
- endTime = timeRange.end(i) + this.bufferPadding;
- if (startPTS >= startTime && endPTS <= endTime) {
- // Fragment is entirely contained in buffer
- // No need to check the other timeRange times since it's completely playable
- fragmentTimes.push({
- startPTS: Math.max(startPTS, timeRange.start(i)),
- endPTS: Math.min(endPTS, timeRange.end(i))
- });
- break;
- } else if (startPTS < endTime && endPTS > startTime) {
- // Check for intersection with buffer
- // Get playable sections of the fragment
- fragmentTimes.push({
- startPTS: Math.max(startPTS, timeRange.start(i)),
- endPTS: Math.min(endPTS, timeRange.end(i))
- });
- fragmentPartial = true;
- } else if (endPTS <= startTime) {
- // No need to check the rest of the timeRange as it is in order
- break;
- }
- }
- return {
- time: fragmentTimes,
- partial: fragmentPartial
- };
- }
- }, {
- key: 'getFragmentKey',
- value: function getFragmentKey(fragment) {
- return fragment.type + '_' + fragment.level + '_' + fragment.urlId + '_' + fragment.sn;
- }
- /**
- * Gets the partial fragment for a certain time
- * @param {Number} time
- * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment
- */
- }, {
- key: 'getPartialFragment',
- value: function getPartialFragment(time) {
- var _this4 = this;
- var timePadding = void 0,
- startTime = void 0,
- endTime = void 0;
- var bestFragment = null;
- var bestOverlap = 0;
- Object.keys(this.fragments).forEach(function (key) {
- var fragmentEntity = _this4.fragments[key];
- if (_this4.isPartial(fragmentEntity)) {
- startTime = fragmentEntity.body.startPTS - _this4.bufferPadding;
- endTime = fragmentEntity.body.endPTS + _this4.bufferPadding;
- if (time >= startTime && time <= endTime) {
- // Use the fragment that has the most padding from start and end time
- timePadding = Math.min(time - startTime, endTime - time);
- if (bestOverlap <= timePadding) {
- bestFragment = fragmentEntity.body;
- bestOverlap = timePadding;
- }
- }
- }
- });
- return bestFragment;
- }
- /**
- * @param {Object} fragment The fragment to check
- * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded
- */
- }, {
- key: 'getState',
- value: function getState(fragment) {
- var fragKey = this.getFragmentKey(fragment);
- var fragmentEntity = this.fragments[fragKey];
- var state = FragmentState.NOT_LOADED;
- if (fragmentEntity !== undefined) {
- if (!fragmentEntity.buffered) {
- state = FragmentState.APPENDING;
- } else if (this.isPartial(fragmentEntity) === true) {
- state = FragmentState.PARTIAL;
- } else {
- state = FragmentState.OK;
- }
- }
- return state;
- }
- }, {
- key: 'isPartial',
- value: function isPartial(fragmentEntity) {
- return fragmentEntity.buffered === true && (fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true || fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true);
- }
- }, {
- key: 'isTimeBuffered',
- value: function isTimeBuffered(startPTS, endPTS, timeRange) {
- var startTime = void 0,
- endTime = void 0;
- for (var i = 0; i < timeRange.length; i++) {
- startTime = timeRange.start(i) - this.bufferPadding;
- endTime = timeRange.end(i) + this.bufferPadding;
- if (startPTS >= startTime && endPTS <= endTime) {
- return true;
- }
- if (endPTS <= startTime) {
- // No need to check the rest of the timeRange as it is in order
- return false;
- }
- }
- return false;
- }
- /**
- * Fires when a fragment loading is completed
- */
- }, {
- key: 'onFragLoaded',
- value: function onFragLoaded(e) {
- var fragment = e.frag;
- // don't track initsegment (for which sn is not a number)
- // don't track frags used for bitrateTest, they're irrelevant.
- if (!Number.isFinite(fragment.sn) || fragment.bitrateTest) {
- return;
- }
- this.fragments[this.getFragmentKey(fragment)] = {
- body: fragment,
- range: Object.create(null),
- buffered: false
- };
- }
- /**
- * Fires when the buffer is updated
- */
- }, {
- key: 'onBufferAppended',
- value: function onBufferAppended(e) {
- var _this5 = this;
- // Store the latest timeRanges loaded in the buffer
- this.timeRanges = e.timeRanges;
- Object.keys(this.timeRanges).forEach(function (elementaryStream) {
- var timeRange = _this5.timeRanges[elementaryStream];
- _this5.detectEvictedFragments(elementaryStream, timeRange);
- });
- }
- /**
- * Fires after a fragment has been loaded into the source buffer
- */
- }, {
- key: 'onFragBuffered',
- value: function onFragBuffered(e) {
- this.detectPartialFragments(e.frag);
- }
- /**
- * Return true if fragment tracker has the fragment.
- * @param {Object} fragment
- * @returns {boolean}
- */
- }, {
- key: 'hasFragment',
- value: function hasFragment(fragment) {
- var fragKey = this.getFragmentKey(fragment);
- return this.fragments[fragKey] !== undefined;
- }
- /**
- * Remove a fragment from fragment tracker until it is loaded again
- * @param {Object} fragment The fragment to remove
- */
- }, {
- key: 'removeFragment',
- value: function removeFragment(fragment) {
- var fragKey = this.getFragmentKey(fragment);
- delete this.fragments[fragKey];
- }
- /**
- * Remove all fragments from fragment tracker.
- */
- }, {
- key: 'removeAllFragments',
- value: function removeAllFragments() {
- this.fragments = Object.create(null);
- }
- }]);
- return FragmentTracker;
- }(_eventHandler2.default);
- /***/ }),
- /* 7 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.addGroupId = addGroupId;
- exports.updatePTS = updatePTS;
- exports.updateFragPTSDTS = updateFragPTSDTS;
- exports.mergeDetails = mergeDetails;
- exports.mergeSubtitlePlaylists = mergeSubtitlePlaylists;
- exports.mapFragmentIntersection = mapFragmentIntersection;
- exports.adjustSliding = adjustSliding;
- exports.computeReloadInterval = computeReloadInterval;
- var _logger = __webpack_require__(0);
- function addGroupId(level, type, id) {
- switch (type) {
- case 'audio':
- if (!level.audioGroupIds) {
- level.audioGroupIds = [];
- }
- level.audioGroupIds.push(id);
- break;
- case 'text':
- if (!level.textGroupIds) {
- level.textGroupIds = [];
- }
- level.textGroupIds.push(id);
- break;
- }
- } /**
- * @module LevelHelper
- *
- * Providing methods dealing with playlist sliding and drift
- *
- * TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner.
- *
- * */
- function updatePTS(fragments, fromIdx, toIdx) {
- var fragFrom = fragments[fromIdx],
- fragTo = fragments[toIdx],
- fragToPTS = fragTo.startPTS;
- // if we know startPTS[toIdx]
- if (Number.isFinite(fragToPTS)) {
- // update fragment duration.
- // it helps to fix drifts between playlist reported duration and fragment real duration
- if (toIdx > fromIdx) {
- fragFrom.duration = fragToPTS - fragFrom.start;
- if (fragFrom.duration < 0) {
- _logger.logger.warn('negative duration computed for frag ' + fragFrom.sn + ',level ' + fragFrom.level + ', there should be some duration drift between playlist and fragment!');
- }
- } else {
- fragTo.duration = fragFrom.start - fragToPTS;
- if (fragTo.duration < 0) {
- _logger.logger.warn('negative duration computed for frag ' + fragTo.sn + ',level ' + fragTo.level + ', there should be some duration drift between playlist and fragment!');
- }
- }
- } else {
- // we dont know startPTS[toIdx]
- if (toIdx > fromIdx) {
- fragTo.start = fragFrom.start + fragFrom.duration;
- } else {
- fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
- }
- }
- }
- function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
- // update frag PTS/DTS
- var maxStartPTS = startPTS;
- if (Number.isFinite(frag.startPTS)) {
- // delta PTS between audio and video
- var deltaPTS = Math.abs(frag.startPTS - startPTS);
- if (!Number.isFinite(frag.deltaPTS)) {
- frag.deltaPTS = deltaPTS;
- } else {
- frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
- }
- maxStartPTS = Math.max(startPTS, frag.startPTS);
- startPTS = Math.min(startPTS, frag.startPTS);
- endPTS = Math.max(endPTS, frag.endPTS);
- startDTS = Math.min(startDTS, frag.startDTS);
- endDTS = Math.max(endDTS, frag.endDTS);
- }
- var drift = startPTS - frag.start;
- frag.start = frag.startPTS = startPTS;
- frag.maxStartPTS = maxStartPTS;
- frag.endPTS = endPTS;
- frag.startDTS = startDTS;
- frag.endDTS = endDTS;
- frag.duration = endPTS - startPTS;
- var sn = frag.sn;
- // exit if sn out of range
- if (!details || sn < details.startSN || sn > details.endSN) {
- return 0;
- }
- var fragIdx = void 0,
- fragments = void 0,
- i = void 0;
- fragIdx = sn - details.startSN;
- fragments = details.fragments;
- // update frag reference in fragments array
- // rationale is that fragments array might not contain this frag object.
- // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
- // if we don't update frag, we won't be able to propagate PTS info on the playlist
- // resulting in invalid sliding computation
- fragments[fragIdx] = frag;
- // adjust fragment PTS/duration from seqnum-1 to frag 0
- for (i = fragIdx; i > 0; i--) {
- updatePTS(fragments, i, i - 1);
- }
- // adjust fragment PTS/duration from seqnum to last frag
- for (i = fragIdx; i < fragments.length - 1; i++) {
- updatePTS(fragments, i, i + 1);
- }
- details.PTSKnown = true;
- return drift;
- }
- function mergeDetails(oldDetails, newDetails) {
- // potentially retrieve cached initsegment
- if (newDetails.initSegment && oldDetails.initSegment) {
- newDetails.initSegment = oldDetails.initSegment;
- }
- // check if old/new playlists have fragments in common
- // loop through overlapping SN and update startPTS , cc, and duration if any found
- var ccOffset = 0;
- var PTSFrag = void 0;
- mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) {
- ccOffset = oldFrag.cc - newFrag.cc;
- if (Number.isFinite(oldFrag.startPTS)) {
- newFrag.start = newFrag.startPTS = oldFrag.startPTS;
- newFrag.endPTS = oldFrag.endPTS;
- newFrag.duration = oldFrag.duration;
- newFrag.backtracked = oldFrag.backtracked;
- newFrag.dropped = oldFrag.dropped;
- PTSFrag = newFrag;
- }
- // PTS is known when there are overlapping segments
- newDetails.PTSKnown = true;
- });
- if (!newDetails.PTSKnown) {
- return;
- }
- if (ccOffset) {
- _logger.logger.log('discontinuity sliding from playlist, take drift into account');
- var newFragments = newDetails.fragments;
- for (var i = 0; i < newFragments.length; i++) {
- newFragments[i].cc += ccOffset;
- }
- }
- // if at least one fragment contains PTS info, recompute PTS information for all fragments
- if (PTSFrag) {
- updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
- } else {
- // ensure that delta is within oldFragments range
- // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
- // in that case we also need to adjust start offset of all fragments
- adjustSliding(oldDetails, newDetails);
- }
- // if we are here, it means we have fragments overlapping between
- // old and new level. reliable PTS info is thus relying on old level
- newDetails.PTSKnown = oldDetails.PTSKnown;
- }
- function mergeSubtitlePlaylists(oldPlaylist, newPlaylist) {
- var referenceStart = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
- var lastIndex = -1;
- mapFragmentIntersection(oldPlaylist, newPlaylist, function (oldFrag, newFrag, index) {
- newFrag.start = oldFrag.start;
- lastIndex = index;
- });
- var frags = newPlaylist.fragments;
- if (lastIndex < 0) {
- frags.forEach(function (frag) {
- frag.start += referenceStart;
- });
- return;
- }
- for (var i = lastIndex + 1; i < frags.length; i++) {
- frags[i].start = frags[i - 1].start + frags[i - 1].duration;
- }
- }
- function mapFragmentIntersection(oldPlaylist, newPlaylist, intersectionFn) {
- if (!oldPlaylist || !newPlaylist) {
- return;
- }
- var start = Math.max(oldPlaylist.startSN, newPlaylist.startSN) - newPlaylist.startSN;
- var end = Math.min(oldPlaylist.endSN, newPlaylist.endSN) - newPlaylist.startSN;
- var delta = newPlaylist.startSN - oldPlaylist.startSN;
- for (var i = start; i <= end; i++) {
- var oldFrag = oldPlaylist.fragments[delta + i];
- var newFrag = newPlaylist.fragments[i];
- if (!oldFrag || !newFrag) {
- break;
- }
- intersectionFn(oldFrag, newFrag, i);
- }
- }
- function adjustSliding(oldPlaylist, newPlaylist) {
- var delta = newPlaylist.startSN - oldPlaylist.startSN;
- var oldFragments = oldPlaylist.fragments;
- var newFragments = newPlaylist.fragments;
- if (delta < 0 || delta > oldFragments.length) {
- return;
- }
- for (var i = 0; i < newFragments.length; i++) {
- newFragments[i].start += oldFragments[delta].start;
- }
- }
- function computeReloadInterval(currentPlaylist, newPlaylist, lastRequestTime) {
- var reloadInterval = 1000 * (newPlaylist.averagetargetduration ? newPlaylist.averagetargetduration : newPlaylist.targetduration);
- var minReloadInterval = reloadInterval / 2;
- if (currentPlaylist && newPlaylist.endSN === currentPlaylist.endSN) {
- // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
- // changed then it MUST wait for a period of one-half the target
- // duration before retrying.
- reloadInterval = minReloadInterval;
- }
- if (lastRequestTime) {
- reloadInterval = Math.max(minReloadInterval, reloadInterval - (window.performance.now() - lastRequestTime));
- }
- // in any case, don't reload more than half of target duration
- return Math.round(reloadInterval);
- }
- /***/ }),
- /* 8 */
- /***/ (function(module, exports, __webpack_require__) {
- // see https://tools.ietf.org/html/rfc1808
- /* jshint ignore:start */
- (function(root) {
- /* jshint ignore:end */
- var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/\?#]*\/)*.*?)??(;.*?)?(\?.*?)?(#.*?)?$/;
- var FIRST_SEGMENT_REGEX = /^([^\/?#]*)(.*)$/;
- var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
- var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/g;
- var URLToolkit = { // jshint ignore:line
- // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
- // E.g
- // With opts.alwaysNormalize = false (default, spec compliant)
- // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
- // With opts.alwaysNormalize = true (not spec compliant)
- // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
- buildAbsoluteURL: function(baseURL, relativeURL, opts) {
- opts = opts || {};
- // remove any remaining space and CRLF
- baseURL = baseURL.trim();
- relativeURL = relativeURL.trim();
- if (!relativeURL) {
- // 2a) If the embedded URL is entirely empty, it inherits the
- // entire base URL (i.e., is set equal to the base URL)
- // and we are done.
- if (!opts.alwaysNormalize) {
- return baseURL;
- }
- var basePartsForNormalise = URLToolkit.parseURL(baseURL);
- if (!basePartsForNormalise) {
- throw new Error('Error trying to parse base URL.');
- }
- basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
- return URLToolkit.buildURLFromParts(basePartsForNormalise);
- }
- var relativeParts = URLToolkit.parseURL(relativeURL);
- if (!relativeParts) {
- throw new Error('Error trying to parse relative URL.');
- }
- if (relativeParts.scheme) {
- // 2b) If the embedded URL starts with a scheme name, it is
- // interpreted as an absolute URL and we are done.
- if (!opts.alwaysNormalize) {
- return relativeURL;
- }
- relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
- return URLToolkit.buildURLFromParts(relativeParts);
- }
- var baseParts = URLToolkit.parseURL(baseURL);
- if (!baseParts) {
- throw new Error('Error trying to parse base URL.');
- }
- if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
- // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
- // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
- var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
- baseParts.netLoc = pathParts[1];
- baseParts.path = pathParts[2];
- }
- if (baseParts.netLoc && !baseParts.path) {
- baseParts.path = '/';
- }
- var builtParts = {
- // 2c) Otherwise, the embedded URL inherits the scheme of
- // the base URL.
- scheme: baseParts.scheme,
- netLoc: relativeParts.netLoc,
- path: null,
- params: relativeParts.params,
- query: relativeParts.query,
- fragment: relativeParts.fragment
- };
- if (!relativeParts.netLoc) {
- // 3) If the embedded URL's <net_loc> is non-empty, we skip to
- // Step 7. Otherwise, the embedded URL inherits the <net_loc>
- // (if any) of the base URL.
- builtParts.netLoc = baseParts.netLoc;
- // 4) If the embedded URL path is preceded by a slash "/", the
- // path is not relative and we skip to Step 7.
- if (relativeParts.path[0] !== '/') {
- if (!relativeParts.path) {
- // 5) If the embedded URL path is empty (and not preceded by a
- // slash), then the embedded URL inherits the base URL path
- builtParts.path = baseParts.path;
- // 5a) if the embedded URL's <params> is non-empty, we skip to
- // step 7; otherwise, it inherits the <params> of the base
- // URL (if any) and
- if (!relativeParts.params) {
- builtParts.params = baseParts.params;
- // 5b) if the embedded URL's <query> is non-empty, we skip to
- // step 7; otherwise, it inherits the <query> of the base
- // URL (if any) and we skip to step 7.
- if (!relativeParts.query) {
- builtParts.query = baseParts.query;
- }
- }
- } else {
- // 6) The last segment of the base URL's path (anything
- // following the rightmost slash "/", or the entire path if no
- // slash is present) is removed and the embedded URL's path is
- // appended in its place.
- var baseURLPath = baseParts.path;
- var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;
- builtParts.path = URLToolkit.normalizePath(newPath);
- }
- }
- }
- if (builtParts.path === null) {
- builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
- }
- return URLToolkit.buildURLFromParts(builtParts);
- },
- parseURL: function(url) {
- var parts = URL_REGEX.exec(url);
- if (!parts) {
- return null;
- }
- return {
- scheme: parts[1] || '',
- netLoc: parts[2] || '',
- path: parts[3] || '',
- params: parts[4] || '',
- query: parts[5] || '',
- fragment: parts[6] || ''
- };
- },
- normalizePath: function(path) {
- // The following operations are
- // then applied, in order, to the new path:
- // 6a) All occurrences of "./", where "." is a complete path
- // segment, are removed.
- // 6b) If the path ends with "." as a complete path segment,
- // that "." is removed.
- path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
- // 6c) All occurrences of "<segment>/../", where <segment> is a
- // complete path segment not equal to "..", are removed.
- // Removal of these path segments is performed iteratively,
- // removing the leftmost matching pattern on each iteration,
- // until no matching pattern remains.
- // 6d) If the path ends with "<segment>/..", where <segment> is a
- // complete path segment not equal to "..", that
- // "<segment>/.." is removed.
- while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {} // jshint ignore:line
- return path.split('').reverse().join('');
- },
- buildURLFromParts: function(parts) {
- return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
- }
- };
- /* jshint ignore:start */
- if(true)
- module.exports = URLToolkit;
- else {}
- })(this);
- /* jshint ignore:end */
- /***/ }),
- /* 9 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var BinarySearch = {
- /**
- * Searches for an item in an array which matches a certain condition.
- * This requires the condition to only match one item in the array,
- * and for the array to be ordered.
- *
- * @param {Array} list The array to search.
- * @param {Function} comparisonFunction
- * Called and provided a candidate item as the first argument.
- * Should return:
- * > -1 if the item should be located at a lower index than the provided item.
- * > 1 if the item should be located at a higher index than the provided item.
- * > 0 if the item is the item you're looking for.
- *
- * @return {*} The object if it is found or null otherwise.
- */
- search: function search(list, comparisonFunction) {
- var minIndex = 0;
- var maxIndex = list.length - 1;
- var currentIndex = null;
- var currentElement = null;
- while (minIndex <= maxIndex) {
- currentIndex = (minIndex + maxIndex) / 2 | 0;
- currentElement = list[currentIndex];
- var comparisonResult = comparisonFunction(currentElement);
- if (comparisonResult > 0) {
- minIndex = currentIndex + 1;
- } else if (comparisonResult < 0) {
- maxIndex = currentIndex - 1;
- } else {
- return currentElement;
- }
- }
- return null;
- }
- };
- exports.default = BinarySearch;
- module.exports = exports["default"];
- /***/ }),
- /* 10 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /**
- * ID3 parser
- */
- var ID3 = function () {
- function ID3() {
- _classCallCheck(this, ID3);
- }
- _createClass(ID3, null, [{
- key: 'isHeader',
- /**
- * Returns true if an ID3 header can be found at offset in data
- * @param {Uint8Array} data - The data to search in
- * @param {number} offset - The offset at which to start searching
- * @return {boolean} - True if an ID3 header is found
- */
- value: function isHeader(data, offset) {
- /*
- * http://id3.org/id3v2.3.0
- * [0] = 'I'
- * [1] = 'D'
- * [2] = '3'
- * [3,4] = {Version}
- * [5] = {Flags}
- * [6-9] = {ID3 Size}
- *
- * An ID3v2 tag can be detected with the following pattern:
- * $49 44 33 yy yy xx zz zz zz zz
- * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
- */
- if (offset + 10 <= data.length) {
- // look for 'ID3' identifier
- if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
- // check version is within range
- if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
- // check size is within range
- if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
- return true;
- }
- }
- }
- }
- return false;
- }
- /**
- * Returns true if an ID3 footer can be found at offset in data
- * @param {Uint8Array} data - The data to search in
- * @param {number} offset - The offset at which to start searching
- * @return {boolean} - True if an ID3 footer is found
- */
- }, {
- key: 'isFooter',
- value: function isFooter(data, offset) {
- /*
- * The footer is a copy of the header, but with a different identifier
- */
- if (offset + 10 <= data.length) {
- // look for '3DI' identifier
- if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
- // check version is within range
- if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
- // check size is within range
- if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
- return true;
- }
- }
- }
- }
- return false;
- }
- /**
- * Returns any adjacent ID3 tags found in data starting at offset, as one block of data
- * @param {Uint8Array} data - The data to search in
- * @param {number} offset - The offset at which to start searching
- * @return {Uint8Array} - The block of data containing any ID3 tags found
- */
- }, {
- key: 'getID3Data',
- value: function getID3Data(data, offset) {
- var front = offset;
- var length = 0;
- while (ID3.isHeader(data, offset)) {
- // ID3 header is 10 bytes
- length += 10;
- var size = ID3._readSize(data, offset + 6);
- length += size;
- if (ID3.isFooter(data, offset + 10)) {
- // ID3 footer is 10 bytes
- length += 10;
- }
- offset += length;
- }
- if (length > 0) {
- return data.subarray(front, front + length);
- }
- return undefined;
- }
- }, {
- key: '_readSize',
- value: function _readSize(data, offset) {
- var size = 0;
- size = (data[offset] & 0x7f) << 21;
- size |= (data[offset + 1] & 0x7f) << 14;
- size |= (data[offset + 2] & 0x7f) << 7;
- size |= data[offset + 3] & 0x7f;
- return size;
- }
- /**
- * Searches for the Elementary Stream timestamp found in the ID3 data chunk
- * @param {Uint8Array} data - Block of data containing one or more ID3 tags
- * @return {number} - The timestamp
- */
- }, {
- key: 'getTimeStamp',
- value: function getTimeStamp(data) {
- var frames = ID3.getID3Frames(data);
- for (var i = 0; i < frames.length; i++) {
- var frame = frames[i];
- if (ID3.isTimeStampFrame(frame)) {
- return ID3._readTimeStamp(frame);
- }
- }
- return undefined;
- }
- /**
- * Returns true if the ID3 frame is an Elementary Stream timestamp frame
- * @param {ID3 frame} frame
- */
- }, {
- key: 'isTimeStampFrame',
- value: function isTimeStampFrame(frame) {
- return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
- }
- }, {
- key: '_getFrameData',
- value: function _getFrameData(data) {
- /*
- Frame ID $xx xx xx xx (four characters)
- Size $xx xx xx xx
- Flags $xx xx
- */
- var type = String.fromCharCode(data[0], data[1], data[2], data[3]);
- var size = ID3._readSize(data, 4);
- // skip frame id, size, and flags
- var offset = 10;
- return { type: type, size: size, data: data.subarray(offset, offset + size) };
- }
- /**
- * Returns an array of ID3 frames found in all the ID3 tags in the id3Data
- * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags
- * @return {ID3 frame[]} - Array of ID3 frame objects
- */
- }, {
- key: 'getID3Frames',
- value: function getID3Frames(id3Data) {
- var offset = 0;
- var frames = [];
- while (ID3.isHeader(id3Data, offset)) {
- var size = ID3._readSize(id3Data, offset + 6);
- // skip past ID3 header
- offset += 10;
- var end = offset + size;
- // loop through frames in the ID3 tag
- while (offset + 8 < end) {
- var frameData = ID3._getFrameData(id3Data.subarray(offset));
- var frame = ID3._decodeFrame(frameData);
- if (frame) {
- frames.push(frame);
- }
- // skip frame header and frame data
- offset += frameData.size + 10;
- }
- if (ID3.isFooter(id3Data, offset)) {
- offset += 10;
- }
- }
- return frames;
- }
- }, {
- key: '_decodeFrame',
- value: function _decodeFrame(frame) {
- if (frame.type === 'PRIV') {
- return ID3._decodePrivFrame(frame);
- } else if (frame.type[0] === 'T') {
- return ID3._decodeTextFrame(frame);
- } else if (frame.type[0] === 'W') {
- return ID3._decodeURLFrame(frame);
- }
- return undefined;
- }
- }, {
- key: '_readTimeStamp',
- value: function _readTimeStamp(timeStampFrame) {
- if (timeStampFrame.data.byteLength === 8) {
- var data = new Uint8Array(timeStampFrame.data);
- // timestamp is 33 bit expressed as a big-endian eight-octet number,
- // with the upper 31 bits set to zero.
- var pts33Bit = data[3] & 0x1;
- var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
- timestamp /= 45;
- if (pts33Bit) {
- timestamp += 47721858.84;
- } // 2^32 / 90
- return Math.round(timestamp);
- }
- return undefined;
- }
- }, {
- key: '_decodePrivFrame',
- value: function _decodePrivFrame(frame) {
- /*
- Format: <text string>\0<binary data>
- */
- if (frame.size < 2) {
- return undefined;
- }
- var owner = ID3._utf8ArrayToStr(frame.data, true);
- var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
- return { key: frame.type, info: owner, data: privateData.buffer };
- }
- }, {
- key: '_decodeTextFrame',
- value: function _decodeTextFrame(frame) {
- if (frame.size < 2) {
- return undefined;
- }
- if (frame.type === 'TXXX') {
- /*
- Format:
- [0] = {Text Encoding}
- [1-?] = {Description}\0{Value}
- */
- var index = 1;
- var description = ID3._utf8ArrayToStr(frame.data.subarray(index));
- index += description.length + 1;
- var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
- return { key: frame.type, info: description, data: value };
- } else {
- /*
- Format:
- [0] = {Text Encoding}
- [1-?] = {Value}
- */
- var text = ID3._utf8ArrayToStr(frame.data.subarray(1));
- return { key: frame.type, data: text };
- }
- }
- }, {
- key: '_decodeURLFrame',
- value: function _decodeURLFrame(frame) {
- if (frame.type === 'WXXX') {
- /*
- Format:
- [0] = {Text Encoding}
- [1-?] = {Description}\0{URL}
- */
- if (frame.size < 2) {
- return undefined;
- }
- var index = 1;
- var description = ID3._utf8ArrayToStr(frame.data.subarray(index));
- index += description.length + 1;
- var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
- return { key: frame.type, info: description, data: value };
- } else {
- /*
- Format:
- [0-?] = {URL}
- */
- var url = ID3._utf8ArrayToStr(frame.data);
- return { key: frame.type, data: url };
- }
- }
- // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
- // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
- /* utf.js - UTF-8 <=> UTF-16 convertion
- *
- * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
- * Version: 1.0
- * LastModified: Dec 25 1999
- * This library is free. You can redistribute it and/or modify it.
- */
- }, {
- key: '_utf8ArrayToStr',
- value: function _utf8ArrayToStr(array) {
- var exitOnNull = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
- var len = array.length;
- var c = void 0;
- var char2 = void 0;
- var char3 = void 0;
- var out = '';
- var i = 0;
- while (i < len) {
- c = array[i++];
- if (c === 0x00 && exitOnNull) {
- return out;
- } else if (c === 0x00 || c === 0x03) {
- // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
- continue;
- }
- switch (c >> 4) {
- case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:
- // 0xxxxxxx
- out += String.fromCharCode(c);
- break;
- case 12:case 13:
- // 110x xxxx 10xx xxxx
- char2 = array[i++];
- out += String.fromCharCode((c & 0x1F) << 6 | char2 & 0x3F);
- break;
- case 14:
- // 1110 xxxx 10xx xxxx 10xx xxxx
- char2 = array[i++];
- char3 = array[i++];
- out += String.fromCharCode((c & 0x0F) << 12 | (char2 & 0x3F) << 6 | (char3 & 0x3F) << 0);
- break;
- default:
- }
- }
- return out;
- }
- }]);
- return ID3;
- }();
- var utf8ArrayToStr = ID3._utf8ArrayToStr;
- exports.default = ID3;
- exports.utf8ArrayToStr = utf8ArrayToStr;
- /***/ }),
- /* 11 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _urlToolkit = __webpack_require__(8);
- var URLToolkit = _interopRequireWildcard(_urlToolkit);
- var _levelKey = __webpack_require__(17);
- var _levelKey2 = _interopRequireDefault(_levelKey);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- 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; } }
- 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; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var Fragment = function () {
- function Fragment() {
- var _elementaryStreams;
- _classCallCheck(this, Fragment);
- this._url = null;
- this._byteRange = null;
- this._decryptdata = null;
- this.tagList = [];
- this.programDateTime = null;
- this.rawProgramDateTime = null;
- // Holds the types of data this fragment supports
- this._elementaryStreams = (_elementaryStreams = {}, _defineProperty(_elementaryStreams, Fragment.ElementaryStreamTypes.AUDIO, false), _defineProperty(_elementaryStreams, Fragment.ElementaryStreamTypes.VIDEO, false), _elementaryStreams);
- }
- /**
- * `type` property for this._elementaryStreams
- *
- * @enum
- */
- _createClass(Fragment, [{
- key: 'addElementaryStream',
- /**
- * @param {ElementaryStreamType} type
- */
- value: function addElementaryStream(type) {
- this._elementaryStreams[type] = true;
- }
- /**
- * @param {ElementaryStreamType} type
- */
- }, {
- key: 'hasElementaryStream',
- value: function hasElementaryStream(type) {
- return this._elementaryStreams[type] === true;
- }
- /**
- * Utility method for parseLevelPlaylist to create an initialization vector for a given segment
- * @returns {Uint8Array}
- */
- }, {
- key: 'createInitializationVector',
- value: function createInitializationVector(segmentNumber) {
- var uint8View = new Uint8Array(16);
- for (var i = 12; i < 16; i++) {
- uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
- }
- return uint8View;
- }
- /**
- * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data
- * @param levelkey - a playlist's encryption info
- * @param segmentNumber - the fragment's segment number
- * @returns {*} - an object to be applied as a fragment's decryptdata
- */
- }, {
- key: 'fragmentDecryptdataFromLevelkey',
- value: function fragmentDecryptdataFromLevelkey(levelkey, segmentNumber) {
- var decryptdata = levelkey;
- if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) {
- decryptdata = new _levelKey2.default();
- decryptdata.method = levelkey.method;
- decryptdata.baseuri = levelkey.baseuri;
- decryptdata.reluri = levelkey.reluri;
- decryptdata.iv = this.createInitializationVector(segmentNumber);
- }
- return decryptdata;
- }
- }, {
- key: 'url',
- get: function get() {
- if (!this._url && this.relurl) {
- this._url = URLToolkit.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });
- }
- return this._url;
- },
- set: function set(value) {
- this._url = value;
- }
- }, {
- key: 'byteRange',
- get: function get() {
- if (!this._byteRange && !this.rawByteRange) {
- return [];
- }
- if (this._byteRange) {
- return this._byteRange;
- }
- var byteRange = [];
- if (this.rawByteRange) {
- var params = this.rawByteRange.split('@', 2);
- if (params.length === 1) {
- var lastByteRangeEndOffset = this.lastByteRangeEndOffset;
- byteRange[0] = lastByteRangeEndOffset || 0;
- } else {
- byteRange[0] = parseInt(params[1]);
- }
- byteRange[1] = parseInt(params[0]) + byteRange[0];
- this._byteRange = byteRange;
- }
- return byteRange;
- }
- /**
- * @type {number}
- */
- }, {
- key: 'byteRangeStartOffset',
- get: function get() {
- return this.byteRange[0];
- }
- }, {
- key: 'byteRangeEndOffset',
- get: function get() {
- return this.byteRange[1];
- }
- }, {
- key: 'decryptdata',
- get: function get() {
- if (!this._decryptdata) {
- this._decryptdata = this.fragmentDecryptdataFromLevelkey(this.levelkey, this.sn);
- }
- return this._decryptdata;
- }
- }, {
- key: 'endProgramDateTime',
- get: function get() {
- if (!Number.isFinite(this.programDateTime)) {
- return null;
- }
- var duration = !Number.isFinite(this.duration) ? 0 : this.duration;
- return this.programDateTime + duration * 1000;
- }
- }, {
- key: 'encrypted',
- get: function get() {
- return !!(this.decryptdata && this.decryptdata.uri !== null && this.decryptdata.key === null);
- }
- }], [{
- key: 'ElementaryStreamTypes',
- get: function get() {
- return {
- AUDIO: 'audio',
- VIDEO: 'video'
- };
- }
- }]);
- return Fragment;
- }();
- exports.default = Fragment;
- module.exports = exports['default'];
- /***/ }),
- /* 12 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _aesCrypto = __webpack_require__(42);
- var _aesCrypto2 = _interopRequireDefault(_aesCrypto);
- var _fastAesKey = __webpack_require__(43);
- var _fastAesKey2 = _interopRequireDefault(_fastAesKey);
- var _aesDecryptor = __webpack_require__(44);
- var _aesDecryptor2 = _interopRequireDefault(_aesDecryptor);
- var _errors = __webpack_require__(2);
- var _logger = __webpack_require__(0);
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _getSelfScope = __webpack_require__(5);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- // see https://stackoverflow.com/a/11237259/589493
- var global = (0, _getSelfScope.getSelfScope)(); // safeguard for code that might run both on worker and main thread
- var Decrypter = function () {
- function Decrypter(observer, config) {
- var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
- _ref$removePKCS7Paddi = _ref.removePKCS7Padding,
- removePKCS7Padding = _ref$removePKCS7Paddi === undefined ? true : _ref$removePKCS7Paddi;
- _classCallCheck(this, Decrypter);
- this.logEnabled = true;
- this.observer = observer;
- this.config = config;
- this.removePKCS7Padding = removePKCS7Padding;
- // built in decryptor expects PKCS7 padding
- if (removePKCS7Padding) {
- try {
- var browserCrypto = global.crypto;
- if (browserCrypto) {
- this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
- }
- } catch (e) {}
- }
- this.disableWebCrypto = !this.subtle;
- }
- _createClass(Decrypter, [{
- key: 'isSync',
- value: function isSync() {
- return this.disableWebCrypto && this.config.enableSoftwareAES;
- }
- }, {
- key: 'decrypt',
- value: function decrypt(data, key, iv, callback) {
- var _this = this;
- if (this.disableWebCrypto && this.config.enableSoftwareAES) {
- if (this.logEnabled) {
- _logger.logger.log('JS AES decrypt');
- this.logEnabled = false;
- }
- var decryptor = this.decryptor;
- if (!decryptor) {
- this.decryptor = decryptor = new _aesDecryptor2.default();
- }
- decryptor.expandKey(key);
- callback(decryptor.decrypt(data, 0, iv, this.removePKCS7Padding));
- } else {
- if (this.logEnabled) {
- _logger.logger.log('WebCrypto AES decrypt');
- this.logEnabled = false;
- }
- var subtle = this.subtle;
- if (this.key !== key) {
- this.key = key;
- this.fastAesKey = new _fastAesKey2.default(subtle, key);
- }
- this.fastAesKey.expandKey().then(function (aesKey) {
- // decrypt using web crypto
- var crypto = new _aesCrypto2.default(subtle, iv);
- crypto.decrypt(data, aesKey).catch(function (err) {
- _this.onWebCryptoError(err, data, key, iv, callback);
- }).then(function (result) {
- callback(result);
- });
- }).catch(function (err) {
- _this.onWebCryptoError(err, data, key, iv, callback);
- });
- }
- }
- }, {
- key: 'onWebCryptoError',
- value: function onWebCryptoError(err, data, key, iv, callback) {
- if (this.config.enableSoftwareAES) {
- _logger.logger.log('WebCrypto Error, disable WebCrypto API');
- this.disableWebCrypto = true;
- this.logEnabled = true;
- this.decrypt(data, key, iv, callback);
- } else {
- _logger.logger.error('decrypting error : ' + err.message);
- this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_DECRYPT_ERROR, fatal: true, reason: err.message });
- }
- }
- }, {
- key: 'destroy',
- value: function destroy() {
- var decryptor = this.decryptor;
- if (decryptor) {
- decryptor.destroy();
- this.decryptor = undefined;
- }
- }
- }]);
- return Decrypter;
- }();
- exports.default = Decrypter;
- module.exports = exports['default'];
- /***/ }),
- /* 13 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getMediaSource = getMediaSource;
- /**
- * MediaSource helper
- */
- function getMediaSource() {
- if (typeof window !== 'undefined') {
- return window.MediaSource || window.WebKitMediaSource;
- }
- }
- /***/ }),
- /* 14 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.State = undefined;
- 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; }; }();
- 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); } };
- var _taskLoop = __webpack_require__(28);
- var _taskLoop2 = _interopRequireDefault(_taskLoop);
- var _fragmentTracker = __webpack_require__(6);
- var _bufferHelper = __webpack_require__(4);
- var _logger = __webpack_require__(0);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; }
- var State = exports.State = {
- STOPPED: 'STOPPED',
- STARTING: 'STARTING',
- IDLE: 'IDLE',
- PAUSED: 'PAUSED',
- KEY_LOADING: 'KEY_LOADING',
- FRAG_LOADING: 'FRAG_LOADING',
- FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
- WAITING_TRACK: 'WAITING_TRACK',
- PARSING: 'PARSING',
- PARSED: 'PARSED',
- BUFFER_FLUSHING: 'BUFFER_FLUSHING',
- ENDED: 'ENDED',
- ERROR: 'ERROR',
- WAITING_INIT_PTS: 'WAITING_INIT_PTS',
- WAITING_LEVEL: 'WAITING_LEVEL'
- };
- var BaseStreamController = function (_TaskLoop) {
- _inherits(BaseStreamController, _TaskLoop);
- function BaseStreamController() {
- _classCallCheck(this, BaseStreamController);
- return _possibleConstructorReturn(this, (BaseStreamController.__proto__ || Object.getPrototypeOf(BaseStreamController)).apply(this, arguments));
- }
- _createClass(BaseStreamController, [{
- key: 'doTick',
- value: function doTick() {}
- }, {
- key: 'startLoad',
- value: function startLoad() {}
- }, {
- key: 'stopLoad',
- value: function stopLoad() {
- var frag = this.fragCurrent;
- if (frag) {
- if (frag.loader) {
- frag.loader.abort();
- }
- this.fragmentTracker.removeFragment(frag);
- }
- if (this.demuxer) {
- this.demuxer.destroy();
- this.demuxer = null;
- }
- this.fragCurrent = null;
- this.fragPrevious = null;
- this.clearInterval();
- this.clearNextTick();
- this.state = State.STOPPED;
- }
- }, {
- key: '_streamEnded',
- value: function _streamEnded(bufferInfo, levelDetails) {
- var fragCurrent = this.fragCurrent,
- fragmentTracker = this.fragmentTracker;
- // we just got done loading the final fragment and there is no other buffered range after ...
- // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
- // so we should not switch to ENDED in that case, to be able to buffer them
- // dont switch to ENDED if we need to backtrack last fragment
- if (!levelDetails.live && fragCurrent && !fragCurrent.backtracked && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) {
- var fragState = fragmentTracker.getState(fragCurrent);
- return fragState === _fragmentTracker.FragmentState.PARTIAL || fragState === _fragmentTracker.FragmentState.OK;
- }
- return false;
- }
- }, {
- key: 'onMediaSeeking',
- value: function onMediaSeeking() {
- var config = this.config,
- media = this.media,
- mediaBuffer = this.mediaBuffer,
- state = this.state;
- var currentTime = media ? media.currentTime : null;
- var bufferInfo = _bufferHelper.BufferHelper.bufferInfo(mediaBuffer || media, currentTime, this.config.maxBufferHole);
- if (Number.isFinite(currentTime)) {
- _logger.logger.log('media seeking to ' + currentTime.toFixed(3));
- }
- if (state === State.FRAG_LOADING) {
- var fragCurrent = this.fragCurrent;
- // check if we are seeking to a unbuffered area AND if frag loading is in progress
- if (bufferInfo.len === 0 && fragCurrent) {
- var tolerance = config.maxFragLookUpTolerance;
- var fragStartOffset = fragCurrent.start - tolerance;
- var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
- // check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything
- if (currentTime < fragStartOffset || currentTime > fragEndOffset) {
- if (fragCurrent.loader) {
- _logger.logger.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
- fragCurrent.loader.abort();
- }
- this.fragCurrent = null;
- this.fragPrevious = null;
- // switch to IDLE state to load new fragment
- this.state = State.IDLE;
- } else {
- _logger.logger.log('seeking outside of buffer but within currently loaded fragment range');
- }
- }
- } else if (state === State.ENDED) {
- // if seeking to unbuffered area, clean up fragPrevious
- if (bufferInfo.len === 0) {
- this.fragPrevious = null;
- this.fragCurrent = null;
- }
- // switch to IDLE state to check for potential new fragment
- this.state = State.IDLE;
- }
- if (media) {
- this.lastCurrentTime = currentTime;
- }
- // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
- if (!this.loadedmetadata) {
- this.nextLoadPosition = this.startPosition = currentTime;
- }
- // tick to speed up processing
- this.tick();
- }
- }, {
- key: 'onMediaEnded',
- value: function onMediaEnded() {
- // reset startPosition and lastCurrentTime to restart playback @ stream beginning
- this.startPosition = this.lastCurrentTime = 0;
- }
- }, {
- key: 'onHandlerDestroying',
- value: function onHandlerDestroying() {
- this.stopLoad();
- _get(BaseStreamController.prototype.__proto__ || Object.getPrototypeOf(BaseStreamController.prototype), 'onHandlerDestroying', this).call(this);
- }
- }, {
- key: 'onHandlerDestroyed',
- value: function onHandlerDestroyed() {
- this.state = State.STOPPED;
- this.fragmentTracker = null;
- }
- }]);
- return BaseStreamController;
- }(_taskLoop2.default);
- exports.default = BaseStreamController;
- /***/ }),
- /* 15 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- 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); } };
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _eventHandler = __webpack_require__(3);
- var _eventHandler2 = _interopRequireDefault(_eventHandler);
- var _errors = __webpack_require__(2);
- var _logger = __webpack_require__(0);
- var _mp4demuxer = __webpack_require__(16);
- var _mp4demuxer2 = _interopRequireDefault(_mp4demuxer);
- var _m3u8Parser = __webpack_require__(35);
- var _m3u8Parser2 = _interopRequireDefault(_m3u8Parser);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /**
- * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.
- *
- * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.
- *
- * Uses loader(s) set in config to do actual internal loading of resource tasks.
- *
- * @module
- *
- */
- var _window = window,
- performance = _window.performance;
- /**
- * `type` property values for this loaders' context object
- * @enum
- *
- */
- var ContextType = {
- MANIFEST: 'manifest',
- LEVEL: 'level',
- AUDIO_TRACK: 'audioTrack',
- SUBTITLE_TRACK: 'subtitleTrack'
- };
- /**
- * @enum {string}
- */
- var LevelType = {
- MAIN: 'main',
- AUDIO: 'audio',
- SUBTITLE: 'subtitle'
- };
- /**
- * @constructor
- */
- var PlaylistLoader = function (_EventHandler) {
- _inherits(PlaylistLoader, _EventHandler);
- /**
- * @constructs
- * @param {Hls} hls
- */
- function PlaylistLoader(hls) {
- _classCallCheck(this, PlaylistLoader);
- 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));
- _this.loaders = {};
- return _this;
- }
- _createClass(PlaylistLoader, [{
- key: 'createInternalLoader',
- /**
- * Returns defaults or configured loader-type overloads (pLoader and loader config params)
- * Default loader is XHRLoader (see utils)
- * @param {object} context
- * @returns {XHRLoader} or other compatible configured overload
- */
- value: function createInternalLoader(context) {
- var config = this.hls.config;
- var PLoader = config.pLoader;
- var Loader = config.loader;
- var InternalLoader = PLoader || Loader;
- var loader = new InternalLoader(config);
- context.loader = loader;
- this.loaders[context.type] = loader;
- return loader;
- }
- }, {
- key: 'getInternalLoader',
- value: function getInternalLoader(context) {
- return this.loaders[context.type];
- }
- }, {
- key: 'resetInternalLoader',
- value: function resetInternalLoader(contextType) {
- if (this.loaders[contextType]) {
- delete this.loaders[contextType];
- }
- }
- /**
- * Call `destroy` on all internal loader instances mapped (one per context type)
- */
- }, {
- key: 'destroyInternalLoaders',
- value: function destroyInternalLoaders() {
- for (var contextType in this.loaders) {
- var loader = this.loaders[contextType];
- if (loader) {
- loader.destroy();
- }
- this.resetInternalLoader(contextType);
- }
- }
- }, {
- key: 'destroy',
- value: function destroy() {
- this.destroyInternalLoaders();
- _get(PlaylistLoader.prototype.__proto__ || Object.getPrototypeOf(PlaylistLoader.prototype), 'destroy', this).call(this);
- }
- }, {
- key: 'onManifestLoading',
- value: function onManifestLoading(data) {
- this.load(data.url, { type: ContextType.MANIFEST, level: 0, id: null });
- }
- }, {
- key: 'onLevelLoading',
- value: function onLevelLoading(data) {
- this.load(data.url, { type: ContextType.LEVEL, level: data.level, id: data.id });
- }
- }, {
- key: 'onAudioTrackLoading',
- value: function onAudioTrackLoading(data) {
- this.load(data.url, { type: ContextType.AUDIO_TRACK, level: null, id: data.id });
- }
- }, {
- key: 'onSubtitleTrackLoading',
- value: function onSubtitleTrackLoading(data) {
- this.load(data.url, { type: ContextType.SUBTITLE_TRACK, level: null, id: data.id });
- }
- }, {
- key: 'load',
- value: function load(url, context) {
- var config = this.hls.config;
- _logger.logger.debug('Loading playlist of type ' + context.type + ', level: ' + context.level + ', id: ' + context.id);
- // Check if a loader for this context already exists
- var loader = this.getInternalLoader(context);
- if (loader) {
- var loaderContext = loader.context;
- if (loaderContext && loaderContext.url === url) {
- // same URL can't overlap
- _logger.logger.trace('playlist request ongoing');
- return false;
- } else {
- _logger.logger.warn('aborting previous loader for type: ' + context.type);
- loader.abort();
- }
- }
- var maxRetry = void 0,
- timeout = void 0,
- retryDelay = void 0,
- maxRetryDelay = void 0;
- // apply different configs for retries depending on
- // context (manifest, level, audio/subs playlist)
- switch (context.type) {
- case ContextType.MANIFEST:
- maxRetry = config.manifestLoadingMaxRetry;
- timeout = config.manifestLoadingTimeOut;
- retryDelay = config.manifestLoadingRetryDelay;
- maxRetryDelay = config.manifestLoadingMaxRetryTimeout;
- break;
- case ContextType.LEVEL:
- // Disable internal loader retry logic, since we are managing retries in Level Controller
- maxRetry = 0;
- timeout = config.levelLoadingTimeOut;
- // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config
- break;
- default:
- maxRetry = config.levelLoadingMaxRetry;
- timeout = config.levelLoadingTimeOut;
- retryDelay = config.levelLoadingRetryDelay;
- maxRetryDelay = config.levelLoadingMaxRetryTimeout;
- break;
- }
- loader = this.createInternalLoader(context);
- context.url = url;
- context.responseType = context.responseType || ''; // FIXME: (should not be necessary to do this)
- var loaderConfig = {
- timeout: timeout,
- maxRetry: maxRetry,
- retryDelay: retryDelay,
- maxRetryDelay: maxRetryDelay
- };
- var loaderCallbacks = {
- onSuccess: this.loadsuccess.bind(this),
- onError: this.loaderror.bind(this),
- onTimeout: this.loadtimeout.bind(this)
- };
- _logger.logger.debug('Calling internal loader delegate for URL: ' + url);
- loader.load(context, loaderConfig, loaderCallbacks);
- return true;
- }
- }, {
- key: 'loadsuccess',
- value: function loadsuccess(response, stats, context) {
- var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
- if (context.isSidxRequest) {
- this._handleSidxRequest(response, context);
- this._handlePlaylistLoaded(response, stats, context, networkDetails);
- return;
- }
- this.resetInternalLoader(context.type);
- var string = response.data;
- stats.tload = performance.now();
- // stats.mtime = new Date(target.getResponseHeader('Last-Modified'));
- // Validate if it is an M3U8 at all
- if (string.indexOf('#EXTM3U') !== 0) {
- this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);
- return;
- }
- // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)
- if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {
- this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);
- } else {
- this._handleMasterPlaylist(response, stats, context, networkDetails);
- }
- }
- }, {
- key: 'loaderror',
- value: function loaderror(response, context) {
- var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
- this._handleNetworkError(context, networkDetails, false, response);
- }
- }, {
- key: 'loadtimeout',
- value: function loadtimeout(stats, context) {
- var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
- this._handleNetworkError(context, networkDetails, true);
- }
- }, {
- key: '_handleMasterPlaylist',
- value: function _handleMasterPlaylist(response, stats, context, networkDetails) {
- var hls = this.hls;
- var string = response.data;
- var url = PlaylistLoader.getResponseUrl(response, context);
- var levels = _m3u8Parser2.default.parseMasterPlaylist(string, url);
- if (!levels.length) {
- this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);
- return;
- }
- // multi level playlist, parse level info
- var audioGroups = levels.map(function (level) {
- return {
- id: level.attrs.AUDIO,
- codec: level.audioCodec
- };
- });
- var audioTracks = _m3u8Parser2.default.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);
- var subtitles = _m3u8Parser2.default.parseMasterPlaylistMedia(string, url, 'SUBTITLES');
- if (audioTracks.length) {
- // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
- var embeddedAudioFound = false;
- audioTracks.forEach(function (audioTrack) {
- if (!audioTrack.url) {
- embeddedAudioFound = true;
- }
- });
- // if no embedded audio track defined, but audio codec signaled in quality level,
- // we need to signal this main audio track this could happen with playlists with
- // alt audio rendition in which quality levels (main)
- // contains both audio+video. but with mixed audio track not signaled
- if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
- _logger.logger.log('audio codec signaled in quality level, but no embedded audio track signaled, create one');
- audioTracks.unshift({
- type: 'main',
- name: 'main'
- });
- }
- }
- hls.trigger(_events2.default.MANIFEST_LOADED, {
- levels: levels,
- audioTracks: audioTracks,
- subtitles: subtitles,
- url: url,
- stats: stats,
- networkDetails: networkDetails
- });
- }
- }, {
- key: '_handleTrackOrLevelPlaylist',
- value: function _handleTrackOrLevelPlaylist(response, stats, context, networkDetails) {
- var hls = this.hls;
- var id = context.id,
- level = context.level,
- type = context.type;
- var url = PlaylistLoader.getResponseUrl(response, context);
- var levelUrlId = Number.isFinite(id) ? id : 0;
- var levelId = Number.isFinite(level) ? level : levelUrlId;
- var levelType = PlaylistLoader.mapContextToLevelType(context);
- var levelDetails = _m3u8Parser2.default.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);
- // set stats on level structure
- levelDetails.tload = stats.tload;
- // We have done our first request (Manifest-type) and receive
- // not a master playlist but a chunk-list (track/level)
- // We fire the manifest-loaded event anyway with the parsed level-details
- // by creating a single-level structure for it.
- if (type === ContextType.MANIFEST) {
- var singleLevel = {
- url: url,
- details: levelDetails
- };
- hls.trigger(_events2.default.MANIFEST_LOADED, {
- levels: [singleLevel],
- audioTracks: [],
- url: url,
- stats: stats,
- networkDetails: networkDetails
- });
- }
- // save parsing time
- stats.tparsed = performance.now();
- // in case we need SIDX ranges
- // return early after calling load for
- // the SIDX box.
- if (levelDetails.needSidxRanges) {
- var sidxUrl = levelDetails.initSegment.url;
- this.load(sidxUrl, {
- isSidxRequest: true,
- type: type,
- level: level,
- levelDetails: levelDetails,
- id: id,
- rangeStart: 0,
- rangeEnd: 2048,
- responseType: 'arraybuffer'
- });
- return;
- }
- // extend the context with the new levelDetails property
- context.levelDetails = levelDetails;
- this._handlePlaylistLoaded(response, stats, context, networkDetails);
- }
- }, {
- key: '_handleSidxRequest',
- value: function _handleSidxRequest(response, context) {
- var sidxInfo = _mp4demuxer2.default.parseSegmentIndex(new Uint8Array(response.data));
- // if provided fragment does not contain sidx, early return
- if (!sidxInfo) {
- return;
- }
- var sidxReferences = sidxInfo.references;
- var levelDetails = context.levelDetails;
- sidxReferences.forEach(function (segmentRef, index) {
- var segRefInfo = segmentRef.info;
- var frag = levelDetails.fragments[index];
- if (frag.byteRange.length === 0) {
- frag.rawByteRange = String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start);
- }
- });
- levelDetails.initSegment.rawByteRange = String(sidxInfo.moovEndOffset) + '@0';
- }
- }, {
- key: '_handleManifestParsingError',
- value: function _handleManifestParsingError(response, context, reason, networkDetails) {
- this.hls.trigger(_events2.default.ERROR, {
- type: _errors.ErrorTypes.NETWORK_ERROR,
- details: _errors.ErrorDetails.MANIFEST_PARSING_ERROR,
- fatal: true,
- url: response.url,
- reason: reason,
- networkDetails: networkDetails
- });
- }
- }, {
- key: '_handleNetworkError',
- value: function _handleNetworkError(context, networkDetails) {
- var timeout = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
- var response = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
- _logger.logger.info('A network error occured while loading a ' + context.type + '-type playlist');
- var details = void 0;
- var fatal = void 0;
- var loader = this.getInternalLoader(context);
- switch (context.type) {
- case ContextType.MANIFEST:
- details = timeout ? _errors.ErrorDetails.MANIFEST_LOAD_TIMEOUT : _errors.ErrorDetails.MANIFEST_LOAD_ERROR;
- fatal = true;
- break;
- case ContextType.LEVEL:
- details = timeout ? _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT : _errors.ErrorDetails.LEVEL_LOAD_ERROR;
- fatal = false;
- break;
- case ContextType.AUDIO_TRACK:
- details = timeout ? _errors.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : _errors.ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
- fatal = false;
- break;
- default:
- // details = ...?
- fatal = false;
- }
- if (loader) {
- loader.abort();
- this.resetInternalLoader(context.type);
- }
- var errorData = {
- type: _errors.ErrorTypes.NETWORK_ERROR,
- details: details,
- fatal: fatal,
- url: loader.url,
- loader: loader,
- context: context,
- networkDetails: networkDetails
- };
- if (response) {
- errorData.response = response;
- }
- this.hls.trigger(_events2.default.ERROR, errorData);
- }
- }, {
- key: '_handlePlaylistLoaded',
- value: function _handlePlaylistLoaded(response, stats, context, networkDetails) {
- var type = context.type,
- level = context.level,
- id = context.id,
- levelDetails = context.levelDetails;
- if (!levelDetails.targetduration) {
- this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails);
- return;
- }
- var canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type);
- if (canHaveLevels) {
- this.hls.trigger(_events2.default.LEVEL_LOADED, {
- details: levelDetails,
- level: level || 0,
- id: id || 0,
- stats: stats,
- networkDetails: networkDetails
- });
- } else {
- switch (type) {
- case ContextType.AUDIO_TRACK:
- this.hls.trigger(_events2.default.AUDIO_TRACK_LOADED, {
- details: levelDetails,
- id: id,
- stats: stats,
- networkDetails: networkDetails
- });
- break;
- case ContextType.SUBTITLE_TRACK:
- this.hls.trigger(_events2.default.SUBTITLE_TRACK_LOADED, {
- details: levelDetails,
- id: id,
- stats: stats,
- networkDetails: networkDetails
- });
- break;
- }
- }
- }
- }], [{
- key: 'canHaveQualityLevels',
- /**
- * @param {ContextType} type
- * @returns {boolean}
- */
- value: function canHaveQualityLevels(type) {
- return type !== ContextType.AUDIO_TRACK && type !== ContextType.SUBTITLE_TRACK;
- }
- /**
- * Map context.type to LevelType
- * @param {{type: ContextType}} context
- * @returns {LevelType}
- */
- }, {
- key: 'mapContextToLevelType',
- value: function mapContextToLevelType(context) {
- var type = context.type;
- switch (type) {
- case ContextType.AUDIO_TRACK:
- return LevelType.AUDIO;
- case ContextType.SUBTITLE_TRACK:
- return LevelType.SUBTITLE;
- default:
- return LevelType.MAIN;
- }
- }
- }, {
- key: 'getResponseUrl',
- value: function getResponseUrl(response, context) {
- var url = response.url;
- // responseURL not supported on some browsers (it is used to detect URL redirection)
- // data-uri mode also not supported (but no need to detect redirection)
- if (url === undefined || url.indexOf('data:') === 0) {
- // fallback to initial URL
- url = context.url;
- }
- return url;
- }
- }, {
- key: 'ContextType',
- get: function get() {
- return ContextType;
- }
- }, {
- key: 'LevelType',
- get: function get() {
- return LevelType;
- }
- }]);
- return PlaylistLoader;
- }(_eventHandler2.default);
- exports.default = PlaylistLoader;
- module.exports = exports['default'];
- /***/ }),
- /* 16 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /**
- * MP4 demuxer
- */
- var _logger = __webpack_require__(0);
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var UINT32_MAX = Math.pow(2, 32) - 1;
- var MP4Demuxer = function () {
- function MP4Demuxer(observer, remuxer) {
- _classCallCheck(this, MP4Demuxer);
- this.observer = observer;
- this.remuxer = remuxer;
- }
- _createClass(MP4Demuxer, [{
- key: 'resetTimeStamp',
- value: function resetTimeStamp(initPTS) {
- this.initPTS = initPTS;
- }
- }, {
- key: 'resetInitSegment',
- value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
- // jshint unused:false
- if (initSegment && initSegment.byteLength) {
- var initData = this.initData = MP4Demuxer.parseInitSegment(initSegment);
- // default audio codec if nothing specified
- // TODO : extract that from initsegment
- if (audioCodec == null) {
- audioCodec = 'mp4a.40.5';
- }
- if (videoCodec == null) {
- videoCodec = 'avc1.42e01e';
- }
- var tracks = {};
- if (initData.audio && initData.video) {
- tracks.audiovideo = { container: 'video/mp4', codec: audioCodec + ',' + videoCodec, initSegment: duration ? initSegment : null };
- } else {
- if (initData.audio) {
- tracks.audio = { container: 'audio/mp4', codec: audioCodec, initSegment: duration ? initSegment : null };
- }
- if (initData.video) {
- tracks.video = { container: 'video/mp4', codec: videoCodec, initSegment: duration ? initSegment : null };
- }
- }
- this.observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, { tracks: tracks });
- } else {
- if (audioCodec) {
- this.audioCodec = audioCodec;
- }
- if (videoCodec) {
- this.videoCodec = videoCodec;
- }
- }
- }
- }, {
- key: 'append',
- // feed incoming data to the front of the parsing pipeline
- value: function append(data, timeOffset, contiguous, accurateTimeOffset) {
- var initData = this.initData;
- if (!initData) {
- this.resetInitSegment(data, this.audioCodec, this.videoCodec, false);
- initData = this.initData;
- }
- var startDTS = void 0,
- initPTS = this.initPTS;
- if (initPTS === undefined) {
- var _startDTS = MP4Demuxer.getStartDTS(initData, data);
- this.initPTS = initPTS = _startDTS - timeOffset;
- this.observer.trigger(_events2.default.INIT_PTS_FOUND, { initPTS: initPTS });
- }
- MP4Demuxer.offsetStartDTS(initData, data, initPTS);
- startDTS = MP4Demuxer.getStartDTS(initData, data);
- this.remuxer.remux(initData.audio, initData.video, null, null, startDTS, contiguous, accurateTimeOffset, data);
- }
- }, {
- key: 'destroy',
- value: function destroy() {}
- }], [{
- key: 'probe',
- value: function probe(data) {
- // ensure we find a moof box in the first 16 kB
- return MP4Demuxer.findBox({ data: data, start: 0, end: Math.min(data.length, 16384) }, ['moof']).length > 0;
- }
- }, {
- key: 'bin2str',
- value: function bin2str(buffer) {
- return String.fromCharCode.apply(null, buffer);
- }
- }, {
- key: 'readUint16',
- value: function readUint16(buffer, offset) {
- if (buffer.data) {
- offset += buffer.start;
- buffer = buffer.data;
- }
- var val = buffer[offset] << 8 | buffer[offset + 1];
- return val < 0 ? 65536 + val : val;
- }
- }, {
- key: 'readUint32',
- value: function readUint32(buffer, offset) {
- if (buffer.data) {
- offset += buffer.start;
- buffer = buffer.data;
- }
- var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
- return val < 0 ? 4294967296 + val : val;
- }
- }, {
- key: 'writeUint32',
- value: function writeUint32(buffer, offset, value) {
- if (buffer.data) {
- offset += buffer.start;
- buffer = buffer.data;
- }
- buffer[offset] = value >> 24;
- buffer[offset + 1] = value >> 16 & 0xff;
- buffer[offset + 2] = value >> 8 & 0xff;
- buffer[offset + 3] = value & 0xff;
- }
- // Find the data for a box specified by its path
- }, {
- key: 'findBox',
- value: function findBox(data, path) {
- var results = [],
- i = void 0,
- size = void 0,
- type = void 0,
- end = void 0,
- subresults = void 0,
- start = void 0,
- endbox = void 0;
- if (data.data) {
- start = data.start;
- end = data.end;
- data = data.data;
- } else {
- start = 0;
- end = data.byteLength;
- }
- if (!path.length) {
- // short-circuit the search for empty paths
- return null;
- }
- for (i = start; i < end;) {
- size = MP4Demuxer.readUint32(data, i);
- type = MP4Demuxer.bin2str(data.subarray(i + 4, i + 8));
- endbox = size > 1 ? i + size : end;
- if (type === path[0]) {
- if (path.length === 1) {
- // this is the end of the path and we've found the box we were
- // looking for
- results.push({ data: data, start: i + 8, end: endbox });
- } else {
- // recursively search for the next box along the path
- subresults = MP4Demuxer.findBox({ data: data, start: i + 8, end: endbox }, path.slice(1));
- if (subresults.length) {
- results = results.concat(subresults);
- }
- }
- }
- i = endbox;
- }
- // we've finished searching all of data
- return results;
- }
- }, {
- key: 'parseSegmentIndex',
- value: function parseSegmentIndex(initSegment) {
- var moov = MP4Demuxer.findBox(initSegment, ['moov'])[0];
- var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data
- var index = 0;
- var sidx = MP4Demuxer.findBox(initSegment, ['sidx']);
- var references = void 0;
- if (!sidx || !sidx[0]) {
- return null;
- }
- references = [];
- sidx = sidx[0];
- var version = sidx.data[0];
- // set initial offset, we skip the reference ID (not needed)
- index = version === 0 ? 8 : 16;
- var timescale = MP4Demuxer.readUint32(sidx, index);
- index += 4;
- // TODO: parse earliestPresentationTime and firstOffset
- // usually zero in our case
- var earliestPresentationTime = 0;
- var firstOffset = 0;
- if (version === 0) {
- index += 8;
- } else {
- index += 16;
- }
- // skip reserved
- index += 2;
- var startByte = sidx.end + firstOffset;
- var referencesCount = MP4Demuxer.readUint16(sidx, index);
- index += 2;
- for (var i = 0; i < referencesCount; i++) {
- var referenceIndex = index;
- var referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex);
- referenceIndex += 4;
- var referenceSize = referenceInfo & 0x7FFFFFFF;
- var referenceType = (referenceInfo & 0x80000000) >>> 31;
- if (referenceType === 1) {
- console.warn('SIDX has hierarchical references (not supported)');
- return;
- }
- var subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex);
- referenceIndex += 4;
- references.push({
- referenceSize: referenceSize,
- subsegmentDuration: subsegmentDuration, // unscaled
- info: {
- duration: subsegmentDuration / timescale,
- start: startByte,
- end: startByte + referenceSize - 1
- }
- });
- startByte += referenceSize;
- // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
- // for |sapDelta|.
- referenceIndex += 4;
- // skip to next ref
- index = referenceIndex;
- }
- return {
- earliestPresentationTime: earliestPresentationTime,
- timescale: timescale,
- version: version,
- referencesCount: referencesCount,
- references: references,
- moovEndOffset: moovEndOffset
- };
- }
- /**
- * Parses an MP4 initialization segment and extracts stream type and
- * timescale values for any declared tracks. Timescale values indicate the
- * number of clock ticks per second to assume for time-based values
- * elsewhere in the MP4.
- *
- * To determine the start time of an MP4, you need two pieces of
- * information: the timescale unit and the earliest base media decode
- * time. Multiple timescales can be specified within an MP4 but the
- * base media decode time is always expressed in the timescale from
- * the media header box for the track:
- * ```
- * moov > trak > mdia > mdhd.timescale
- * moov > trak > mdia > hdlr
- * ```
- * @param init {Uint8Array} the bytes of the init segment
- * @return {object} a hash of track type to timescale values or null if
- * the init segment is malformed.
- */
- }, {
- key: 'parseInitSegment',
- value: function parseInitSegment(initSegment) {
- var result = [];
- var traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']);
- traks.forEach(function (trak) {
- var tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0];
- if (tkhd) {
- var version = tkhd.data[tkhd.start];
- var index = version === 0 ? 12 : 20;
- var trackId = MP4Demuxer.readUint32(tkhd, index);
- var mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0];
- if (mdhd) {
- version = mdhd.data[mdhd.start];
- index = version === 0 ? 12 : 20;
- var timescale = MP4Demuxer.readUint32(mdhd, index);
- var hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0];
- if (hdlr) {
- var hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));
- var type = { 'soun': 'audio', 'vide': 'video' }[hdlrType];
- if (type) {
- // extract codec info. TODO : parse codec details to be able to build MIME type
- var codecBox = MP4Demuxer.findBox(trak, ['mdia', 'minf', 'stbl', 'stsd']);
- if (codecBox.length) {
- codecBox = codecBox[0];
- var codecType = MP4Demuxer.bin2str(codecBox.data.subarray(codecBox.start + 12, codecBox.start + 16));
- _logger.logger.log('MP4Demuxer:' + type + ':' + codecType + ' found');
- }
- result[trackId] = { timescale: timescale, type: type };
- result[type] = { timescale: timescale, id: trackId };
- }
- }
- }
- }
- });
- return result;
- }
- /**
- * Determine the base media decode start time, in seconds, for an MP4
- * fragment. If multiple fragments are specified, the earliest time is
- * returned.
- *
- * The base media decode time can be parsed from track fragment
- * metadata:
- * ```
- * moof > traf > tfdt.baseMediaDecodeTime
- * ```
- * It requires the timescale value from the mdhd to interpret.
- *
- * @param timescale {object} a hash of track ids to timescale values.
- * @return {number} the earliest base media decode start time for the
- * fragment, in seconds
- */
- }, {
- key: 'getStartDTS',
- value: function getStartDTS(initData, fragment) {
- var trafs = void 0,
- baseTimes = void 0,
- result = void 0;
- // we need info from two childrend of each track fragment box
- trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']);
- // determine the start times for each track
- baseTimes = [].concat.apply([], trafs.map(function (traf) {
- return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
- var id = void 0,
- scale = void 0,
- baseTime = void 0;
- // get the track id from the tfhd
- id = MP4Demuxer.readUint32(tfhd, 4);
- // assume a 90kHz clock if no timescale was specified
- scale = initData[id].timescale || 90e3;
- // get the base media decode time from the tfdt
- baseTime = MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
- var version = void 0,
- result = void 0;
- version = tfdt.data[tfdt.start];
- result = MP4Demuxer.readUint32(tfdt, 4);
- if (version === 1) {
- result *= Math.pow(2, 32);
- result += MP4Demuxer.readUint32(tfdt, 8);
- }
- return result;
- })[0];
- // convert base time to seconds
- return baseTime / scale;
- });
- }));
- // return the minimum
- result = Math.min.apply(null, baseTimes);
- return isFinite(result) ? result : 0;
- }
- }, {
- key: 'offsetStartDTS',
- value: function offsetStartDTS(initData, fragment, timeOffset) {
- MP4Demuxer.findBox(fragment, ['moof', 'traf']).map(function (traf) {
- return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
- // get the track id from the tfhd
- var id = MP4Demuxer.readUint32(tfhd, 4);
- // assume a 90kHz clock if no timescale was specified
- var timescale = initData[id].timescale || 90e3;
- // get the base media decode time from the tfdt
- MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
- var version = tfdt.data[tfdt.start];
- var baseMediaDecodeTime = MP4Demuxer.readUint32(tfdt, 4);
- if (version === 0) {
- MP4Demuxer.writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);
- } else {
- baseMediaDecodeTime *= Math.pow(2, 32);
- baseMediaDecodeTime += MP4Demuxer.readUint32(tfdt, 8);
- baseMediaDecodeTime -= timeOffset * timescale;
- baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
- var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
- var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
- MP4Demuxer.writeUint32(tfdt, 4, upper);
- MP4Demuxer.writeUint32(tfdt, 8, lower);
- }
- });
- });
- });
- }
- }]);
- return MP4Demuxer;
- }();
- exports.default = MP4Demuxer;
- module.exports = exports['default'];
- /***/ }),
- /* 17 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _urlToolkit = __webpack_require__(8);
- var URLToolkit = _interopRequireWildcard(_urlToolkit);
- 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; } }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var LevelKey = function () {
- function LevelKey() {
- _classCallCheck(this, LevelKey);
- this.method = null;
- this.key = null;
- this.iv = null;
- this._uri = null;
- }
- _createClass(LevelKey, [{
- key: 'uri',
- get: function get() {
- if (!this._uri && this.reluri) {
- this._uri = URLToolkit.buildAbsoluteURL(this.baseuri, this.reluri, { alwaysNormalize: true });
- }
- return this._uri;
- }
- }]);
- return LevelKey;
- }();
- exports.default = LevelKey;
- module.exports = exports['default'];
- /***/ }),
- /* 18 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- // from http://mp4ra.org/codecs.html
- var sampleEntryCodesISO = {
- audio: {
- 'a3ds': true,
- 'ac-3': true,
- 'ac-4': true,
- 'alac': true,
- 'alaw': true,
- 'dra1': true,
- 'dts+': true,
- 'dts-': true,
- 'dtsc': true,
- 'dtse': true,
- 'dtsh': true,
- 'ec-3': true,
- 'enca': true,
- 'g719': true,
- 'g726': true,
- 'm4ae': true,
- 'mha1': true,
- 'mha2': true,
- 'mhm1': true,
- 'mhm2': true,
- 'mlpa': true,
- 'mp4a': true,
- 'raw ': true,
- 'Opus': true,
- 'samr': true,
- 'sawb': true,
- 'sawp': true,
- 'sevc': true,
- 'sqcp': true,
- 'ssmv': true,
- 'twos': true,
- 'ulaw': true
- },
- video: {
- 'avc1': true,
- 'avc2': true,
- 'avc3': true,
- 'avc4': true,
- 'avcp': true,
- 'drac': true,
- 'dvav': true,
- 'dvhe': true,
- 'encv': true,
- 'hev1': true,
- 'hvc1': true,
- 'mjp2': true,
- 'mp4v': true,
- 'mvc1': true,
- 'mvc2': true,
- 'mvc3': true,
- 'mvc4': true,
- 'resv': true,
- 'rv60': true,
- 's263': true,
- 'svc1': true,
- 'svc2': true,
- 'vc-1': true,
- 'vp08': true,
- 'vp09': true
- }
- };
- function isCodecType(codec, type) {
- var typeCodes = sampleEntryCodesISO[type];
- return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;
- }
- function isCodecSupportedInMp4(codec, type) {
- return window.MediaSource.isTypeSupported((type || 'video') + '/mp4;codecs="' + codec + '"');
- }
- exports.isCodecType = isCodecType;
- exports.isCodecSupportedInMp4 = isCodecSupportedInMp4;
- /***/ }),
- /* 19 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _events = __webpack_require__(20);
- var _webworkifyWebpack = __webpack_require__(41);
- var work = _interopRequireWildcard(_webworkifyWebpack);
- var _events2 = __webpack_require__(1);
- var _events3 = _interopRequireDefault(_events2);
- var _demuxerInline = __webpack_require__(21);
- var _demuxerInline2 = _interopRequireDefault(_demuxerInline);
- var _logger = __webpack_require__(0);
- var _errors = __webpack_require__(2);
- var _mediasourceHelper = __webpack_require__(13);
- var _getSelfScope = __webpack_require__(5);
- var _observer = __webpack_require__(24);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- 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; } }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- // see https://stackoverflow.com/a/11237259/589493
- var global = (0, _getSelfScope.getSelfScope)(); // safeguard for code that might run both on worker and main thread
- var MediaSource = (0, _mediasourceHelper.getMediaSource)();
- var Demuxer = function () {
- function Demuxer(hls, id) {
- var _this = this;
- _classCallCheck(this, Demuxer);
- this.hls = hls;
- this.id = id;
- var observer = this.observer = new _observer.Observer();
- var config = hls.config;
- var forwardMessage = function forwardMessage(ev, data) {
- data = data || {};
- data.frag = _this.frag;
- data.id = _this.id;
- hls.trigger(ev, data);
- };
- // forward events to main thread
- observer.on(_events3.default.FRAG_DECRYPTED, forwardMessage);
- observer.on(_events3.default.FRAG_PARSING_INIT_SEGMENT, forwardMessage);
- observer.on(_events3.default.FRAG_PARSING_DATA, forwardMessage);
- observer.on(_events3.default.FRAG_PARSED, forwardMessage);
- observer.on(_events3.default.ERROR, forwardMessage);
- observer.on(_events3.default.FRAG_PARSING_METADATA, forwardMessage);
- observer.on(_events3.default.FRAG_PARSING_USERDATA, forwardMessage);
- observer.on(_events3.default.INIT_PTS_FOUND, forwardMessage);
- var typeSupported = {
- mp4: MediaSource.isTypeSupported('video/mp4'),
- mpeg: MediaSource.isTypeSupported('audio/mpeg'),
- mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"')
- };
- // navigator.vendor is not always available in Web Worker
- // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator
- var vendor = navigator.vendor;
- if (config.enableWorker && typeof Worker !== 'undefined') {
- _logger.logger.log('demuxing in webworker');
- var w = void 0;
- try {
- w = this.w = work(/*require.resolve*/(55));
- this.onwmsg = this.onWorkerMessage.bind(this);
- w.addEventListener('message', this.onwmsg);
- w.onerror = function (event) {
- 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 + ')' } });
- };
- w.postMessage({ cmd: 'init', typeSupported: typeSupported, vendor: vendor, id: id, config: JSON.stringify(config) });
- } catch (err) {
- _logger.logger.warn('Error in worker:', err);
- _logger.logger.error('Error while initializing DemuxerWorker, fallback on DemuxerInline');
- if (w) {
- // revoke the Object URL that was used to create demuxer worker, so as not to leak it
- global.URL.revokeObjectURL(w.objectURL);
- }
- this.demuxer = new _demuxerInline2.default(observer, typeSupported, config, vendor);
- this.w = undefined;
- }
- } else {
- this.demuxer = new _demuxerInline2.default(observer, typeSupported, config, vendor);
- }
- }
- _createClass(Demuxer, [{
- key: 'destroy',
- value: function destroy() {
- var w = this.w;
- if (w) {
- w.removeEventListener('message', this.onwmsg);
- w.terminate();
- this.w = null;
- } else {
- var demuxer = this.demuxer;
- if (demuxer) {
- demuxer.destroy();
- this.demuxer = null;
- }
- }
- var observer = this.observer;
- if (observer) {
- observer.removeAllListeners();
- this.observer = null;
- }
- }
- }, {
- key: 'push',
- value: function push(data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) {
- var w = this.w;
- var timeOffset = Number.isFinite(frag.startPTS) ? frag.startPTS : frag.start;
- var decryptdata = frag.decryptdata;
- var lastFrag = this.frag;
- var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
- var trackSwitch = !(lastFrag && frag.level === lastFrag.level);
- var nextSN = lastFrag && frag.sn === lastFrag.sn + 1;
- var contiguous = !trackSwitch && nextSN;
- if (discontinuity) {
- _logger.logger.log(this.id + ':discontinuity detected');
- }
- if (trackSwitch) {
- _logger.logger.log(this.id + ':switch detected');
- }
- this.frag = frag;
- if (w) {
- // post fragment payload as transferable objects for ArrayBuffer (no copy)
- 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] : []);
- } else {
- var demuxer = this.demuxer;
- if (demuxer) {
- demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
- }
- }
- }
- }, {
- key: 'onWorkerMessage',
- value: function onWorkerMessage(ev) {
- var data = ev.data,
- hls = this.hls;
- switch (data.event) {
- case 'init':
- // revoke the Object URL that was used to create demuxer worker, so as not to leak it
- global.URL.revokeObjectURL(this.w.objectURL);
- break;
- // special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects
- case _events3.default.FRAG_PARSING_DATA:
- data.data.data1 = new Uint8Array(data.data1);
- if (data.data2) {
- data.data.data2 = new Uint8Array(data.data2);
- }
- /* falls through */
- default:
- data.data = data.data || {};
- data.data.frag = this.frag;
- data.data.id = this.id;
- hls.trigger(data.event, data.data);
- break;
- }
- }
- }]);
- return Demuxer;
- }();
- exports.default = Demuxer;
- module.exports = exports['default'];
- /***/ }),
- /* 20 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- var R = typeof Reflect === 'object' ? Reflect : null
- var ReflectApply = R && typeof R.apply === 'function'
- ? R.apply
- : function ReflectApply(target, receiver, args) {
- return Function.prototype.apply.call(target, receiver, args);
- }
- var ReflectOwnKeys
- if (R && typeof R.ownKeys === 'function') {
- ReflectOwnKeys = R.ownKeys
- } else if (Object.getOwnPropertySymbols) {
- ReflectOwnKeys = function ReflectOwnKeys(target) {
- return Object.getOwnPropertyNames(target)
- .concat(Object.getOwnPropertySymbols(target));
- };
- } else {
- ReflectOwnKeys = function ReflectOwnKeys(target) {
- return Object.getOwnPropertyNames(target);
- };
- }
- function ProcessEmitWarning(warning) {
- if (console && console.warn) console.warn(warning);
- }
- var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
- return value !== value;
- }
- function EventEmitter() {
- EventEmitter.init.call(this);
- }
- module.exports = EventEmitter;
- // Backwards-compat with node 0.10.x
- EventEmitter.EventEmitter = EventEmitter;
- EventEmitter.prototype._events = undefined;
- EventEmitter.prototype._eventsCount = 0;
- EventEmitter.prototype._maxListeners = undefined;
- // By default EventEmitters will print a warning if more than 10 listeners are
- // added to it. This is a useful default which helps finding memory leaks.
- var defaultMaxListeners = 10;
- function checkListener(listener) {
- if (typeof listener !== 'function') {
- throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
- }
- }
- Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
- enumerable: true,
- get: function() {
- return defaultMaxListeners;
- },
- set: function(arg) {
- if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
- throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
- }
- defaultMaxListeners = arg;
- }
- });
- EventEmitter.init = function() {
- if (this._events === undefined ||
- this._events === Object.getPrototypeOf(this)._events) {
- this._events = Object.create(null);
- this._eventsCount = 0;
- }
- this._maxListeners = this._maxListeners || undefined;
- };
- // Obviously not all Emitters should be limited to 10. This function allows
- // that to be increased. Set to zero for unlimited.
- EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
- if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
- throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
- }
- this._maxListeners = n;
- return this;
- };
- function _getMaxListeners(that) {
- if (that._maxListeners === undefined)
- return EventEmitter.defaultMaxListeners;
- return that._maxListeners;
- }
- EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
- return _getMaxListeners(this);
- };
- EventEmitter.prototype.emit = function emit(type) {
- var args = [];
- for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
- var doError = (type === 'error');
- var events = this._events;
- if (events !== undefined)
- doError = (doError && events.error === undefined);
- else if (!doError)
- return false;
- // If there is no 'error' event listener then throw.
- if (doError) {
- var er;
- if (args.length > 0)
- er = args[0];
- if (er instanceof Error) {
- // Note: The comments on the `throw` lines are intentional, they show
- // up in Node's output if this results in an unhandled exception.
- throw er; // Unhandled 'error' event
- }
- // At least give some kind of context to the user
- var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
- err.context = er;
- throw err; // Unhandled 'error' event
- }
- var handler = events[type];
- if (handler === undefined)
- return false;
- if (typeof handler === 'function') {
- ReflectApply(handler, this, args);
- } else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- ReflectApply(listeners[i], this, args);
- }
- return true;
- };
- function _addListener(target, type, listener, prepend) {
- var m;
- var events;
- var existing;
- checkListener(listener);
- events = target._events;
- if (events === undefined) {
- events = target._events = Object.create(null);
- target._eventsCount = 0;
- } else {
- // To avoid recursion in the case that type === "newListener"! Before
- // adding it to the listeners, first emit "newListener".
- if (events.newListener !== undefined) {
- target.emit('newListener', type,
- listener.listener ? listener.listener : listener);
- // Re-assign `events` because a newListener handler could have caused the
- // this._events to be assigned to a new object
- events = target._events;
- }
- existing = events[type];
- }
- if (existing === undefined) {
- // Optimize the case of one listener. Don't need the extra array object.
- existing = events[type] = listener;
- ++target._eventsCount;
- } else {
- if (typeof existing === 'function') {
- // Adding the second element, need to change to array.
- existing = events[type] =
- prepend ? [listener, existing] : [existing, listener];
- // If we've already got an array, just append.
- } else if (prepend) {
- existing.unshift(listener);
- } else {
- existing.push(listener);
- }
- // Check for listener leak
- m = _getMaxListeners(target);
- if (m > 0 && existing.length > m && !existing.warned) {
- existing.warned = true;
- // No error code for this since it is a Warning
- // eslint-disable-next-line no-restricted-syntax
- var w = new Error('Possible EventEmitter memory leak detected. ' +
- existing.length + ' ' + String(type) + ' listeners ' +
- 'added. Use emitter.setMaxListeners() to ' +
- 'increase limit');
- w.name = 'MaxListenersExceededWarning';
- w.emitter = target;
- w.type = type;
- w.count = existing.length;
- ProcessEmitWarning(w);
- }
- }
- return target;
- }
- EventEmitter.prototype.addListener = function addListener(type, listener) {
- return _addListener(this, type, listener, false);
- };
- EventEmitter.prototype.on = EventEmitter.prototype.addListener;
- EventEmitter.prototype.prependListener =
- function prependListener(type, listener) {
- return _addListener(this, type, listener, true);
- };
- function onceWrapper() {
- if (!this.fired) {
- this.target.removeListener(this.type, this.wrapFn);
- this.fired = true;
- if (arguments.length === 0)
- return this.listener.call(this.target);
- return this.listener.apply(this.target, arguments);
- }
- }
- function _onceWrap(target, type, listener) {
- var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
- var wrapped = onceWrapper.bind(state);
- wrapped.listener = listener;
- state.wrapFn = wrapped;
- return wrapped;
- }
- EventEmitter.prototype.once = function once(type, listener) {
- checkListener(listener);
- this.on(type, _onceWrap(this, type, listener));
- return this;
- };
- EventEmitter.prototype.prependOnceListener =
- function prependOnceListener(type, listener) {
- checkListener(listener);
- this.prependListener(type, _onceWrap(this, type, listener));
- return this;
- };
- // Emits a 'removeListener' event if and only if the listener was removed.
- EventEmitter.prototype.removeListener =
- function removeListener(type, listener) {
- var list, events, position, i, originalListener;
- checkListener(listener);
- events = this._events;
- if (events === undefined)
- return this;
- list = events[type];
- if (list === undefined)
- return this;
- if (list === listener || list.listener === listener) {
- if (--this._eventsCount === 0)
- this._events = Object.create(null);
- else {
- delete events[type];
- if (events.removeListener)
- this.emit('removeListener', type, list.listener || listener);
- }
- } else if (typeof list !== 'function') {
- position = -1;
- for (i = list.length - 1; i >= 0; i--) {
- if (list[i] === listener || list[i].listener === listener) {
- originalListener = list[i].listener;
- position = i;
- break;
- }
- }
- if (position < 0)
- return this;
- if (position === 0)
- list.shift();
- else {
- spliceOne(list, position);
- }
- if (list.length === 1)
- events[type] = list[0];
- if (events.removeListener !== undefined)
- this.emit('removeListener', type, originalListener || listener);
- }
- return this;
- };
- EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
- EventEmitter.prototype.removeAllListeners =
- function removeAllListeners(type) {
- var listeners, events, i;
- events = this._events;
- if (events === undefined)
- return this;
- // not listening for removeListener, no need to emit
- if (events.removeListener === undefined) {
- if (arguments.length === 0) {
- this._events = Object.create(null);
- this._eventsCount = 0;
- } else if (events[type] !== undefined) {
- if (--this._eventsCount === 0)
- this._events = Object.create(null);
- else
- delete events[type];
- }
- return this;
- }
- // emit removeListener for all listeners on all events
- if (arguments.length === 0) {
- var keys = Object.keys(events);
- var key;
- for (i = 0; i < keys.length; ++i) {
- key = keys[i];
- if (key === 'removeListener') continue;
- this.removeAllListeners(key);
- }
- this.removeAllListeners('removeListener');
- this._events = Object.create(null);
- this._eventsCount = 0;
- return this;
- }
- listeners = events[type];
- if (typeof listeners === 'function') {
- this.removeListener(type, listeners);
- } else if (listeners !== undefined) {
- // LIFO order
- for (i = listeners.length - 1; i >= 0; i--) {
- this.removeListener(type, listeners[i]);
- }
- }
- return this;
- };
- function _listeners(target, type, unwrap) {
- var events = target._events;
- if (events === undefined)
- return [];
- var evlistener = events[type];
- if (evlistener === undefined)
- return [];
- if (typeof evlistener === 'function')
- return unwrap ? [evlistener.listener || evlistener] : [evlistener];
- return unwrap ?
- unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
- }
- EventEmitter.prototype.listeners = function listeners(type) {
- return _listeners(this, type, true);
- };
- EventEmitter.prototype.rawListeners = function rawListeners(type) {
- return _listeners(this, type, false);
- };
- EventEmitter.listenerCount = function(emitter, type) {
- if (typeof emitter.listenerCount === 'function') {
- return emitter.listenerCount(type);
- } else {
- return listenerCount.call(emitter, type);
- }
- };
- EventEmitter.prototype.listenerCount = listenerCount;
- function listenerCount(type) {
- var events = this._events;
- if (events !== undefined) {
- var evlistener = events[type];
- if (typeof evlistener === 'function') {
- return 1;
- } else if (evlistener !== undefined) {
- return evlistener.length;
- }
- }
- return 0;
- }
- EventEmitter.prototype.eventNames = function eventNames() {
- return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
- };
- function arrayClone(arr, n) {
- var copy = new Array(n);
- for (var i = 0; i < n; ++i)
- copy[i] = arr[i];
- return copy;
- }
- function spliceOne(list, index) {
- for (; index + 1 < list.length; index++)
- list[index] = list[index + 1];
- list.pop();
- }
- function unwrapListeners(arr) {
- var ret = new Array(arr.length);
- for (var i = 0; i < ret.length; ++i) {
- ret[i] = arr[i].listener || arr[i];
- }
- return ret;
- }
- /***/ }),
- /* 21 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /**
- *
- * inline demuxer: probe fragments and instantiate
- * appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)
- *
- */
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _errors = __webpack_require__(2);
- var _decrypter = __webpack_require__(12);
- var _decrypter2 = _interopRequireDefault(_decrypter);
- var _aacdemuxer = __webpack_require__(45);
- var _aacdemuxer2 = _interopRequireDefault(_aacdemuxer);
- var _mp4demuxer = __webpack_require__(16);
- var _mp4demuxer2 = _interopRequireDefault(_mp4demuxer);
- var _tsdemuxer = __webpack_require__(46);
- var _tsdemuxer2 = _interopRequireDefault(_tsdemuxer);
- var _mp3demuxer = __webpack_require__(49);
- var _mp3demuxer2 = _interopRequireDefault(_mp3demuxer);
- var _mp4Remuxer = __webpack_require__(50);
- var _mp4Remuxer2 = _interopRequireDefault(_mp4Remuxer);
- var _passthroughRemuxer = __webpack_require__(53);
- var _passthroughRemuxer2 = _interopRequireDefault(_passthroughRemuxer);
- var _getSelfScope = __webpack_require__(5);
- var _logger = __webpack_require__(0);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- // see https://stackoverflow.com/a/11237259/589493
- var global = (0, _getSelfScope.getSelfScope)(); // safeguard for code that might run both on worker and main thread
- var now = void 0;
- // performance.now() not available on WebWorker, at least on Safari Desktop
- try {
- now = global.performance.now.bind(global.performance);
- } catch (err) {
- _logger.logger.debug('Unable to use Performance API on this environment');
- now = global.Date.now;
- }
- var DemuxerInline = function () {
- function DemuxerInline(observer, typeSupported, config, vendor) {
- _classCallCheck(this, DemuxerInline);
- this.observer = observer;
- this.typeSupported = typeSupported;
- this.config = config;
- this.vendor = vendor;
- }
- _createClass(DemuxerInline, [{
- key: 'destroy',
- value: function destroy() {
- var demuxer = this.demuxer;
- if (demuxer) {
- demuxer.destroy();
- }
- }
- }, {
- key: 'push',
- value: function push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
- var _this = this;
- if (data.byteLength > 0 && decryptdata != null && decryptdata.key != null && decryptdata.method === 'AES-128') {
- var decrypter = this.decrypter;
- if (decrypter == null) {
- decrypter = this.decrypter = new _decrypter2.default(this.observer, this.config);
- }
- var startTime = now();
- decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) {
- var endTime = now();
- _this.observer.trigger(_events2.default.FRAG_DECRYPTED, { stats: { tstart: startTime, tdecrypt: endTime } });
- _this.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
- });
- } else {
- this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
- }
- }
- }, {
- key: 'pushDecrypted',
- value: function pushDecrypted(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
- var demuxer = this.demuxer;
- if (!demuxer ||
- // in case of continuity change, or track switch
- // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
- // so let's check that current demuxer is still valid
- (discontinuity || trackSwitch) && !this.probe(data)) {
- var observer = this.observer;
- var typeSupported = this.typeSupported;
- var config = this.config;
- // probing order is TS/AAC/MP3/MP4
- 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 }];
- // probe for content type
- for (var i = 0, len = muxConfig.length; i < len; i++) {
- var mux = muxConfig[i];
- var probe = mux.demux.probe;
- if (probe(data)) {
- var _remuxer = this.remuxer = new mux.remux(observer, config, typeSupported, this.vendor);
- demuxer = new mux.demux(observer, _remuxer, config, typeSupported);
- this.probe = probe;
- break;
- }
- }
- if (!demuxer) {
- 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' });
- return;
- }
- this.demuxer = demuxer;
- }
- var remuxer = this.remuxer;
- if (discontinuity || trackSwitch) {
- demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration);
- remuxer.resetInitSegment();
- }
- if (discontinuity) {
- demuxer.resetTimeStamp(defaultInitPTS);
- remuxer.resetTimeStamp(defaultInitPTS);
- }
- if (typeof demuxer.setDecryptData === 'function') {
- demuxer.setDecryptData(decryptdata);
- }
- demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);
- }
- }]);
- return DemuxerInline;
- }();
- exports.default = DemuxerInline;
- module.exports = exports['default'];
- /***/ }),
- /* 22 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getAudioConfig = getAudioConfig;
- exports.isHeaderPattern = isHeaderPattern;
- exports.getHeaderLength = getHeaderLength;
- exports.getFullFrameLength = getFullFrameLength;
- exports.isHeader = isHeader;
- exports.probe = probe;
- exports.initTrackConfig = initTrackConfig;
- exports.getFrameDuration = getFrameDuration;
- exports.parseFrameHeader = parseFrameHeader;
- exports.appendFrame = appendFrame;
- var _logger = __webpack_require__(0);
- var _errors = __webpack_require__(2);
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _getSelfScope = __webpack_require__(5);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * ADTS parser helper
- */
- function getAudioConfig(observer, data, offset, audioCodec) {
- var adtsObjectType = void 0,
- // :int
- adtsSampleingIndex = void 0,
- // :int
- adtsExtensionSampleingIndex = void 0,
- // :int
- adtsChanelConfig = void 0,
- // :int
- config = void 0,
- userAgent = navigator.userAgent.toLowerCase(),
- manifestCodec = audioCodec,
- adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
- // byte 2
- adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1;
- adtsSampleingIndex = (data[offset + 2] & 0x3C) >>> 2;
- if (adtsSampleingIndex > adtsSampleingRates.length - 1) {
- observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'invalid ADTS sampling index:' + adtsSampleingIndex });
- return;
- }
- adtsChanelConfig = (data[offset + 2] & 0x01) << 2;
- // byte 3
- adtsChanelConfig |= (data[offset + 3] & 0xC0) >>> 6;
- _logger.logger.log('manifest codec:' + audioCodec + ',ADTS data:type:' + adtsObjectType + ',sampleingIndex:' + adtsSampleingIndex + '[' + adtsSampleingRates[adtsSampleingIndex] + 'Hz],channelConfig:' + adtsChanelConfig);
- // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
- if (/firefox/i.test(userAgent)) {
- if (adtsSampleingIndex >= 6) {
- adtsObjectType = 5;
- config = new Array(4);
- // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
- // there is a factor 2 between frame sample rate and output sample rate
- // multiply frequency by 2 (see table below, equivalent to substract 3)
- adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
- } else {
- adtsObjectType = 2;
- config = new Array(2);
- adtsExtensionSampleingIndex = adtsSampleingIndex;
- }
- // Android : always use AAC
- } else if (userAgent.indexOf('android') !== -1) {
- adtsObjectType = 2;
- config = new Array(2);
- adtsExtensionSampleingIndex = adtsSampleingIndex;
- } else {
- /* for other browsers (Chrome/Vivaldi/Opera ...)
- always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
- */
- adtsObjectType = 5;
- config = new Array(4);
- // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
- if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSampleingIndex >= 6) {
- // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
- // there is a factor 2 between frame sample rate and output sample rate
- // multiply frequency by 2 (see table below, equivalent to substract 3)
- adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
- } else {
- // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
- // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
- if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSampleingIndex >= 6 && adtsChanelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChanelConfig === 1) {
- adtsObjectType = 2;
- config = new Array(2);
- }
- adtsExtensionSampleingIndex = adtsSampleingIndex;
- }
- }
- /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
- ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
- Audio Profile / Audio Object Type
- 0: Null
- 1: AAC Main
- 2: AAC LC (Low Complexity)
- 3: AAC SSR (Scalable Sample Rate)
- 4: AAC LTP (Long Term Prediction)
- 5: SBR (Spectral Band Replication)
- 6: AAC Scalable
- sampling freq
- 0: 96000 Hz
- 1: 88200 Hz
- 2: 64000 Hz
- 3: 48000 Hz
- 4: 44100 Hz
- 5: 32000 Hz
- 6: 24000 Hz
- 7: 22050 Hz
- 8: 16000 Hz
- 9: 12000 Hz
- 10: 11025 Hz
- 11: 8000 Hz
- 12: 7350 Hz
- 13: Reserved
- 14: Reserved
- 15: frequency is written explictly
- Channel Configurations
- These are the channel configurations:
- 0: Defined in AOT Specifc Config
- 1: 1 channel: front-center
- 2: 2 channels: front-left, front-right
- */
- // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
- config[0] = adtsObjectType << 3;
- // samplingFrequencyIndex
- config[0] |= (adtsSampleingIndex & 0x0E) >> 1;
- config[1] |= (adtsSampleingIndex & 0x01) << 7;
- // channelConfiguration
- config[1] |= adtsChanelConfig << 3;
- if (adtsObjectType === 5) {
- // adtsExtensionSampleingIndex
- config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1;
- config[2] = (adtsExtensionSampleingIndex & 0x01) << 7;
- // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
- // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
- config[2] |= 2 << 2;
- config[3] = 0;
- }
- return { config: config, samplerate: adtsSampleingRates[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: 'mp4a.40.' + adtsObjectType, manifestCodec: manifestCodec };
- }
- function isHeaderPattern(data, offset) {
- return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
- }
- function getHeaderLength(data, offset) {
- return data[offset + 1] & 0x01 ? 7 : 9;
- }
- function getFullFrameLength(data, offset) {
- return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;
- }
- function isHeader(data, offset) {
- // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
- // Layer bits (position 14 and 15) in header should be always 0 for ADTS
- // More info https://wiki.multimedia.cx/index.php?title=ADTS
- if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
- return true;
- }
- return false;
- }
- function probe(data, offset) {
- // same as isHeader but we also check that ADTS frame follows last ADTS frame
- // or end of data is reached
- if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
- // ADTS header Length
- var headerLength = getHeaderLength(data, offset);
- // ADTS frame Length
- var frameLength = headerLength;
- if (offset + 5 < data.length) {
- frameLength = getFullFrameLength(data, offset);
- }
- var newOffset = offset + frameLength;
- if (newOffset === data.length || newOffset + 1 < data.length && isHeaderPattern(data, newOffset)) {
- return true;
- }
- }
- return false;
- }
- function initTrackConfig(track, observer, data, offset, audioCodec) {
- if (!track.samplerate) {
- var config = getAudioConfig(observer, data, offset, audioCodec);
- track.config = config.config;
- track.samplerate = config.samplerate;
- track.channelCount = config.channelCount;
- track.codec = config.codec;
- track.manifestCodec = config.manifestCodec;
- _logger.logger.log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount);
- }
- }
- function getFrameDuration(samplerate) {
- return 1024 * 90000 / samplerate;
- }
- function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {
- var headerLength = void 0,
- frameLength = void 0,
- stamp = void 0;
- var length = data.length;
- // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
- headerLength = getHeaderLength(data, offset);
- // retrieve frame size
- frameLength = getFullFrameLength(data, offset);
- frameLength -= headerLength;
- if (frameLength > 0 && offset + headerLength + frameLength <= length) {
- stamp = pts + frameIndex * frameDuration;
- // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
- return { headerLength: headerLength, frameLength: frameLength, stamp: stamp };
- }
- return undefined;
- }
- function appendFrame(track, data, offset, pts, frameIndex) {
- var frameDuration = getFrameDuration(track.samplerate);
- var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);
- if (header) {
- var stamp = header.stamp;
- var headerLength = header.headerLength;
- var frameLength = header.frameLength;
- // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
- var aacSample = {
- unit: data.subarray(offset + headerLength, offset + headerLength + frameLength),
- pts: stamp,
- dts: stamp
- };
- track.samples.push(aacSample);
- track.len += frameLength;
- return { sample: aacSample, length: frameLength + headerLength };
- }
- return undefined;
- }
- /***/ }),
- /* 23 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- /**
- * MPEG parser helper
- */
- var MpegAudio = {
- 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],
- SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000],
- SamplesCoefficients: [
- // MPEG 2.5
- [0, // Reserved
- 72, // Layer3
- 144, // Layer2
- 12 // Layer1
- ],
- // Reserved
- [0, // Reserved
- 0, // Layer3
- 0, // Layer2
- 0 // Layer1
- ],
- // MPEG 2
- [0, // Reserved
- 72, // Layer3
- 144, // Layer2
- 12 // Layer1
- ],
- // MPEG 1
- [0, // Reserved
- 144, // Layer3
- 144, // Layer2
- 12 // Layer1
- ]],
- BytesInSlot: [0, // Reserved
- 1, // Layer3
- 1, // Layer2
- 4 // Layer1
- ],
- appendFrame: function appendFrame(track, data, offset, pts, frameIndex) {
- // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
- if (offset + 24 > data.length) {
- return undefined;
- }
- var header = this.parseHeader(data, offset);
- if (header && offset + header.frameLength <= data.length) {
- var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
- var stamp = pts + frameIndex * frameDuration;
- var sample = { unit: data.subarray(offset, offset + header.frameLength), pts: stamp, dts: stamp };
- track.config = [];
- track.channelCount = header.channelCount;
- track.samplerate = header.sampleRate;
- track.samples.push(sample);
- track.len += header.frameLength;
- return { sample: sample, length: header.frameLength };
- }
- return undefined;
- },
- parseHeader: function parseHeader(data, offset) {
- var headerB = data[offset + 1] >> 3 & 3;
- var headerC = data[offset + 1] >> 1 & 3;
- var headerE = data[offset + 2] >> 4 & 15;
- var headerF = data[offset + 2] >> 2 & 3;
- var headerG = data[offset + 2] >> 1 & 1;
- if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {
- var columnInBitrates = headerB === 3 ? 3 - headerC : headerC === 3 ? 3 : 4;
- var bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;
- var columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;
- var sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];
- var channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
- var sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];
- var bytesInSlot = MpegAudio.BytesInSlot[headerC];
- var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
- var frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot;
- return { sampleRate: sampleRate, channelCount: channelCount, frameLength: frameLength, samplesPerFrame: samplesPerFrame };
- }
- return undefined;
- },
- isHeaderPattern: function isHeaderPattern(data, offset) {
- return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
- },
- isHeader: function isHeader(data, offset) {
- // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
- // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
- // More info http://www.mp3-tech.org/programmer/frame_header.html
- if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
- return true;
- }
- return false;
- },
- probe: function probe(data, offset) {
- // same as isHeader but we also check that MPEG frame follows last MPEG frame
- // or end of data is reached
- if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
- // MPEG header Length
- var headerLength = 4;
- // MPEG frame Length
- var header = this.parseHeader(data, offset);
- var frameLength = headerLength;
- if (header && header.frameLength) {
- frameLength = header.frameLength;
- }
- var newOffset = offset + frameLength;
- if (newOffset === data.length || newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset)) {
- return true;
- }
- }
- return false;
- }
- };
- exports.default = MpegAudio;
- module.exports = exports["default"];
- /***/ }),
- /* 24 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.Observer = undefined;
- 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; }; }();
- var _eventemitter = __webpack_require__(54);
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; }
- /**
- * @class
- *
- * Simple adapter sub-class of Nodejs-like EventEmitter.
- *
- * We simply want to pass along the event-name itself
- * in every call to a handler, which is the purpose of our `trigger` method
- * extending the standard API.
- *
- */
- var Observer = exports.Observer = function (_EventEmitter) {
- _inherits(Observer, _EventEmitter);
- function Observer() {
- _classCallCheck(this, Observer);
- return _possibleConstructorReturn(this, (Observer.__proto__ || Object.getPrototypeOf(Observer)).apply(this, arguments));
- }
- _createClass(Observer, [{
- key: 'trigger',
- /**
- *
- * @param {string} event
- * @param {any} data
- */
- value: function trigger(event) {
- for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- data[_key - 1] = arguments[_key];
- }
- this.emit.apply(this, [event, event].concat(data));
- }
- }]);
- return Observer;
- }(_eventemitter.EventEmitter);
- /***/ }),
- /* 25 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- /**
- * TimeRanges to string helper
- */
- var TimeRanges = {
- toString: function toString(r) {
- var log = '',
- len = r.length;
- for (var i = 0; i < len; i++) {
- log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';
- }
- return log;
- }
- };
- exports.default = TimeRanges;
- module.exports = exports['default'];
- /***/ }),
- /* 26 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.findFirstFragWithCC = findFirstFragWithCC;
- exports.findFragWithCC = findFragWithCC;
- exports.shouldAlignOnDiscontinuities = shouldAlignOnDiscontinuities;
- exports.findDiscontinuousReferenceFrag = findDiscontinuousReferenceFrag;
- exports.adjustPts = adjustPts;
- exports.alignStream = alignStream;
- exports.alignDiscontinuities = alignDiscontinuities;
- exports.alignPDT = alignPDT;
- var _binarySearch = __webpack_require__(9);
- var _binarySearch2 = _interopRequireDefault(_binarySearch);
- var _logger = __webpack_require__(0);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function findFirstFragWithCC(fragments, cc) {
- var firstFrag = null;
- for (var i = 0; i < fragments.length; i += 1) {
- var currentFrag = fragments[i];
- if (currentFrag && currentFrag.cc === cc) {
- firstFrag = currentFrag;
- break;
- }
- }
- return firstFrag;
- }
- function findFragWithCC(fragments, CC) {
- return _binarySearch2.default.search(fragments, function (candidate) {
- if (candidate.cc < CC) {
- return 1;
- } else if (candidate.cc > CC) {
- return -1;
- } else {
- return 0;
- }
- });
- }
- function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {
- var shouldAlign = false;
- if (lastLevel && lastLevel.details && details) {
- if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
- shouldAlign = true;
- }
- }
- return shouldAlign;
- }
- // Find the first frag in the previous level which matches the CC of the first frag of the new level
- function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
- var prevFrags = prevDetails.fragments;
- var curFrags = curDetails.fragments;
- if (!curFrags.length || !prevFrags.length) {
- _logger.logger.log('No fragments to align');
- return;
- }
- var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
- if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
- _logger.logger.log('No frag in previous level to align on');
- return;
- }
- return prevStartFrag;
- }
- function adjustPts(sliding, details) {
- details.fragments.forEach(function (frag) {
- if (frag) {
- var start = frag.start + sliding;
- frag.start = frag.startPTS = start;
- frag.endPTS = start + frag.duration;
- }
- });
- details.PTSKnown = true;
- }
- /**
- * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
- * contiguous stream with the last fragments.
- * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
- * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
- * and an extra download.
- * @param lastFrag
- * @param lastLevel
- * @param details
- */
- function alignStream(lastFrag, lastLevel, details) {
- alignDiscontinuities(lastFrag, details, lastLevel);
- if (!details.PTSKnown && lastLevel) {
- // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
- // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
- // discontinuity sequence.
- alignPDT(details, lastLevel.details);
- }
- }
- /**
- * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
- * discontinuity sequence.
- * @param lastLevel - The details of the last loaded level
- * @param details - The details of the new level
- */
- function alignDiscontinuities(lastFrag, details, lastLevel) {
- if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {
- var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);
- if (referenceFrag) {
- _logger.logger.log('Adjusting PTS using last level due to CC increase within current level');
- adjustPts(referenceFrag.start, details);
- }
- }
- }
- /**
- * Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.
- * @param details - The details of the new level
- * @param lastDetails - The details of the last loaded level
- */
- function alignPDT(details, lastDetails) {
- if (lastDetails && lastDetails.fragments.length) {
- if (!details.hasProgramDateTime || !lastDetails.hasProgramDateTime) {
- return;
- }
- // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM
- // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM
- // then we can deduce that playlist B sliding is 1000+8 = 1008s
- var lastPDT = lastDetails.fragments[0].programDateTime;
- var newPDT = details.fragments[0].programDateTime;
- // date diff is in ms. frag.start is in seconds
- var sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;
- if (Number.isFinite(sliding)) {
- _logger.logger.log('adjusting PTS using programDateTime delta, sliding:' + sliding.toFixed(3));
- adjustPts(sliding, details);
- }
- }
- }
- /***/ }),
- /* 27 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.findFragmentByPDT = findFragmentByPDT;
- exports.findFragmentByPTS = findFragmentByPTS;
- exports.fragmentWithinToleranceTest = fragmentWithinToleranceTest;
- exports.pdtWithinToleranceTest = pdtWithinToleranceTest;
- var _binarySearch = __webpack_require__(9);
- var _binarySearch2 = _interopRequireDefault(_binarySearch);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Returns first fragment whose endPdt value exceeds the given PDT.
- * @param {Array<Fragment>} fragments - The array of candidate fragments
- * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded
- * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous
- * @returns {*|null} fragment - The best matching fragment
- */
- function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
- if (!Array.isArray(fragments) || !fragments.length || !Number.isFinite(PDTValue)) {
- return null;
- }
- // if less than start
- if (PDTValue < fragments[0].programDateTime) {
- return null;
- }
- if (PDTValue >= fragments[fragments.length - 1].endProgramDateTime) {
- return null;
- }
- maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
- for (var seg = 0; seg < fragments.length; ++seg) {
- var frag = fragments[seg];
- if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
- return frag;
- }
- }
- return null;
- }
- /**
- * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
- * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
- * breaking any traps which would cause the same fragment to be continuously selected within a small range.
- * @param {*} fragPrevious - The last frag successfully appended
- * @param {Array<Fragment>} fragments - The array of candidate fragments
- * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within
- * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
- * @returns {*} foundFrag - The best matching fragment
- */
- function findFragmentByPTS(fragPrevious, fragments) {
- var bufferEnd = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
- var maxFragLookUpTolerance = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
- var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : null;
- // Prefer the next fragment if it's within tolerance
- if (fragNext && !fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) {
- return fragNext;
- }
- return _binarySearch2.default.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
- }
- /**
- * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
- * @param {*} candidate - The fragment to test
- * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within
- * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
- * @returns {number} - 0 if it matches, 1 if too low, -1 if too high
- */
- function fragmentWithinToleranceTest() {
- var bufferEnd = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
- var maxFragLookUpTolerance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
- var candidate = arguments[2];
- // offset should be within fragment boundary - config.maxFragLookUpTolerance
- // this is to cope with situations like
- // bufferEnd = 9.991
- // frag[Ø] : [0,10]
- // frag[1] : [10,20]
- // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
- // frag start frag start+duration
- // |-----------------------------|
- // <---> <--->
- // ...--------><-----------------------------><---------....
- // previous frag matching fragment next frag
- // return -1 return 0 return 1
- // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
- // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
- var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
- if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
- return 1;
- } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
- // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
- return -1;
- }
- return 0;
- }
- /**
- * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
- * This function tests the candidate's program date time values, as represented in Unix time
- * @param {*} candidate - The fragment to test
- * @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range
- * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
- * @returns {boolean} True if contiguous, false otherwise
- */
- function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
- var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;
- return candidate.endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
- }
- /***/ }),
- /* 28 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _eventHandler = __webpack_require__(3);
- var _eventHandler2 = _interopRequireDefault(_eventHandler);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; }
- /**
- * Sub-class specialization of EventHandler base class.
- *
- * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
- * scheduled asynchroneously, avoiding recursive calls in the same tick.
- *
- * The task itself is implemented in `doTick`. It can be requested and called for single execution
- * using the `tick` method.
- *
- * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
- * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
- *
- * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
- * and cancelled with `clearNextTick`.
- *
- * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
- *
- * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
- *
- * Further explanations:
- *
- * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
- * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
- *
- * When the task execution (`tick` method) is called in re-entrant way this is detected and
- * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
- * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
- */
- var TaskLoop = function (_EventHandler) {
- _inherits(TaskLoop, _EventHandler);
- function TaskLoop(hls) {
- var _ref;
- _classCallCheck(this, TaskLoop);
- for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- events[_key - 1] = arguments[_key];
- }
- var _this = _possibleConstructorReturn(this, (_ref = TaskLoop.__proto__ || Object.getPrototypeOf(TaskLoop)).call.apply(_ref, [this, hls].concat(events)));
- _this._tickInterval = null;
- _this._tickTimer = null;
- _this._tickCallCount = 0;
- _this._boundTick = _this.tick.bind(_this);
- return _this;
- }
- /**
- * @override
- */
- _createClass(TaskLoop, [{
- key: 'onHandlerDestroying',
- value: function onHandlerDestroying() {
- // clear all timers before unregistering from event bus
- this.clearNextTick();
- this.clearInterval();
- }
- /**
- * @returns {boolean}
- */
- }, {
- key: 'hasInterval',
- value: function hasInterval() {
- return !!this._tickInterval;
- }
- /**
- * @returns {boolean}
- */
- }, {
- key: 'hasNextTick',
- value: function hasNextTick() {
- return !!this._tickTimer;
- }
- /**
- * @param {number} millis Interval time (ms)
- * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)
- */
- }, {
- key: 'setInterval',
- value: function (_setInterval) {
- function setInterval(_x) {
- return _setInterval.apply(this, arguments);
- }
- setInterval.toString = function () {
- return _setInterval.toString();
- };
- return setInterval;
- }(function (millis) {
- if (!this._tickInterval) {
- this._tickInterval = setInterval(this._boundTick, millis);
- return true;
- }
- return false;
- })
- /**
- * @returns {boolean} True when interval was cleared, false when none was set (no effect)
- */
- }, {
- key: 'clearInterval',
- value: function (_clearInterval) {
- function clearInterval() {
- return _clearInterval.apply(this, arguments);
- }
- clearInterval.toString = function () {
- return _clearInterval.toString();
- };
- return clearInterval;
- }(function () {
- if (this._tickInterval) {
- clearInterval(this._tickInterval);
- this._tickInterval = null;
- return true;
- }
- return false;
- })
- /**
- * @returns {boolean} True when timeout was cleared, false when none was set (no effect)
- */
- }, {
- key: 'clearNextTick',
- value: function clearNextTick() {
- if (this._tickTimer) {
- clearTimeout(this._tickTimer);
- this._tickTimer = null;
- return true;
- }
- return false;
- }
- /**
- * Will call the subclass doTick implementation in this main loop tick
- * or in the next one (via setTimeout(,0)) in case it has already been called
- * in this tick (in case this is a re-entrant call).
- */
- }, {
- key: 'tick',
- value: function tick() {
- this._tickCallCount++;
- if (this._tickCallCount === 1) {
- this.doTick();
- // re-entrant call to tick from previous doTick call stack
- // -> schedule a call on the next main loop iteration to process this task processing request
- if (this._tickCallCount > 1) {
- // make sure only one timer exists at any time at max
- this.clearNextTick();
- this._tickTimer = setTimeout(this._boundTick, 0);
- }
- this._tickCallCount = 0;
- }
- }
- /**
- * For subclass to implement task logic
- * @abstract
- */
- }, {
- key: 'doTick',
- value: function doTick() {}
- }]);
- return TaskLoop;
- }(_eventHandler2.default);
- exports.default = TaskLoop;
- module.exports = exports['default'];
- /***/ }),
- /* 29 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.sendAddTrackEvent = sendAddTrackEvent;
- exports.clearCurrentCues = clearCurrentCues;
- function sendAddTrackEvent(track, videoEl) {
- var event = null;
- try {
- event = new window.Event('addtrack');
- } catch (err) {
- // for IE11
- event = document.createEvent('Event');
- event.initEvent('addtrack', false, false);
- }
- event.track = track;
- videoEl.dispatchEvent(event);
- }
- function clearCurrentCues(track) {
- if (track && track.cues) {
- while (track.cues.length > 0) {
- track.removeCue(track.cues[0]);
- }
- }
- }
- /***/ }),
- /* 30 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.fixLineBreaks = undefined;
- var _vttcue = __webpack_require__(71);
- var _vttcue2 = _interopRequireDefault(_vttcue);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- var StringDecoder = function StringDecoder() {
- return {
- decode: function decode(data) {
- if (!data) {
- return '';
- }
- if (typeof data !== 'string') {
- throw new Error('Error - expected string data.');
- }
- return decodeURIComponent(encodeURIComponent(data));
- }
- };
- }; /*
- * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js#L1716
- */
- function VTTParser() {
- this.window = window;
- this.state = 'INITIAL';
- this.buffer = '';
- this.decoder = new StringDecoder();
- this.regionList = [];
- }
- // Try to parse input as a time stamp.
- function parseTimeStamp(input) {
- function computeSeconds(h, m, s, f) {
- return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
- }
- var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);
- if (!m) {
- return null;
- }
- if (m[3]) {
- // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
- return computeSeconds(m[1], m[2], m[3].replace(':', ''), m[4]);
- } else if (m[1] > 59) {
- // Timestamp takes the form of [hours]:[minutes].[milliseconds]
- // First position is hours as it's over 59.
- return computeSeconds(m[1], m[2], 0, m[4]);
- } else {
- // Timestamp takes the form of [minutes]:[seconds].[milliseconds]
- return computeSeconds(0, m[1], m[2], m[4]);
- }
- }
- // A settings object holds key/value pairs and will ignore anything but the first
- // assignment to a specific key.
- function Settings() {
- this.values = Object.create(null);
- }
- Settings.prototype = {
- // Only accept the first assignment to any key.
- set: function set(k, v) {
- if (!this.get(k) && v !== '') {
- this.values[k] = v;
- }
- },
- // Return the value for a key, or a default value.
- // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
- // a number of possible default values as properties where 'defaultKey' is
- // the key of the property that will be chosen; otherwise it's assumed to be
- // a single value.
- get: function get(k, dflt, defaultKey) {
- if (defaultKey) {
- return this.has(k) ? this.values[k] : dflt[defaultKey];
- }
- return this.has(k) ? this.values[k] : dflt;
- },
- // Check whether we have a value for a key.
- has: function has(k) {
- return k in this.values;
- },
- // Accept a setting if its one of the given alternatives.
- alt: function alt(k, v, a) {
- for (var n = 0; n < a.length; ++n) {
- if (v === a[n]) {
- this.set(k, v);
- break;
- }
- }
- },
- // Accept a setting if its a valid (signed) integer.
- integer: function integer(k, v) {
- if (/^-?\d+$/.test(v)) {
- // integer
- this.set(k, parseInt(v, 10));
- }
- },
- // Accept a setting if its a valid percentage.
- percent: function percent(k, v) {
- var m = void 0;
- if (m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/)) {
- v = parseFloat(v);
- if (v >= 0 && v <= 100) {
- this.set(k, v);
- return true;
- }
- }
- return false;
- }
- };
- // Helper function to parse input into groups separated by 'groupDelim', and
- // interprete each group as a key/value pair separated by 'keyValueDelim'.
- function parseOptions(input, callback, keyValueDelim, groupDelim) {
- var groups = groupDelim ? input.split(groupDelim) : [input];
- for (var i in groups) {
- if (typeof groups[i] !== 'string') {
- continue;
- }
- var kv = groups[i].split(keyValueDelim);
- if (kv.length !== 2) {
- continue;
- }
- var k = kv[0];
- var v = kv[1];
- callback(k, v);
- }
- }
- var defaults = new _vttcue2.default(0, 0, 0);
- // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244
- // Safari doesn't yet support this change, but FF and Chrome do.
- var center = defaults.align === 'middle' ? 'middle' : 'center';
- function parseCue(input, cue, regionList) {
- // Remember the original input if we need to throw an error.
- var oInput = input;
- // 4.1 WebVTT timestamp
- function consumeTimeStamp() {
- var ts = parseTimeStamp(input);
- if (ts === null) {
- throw new Error('Malformed timestamp: ' + oInput);
- }
- // Remove time stamp from input.
- input = input.replace(/^[^\sa-zA-Z-]+/, '');
- return ts;
- }
- // 4.4.2 WebVTT cue settings
- function consumeCueSettings(input, cue) {
- var settings = new Settings();
- parseOptions(input, function (k, v) {
- switch (k) {
- case 'region':
- // Find the last region we parsed with the same region id.
- for (var i = regionList.length - 1; i >= 0; i--) {
- if (regionList[i].id === v) {
- settings.set(k, regionList[i].region);
- break;
- }
- }
- break;
- case 'vertical':
- settings.alt(k, v, ['rl', 'lr']);
- break;
- case 'line':
- var vals = v.split(','),
- vals0 = vals[0];
- settings.integer(k, vals0);
- if (settings.percent(k, vals0)) {
- settings.set('snapToLines', false);
- }
- settings.alt(k, vals0, ['auto']);
- if (vals.length === 2) {
- settings.alt('lineAlign', vals[1], ['start', center, 'end']);
- }
- break;
- case 'position':
- vals = v.split(',');
- settings.percent(k, vals[0]);
- if (vals.length === 2) {
- settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);
- }
- break;
- case 'size':
- settings.percent(k, v);
- break;
- case 'align':
- settings.alt(k, v, ['start', center, 'end', 'left', 'right']);
- break;
- }
- }, /:/, /\s/);
- // Apply default values for any missing fields.
- cue.region = settings.get('region', null);
- cue.vertical = settings.get('vertical', '');
- var line = settings.get('line', 'auto');
- if (line === 'auto' && defaults.line === -1) {
- // set numeric line number for Safari
- line = -1;
- }
- cue.line = line;
- cue.lineAlign = settings.get('lineAlign', 'start');
- cue.snapToLines = settings.get('snapToLines', true);
- cue.size = settings.get('size', 100);
- cue.align = settings.get('align', center);
- var position = settings.get('position', 'auto');
- if (position === 'auto' && defaults.position === 50) {
- // set numeric position for Safari
- position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;
- }
- cue.position = position;
- }
- function skipWhitespace() {
- input = input.replace(/^\s+/, '');
- }
- // 4.1 WebVTT cue timings.
- skipWhitespace();
- cue.startTime = consumeTimeStamp(); // (1) collect cue start time
- skipWhitespace();
- if (input.substr(0, 3) !== '-->') {
- // (3) next characters must match '-->'
- throw new Error('Malformed time stamp (time stamps must be separated by \'-->\'): ' + oInput);
- }
- input = input.substr(3);
- skipWhitespace();
- cue.endTime = consumeTimeStamp(); // (5) collect cue end time
- // 4.1 WebVTT cue settings list.
- skipWhitespace();
- consumeCueSettings(input, cue);
- }
- function fixLineBreaks(input) {
- return input.replace(/<br(?: \/)?>/gi, '\n');
- }
- VTTParser.prototype = {
- parse: function parse(data) {
- var self = this;
- // If there is no data then we won't decode it, but will just try to parse
- // whatever is in buffer already. This may occur in circumstances, for
- // example when flush() is called.
- if (data) {
- // Try to decode the data that we received.
- self.buffer += self.decoder.decode(data, { stream: true });
- }
- function collectNextLine() {
- var buffer = self.buffer;
- var pos = 0;
- buffer = fixLineBreaks(buffer);
- while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
- ++pos;
- }
- var line = buffer.substr(0, pos);
- // Advance the buffer early in case we fail below.
- if (buffer[pos] === '\r') {
- ++pos;
- }
- if (buffer[pos] === '\n') {
- ++pos;
- }
- self.buffer = buffer.substr(pos);
- return line;
- }
- // 3.2 WebVTT metadata header syntax
- function parseHeader(input) {
- parseOptions(input, function (k, v) {
- switch (k) {
- case 'Region':
- // 3.3 WebVTT region metadata header syntax
- // console.log('parse region', v);
- // parseRegion(v);
- break;
- }
- }, /:/);
- }
- // 5.1 WebVTT file parsing.
- try {
- var line = void 0;
- if (self.state === 'INITIAL') {
- // We can't start parsing until we have the first line.
- if (!/\r\n|\n/.test(self.buffer)) {
- return this;
- }
- line = collectNextLine();
- // strip of UTF-8 BOM if any
- // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
- var m = line.match(/^()?WEBVTT([ \t].*)?$/);
- if (!m || !m[0]) {
- throw new Error('Malformed WebVTT signature.');
- }
- self.state = 'HEADER';
- }
- var alreadyCollectedLine = false;
- while (self.buffer) {
- // We can't parse a line until we have the full line.
- if (!/\r\n|\n/.test(self.buffer)) {
- return this;
- }
- if (!alreadyCollectedLine) {
- line = collectNextLine();
- } else {
- alreadyCollectedLine = false;
- }
- switch (self.state) {
- case 'HEADER':
- // 13-18 - Allow a header (metadata) under the WEBVTT line.
- if (/:/.test(line)) {
- parseHeader(line);
- } else if (!line) {
- // An empty line terminates the header and starts the body (cues).
- self.state = 'ID';
- }
- continue;
- case 'NOTE':
- // Ignore NOTE blocks.
- if (!line) {
- self.state = 'ID';
- }
- continue;
- case 'ID':
- // Check for the start of NOTE blocks.
- if (/^NOTE($|[ \t])/.test(line)) {
- self.state = 'NOTE';
- break;
- }
- // 19-29 - Allow any number of line terminators, then initialize new cue values.
- if (!line) {
- continue;
- }
- self.cue = new _vttcue2.default(0, 0, '');
- self.state = 'CUE';
- // 30-39 - Check if self line contains an optional identifier or timing data.
- if (line.indexOf('-->') === -1) {
- self.cue.id = line;
- continue;
- }
- // Process line as start of a cue.
- /* falls through */
- case 'CUE':
- // 40 - Collect cue timings and settings.
- try {
- parseCue(line, self.cue, self.regionList);
- } catch (e) {
- // In case of an error ignore rest of the cue.
- self.cue = null;
- self.state = 'BADCUE';
- continue;
- }
- self.state = 'CUETEXT';
- continue;
- case 'CUETEXT':
- var hasSubstring = line.indexOf('-->') !== -1;
- // 34 - If we have an empty line then report the cue.
- // 35 - If we have the special substring '-->' then report the cue,
- // but do not collect the line as we need to process the current
- // one as a new cue.
- if (!line || hasSubstring && (alreadyCollectedLine = true)) {
- // We are done parsing self cue.
- if (self.oncue) {
- self.oncue(self.cue);
- }
- self.cue = null;
- self.state = 'ID';
- continue;
- }
- if (self.cue.text) {
- self.cue.text += '\n';
- }
- self.cue.text += line;
- continue;
- case 'BADCUE':
- // BADCUE
- // 54-62 - Collect and discard the remaining cue.
- if (!line) {
- self.state = 'ID';
- }
- continue;
- }
- }
- } catch (e) {
- // If we are currently parsing a cue, report what we have.
- if (self.state === 'CUETEXT' && self.cue && self.oncue) {
- self.oncue(self.cue);
- }
- self.cue = null;
- // Enter BADWEBVTT state if header was not parsed correctly otherwise
- // another exception occurred so enter BADCUE state.
- self.state = self.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';
- }
- return this;
- },
- flush: function flush() {
- var self = this;
- try {
- // Finish decoding the stream.
- self.buffer += self.decoder.decode();
- // Synthesize the end of the current cue or region.
- if (self.cue || self.state === 'HEADER') {
- self.buffer += '\n\n';
- self.parse();
- }
- // If we've flushed, parsed, and we're still on the INITIAL state then
- // that means we don't have enough of the stream to parse the first
- // line.
- if (self.state === 'INITIAL') {
- throw new Error('Malformed WebVTT signature.');
- }
- } catch (e) {
- throw e;
- }
- if (self.onflush) {
- self.onflush();
- }
- return this;
- }
- };
- exports.fixLineBreaks = fixLineBreaks;
- exports.default = VTTParser;
- /***/ }),
- /* 31 */
- /***/ (function(module, exports, __webpack_require__) {
- module.exports = __webpack_require__(32);
- /***/ }),
- /* 32 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- 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); } };
- var _xgplayer = __webpack_require__(33);
- var _xgplayer2 = _interopRequireDefault(_xgplayer);
- var _hls = __webpack_require__(34);
- var _hls2 = _interopRequireDefault(_hls);
- var _utils = __webpack_require__(80);
- var _utils2 = _interopRequireDefault(_utils);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; }
- var HlsJsPlayer = function (_Player) {
- _inherits(HlsJsPlayer, _Player);
- function HlsJsPlayer(options) {
- _classCallCheck(this, HlsJsPlayer);
- var _this = _possibleConstructorReturn(this, (HlsJsPlayer.__proto__ || Object.getPrototypeOf(HlsJsPlayer)).call(this, options));
- _this.hlsOpts = options.hlsOpts || {};
- var util = _xgplayer2.default.util;
- var player = _this;
- player.once('complete', function () {
- if (player.config.isLive) {
- util.addClass(player.root, 'xgplayer-is-live');
- if (!util.findDom(player.controls, '.xgplayer-live')) {
- var live = util.createDom('xg-live', '正在直播', {}, 'xgplayer-live');
- player.controls.appendChild(live);
- }
- }
- });
- _this.browser = _utils2.default.getBrowserVersion();
- if (player.config.useHls === undefined) {
- if (_xgplayer2.default.sniffer.device === 'mobile' && navigator.platform !== 'MacIntel' && navigator.platform !== 'Win32' || _this.browser.indexOf('Safari') > -1) {
- return _possibleConstructorReturn(_this);
- }
- } else if (!player.config.useHls) {
- return _possibleConstructorReturn(_this);
- }
- Number.isFinite = Number.isFinite || function (value) {
- return typeof value === "number" && isFinite(value);
- };
- var hls = void 0;
- hls = new _hls2.default(_this.hlsOpts);
- _this.hls = hls;
- Object.defineProperty(player, 'src', {
- get: function get() {
- return player.currentSrc;
- },
- set: function set(url) {
- util.removeClass(player.root, 'xgplayer-is-live');
- var liveDom = document.querySelector('.xgplayer-live');
- if (liveDom) {
- liveDom.parentNode.removeChild(liveDom);
- }
- // player.config.url = url
- var paused = player.paused;
- player.hls.stopLoad();
- player.hls.detachMedia();
- player.hls.destroy();
- player.hls = new _hls2.default(player.hlsOpts);
- player.register(url);
- if (!paused) {
- player.pause();
- player.once('pause', function () {
- player.hls.loadSource(url);
- });
- player.once('canplay', function () {
- player.play().catch(function (err) {});
- });
- } else {
- player.hls.loadSource(url);
- }
- player.hls.attachMedia(player.video);
- player.once('canplay', function () {
- player.currentTime = 0;
- });
- },
- configurable: true
- });
- _this.register(_this.config.url);
- _this.once('complete', function () {
- hls.attachMedia(player.video);
- player.once('canplay', function () {
- player.play().catch(function (err) {});
- });
- });
- _this.once('destroy', function () {
- hls.stopLoad();
- });
- return _this;
- }
- _createClass(HlsJsPlayer, [{
- key: 'register',
- value: function register(url) {
- var hls = this.hls;
- var util = _xgplayer2.default.util;
- var player = this;
- hls.on(_hls2.default.Events.MEDIA_ATTACHED, function () {
- hls.loadSource(url);
- });
- hls.on(_hls2.default.Events.LEVEL_LOADED, function (name, e) {
- if (!hls.inited) {
- hls.inited = true;
- if (e && e.details && e.details.live) {
- util.addClass(player.root, 'xgplayer-is-live');
- if (!util.findDom(player.root, '.xgplayer-live')) {
- var live = util.createDom('xg-live', '正在直播', {}, 'xgplayer-live');
- player.controls.appendChild(live);
- }
- }
- }
- });
- hls.on(_hls2.default.Events.ERROR, function (event, data) {
- player.emit('HLS_ERROR', {
- errorType: data.type,
- errorDetails: data.details,
- errorFatal: data.fatal
- });
- if (data.fatal) {
- switch (data.type) {
- case _hls2.default.ErrorTypes.NETWORK_ERROR:
- hls.startLoad();
- break;
- case _hls2.default.ErrorTypes.MEDIA_ERROR:
- hls.recoverMediaError();
- break;
- default:
- player.emit('error', data);
- }
- }
- });
- this._statistics();
- }
- }, {
- key: '_statistics',
- value: function _statistics() {
- var statsInfo = {
- speed: 0,
- playerType: "HlsPlayer"
- };
- var mediainfo = {
- videoDataRate: 0,
- audioDataRate: 0
- };
- var hls = this.hls;
- var player = this;
- hls.on(_hls2.default.Events.FRAG_LOAD_PROGRESS, function (flag, payload) {
- statsInfo.speed = payload.stats.loaded / 1000;
- });
- hls.on(_hls2.default.Events.FRAG_PARSING_DATA, function (flag, payload) {
- if (payload.type === 'video') {
- mediainfo.fps = parseInt(payload.nb / (payload.endPTS - payload.startPTS));
- }
- });
- hls.on(_hls2.default.Events.FRAG_PARSING_INIT_SEGMENT, function (flag, payload) {
- mediainfo.hasAudio = payload.tracks && payload.tracks.audio ? true : false;
- mediainfo.hasVideo = payload.tracks && payload.tracks.audio ? true : false;
- if (mediainfo.hasAudio) {
- var track = payload.tracks.audio;
- mediainfo.audioChannelCount = track.metadata && track.metadata.channelCount ? track.metadata.channelCount : 0;
- mediainfo.audioCodec = track.codec;
- }
- if (mediainfo.hasVideo) {
- var _track = payload.tracks.video;
- mediainfo.videoCodec = _track.codec;
- mediainfo.width = _track.metadata && _track.metadata.width ? _track.metadata.width : 0;
- mediainfo.height = _track.metadata && _track.metadata.height ? _track.metadata.height : 0;
- }
- mediainfo.duration = payload.frag && payload.frag.duration ? payload.frag.duration : 0;
- mediainfo.level = payload.frag && payload.frag.level ? payload.frag.level : 0;
- if (mediainfo.videoCodec || mediainfo.audioCodec) {
- mediainfo.mimeType = 'video/hls; codecs="' + mediainfo.videoCodec + ';' + mediainfo.audioCodec + '"';
- }
- player.mediainfo = mediainfo;
- player.emit("media_info", mediainfo);
- });
- this._statisticsTimmer = setInterval(function () {
- player.emit("statistics_info", statsInfo);
- statsInfo.speed = 0;
- }, 1000);
- }
- }, {
- key: 'destroy',
- value: function destroy() {
- _get(HlsJsPlayer.prototype.__proto__ || Object.getPrototypeOf(HlsJsPlayer.prototype), 'destroy', this).call(this);
- clearInterval(this._statisticsTimmer);
- }
- }]);
- return HlsJsPlayer;
- }(_xgplayer2.default);
- HlsJsPlayer.isSupported = _hls2.default.isSupported;
- exports.default = HlsJsPlayer;
- module.exports = exports['default'];
- /***/ }),
- /* 33 */
- /***/ (function(module, exports) {
- module.exports = __WEBPACK_EXTERNAL_MODULE__33__;
- /***/ }),
- /* 34 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _urlToolkit = __webpack_require__(8);
- var URLToolkit = _interopRequireWildcard(_urlToolkit);
- var _errors = __webpack_require__(2);
- var _playlistLoader = __webpack_require__(15);
- var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
- var _fragmentLoader = __webpack_require__(38);
- var _fragmentLoader2 = _interopRequireDefault(_fragmentLoader);
- var _keyLoader = __webpack_require__(39);
- var _keyLoader2 = _interopRequireDefault(_keyLoader);
- var _fragmentTracker = __webpack_require__(6);
- var _streamController = __webpack_require__(40);
- var _streamController2 = _interopRequireDefault(_streamController);
- var _levelController = __webpack_require__(57);
- var _levelController2 = _interopRequireDefault(_levelController);
- var _id3TrackController = __webpack_require__(58);
- var _id3TrackController2 = _interopRequireDefault(_id3TrackController);
- var _isSupported2 = __webpack_require__(59);
- var _logger = __webpack_require__(0);
- var _config = __webpack_require__(60);
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _observer = __webpack_require__(24);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- 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; } }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; }
- /**
- * @module Hls
- * @class
- * @constructor
- */
- var Hls = function (_Observer) {
- _inherits(Hls, _Observer);
- _createClass(Hls, null, [{
- key: 'isSupported',
- /**
- * @type {boolean}
- */
- value: function isSupported() {
- return (0, _isSupported2.isSupported)();
- }
- /**
- * @type {HlsEvents}
- */
- }, {
- key: 'version',
- /**
- * @type {string}
- */
- get: function get() {
- return __VERSION__;
- }
- }, {
- key: 'Events',
- get: function get() {
- return _events2.default;
- }
- /**
- * @type {HlsErrorTypes}
- */
- }, {
- key: 'ErrorTypes',
- get: function get() {
- return _errors.ErrorTypes;
- }
- /**
- * @type {HlsErrorDetails}
- */
- }, {
- key: 'ErrorDetails',
- get: function get() {
- return _errors.ErrorDetails;
- }
- /**
- * @type {HlsConfig}
- */
- }, {
- key: 'DefaultConfig',
- get: function get() {
- if (!Hls.defaultConfig) {
- return _config.hlsDefaultConfig;
- }
- return Hls.defaultConfig;
- }
- /**
- * @type {HlsConfig}
- */
- ,
- set: function set(defaultConfig) {
- Hls.defaultConfig = defaultConfig;
- }
- /**
- * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
- *
- * @constructs Hls
- * @param {HlsConfig} config
- */
- }]);
- function Hls() {
- var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- _classCallCheck(this, Hls);
- var _this = _possibleConstructorReturn(this, (Hls.__proto__ || Object.getPrototypeOf(Hls)).call(this));
- var defaultConfig = Hls.DefaultConfig;
- if ((config.liveSyncDurationCount || config.liveMaxLatencyDurationCount) && (config.liveSyncDuration || config.liveMaxLatencyDuration)) {
- throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');
- }
- for (var prop in defaultConfig) {
- if (prop in config) continue;
- config[prop] = defaultConfig[prop];
- }
- if (config.liveMaxLatencyDurationCount !== undefined && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {
- throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');
- }
- if (config.liveMaxLatencyDuration !== undefined && (config.liveMaxLatencyDuration <= config.liveSyncDuration || config.liveSyncDuration === undefined)) {
- throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');
- }
- (0, _logger.enableLogs)(config.debug);
- _this.config = config;
- _this._autoLevelCapping = -1;
- // core controllers and network loaders
- /**
- * @member {AbrController} abrController
- */
- var abrController = _this.abrController = new config.abrController(_this);
- var bufferController = new config.bufferController(_this);
- var capLevelController = new config.capLevelController(_this);
- var fpsController = new config.fpsController(_this);
- var playListLoader = new _playlistLoader2.default(_this);
- var fragmentLoader = new _fragmentLoader2.default(_this);
- var keyLoader = new _keyLoader2.default(_this);
- var id3TrackController = new _id3TrackController2.default(_this);
- // network controllers
- /**
- * @member {LevelController} levelController
- */
- var levelController = _this.levelController = new _levelController2.default(_this);
- // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important
- var fragmentTracker = new _fragmentTracker.FragmentTracker(_this);
- /**
- * @member {StreamController} streamController
- */
- var streamController = _this.streamController = new _streamController2.default(_this, fragmentTracker);
- var networkControllers = [levelController, streamController];
- // optional audio stream controller
- /**
- * @var {ICoreComponent | Controller}
- */
- var Controller = config.audioStreamController;
- if (Controller) {
- networkControllers.push(new Controller(_this, fragmentTracker));
- }
- /**
- * @member {INetworkController[]} networkControllers
- */
- _this.networkControllers = networkControllers;
- /**
- * @var {ICoreComponent[]}
- */
- var coreComponents = [playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];
- // optional audio track and subtitle controller
- Controller = config.audioTrackController;
- if (Controller) {
- var audioTrackController = new Controller(_this);
- /**
- * @member {AudioTrackController} audioTrackController
- */
- _this.audioTrackController = audioTrackController;
- coreComponents.push(audioTrackController);
- }
- Controller = config.subtitleTrackController;
- if (Controller) {
- var subtitleTrackController = new Controller(_this);
- /**
- * @member {SubtitleTrackController} subtitleTrackController
- */
- _this.subtitleTrackController = subtitleTrackController;
- networkControllers.push(subtitleTrackController);
- }
- Controller = config.emeController;
- if (Controller) {
- var emeController = new Controller(_this);
- /**
- * @member {EMEController} emeController
- */
- _this.emeController = emeController;
- coreComponents.push(emeController);
- }
- // optional subtitle controllers
- Controller = config.subtitleStreamController;
- if (Controller) {
- networkControllers.push(new Controller(_this, fragmentTracker));
- }
- Controller = config.timelineController;
- if (Controller) {
- coreComponents.push(new Controller(_this));
- }
- /**
- * @member {ICoreComponent[]}
- */
- _this.coreComponents = coreComponents;
- return _this;
- }
- /**
- * Dispose of the instance
- */
- _createClass(Hls, [{
- key: 'destroy',
- value: function destroy() {
- _logger.logger.log('destroy');
- this.trigger(_events2.default.DESTROYING);
- this.detachMedia();
- this.coreComponents.concat(this.networkControllers).forEach(function (component) {
- component.destroy();
- });
- this.url = null;
- this.removeAllListeners();
- this._autoLevelCapping = -1;
- }
- /**
- * Attach a media element
- * @param {HTMLMediaElement} media
- */
- }, {
- key: 'attachMedia',
- value: function attachMedia(media) {
- _logger.logger.log('attachMedia');
- this.media = media;
- this.trigger(_events2.default.MEDIA_ATTACHING, { media: media });
- }
- /**
- * Detach from the media
- */
- }, {
- key: 'detachMedia',
- value: function detachMedia() {
- _logger.logger.log('detachMedia');
- this.trigger(_events2.default.MEDIA_DETACHING);
- this.media = null;
- }
- /**
- * Set the source URL. Can be relative or absolute.
- * @param {string} url
- */
- }, {
- key: 'loadSource',
- value: function loadSource(url) {
- url = URLToolkit.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true });
- _logger.logger.log('loadSource:' + url);
- this.url = url;
- // when attaching to a source URL, trigger a playlist load
- this.trigger(_events2.default.MANIFEST_LOADING, { url: url });
- }
- /**
- * Start loading data from the stream source.
- * Depending on default config, client starts loading automatically when a source is set.
- *
- * @param {number} startPosition Set the start position to stream from
- * @default -1 None (from earliest point)
- */
- }, {
- key: 'startLoad',
- value: function startLoad() {
- var startPosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1;
- _logger.logger.log('startLoad(' + startPosition + ')');
- this.networkControllers.forEach(function (controller) {
- controller.startLoad(startPosition);
- });
- }
- /**
- * Stop loading of any stream data.
- */
- }, {
- key: 'stopLoad',
- value: function stopLoad() {
- _logger.logger.log('stopLoad');
- this.networkControllers.forEach(function (controller) {
- controller.stopLoad();
- });
- }
- /**
- * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
- */
- }, {
- key: 'swapAudioCodec',
- value: function swapAudioCodec() {
- _logger.logger.log('swapAudioCodec');
- this.streamController.swapAudioCodec();
- }
- /**
- * When the media-element fails, this allows to detach and then re-attach it
- * as one call (convenience method).
- *
- * Automatic recovery of media-errors by this process is configurable.
- */
- }, {
- key: 'recoverMediaError',
- value: function recoverMediaError() {
- _logger.logger.log('recoverMediaError');
- var media = this.media;
- this.detachMedia();
- this.attachMedia(media);
- }
- /**
- * @type {QualityLevel[]}
- */
- }, {
- key: 'levels',
- get: function get() {
- return this.levelController.levels;
- }
- /**
- * Index of quality level currently played
- * @type {number}
- */
- }, {
- key: 'currentLevel',
- get: function get() {
- return this.streamController.currentLevel;
- }
- /**
- * Set quality level index immediately .
- * This will flush the current buffer to replace the quality asap.
- * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.
- * @type {number} -1 for automatic level selection
- */
- ,
- set: function set(newLevel) {
- _logger.logger.log('set currentLevel:' + newLevel);
- this.loadLevel = newLevel;
- this.streamController.immediateLevelSwitch();
- }
- /**
- * Index of next quality level loaded as scheduled by stream controller.
- * @type {number}
- */
- }, {
- key: 'nextLevel',
- get: function get() {
- return this.streamController.nextLevel;
- }
- /**
- * Set quality level index for next loaded data.
- * This will switch the video quality asap, without interrupting playback.
- * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
- * @type {number} -1 for automatic level selection
- */
- ,
- set: function set(newLevel) {
- _logger.logger.log('set nextLevel:' + newLevel);
- this.levelController.manualLevel = newLevel;
- this.streamController.nextLevelSwitch();
- }
- /**
- * Return the quality level of the currently or last (of none is loaded currently) segment
- * @type {number}
- */
- }, {
- key: 'loadLevel',
- get: function get() {
- return this.levelController.level;
- }
- /**
- * Set quality level index for next loaded data in a conservative way.
- * This will switch the quality without flushing, but interrupt current loading.
- * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
- * @type {number} newLevel -1 for automatic level selection
- */
- ,
- set: function set(newLevel) {
- _logger.logger.log('set loadLevel:' + newLevel);
- this.levelController.manualLevel = newLevel;
- }
- /**
- * get next quality level loaded
- * @type {number}
- */
- }, {
- key: 'nextLoadLevel',
- get: function get() {
- return this.levelController.nextLoadLevel;
- }
- /**
- * Set quality level of next loaded segment in a fully "non-destructive" way.
- * Same as `loadLevel` but will wait for next switch (until current loading is done).
- * @type {number} level
- */
- ,
- set: function set(level) {
- this.levelController.nextLoadLevel = level;
- }
- /**
- * Return "first level": like a default level, if not set,
- * falls back to index of first level referenced in manifest
- * @type {number}
- */
- }, {
- key: 'firstLevel',
- get: function get() {
- return Math.max(this.levelController.firstLevel, this.minAutoLevel);
- }
- /**
- * Sets "first-level", see getter.
- * @type {number}
- */
- ,
- set: function set(newLevel) {
- _logger.logger.log('set firstLevel:' + newLevel);
- this.levelController.firstLevel = newLevel;
- }
- /**
- * Return start level (level of first fragment that will be played back)
- * if not overrided by user, first level appearing in manifest will be used as start level
- * if -1 : automatic start level selection, playback will start from level matching download bandwidth
- * (determined from download of first segment)
- * @type {number}
- */
- }, {
- key: 'startLevel',
- get: function get() {
- return this.levelController.startLevel;
- }
- /**
- * set start level (level of first fragment that will be played back)
- * if not overrided by user, first level appearing in manifest will be used as start level
- * if -1 : automatic start level selection, playback will start from level matching download bandwidth
- * (determined from download of first segment)
- * @type {number} newLevel
- */
- ,
- set: function set(newLevel) {
- _logger.logger.log('set startLevel:' + newLevel);
- var hls = this;
- // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
- if (newLevel !== -1) {
- newLevel = Math.max(newLevel, hls.minAutoLevel);
- }
- hls.levelController.startLevel = newLevel;
- }
- /**
- * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
- * @type {number}
- */
- }, {
- key: 'autoLevelCapping',
- get: function get() {
- return this._autoLevelCapping;
- }
- /**
- * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
- * @type {number}
- */
- ,
- set: function set(newLevel) {
- _logger.logger.log('set autoLevelCapping:' + newLevel);
- this._autoLevelCapping = newLevel;
- }
- /**
- * True when automatic level selection enabled
- * @type {boolean}
- */
- }, {
- key: 'autoLevelEnabled',
- get: function get() {
- return this.levelController.manualLevel === -1;
- }
- /**
- * Level set manually (if any)
- * @type {number}
- */
- }, {
- key: 'manualLevel',
- get: function get() {
- return this.levelController.manualLevel;
- }
- /**
- * min level selectable in auto mode according to config.minAutoBitrate
- * @type {number}
- */
- }, {
- key: 'minAutoLevel',
- get: function get() {
- var hls = this,
- levels = hls.levels,
- minAutoBitrate = hls.config.minAutoBitrate,
- len = levels ? levels.length : 0;
- for (var i = 0; i < len; i++) {
- var levelNextBitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate;
- if (levelNextBitrate > minAutoBitrate) {
- return i;
- }
- }
- return 0;
- }
- /**
- * max level selectable in auto mode according to autoLevelCapping
- * @type {number}
- */
- }, {
- key: 'maxAutoLevel',
- get: function get() {
- var hls = this;
- var levels = hls.levels;
- var autoLevelCapping = hls.autoLevelCapping;
- var maxAutoLevel = void 0;
- if (autoLevelCapping === -1 && levels && levels.length) {
- maxAutoLevel = levels.length - 1;
- } else {
- maxAutoLevel = autoLevelCapping;
- }
- return maxAutoLevel;
- }
- /**
- * next automatically selected quality level
- * @type {number}
- */
- }, {
- key: 'nextAutoLevel',
- get: function get() {
- var hls = this;
- // ensure next auto level is between min and max auto level
- return Math.min(Math.max(hls.abrController.nextAutoLevel, hls.minAutoLevel), hls.maxAutoLevel);
- }
- /**
- * this setter is used to force next auto level.
- * this is useful to force a switch down in auto mode:
- * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
- * forced value is valid for one fragment. upon succesful frag loading at forced level,
- * this value will be resetted to -1 by ABR controller.
- * @type {number}
- */
- ,
- set: function set(nextLevel) {
- var hls = this;
- hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel);
- }
- /**
- * @type {AudioTrack[]}
- */
- }, {
- key: 'audioTracks',
- get: function get() {
- var audioTrackController = this.audioTrackController;
- return audioTrackController ? audioTrackController.audioTracks : [];
- }
- /**
- * index of the selected audio track (index in audio track lists)
- * @type {number}
- */
- }, {
- key: 'audioTrack',
- get: function get() {
- var audioTrackController = this.audioTrackController;
- return audioTrackController ? audioTrackController.audioTrack : -1;
- }
- /**
- * selects an audio track, based on its index in audio track lists
- * @type {number}
- */
- ,
- set: function set(audioTrackId) {
- var audioTrackController = this.audioTrackController;
- if (audioTrackController) {
- audioTrackController.audioTrack = audioTrackId;
- }
- }
- /**
- * @type {Seconds}
- */
- }, {
- key: 'liveSyncPosition',
- get: function get() {
- return this.streamController.liveSyncPosition;
- }
- /**
- * get alternate subtitle tracks list from playlist
- * @type {SubtitleTrack[]}
- */
- }, {
- key: 'subtitleTracks',
- get: function get() {
- var subtitleTrackController = this.subtitleTrackController;
- return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
- }
- /**
- * index of the selected subtitle track (index in subtitle track lists)
- * @type {number}
- */
- }, {
- key: 'subtitleTrack',
- get: function get() {
- var subtitleTrackController = this.subtitleTrackController;
- return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
- }
- /**
- * select an subtitle track, based on its index in subtitle track lists
- * @type{number}
- */
- ,
- set: function set(subtitleTrackId) {
- var subtitleTrackController = this.subtitleTrackController;
- if (subtitleTrackController) {
- subtitleTrackController.subtitleTrack = subtitleTrackId;
- }
- }
- /**
- * @type {boolean}
- */
- }, {
- key: 'subtitleDisplay',
- get: function get() {
- var subtitleTrackController = this.subtitleTrackController;
- return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
- }
- /**
- * Enable/disable subtitle display rendering
- * @type {boolean}
- */
- ,
- set: function set(value) {
- var subtitleTrackController = this.subtitleTrackController;
- if (subtitleTrackController) {
- subtitleTrackController.subtitleDisplay = value;
- }
- }
- }]);
- return Hls;
- }(_observer.Observer);
- exports.default = Hls;
- module.exports = exports['default'];
- /***/ }),
- /* 35 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _urlToolkit = __webpack_require__(8);
- var URLToolkit = _interopRequireWildcard(_urlToolkit);
- var _fragment = __webpack_require__(11);
- var _fragment2 = _interopRequireDefault(_fragment);
- var _level = __webpack_require__(36);
- var _level2 = _interopRequireDefault(_level);
- var _levelKey = __webpack_require__(17);
- var _levelKey2 = _interopRequireDefault(_levelKey);
- var _attrList = __webpack_require__(37);
- var _attrList2 = _interopRequireDefault(_attrList);
- var _logger = __webpack_require__(0);
- var _codecs = __webpack_require__(18);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- 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; } }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /**
- * M3U8 parser
- * @module
- */
- // https://regex101.com is your friend
- var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g;
- var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
- var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
- /|(?!#)([\S+ ?]+)/.source, // segment URI, group 3 => the URI (note newline is not eaten)
- /|#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)
- /|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec
- /|#.*/.source // All other non-segment oriented tags will match with all groups empty
- ].join(''), 'g');
- 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?/;
- var MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i;
- var M3U8Parser = function () {
- function M3U8Parser() {
- _classCallCheck(this, M3U8Parser);
- }
- _createClass(M3U8Parser, null, [{
- key: 'findGroup',
- value: function findGroup(groups, mediaGroupId) {
- if (!groups) {
- return null;
- }
- var matchingGroup = null;
- for (var i = 0; i < groups.length; i++) {
- var group = groups[i];
- if (group.id === mediaGroupId) {
- matchingGroup = group;
- }
- }
- return matchingGroup;
- }
- }, {
- key: 'convertAVC1ToAVCOTI',
- value: function convertAVC1ToAVCOTI(codec) {
- var result = void 0,
- avcdata = codec.split('.');
- if (avcdata.length > 2) {
- result = avcdata.shift() + '.';
- result += parseInt(avcdata.shift()).toString(16);
- result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
- } else {
- result = codec;
- }
- return result;
- }
- }, {
- key: 'resolve',
- value: function resolve(url, baseUrl) {
- return URLToolkit.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });
- }
- }, {
- key: 'parseMasterPlaylist',
- value: function parseMasterPlaylist(string, baseurl) {
- var levels = [],
- result = void 0;
- MASTER_PLAYLIST_REGEX.lastIndex = 0;
- function setCodecs(codecs, level) {
- ['video', 'audio'].forEach(function (type) {
- var filtered = codecs.filter(function (codec) {
- return (0, _codecs.isCodecType)(codec, type);
- });
- if (filtered.length) {
- var preferred = filtered.filter(function (codec) {
- return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;
- });
- level[type + 'Codec'] = preferred.length > 0 ? preferred[0] : filtered[0];
- // remove from list
- codecs = codecs.filter(function (codec) {
- return filtered.indexOf(codec) === -1;
- });
- }
- });
- level.unknownCodecs = codecs;
- }
- while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
- var level = {};
- var attrs = level.attrs = new _attrList2.default(result[1]);
- level.url = M3U8Parser.resolve(result[2], baseurl);
- var resolution = attrs.decimalResolution('RESOLUTION');
- if (resolution) {
- level.width = resolution.width;
- level.height = resolution.height;
- }
- level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');
- level.name = attrs.NAME;
- setCodecs([].concat((attrs.CODECS || '').split(/[ ,]+/)), level);
- if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {
- level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);
- }
- levels.push(level);
- }
- return levels;
- }
- }, {
- key: 'parseMasterPlaylistMedia',
- value: function parseMasterPlaylistMedia(string, baseurl, type) {
- var audioGroups = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
- var result = void 0;
- var medias = [];
- var id = 0;
- MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
- while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
- var media = {};
- var attrs = new _attrList2.default(result[1]);
- if (attrs.TYPE === type) {
- media.groupId = attrs['GROUP-ID'];
- media.name = attrs.NAME;
- media.type = type;
- media.default = attrs.DEFAULT === 'YES';
- media.autoselect = attrs.AUTOSELECT === 'YES';
- media.forced = attrs.FORCED === 'YES';
- if (attrs.URI) {
- media.url = M3U8Parser.resolve(attrs.URI, baseurl);
- }
- media.lang = attrs.LANGUAGE;
- if (!media.name) {
- media.name = media.lang;
- }
- if (audioGroups.length) {
- var groupCodec = M3U8Parser.findGroup(audioGroups, media.groupId);
- media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec;
- }
- media.id = id++;
- medias.push(media);
- }
- }
- return medias;
- }
- }, {
- key: 'parseLevelPlaylist',
- value: function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) {
- var currentSN = 0;
- var totalduration = 0;
- var level = new _level2.default(baseurl);
- var levelkey = new _levelKey2.default();
- var cc = 0;
- var prevFrag = null;
- var frag = new _fragment2.default();
- var result = void 0;
- var i = void 0;
- var firstPdtIndex = null;
- LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
- while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
- var duration = result[1];
- if (duration) {
- // INF
- frag.duration = parseFloat(duration);
- // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
- var title = (' ' + result[2]).slice(1);
- frag.title = title || null;
- frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
- } else if (result[3]) {
- // url
- if (Number.isFinite(frag.duration)) {
- var sn = currentSN++;
- frag.type = type;
- frag.start = totalduration;
- frag.levelkey = levelkey;
- frag.sn = sn;
- frag.level = id;
- frag.cc = cc;
- frag.urlId = levelUrlId;
- frag.baseurl = baseurl;
- // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
- frag.relurl = (' ' + result[3]).slice(1);
- assignProgramDateTime(frag, prevFrag);
- level.fragments.push(frag);
- prevFrag = frag;
- totalduration += frag.duration;
- frag = new _fragment2.default();
- }
- } else if (result[4]) {
- // X-BYTERANGE
- frag.rawByteRange = (' ' + result[4]).slice(1);
- if (prevFrag) {
- var lastByteRangeEndOffset = prevFrag.byteRangeEndOffset;
- if (lastByteRangeEndOffset) {
- frag.lastByteRangeEndOffset = lastByteRangeEndOffset;
- }
- }
- } else if (result[5]) {
- // PROGRAM-DATE-TIME
- // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
- frag.rawProgramDateTime = (' ' + result[5]).slice(1);
- frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
- if (firstPdtIndex === null) {
- firstPdtIndex = level.fragments.length;
- }
- } else {
- result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
- for (i = 1; i < result.length; i++) {
- if (result[i] !== undefined) {
- break;
- }
- }
- // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
- var value1 = (' ' + result[i + 1]).slice(1);
- var value2 = (' ' + result[i + 2]).slice(1);
- switch (result[i]) {
- case '#':
- frag.tagList.push(value2 ? [value1, value2] : [value1]);
- break;
- case 'PLAYLIST-TYPE':
- level.type = value1.toUpperCase();
- break;
- case 'MEDIA-SEQUENCE':
- currentSN = level.startSN = parseInt(value1);
- break;
- case 'TARGETDURATION':
- level.targetduration = parseFloat(value1);
- break;
- case 'VERSION':
- level.version = parseInt(value1);
- break;
- case 'EXTM3U':
- break;
- case 'ENDLIST':
- level.live = false;
- break;
- case 'DIS':
- cc++;
- frag.tagList.push(['DIS']);
- break;
- case 'DISCONTINUITY-SEQ':
- cc = parseInt(value1);
- break;
- case 'KEY':
- // https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4
- var decryptparams = value1;
- var keyAttrs = new _attrList2.default(decryptparams);
- var decryptmethod = keyAttrs.enumeratedString('METHOD'),
- decrypturi = keyAttrs.URI,
- decryptiv = keyAttrs.hexadecimalInteger('IV');
- if (decryptmethod) {
- levelkey = new _levelKey2.default();
- if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0) {
- levelkey.method = decryptmethod;
- // URI to get the key
- levelkey.baseuri = baseurl;
- levelkey.reluri = decrypturi;
- levelkey.key = null;
- // Initialization Vector (IV)
- levelkey.iv = decryptiv;
- }
- }
- break;
- case 'START':
- var startParams = value1;
- var startAttrs = new _attrList2.default(startParams);
- var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
- // TIME-OFFSET can be 0
- if (Number.isFinite(startTimeOffset)) {
- level.startTimeOffset = startTimeOffset;
- }
- break;
- case 'MAP':
- var mapAttrs = new _attrList2.default(value1);
- frag.relurl = mapAttrs.URI;
- frag.rawByteRange = mapAttrs.BYTERANGE;
- frag.baseurl = baseurl;
- frag.level = id;
- frag.type = type;
- frag.sn = 'initSegment';
- level.initSegment = frag;
- frag = new _fragment2.default();
- frag.rawProgramDateTime = level.initSegment.rawProgramDateTime;
- break;
- default:
- _logger.logger.warn('line parsed but not handled: ' + result);
- break;
- }
- }
- }
- frag = prevFrag;
- // logger.log('found ' + level.fragments.length + ' fragments');
- if (frag && !frag.relurl) {
- level.fragments.pop();
- totalduration -= frag.duration;
- }
- level.totalduration = totalduration;
- level.averagetargetduration = totalduration / level.fragments.length;
- level.endSN = currentSN - 1;
- level.startCC = level.fragments[0] ? level.fragments[0].cc : 0;
- level.endCC = cc;
- if (!level.initSegment && level.fragments.length) {
- // this is a bit lurky but HLS really has no other way to tell us
- // if the fragments are TS or MP4, except if we download them :/
- // but this is to be able to handle SIDX.
- if (level.fragments.every(function (frag) {
- return MP4_REGEX_SUFFIX.test(frag.relurl);
- })) {
- _logger.logger.warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');
- frag = new _fragment2.default();
- frag.relurl = level.fragments[0].relurl;
- frag.baseurl = baseurl;
- frag.level = id;
- frag.type = type;
- frag.sn = 'initSegment';
- level.initSegment = frag;
- level.needSidxRanges = true;
- }
- }
- /**
- * Backfill any missing PDT values
- "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
- one or more Media Segment URIs, the client SHOULD extrapolate
- backward from that tag (using EXTINF durations and/or media
- timestamps) to associate dates with those segments."
- * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
- * computed.
- */
- if (firstPdtIndex) {
- backfillProgramDateTimes(level.fragments, firstPdtIndex);
- }
- return level;
- }
- }]);
- return M3U8Parser;
- }();
- exports.default = M3U8Parser;
- function backfillProgramDateTimes(fragments, startIndex) {
- var fragPrev = fragments[startIndex];
- for (var i = startIndex - 1; i >= 0; i--) {
- var frag = fragments[i];
- frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
- fragPrev = frag;
- }
- }
- function assignProgramDateTime(frag, prevFrag) {
- if (frag.rawProgramDateTime) {
- frag.programDateTime = Date.parse(frag.rawProgramDateTime);
- } else if (prevFrag && prevFrag.programDateTime) {
- frag.programDateTime = prevFrag.endProgramDateTime;
- }
- if (!Number.isFinite(frag.programDateTime)) {
- frag.programDateTime = null;
- frag.rawProgramDateTime = null;
- }
- }
- module.exports = exports['default'];
- /***/ }),
- /* 36 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var Level = function () {
- function Level(baseUrl) {
- _classCallCheck(this, Level);
- // Please keep properties in alphabetical order
- this.endCC = 0;
- this.endSN = 0;
- this.fragments = [];
- this.initSegment = null;
- this.live = true;
- this.needSidxRanges = false;
- this.startCC = 0;
- this.startSN = 0;
- this.startTimeOffset = null;
- this.targetduration = 0;
- this.totalduration = 0;
- this.type = null;
- this.url = baseUrl;
- this.version = null;
- }
- _createClass(Level, [{
- key: "hasProgramDateTime",
- get: function get() {
- return !!(this.fragments[0] && Number.isFinite(this.fragments[0].programDateTime));
- }
- }]);
- return Level;
- }();
- exports.default = Level;
- module.exports = exports["default"];
- /***/ }),
- /* 37 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; // eslint-disable-line no-useless-escape
- var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape
- // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
- var AttrList = function () {
- function AttrList(attrs) {
- _classCallCheck(this, AttrList);
- if (typeof attrs === 'string') {
- attrs = AttrList.parseAttrList(attrs);
- }
- for (var attr in attrs) {
- if (attrs.hasOwnProperty(attr)) {
- this[attr] = attrs[attr];
- }
- }
- }
- _createClass(AttrList, [{
- key: 'decimalInteger',
- value: function decimalInteger(attrName) {
- var intValue = parseInt(this[attrName], 10);
- if (intValue > Number.MAX_SAFE_INTEGER) {
- return Infinity;
- }
- return intValue;
- }
- }, {
- key: 'hexadecimalInteger',
- value: function hexadecimalInteger(attrName) {
- if (this[attrName]) {
- var stringValue = (this[attrName] || '0x').slice(2);
- stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
- var value = new Uint8Array(stringValue.length / 2);
- for (var i = 0; i < stringValue.length / 2; i++) {
- value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
- }
- return value;
- } else {
- return null;
- }
- }
- }, {
- key: 'hexadecimalIntegerAsNumber',
- value: function hexadecimalIntegerAsNumber(attrName) {
- var intValue = parseInt(this[attrName], 16);
- if (intValue > Number.MAX_SAFE_INTEGER) {
- return Infinity;
- }
- return intValue;
- }
- }, {
- key: 'decimalFloatingPoint',
- value: function decimalFloatingPoint(attrName) {
- return parseFloat(this[attrName]);
- }
- }, {
- key: 'enumeratedString',
- value: function enumeratedString(attrName) {
- return this[attrName];
- }
- }, {
- key: 'decimalResolution',
- value: function decimalResolution(attrName) {
- var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
- if (res === null) {
- return undefined;
- }
- return {
- width: parseInt(res[1], 10),
- height: parseInt(res[2], 10)
- };
- }
- }], [{
- key: 'parseAttrList',
- value: function parseAttrList(input) {
- var match = void 0,
- attrs = {};
- ATTR_LIST_REGEX.lastIndex = 0;
- while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
- var value = match[2],
- quote = '"';
- if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
- value = value.slice(1, -1);
- }
- attrs[match[1]] = value;
- }
- return attrs;
- }
- }]);
- return AttrList;
- }();
- exports.default = AttrList;
- module.exports = exports['default'];
- /***/ }),
- /* 38 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- 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); } };
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _eventHandler = __webpack_require__(3);
- var _eventHandler2 = _interopRequireDefault(_eventHandler);
- var _errors = __webpack_require__(2);
- var _logger = __webpack_require__(0);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /*
- * Fragment Loader
- */
- var FragmentLoader = function (_EventHandler) {
- _inherits(FragmentLoader, _EventHandler);
- function FragmentLoader(hls) {
- _classCallCheck(this, FragmentLoader);
- var _this = _possibleConstructorReturn(this, (FragmentLoader.__proto__ || Object.getPrototypeOf(FragmentLoader)).call(this, hls, _events2.default.FRAG_LOADING));
- _this.loaders = {};
- return _this;
- }
- _createClass(FragmentLoader, [{
- key: 'destroy',
- value: function destroy() {
- var loaders = this.loaders;
- for (var loaderName in loaders) {
- var loader = loaders[loaderName];
- if (loader) {
- loader.destroy();
- }
- }
- this.loaders = {};
- _get(FragmentLoader.prototype.__proto__ || Object.getPrototypeOf(FragmentLoader.prototype), 'destroy', this).call(this);
- }
- }, {
- key: 'onFragLoading',
- value: function onFragLoading(data) {
- var frag = data.frag,
- type = frag.type,
- loaders = this.loaders,
- config = this.hls.config,
- FragmentILoader = config.fLoader,
- DefaultILoader = config.loader;
- // reset fragment state
- frag.loaded = 0;
- var loader = loaders[type];
- if (loader) {
- _logger.logger.warn('abort previous fragment loader for type: ' + type);
- loader.abort();
- }
- loader = loaders[type] = frag.loader = config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);
- var loaderContext = void 0,
- loaderConfig = void 0,
- loaderCallbacks = void 0;
- loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false };
- var start = frag.byteRangeStartOffset,
- end = frag.byteRangeEndOffset;
- if (Number.isFinite(start) && Number.isFinite(end)) {
- loaderContext.rangeStart = start;
- loaderContext.rangeEnd = end;
- }
- loaderConfig = {
- timeout: config.fragLoadingTimeOut,
- maxRetry: 0,
- retryDelay: 0,
- maxRetryDelay: config.fragLoadingMaxRetryTimeout
- };
- loaderCallbacks = {
- onSuccess: this.loadsuccess.bind(this),
- onError: this.loaderror.bind(this),
- onTimeout: this.loadtimeout.bind(this),
- onProgress: this.loadprogress.bind(this)
- };
- loader.load(loaderContext, loaderConfig, loaderCallbacks);
- }
- }, {
- key: 'loadsuccess',
- value: function loadsuccess(response, stats, context) {
- var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
- var payload = response.data,
- frag = context.frag;
- // detach fragment loader on load success
- frag.loader = undefined;
- this.loaders[frag.type] = undefined;
- this.hls.trigger(_events2.default.FRAG_LOADED, { payload: payload, frag: frag, stats: stats, networkDetails: networkDetails });
- }
- }, {
- key: 'loaderror',
- value: function loaderror(response, context) {
- var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
- var frag = context.frag;
- var loader = frag.loader;
- if (loader) {
- loader.abort();
- }
- this.loaders[frag.type] = undefined;
- 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 });
- }
- }, {
- key: 'loadtimeout',
- value: function loadtimeout(stats, context) {
- var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
- var frag = context.frag;
- var loader = frag.loader;
- if (loader) {
- loader.abort();
- }
- this.loaders[frag.type] = undefined;
- this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag, networkDetails: networkDetails });
- }
- // data will be used for progressive parsing
- }, {
- key: 'loadprogress',
- value: function loadprogress(stats, context, data) {
- var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
- // jshint ignore:line
- var frag = context.frag;
- frag.loaded = stats.loaded;
- this.hls.trigger(_events2.default.FRAG_LOAD_PROGRESS, { frag: frag, stats: stats, networkDetails: networkDetails });
- }
- }]);
- return FragmentLoader;
- }(_eventHandler2.default);
- exports.default = FragmentLoader;
- module.exports = exports['default'];
- /***/ }),
- /* 39 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _eventHandler = __webpack_require__(3);
- var _eventHandler2 = _interopRequireDefault(_eventHandler);
- var _errors = __webpack_require__(2);
- var _logger = __webpack_require__(0);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /*
- * Decrypt key Loader
- */
- var KeyLoader = function (_EventHandler) {
- _inherits(KeyLoader, _EventHandler);
- function KeyLoader(hls) {
- _classCallCheck(this, KeyLoader);
- var _this = _possibleConstructorReturn(this, (KeyLoader.__proto__ || Object.getPrototypeOf(KeyLoader)).call(this, hls, _events2.default.KEY_LOADING));
- _this.loaders = {};
- _this.decryptkey = null;
- _this.decrypturl = null;
- return _this;
- }
- _createClass(KeyLoader, [{
- key: 'destroy',
- value: function destroy() {
- for (var loaderName in this.loaders) {
- var loader = this.loaders[loaderName];
- if (loader) {
- loader.destroy();
- }
- }
- this.loaders = {};
- _eventHandler2.default.prototype.destroy.call(this);
- }
- }, {
- key: 'onKeyLoading',
- value: function onKeyLoading(data) {
- var frag = data.frag,
- type = frag.type,
- loader = this.loaders[type],
- decryptdata = frag.decryptdata,
- uri = decryptdata.uri;
- // if uri is different from previous one or if decrypt key not retrieved yet
- if (uri !== this.decrypturl || this.decryptkey === null) {
- var config = this.hls.config;
- if (loader) {
- _logger.logger.warn('abort previous key loader for type:' + type);
- loader.abort();
- }
- frag.loader = this.loaders[type] = new config.loader(config);
- this.decrypturl = uri;
- this.decryptkey = null;
- var loaderContext = void 0,
- loaderConfig = void 0,
- loaderCallbacks = void 0;
- loaderContext = { url: uri, frag: frag, responseType: 'arraybuffer' };
- // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
- // key-loader will trigger an error and rely on stream-controller to handle retry logic.
- // this will also align retry logic with fragment-loader
- loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: 0, retryDelay: config.fragLoadingRetryDelay, maxRetryDelay: config.fragLoadingMaxRetryTimeout };
- loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) };
- frag.loader.load(loaderContext, loaderConfig, loaderCallbacks);
- } else if (this.decryptkey) {
- // we already loaded this key, return it
- decryptdata.key = this.decryptkey;
- this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag });
- }
- }
- }, {
- key: 'loadsuccess',
- value: function loadsuccess(response, stats, context) {
- var frag = context.frag;
- this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data);
- // detach fragment loader on load success
- frag.loader = undefined;
- this.loaders[frag.type] = undefined;
- this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag });
- }
- }, {
- key: 'loaderror',
- value: function loaderror(response, context) {
- var frag = context.frag,
- loader = frag.loader;
- if (loader) {
- loader.abort();
- }
- this.loaders[context.type] = undefined;
- this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: frag, response: response });
- }
- }, {
- key: 'loadtimeout',
- value: function loadtimeout(stats, context) {
- var frag = context.frag,
- loader = frag.loader;
- if (loader) {
- loader.abort();
- }
- this.loaders[context.type] = undefined;
- this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_TIMEOUT, fatal: false, frag: frag });
- }
- }]);
- return KeyLoader;
- }(_eventHandler2.default);
- exports.default = KeyLoader;
- module.exports = exports['default'];
- /***/ }),
- /* 40 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- 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); } };
- var _binarySearch = __webpack_require__(9);
- var _binarySearch2 = _interopRequireDefault(_binarySearch);
- var _bufferHelper = __webpack_require__(4);
- var _demuxer = __webpack_require__(19);
- var _demuxer2 = _interopRequireDefault(_demuxer);
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _fragmentTracker = __webpack_require__(6);
- var _fragment = __webpack_require__(11);
- var _fragment2 = _interopRequireDefault(_fragment);
- var _playlistLoader = __webpack_require__(15);
- var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
- var _levelHelper = __webpack_require__(7);
- var LevelHelper = _interopRequireWildcard(_levelHelper);
- var _timeRanges = __webpack_require__(25);
- var _timeRanges2 = _interopRequireDefault(_timeRanges);
- var _errors = __webpack_require__(2);
- var _logger = __webpack_require__(0);
- var _discontinuities = __webpack_require__(26);
- var _fragmentFinders = __webpack_require__(27);
- var _gapController = __webpack_require__(56);
- var _gapController2 = _interopRequireDefault(_gapController);
- var _baseStreamController = __webpack_require__(14);
- var _baseStreamController2 = _interopRequireDefault(_baseStreamController);
- 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; } }
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /*
- * Stream Controller
- */
- var TICK_INTERVAL = 100; // how often to tick in ms
- var StreamController = function (_BaseStreamController) {
- _inherits(StreamController, _BaseStreamController);
- function StreamController(hls, fragmentTracker) {
- _classCallCheck(this, StreamController);
- 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));
- _this.fragmentTracker = fragmentTracker;
- _this.config = hls.config;
- _this.audioCodecSwap = false;
- _this._state = _baseStreamController.State.STOPPED;
- _this.stallReported = false;
- _this.gapController = null;
- return _this;
- }
- _createClass(StreamController, [{
- key: 'startLoad',
- value: function startLoad(startPosition) {
- if (this.levels) {
- var lastCurrentTime = this.lastCurrentTime,
- hls = this.hls;
- this.stopLoad();
- this.setInterval(TICK_INTERVAL);
- this.level = -1;
- this.fragLoadError = 0;
- if (!this.startFragRequested) {
- // determine load level
- var startLevel = hls.startLevel;
- if (startLevel === -1) {
- // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
- startLevel = 0;
- this.bitrateTest = true;
- }
- // set new level to playlist loader : this will trigger start level load
- // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
- this.level = hls.nextLoadLevel = startLevel;
- this.loadedmetadata = false;
- }
- // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
- if (lastCurrentTime > 0 && startPosition === -1) {
- _logger.logger.log('override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3));
- startPosition = lastCurrentTime;
- }
- this.state = _baseStreamController.State.IDLE;
- this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
- this.tick();
- } else {
- this.forceStartLoad = true;
- this.state = _baseStreamController.State.STOPPED;
- }
- }
- }, {
- key: 'stopLoad',
- value: function stopLoad() {
- this.forceStartLoad = false;
- _get(StreamController.prototype.__proto__ || Object.getPrototypeOf(StreamController.prototype), 'stopLoad', this).call(this);
- }
- }, {
- key: 'doTick',
- value: function doTick() {
- switch (this.state) {
- case _baseStreamController.State.BUFFER_FLUSHING:
- // in buffer flushing state, reset fragLoadError counter
- this.fragLoadError = 0;
- break;
- case _baseStreamController.State.IDLE:
- this._doTickIdle();
- break;
- case _baseStreamController.State.WAITING_LEVEL:
- var level = this.levels[this.level];
- // check if playlist is already loaded
- if (level && level.details) {
- this.state = _baseStreamController.State.IDLE;
- }
- break;
- case _baseStreamController.State.FRAG_LOADING_WAITING_RETRY:
- var now = window.performance.now();
- var retryDate = this.retryDate;
- // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
- if (!retryDate || now >= retryDate || this.media && this.media.seeking) {
- _logger.logger.log('mediaController: retryDate reached, switch back to IDLE state');
- this.state = _baseStreamController.State.IDLE;
- }
- break;
- case _baseStreamController.State.ERROR:
- case _baseStreamController.State.STOPPED:
- case _baseStreamController.State.FRAG_LOADING:
- case _baseStreamController.State.PARSING:
- case _baseStreamController.State.PARSED:
- case _baseStreamController.State.ENDED:
- break;
- default:
- break;
- }
- // check buffer
- this._checkBuffer();
- // check/update current fragment
- this._checkFragmentChanged();
- }
- // Ironically the "idle" state is the on we do the most logic in it seems ....
- // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently
- // played segment, or on pause/play/seek instead of naively checking every 100ms?
- }, {
- key: '_doTickIdle',
- value: function _doTickIdle() {
- var hls = this.hls,
- config = hls.config,
- media = this.media;
- // if start level not parsed yet OR
- // if video not attached AND start fragment already requested OR start frag prefetch disable
- // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
- if (this.levelLastLoaded === undefined || !media && (this.startFragRequested || !config.startFragPrefetch)) {
- return;
- }
- // if we have not yet loaded any fragment, start loading from start position
- var pos = void 0;
- if (this.loadedmetadata) {
- pos = media.currentTime;
- } else {
- pos = this.nextLoadPosition;
- }
- // determine next load level
- var level = hls.nextLoadLevel,
- levelInfo = this.levels[level];
- if (!levelInfo) {
- return;
- }
- var levelBitrate = levelInfo.bitrate,
- maxBufLen = void 0;
- // 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
- if (levelBitrate) {
- maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
- } else {
- maxBufLen = config.maxBufferLength;
- }
- maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);
- // determine next candidate fragment to be loaded, based on current position and end of buffer position
- // ensure up to `config.maxMaxBufferLength` of buffer upfront
- var bufferInfo = _bufferHelper.BufferHelper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, config.maxBufferHole),
- bufferLen = bufferInfo.len;
- // Stay idle if we are still with buffer margins
- if (bufferLen >= maxBufLen) {
- return;
- }
- // if buffer length is less than maxBufLen try to load a new fragment ...
- _logger.logger.trace('buffer length of ' + bufferLen.toFixed(3) + ' is below max of ' + maxBufLen.toFixed(3) + '. checking for more payload ...');
- // set next load level : this will trigger a playlist load if needed
- this.level = hls.nextLoadLevel = level;
- var levelDetails = levelInfo.details;
- // if level info not retrieved yet, switch state and wait for level retrieval
- // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
- // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
- if (!levelDetails || levelDetails.live && this.levelLastLoaded !== level) {
- this.state = _baseStreamController.State.WAITING_LEVEL;
- return;
- }
- if (this._streamEnded(bufferInfo, levelDetails)) {
- var data = {};
- if (this.altAudio) {
- data.type = 'video';
- }
- this.hls.trigger(_events2.default.BUFFER_EOS, data);
- this.state = _baseStreamController.State.ENDED;
- return;
- }
- // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)
- this._fetchPayloadOrEos(pos, bufferInfo, levelDetails);
- }
- }, {
- key: '_fetchPayloadOrEos',
- value: function _fetchPayloadOrEos(pos, bufferInfo, levelDetails) {
- var fragPrevious = this.fragPrevious,
- level = this.level,
- fragments = levelDetails.fragments,
- fragLen = fragments.length;
- // empty playlist
- if (fragLen === 0) {
- return;
- }
- // find fragment index, contiguous with end of buffer position
- var start = fragments[0].start,
- end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
- bufferEnd = bufferInfo.end,
- frag = void 0;
- if (levelDetails.initSegment && !levelDetails.initSegment.data) {
- frag = levelDetails.initSegment;
- } else {
- // in case of live playlist we need to ensure that requested position is not located before playlist start
- if (levelDetails.live) {
- var initialLiveManifestSize = this.config.initialLiveManifestSize;
- if (fragLen < initialLiveManifestSize) {
- _logger.logger.warn('Can not start playback of a level, reason: not enough fragments ' + fragLen + ' < ' + initialLiveManifestSize);
- return;
- }
- frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen);
- // if it explicitely returns null don't load any fragment and exit function now
- if (frag === null) {
- return;
- }
- } else {
- // VoD playlist: if bufferEnd before start of playlist, load first fragment
- if (bufferEnd < start) {
- frag = fragments[0];
- }
- }
- }
- if (!frag) {
- frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);
- }
- if (frag) {
- if (frag.encrypted) {
- _logger.logger.log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level);
- this._loadKey(frag);
- } else {
- _logger.logger.log('Loading ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level + ', currentTime:' + pos.toFixed(3) + ',bufferEnd:' + bufferEnd.toFixed(3));
- this._loadFragment(frag);
- }
- }
- }
- }, {
- key: '_ensureFragmentAtLivePoint',
- value: function _ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen) {
- var config = this.hls.config,
- media = this.media;
- var frag = void 0;
- // check if requested position is within seekable boundaries :
- // logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);
- var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
- if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {
- var liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);
- _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));
- bufferEnd = liveSyncPosition;
- if (media && media.readyState && media.duration > liveSyncPosition) {
- media.currentTime = liveSyncPosition;
- }
- this.nextLoadPosition = liveSyncPosition;
- }
- // if end of buffer greater than live edge, don't load any fragment
- // this could happen if live playlist intermittently slides in the past.
- // level 1 loaded [182580161,182580167]
- // level 1 loaded [182580162,182580169]
- // Loading 182580168 of [182580162 ,182580169],level 1 ..
- // Loading 182580169 of [182580162 ,182580169],level 1 ..
- // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168
- // level 1 loaded [182580164,182580171]
- //
- // don't return null in case media not loaded yet (readystate === 0)
- if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {
- return null;
- }
- if (this.startFragRequested && !levelDetails.PTSKnown) {
- /* we are switching level on live playlist, but we don't have any PTS info for that quality level ...
- try to load frag matching with next SN.
- even if SN are not synchronized between playlists, loading this frag will help us
- compute playlist sliding and find the right one after in case it was not the right consecutive one */
- if (fragPrevious) {
- if (levelDetails.hasProgramDateTime) {
- // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)
- _logger.logger.log('live playlist, switching playlist, load frag with same PDT: ' + fragPrevious.programDateTime);
- frag = (0, _fragmentFinders.findFragmentByPDT)(fragments, fragPrevious.endProgramDateTime, config.maxFragLookUpTolerance);
- } else {
- // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
- var targetSN = fragPrevious.sn + 1;
- if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
- var fragNext = fragments[targetSN - levelDetails.startSN];
- if (fragPrevious.cc === fragNext.cc) {
- frag = fragNext;
- _logger.logger.log('live playlist, switching playlist, load frag with next SN: ' + frag.sn);
- }
- }
- // next frag SN not available (or not with same continuity counter)
- // look for a frag sharing the same CC
- if (!frag) {
- frag = _binarySearch2.default.search(fragments, function (frag) {
- return fragPrevious.cc - frag.cc;
- });
- if (frag) {
- _logger.logger.log('live playlist, switching playlist, load frag with same CC: ' + frag.sn);
- }
- }
- }
- }
- if (!frag) {
- /* we have no idea about which fragment should be loaded.
- so let's load mid fragment. it will help computing playlist sliding and find the right one
- */
- frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))];
- _logger.logger.log('live playlist, switching playlist, unknown, load middle frag : ' + frag.sn);
- }
- }
- return frag;
- }
- }, {
- key: '_findFragment',
- value: function _findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails) {
- var config = this.hls.config;
- var frag = void 0;
- if (bufferEnd < end) {
- var lookupTolerance = bufferEnd > end - config.maxFragLookUpTolerance ? 0 : config.maxFragLookUpTolerance;
- // Remove the tolerance if it would put the bufferEnd past the actual end of stream
- // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
- frag = (0, _fragmentFinders.findFragmentByPTS)(fragPrevious, fragments, bufferEnd, lookupTolerance);
- } else {
- // reach end of playlist
- frag = fragments[fragLen - 1];
- }
- if (frag) {
- var curSNIdx = frag.sn - levelDetails.startSN;
- var sameLevel = fragPrevious && frag.level === fragPrevious.level;
- var prevFrag = fragments[curSNIdx - 1];
- var nextFrag = fragments[curSNIdx + 1];
- // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
- if (fragPrevious && frag.sn === fragPrevious.sn) {
- if (sameLevel && !frag.backtracked) {
- if (frag.sn < levelDetails.endSN) {
- var deltaPTS = fragPrevious.deltaPTS;
- // if there is a significant delta between audio and video, larger than max allowed hole,
- // and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)
- // let's try to load previous fragment again to get last keyframe
- // then we will reload again current fragment (that way we should be able to fill the buffer hole ...)
- if (deltaPTS && deltaPTS > config.maxBufferHole && fragPrevious.dropped && curSNIdx) {
- frag = prevFrag;
- _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');
- } else {
- frag = nextFrag;
- _logger.logger.log('SN just loaded, load next one: ' + frag.sn, frag);
- }
- } else {
- frag = null;
- }
- } else if (frag.backtracked) {
- // Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes
- if (nextFrag && nextFrag.backtracked) {
- _logger.logger.warn('Already backtracked from fragment ' + nextFrag.sn + ', will not backtrack to fragment ' + frag.sn + '. Loading fragment ' + nextFrag.sn);
- frag = nextFrag;
- } else {
- // If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe
- // 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
- _logger.logger.warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');
- frag.dropped = 0;
- if (prevFrag) {
- frag = prevFrag;
- frag.backtracked = true;
- } else if (curSNIdx) {
- // can't backtrack on very first fragment
- frag = null;
- }
- }
- }
- }
- }
- return frag;
- }
- }, {
- key: '_loadKey',
- value: function _loadKey(frag) {
- this.state = _baseStreamController.State.KEY_LOADING;
- this.hls.trigger(_events2.default.KEY_LOADING, { frag: frag });
- }
- }, {
- key: '_loadFragment',
- value: function _loadFragment(frag) {
- // Check if fragment is not loaded
- var fragState = this.fragmentTracker.getState(frag);
- this.fragCurrent = frag;
- this.startFragRequested = true;
- // Don't update nextLoadPosition for fragments which are not buffered
- if (Number.isFinite(frag.sn) && !frag.bitrateTest) {
- this.nextLoadPosition = frag.start + frag.duration;
- }
- // Allow backtracked fragments to load
- if (frag.backtracked || fragState === _fragmentTracker.FragmentState.NOT_LOADED || fragState === _fragmentTracker.FragmentState.PARTIAL) {
- frag.autoLevel = this.hls.autoLevelEnabled;
- frag.bitrateTest = this.bitrateTest;
- this.hls.trigger(_events2.default.FRAG_LOADING, { frag: frag });
- // lazy demuxer init, as this could take some time ... do it during frag loading
- if (!this.demuxer) {
- this.demuxer = new _demuxer2.default(this.hls, 'main');
- }
- this.state = _baseStreamController.State.FRAG_LOADING;
- } else if (fragState === _fragmentTracker.FragmentState.APPENDING) {
- // Lower the buffer size and try again
- if (this._reduceMaxBufferLength(frag.duration)) {
- this.fragmentTracker.removeFragment(frag);
- }
- }
- }
- }, {
- key: 'getBufferedFrag',
- value: function getBufferedFrag(position) {
- return this.fragmentTracker.getBufferedFrag(position, _playlistLoader2.default.LevelType.MAIN);
- }
- }, {
- key: 'followingBufferedFrag',
- value: function followingBufferedFrag(frag) {
- if (frag) {
- // try to get range of next fragment (500ms after this range)
- return this.getBufferedFrag(frag.endPTS + 0.5);
- }
- return null;
- }
- }, {
- key: '_checkFragmentChanged',
- value: function _checkFragmentChanged() {
- var fragPlayingCurrent = void 0,
- currentTime = void 0,
- video = this.media;
- if (video && video.readyState && video.seeking === false) {
- currentTime = video.currentTime;
- /* if video element is in seeked state, currentTime can only increase.
- (assuming that playback rate is positive ...)
- As sometimes currentTime jumps back to zero after a
- media decode error, check this, to avoid seeking back to
- wrong position after a media decode error
- */
- if (currentTime > this.lastCurrentTime) {
- this.lastCurrentTime = currentTime;
- }
- if (_bufferHelper.BufferHelper.isBuffered(video, currentTime)) {
- fragPlayingCurrent = this.getBufferedFrag(currentTime);
- } else if (_bufferHelper.BufferHelper.isBuffered(video, currentTime + 0.1)) {
- /* ensure that FRAG_CHANGED event is triggered at startup,
- when first video frame is displayed and playback is paused.
- add a tolerance of 100ms, in case current position is not buffered,
- check if current pos+100ms is buffered and use that buffer range
- for FRAG_CHANGED event reporting */
- fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1);
- }
- if (fragPlayingCurrent) {
- var fragPlaying = fragPlayingCurrent;
- if (fragPlaying !== this.fragPlaying) {
- this.hls.trigger(_events2.default.FRAG_CHANGED, { frag: fragPlaying });
- var fragPlayingLevel = fragPlaying.level;
- if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {
- this.hls.trigger(_events2.default.LEVEL_SWITCHED, { level: fragPlayingLevel });
- }
- this.fragPlaying = fragPlaying;
- }
- }
- }
- }
- /*
- on immediate level switch :
- - pause playback if playing
- - cancel any pending load request
- - and trigger a buffer flush
- */
- }, {
- key: 'immediateLevelSwitch',
- value: function immediateLevelSwitch() {
- _logger.logger.log('immediateLevelSwitch');
- if (!this.immediateSwitch) {
- this.immediateSwitch = true;
- var media = this.media,
- previouslyPaused = void 0;
- if (media) {
- previouslyPaused = media.paused;
- media.pause();
- } else {
- // don't restart playback after instant level switch in case media not attached
- previouslyPaused = true;
- }
- this.previouslyPaused = previouslyPaused;
- }
- var fragCurrent = this.fragCurrent;
- if (fragCurrent && fragCurrent.loader) {
- fragCurrent.loader.abort();
- }
- this.fragCurrent = null;
- // flush everything
- this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
- }
- /**
- * on immediate level switch end, after new fragment has been buffered:
- * - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)
- * - resume the playback if needed
- */
- }, {
- key: 'immediateLevelSwitchEnd',
- value: function immediateLevelSwitchEnd() {
- var media = this.media;
- if (media && media.buffered.length) {
- this.immediateSwitch = false;
- if (_bufferHelper.BufferHelper.isBuffered(media, media.currentTime)) {
- // only nudge if currentTime is buffered
- media.currentTime -= 0.0001;
- }
- if (!this.previouslyPaused) {
- media.play();
- }
- }
- }
- /**
- * try to switch ASAP without breaking video playback:
- * in order to ensure smooth but quick level switching,
- * we need to find the next flushable buffer range
- * we should take into account new segment fetch time
- */
- }, {
- key: 'nextLevelSwitch',
- value: function nextLevelSwitch() {
- var media = this.media;
- // ensure that media is defined and that metadata are available (to retrieve currentTime)
- if (media && media.readyState) {
- var fetchdelay = void 0,
- fragPlayingCurrent = void 0,
- nextBufferedFrag = void 0;
- fragPlayingCurrent = this.getBufferedFrag(media.currentTime);
- if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) {
- // flush buffer preceding current fragment (flush until current fragment start offset)
- // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
- this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1);
- }
- if (!media.paused) {
- // add a safety delay of 1s
- var nextLevelId = this.hls.nextLoadLevel,
- nextLevel = this.levels[nextLevelId],
- fragLastKbps = this.fragLastKbps;
- if (fragLastKbps && this.fragCurrent) {
- fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;
- } else {
- fetchdelay = 0;
- }
- } else {
- fetchdelay = 0;
- }
- // logger.log('fetchdelay:'+fetchdelay);
- // find buffer range that will be reached once new fragment will be fetched
- nextBufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
- if (nextBufferedFrag) {
- // we can flush buffer range following this one without stalling playback
- nextBufferedFrag = this.followingBufferedFrag(nextBufferedFrag);
- if (nextBufferedFrag) {
- // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
- var fragCurrent = this.fragCurrent;
- if (fragCurrent && fragCurrent.loader) {
- fragCurrent.loader.abort();
- }
- this.fragCurrent = null;
- // start flush position is the start PTS of next buffered frag.
- // we use frag.naxStartPTS which is max(audio startPTS, video startPTS).
- // in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment
- this.flushMainBuffer(nextBufferedFrag.maxStartPTS, Number.POSITIVE_INFINITY);
- }
- }
- }
- }
- }, {
- key: 'flushMainBuffer',
- value: function flushMainBuffer(startOffset, endOffset) {
- this.state = _baseStreamController.State.BUFFER_FLUSHING;
- var flushScope = { startOffset: startOffset, endOffset: endOffset };
- // if alternate audio tracks are used, only flush video, otherwise flush everything
- if (this.altAudio) {
- flushScope.type = 'video';
- }
- this.hls.trigger(_events2.default.BUFFER_FLUSHING, flushScope);
- }
- }, {
- key: 'onMediaAttached',
- value: function onMediaAttached(data) {
- var media = this.media = this.mediaBuffer = data.media;
- this.onvseeking = this.onMediaSeeking.bind(this);
- this.onvseeked = this.onMediaSeeked.bind(this);
- this.onvended = this.onMediaEnded.bind(this);
- media.addEventListener('seeking', this.onvseeking);
- media.addEventListener('seeked', this.onvseeked);
- media.addEventListener('ended', this.onvended);
- var config = this.config;
- if (this.levels && config.autoStartLoad) {
- this.hls.startLoad(config.startPosition);
- }
- this.gapController = new _gapController2.default(config, media, this.fragmentTracker, this.hls);
- }
- }, {
- key: 'onMediaDetaching',
- value: function onMediaDetaching() {
- var media = this.media;
- if (media && media.ended) {
- _logger.logger.log('MSE detaching and video ended, reset startPosition');
- this.startPosition = this.lastCurrentTime = 0;
- }
- // reset fragment backtracked flag
- var levels = this.levels;
- if (levels) {
- levels.forEach(function (level) {
- if (level.details) {
- level.details.fragments.forEach(function (fragment) {
- fragment.backtracked = undefined;
- });
- }
- });
- }
- // remove video listeners
- if (media) {
- media.removeEventListener('seeking', this.onvseeking);
- media.removeEventListener('seeked', this.onvseeked);
- media.removeEventListener('ended', this.onvended);
- this.onvseeking = this.onvseeked = this.onvended = null;
- }
- this.media = this.mediaBuffer = null;
- this.loadedmetadata = false;
- this.stopLoad();
- }
- }, {
- key: 'onMediaSeeked',
- value: function onMediaSeeked() {
- var media = this.media,
- currentTime = media ? media.currentTime : undefined;
- if (Number.isFinite(currentTime)) {
- _logger.logger.log('media seeked to ' + currentTime.toFixed(3));
- }
- // tick to speed up FRAGMENT_PLAYING triggering
- this.tick();
- }
- }, {
- key: 'onManifestLoading',
- value: function onManifestLoading() {
- // reset buffer on manifest loading
- _logger.logger.log('trigger BUFFER_RESET');
- this.hls.trigger(_events2.default.BUFFER_RESET);
- this.fragmentTracker.removeAllFragments();
- this.stalled = false;
- this.startPosition = this.lastCurrentTime = 0;
- }
- }, {
- key: 'onManifestParsed',
- value: function onManifestParsed(data) {
- var aac = false,
- heaac = false,
- codec = void 0;
- data.levels.forEach(function (level) {
- // detect if we have different kind of audio codecs used amongst playlists
- codec = level.audioCodec;
- if (codec) {
- if (codec.indexOf('mp4a.40.2') !== -1) {
- aac = true;
- }
- if (codec.indexOf('mp4a.40.5') !== -1) {
- heaac = true;
- }
- }
- });
- this.audioCodecSwitch = aac && heaac;
- if (this.audioCodecSwitch) {
- _logger.logger.log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
- }
- this.levels = data.levels;
- this.startFragRequested = false;
- var config = this.config;
- if (config.autoStartLoad || this.forceStartLoad) {
- this.hls.startLoad(config.startPosition);
- }
- }
- }, {
- key: 'onLevelLoaded',
- value: function onLevelLoaded(data) {
- var newDetails = data.details;
- var newLevelId = data.level;
- var lastLevel = this.levels[this.levelLastLoaded];
- var curLevel = this.levels[newLevelId];
- var duration = newDetails.totalduration;
- var sliding = 0;
- _logger.logger.log('level ' + newLevelId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration);
- if (newDetails.live) {
- var curDetails = curLevel.details;
- if (curDetails && newDetails.fragments.length > 0) {
- // we already have details for that level, merge them
- LevelHelper.mergeDetails(curDetails, newDetails);
- sliding = newDetails.fragments[0].start;
- this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
- if (newDetails.PTSKnown && Number.isFinite(sliding)) {
- _logger.logger.log('live playlist sliding:' + sliding.toFixed(3));
- } else {
- _logger.logger.log('live playlist - outdated PTS, unknown sliding');
- (0, _discontinuities.alignStream)(this.fragPrevious, lastLevel, newDetails);
- }
- } else {
- _logger.logger.log('live playlist - first load, unknown sliding');
- newDetails.PTSKnown = false;
- (0, _discontinuities.alignStream)(this.fragPrevious, lastLevel, newDetails);
- }
- } else {
- newDetails.PTSKnown = false;
- }
- // override level info
- curLevel.details = newDetails;
- this.levelLastLoaded = newLevelId;
- this.hls.trigger(_events2.default.LEVEL_UPDATED, { details: newDetails, level: newLevelId });
- if (this.startFragRequested === false) {
- // compute start position if set to -1. use it straight away if value is defined
- if (this.startPosition === -1 || this.lastCurrentTime === -1) {
- // first, check if start time offset has been set in playlist, if yes, use this value
- var startTimeOffset = newDetails.startTimeOffset;
- if (Number.isFinite(startTimeOffset)) {
- if (startTimeOffset < 0) {
- _logger.logger.log('negative start time offset ' + startTimeOffset + ', count from end of last fragment');
- startTimeOffset = sliding + duration + startTimeOffset;
- }
- _logger.logger.log('start time offset found in playlist, adjust startPosition to ' + startTimeOffset);
- this.startPosition = startTimeOffset;
- } else {
- // if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)
- if (newDetails.live) {
- this.startPosition = this.computeLivePosition(sliding, newDetails);
- _logger.logger.log('configure startPosition to ' + this.startPosition);
- } else {
- this.startPosition = 0;
- }
- }
- this.lastCurrentTime = this.startPosition;
- }
- this.nextLoadPosition = this.startPosition;
- }
- // only switch batck to IDLE state if we were waiting for level to start downloading a new fragment
- if (this.state === _baseStreamController.State.WAITING_LEVEL) {
- this.state = _baseStreamController.State.IDLE;
- }
- // trigger handler right now
- this.tick();
- }
- }, {
- key: 'onKeyLoaded',
- value: function onKeyLoaded() {
- if (this.state === _baseStreamController.State.KEY_LOADING) {
- this.state = _baseStreamController.State.IDLE;
- this.tick();
- }
- }
- }, {
- key: 'onFragLoaded',
- value: function onFragLoaded(data) {
- var fragCurrent = this.fragCurrent,
- hls = this.hls,
- levels = this.levels,
- media = this.media;
- var fragLoaded = data.frag;
- if (this.state === _baseStreamController.State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'main' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
- var stats = data.stats;
- var currentLevel = levels[fragCurrent.level];
- var details = currentLevel.details;
- // reset frag bitrate test in any case after frag loaded event
- // if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0
- // then this means that we should be able to load a fragment at a higher quality level
- this.bitrateTest = false;
- this.stats = stats;
- _logger.logger.log('Loaded ' + fragCurrent.sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + fragCurrent.level);
- if (fragLoaded.bitrateTest && hls.nextLoadLevel) {
- // switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo
- this.state = _baseStreamController.State.IDLE;
- this.startFragRequested = false;
- stats.tparsed = stats.tbuffered = window.performance.now();
- hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
- this.tick();
- } else if (fragLoaded.sn === 'initSegment') {
- this.state = _baseStreamController.State.IDLE;
- stats.tparsed = stats.tbuffered = window.performance.now();
- details.initSegment.data = data.payload;
- hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
- this.tick();
- } else {
- _logger.logger.log('Parsing ' + fragCurrent.sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + fragCurrent.level + ', cc ' + fragCurrent.cc);
- this.state = _baseStreamController.State.PARSING;
- this.pendingBuffering = true;
- this.appended = false;
- // Bitrate test frags are not usually buffered so the fragment tracker ignores them. If Hls.js decides to buffer
- // it (and therefore ends up at this line), then the fragment tracker needs to be manually informed.
- if (fragLoaded.bitrateTest) {
- fragLoaded.bitrateTest = false;
- this.fragmentTracker.onFragLoaded({
- frag: fragLoaded
- });
- }
- // 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)
- var accurateTimeOffset = !(media && media.seeking) && (details.PTSKnown || !details.live);
- var initSegmentData = details.initSegment ? details.initSegment.data : [];
- var audioCodec = this._getAudioCodec(currentLevel);
- // transmux the MPEG-TS data to ISO-BMFF segments
- var demuxer = this.demuxer = this.demuxer || new _demuxer2.default(this.hls, 'main');
- demuxer.push(data.payload, initSegmentData, audioCodec, currentLevel.videoCodec, fragCurrent, details.totalduration, accurateTimeOffset);
- }
- }
- this.fragLoadError = 0;
- }
- }, {
- key: 'onFragParsingInitSegment',
- value: function onFragParsingInitSegment(data) {
- var fragCurrent = this.fragCurrent;
- var fragNew = data.frag;
- if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === _baseStreamController.State.PARSING) {
- var tracks = data.tracks,
- trackName = void 0,
- track = void 0;
- // if audio track is expected to come from audio stream controller, discard any coming from main
- if (tracks.audio && this.altAudio) {
- delete tracks.audio;
- }
- // include levelCodec in audio and video tracks
- track = tracks.audio;
- if (track) {
- var audioCodec = this.levels[this.level].audioCodec,
- ua = navigator.userAgent.toLowerCase();
- if (audioCodec && this.audioCodecSwap) {
- _logger.logger.log('swapping playlist audio codec');
- if (audioCodec.indexOf('mp4a.40.5') !== -1) {
- audioCodec = 'mp4a.40.2';
- } else {
- audioCodec = 'mp4a.40.5';
- }
- }
- // in case AAC and HE-AAC audio codecs are signalled in manifest
- // force HE-AAC , as it seems that most browsers prefers that way,
- // except for mono streams OR on FF
- // these conditions might need to be reviewed ...
- if (this.audioCodecSwitch) {
- // don't force HE-AAC if mono stream
- if (track.metadata.channelCount !== 1 &&
- // don't force HE-AAC if firefox
- ua.indexOf('firefox') === -1) {
- audioCodec = 'mp4a.40.5';
- }
- }
- // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
- if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') {
- // Exclude mpeg audio
- audioCodec = 'mp4a.40.2';
- _logger.logger.log('Android: force audio codec to ' + audioCodec);
- }
- track.levelCodec = audioCodec;
- track.id = data.id;
- }
- track = tracks.video;
- if (track) {
- track.levelCodec = this.levels[this.level].videoCodec;
- track.id = data.id;
- }
- this.hls.trigger(_events2.default.BUFFER_CODECS, tracks);
- // loop through tracks that are going to be provided to bufferController
- for (trackName in tracks) {
- track = tracks[trackName];
- _logger.logger.log('main track:' + trackName + ',container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']');
- var initSegment = track.initSegment;
- if (initSegment) {
- this.appended = true;
- // arm pending Buffering flag before appending a segment
- this.pendingBuffering = true;
- this.hls.trigger(_events2.default.BUFFER_APPENDING, { type: trackName, data: initSegment, parent: 'main', content: 'initSegment' });
- }
- }
- // trigger handler right now
- this.tick();
- }
- }
- }, {
- key: 'onFragParsingData',
- value: function onFragParsingData(data) {
- var _this2 = this;
- var fragCurrent = this.fragCurrent;
- var fragNew = data.frag;
- 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
- this.state === _baseStreamController.State.PARSING) {
- var level = this.levels[this.level],
- frag = fragCurrent;
- if (!Number.isFinite(data.endPTS)) {
- data.endPTS = data.startPTS + fragCurrent.duration;
- data.endDTS = data.startDTS + fragCurrent.duration;
- }
- if (data.hasAudio === true) {
- frag.addElementaryStream(_fragment2.default.ElementaryStreamTypes.AUDIO);
- }
- if (data.hasVideo === true) {
- frag.addElementaryStream(_fragment2.default.ElementaryStreamTypes.VIDEO);
- }
- _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));
- // Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments)
- if (data.type === 'video') {
- frag.dropped = data.dropped;
- if (frag.dropped) {
- if (!frag.backtracked) {
- var levelDetails = level.details;
- if (levelDetails && frag.sn === levelDetails.startSN) {
- _logger.logger.warn('missing video frame(s) on first frag, appending with gap', frag.sn);
- } else {
- _logger.logger.warn('missing video frame(s), backtracking fragment', frag.sn);
- // Return back to the IDLE state without appending to buffer
- // Causes findFragments to backtrack a segment and find the keyframe
- // Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment
- this.fragmentTracker.removeFragment(frag);
- frag.backtracked = true;
- this.nextLoadPosition = data.startPTS;
- this.state = _baseStreamController.State.IDLE;
- this.fragPrevious = frag;
- this.tick();
- return;
- }
- } else {
- _logger.logger.warn('Already backtracked on this fragment, appending with the gap', frag.sn);
- }
- } else {
- // Only reset the backtracked flag if we've loaded the frag without any dropped frames
- frag.backtracked = false;
- }
- }
- var drift = LevelHelper.updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS),
- hls = this.hls;
- hls.trigger(_events2.default.LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS });
- // has remuxer dropped video frames located before first keyframe ?
- [data.data1, data.data2].forEach(function (buffer) {
- // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
- // in that case it is useless to append following segments
- if (buffer && buffer.length && _this2.state === _baseStreamController.State.PARSING) {
- _this2.appended = true;
- // arm pending Buffering flag before appending a segment
- _this2.pendingBuffering = true;
- hls.trigger(_events2.default.BUFFER_APPENDING, { type: data.type, data: buffer, parent: 'main', content: 'data' });
- }
- });
- // trigger handler right now
- this.tick();
- }
- }
- }, {
- key: 'onFragParsed',
- value: function onFragParsed(data) {
- var fragCurrent = this.fragCurrent;
- var fragNew = data.frag;
- if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === _baseStreamController.State.PARSING) {
- this.stats.tparsed = window.performance.now();
- this.state = _baseStreamController.State.PARSED;
- this._checkAppendedParsed();
- }
- }
- }, {
- key: 'onAudioTrackSwitching',
- value: function onAudioTrackSwitching(data) {
- // if any URL found on new audio track, it is an alternate audio track
- var altAudio = !!data.url,
- trackId = data.id;
- // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
- // don't do anything if we switch to alt audio: audio stream controller is handling it.
- // we will just have to change buffer scheduling on audioTrackSwitched
- if (!altAudio) {
- if (this.mediaBuffer !== this.media) {
- _logger.logger.log('switching on main audio, use media.buffered to schedule main fragment loading');
- this.mediaBuffer = this.media;
- var fragCurrent = this.fragCurrent;
- // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
- if (fragCurrent.loader) {
- _logger.logger.log('switching to main audio track, cancel main fragment load');
- fragCurrent.loader.abort();
- }
- this.fragCurrent = null;
- this.fragPrevious = null;
- // destroy demuxer to force init segment generation (following audio switch)
- if (this.demuxer) {
- this.demuxer.destroy();
- this.demuxer = null;
- }
- // switch to IDLE state to load new fragment
- this.state = _baseStreamController.State.IDLE;
- }
- var hls = this.hls;
- // switching to main audio, flush all audio and trigger track switched
- hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
- hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: trackId });
- this.altAudio = false;
- }
- }
- }, {
- key: 'onAudioTrackSwitched',
- value: function onAudioTrackSwitched(data) {
- var trackId = data.id,
- altAudio = !!this.hls.audioTracks[trackId].url;
- if (altAudio) {
- var videoBuffer = this.videoBuffer;
- // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
- if (videoBuffer && this.mediaBuffer !== videoBuffer) {
- _logger.logger.log('switching on alternate audio, use video.buffered to schedule main fragment loading');
- this.mediaBuffer = videoBuffer;
- }
- }
- this.altAudio = altAudio;
- this.tick();
- }
- }, {
- key: 'onBufferCreated',
- value: function onBufferCreated(data) {
- var tracks = data.tracks,
- mediaTrack = void 0,
- name = void 0,
- alternate = false;
- for (var type in tracks) {
- var track = tracks[type];
- if (track.id === 'main') {
- name = type;
- mediaTrack = track;
- // keep video source buffer reference
- if (type === 'video') {
- this.videoBuffer = tracks[type].buffer;
- }
- } else {
- alternate = true;
- }
- }
- if (alternate && mediaTrack) {
- _logger.logger.log('alternate track found, use ' + name + '.buffered to schedule main fragment loading');
- this.mediaBuffer = mediaTrack.buffer;
- } else {
- this.mediaBuffer = this.media;
- }
- }
- }, {
- key: 'onBufferAppended',
- value: function onBufferAppended(data) {
- if (data.parent === 'main') {
- var state = this.state;
- if (state === _baseStreamController.State.PARSING || state === _baseStreamController.State.PARSED) {
- // check if all buffers have been appended
- this.pendingBuffering = data.pending > 0;
- this._checkAppendedParsed();
- }
- }
- }
- }, {
- key: '_checkAppendedParsed',
- value: function _checkAppendedParsed() {
- // trigger handler right now
- if (this.state === _baseStreamController.State.PARSED && (!this.appended || !this.pendingBuffering)) {
- var frag = this.fragCurrent;
- if (frag) {
- var media = this.mediaBuffer ? this.mediaBuffer : this.media;
- _logger.logger.log('main buffered : ' + _timeRanges2.default.toString(media.buffered));
- this.fragPrevious = frag;
- var stats = this.stats;
- stats.tbuffered = window.performance.now();
- // we should get rid of this.fragLastKbps
- this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));
- this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' });
- this.state = _baseStreamController.State.IDLE;
- }
- this.tick();
- }
- }
- }, {
- key: 'onError',
- value: function onError(data) {
- var frag = data.frag || this.fragCurrent;
- // don't handle frag error not related to main fragment
- if (frag && frag.type !== 'main') {
- return;
- }
- // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
- var mediaBuffered = !!this.media && _bufferHelper.BufferHelper.isBuffered(this.media, this.media.currentTime) && _bufferHelper.BufferHelper.isBuffered(this.media, this.media.currentTime + 0.5);
- switch (data.details) {
- case _errors.ErrorDetails.FRAG_LOAD_ERROR:
- case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
- case _errors.ErrorDetails.KEY_LOAD_ERROR:
- case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
- if (!data.fatal) {
- // keep retrying until the limit will be reached
- if (this.fragLoadError + 1 <= this.config.fragLoadingMaxRetry) {
- // exponential backoff capped to config.fragLoadingMaxRetryTimeout
- var delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);
- _logger.logger.warn('mediaController: frag loading failed, retry in ' + delay + ' ms');
- this.retryDate = window.performance.now() + delay;
- // retry loading state
- // if loadedmetadata is not set, it means that we are emergency switch down on first frag
- // in that case, reset startFragRequested flag
- if (!this.loadedmetadata) {
- this.startFragRequested = false;
- this.nextLoadPosition = this.startPosition;
- }
- this.fragLoadError++;
- this.state = _baseStreamController.State.FRAG_LOADING_WAITING_RETRY;
- } else {
- _logger.logger.error('mediaController: ' + data.details + ' reaches max retry, redispatch as fatal ...');
- // switch error to fatal
- data.fatal = true;
- this.state = _baseStreamController.State.ERROR;
- }
- }
- break;
- case _errors.ErrorDetails.LEVEL_LOAD_ERROR:
- case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT:
- if (this.state !== _baseStreamController.State.ERROR) {
- if (data.fatal) {
- // if fatal error, stop processing
- this.state = _baseStreamController.State.ERROR;
- _logger.logger.warn('streamController: ' + data.details + ',switch to ' + this.state + ' state ...');
- } else {
- // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE
- if (!data.levelRetry && this.state === _baseStreamController.State.WAITING_LEVEL) {
- this.state = _baseStreamController.State.IDLE;
- }
- }
- }
- break;
- case _errors.ErrorDetails.BUFFER_FULL_ERROR:
- // if in appending state
- if (data.parent === 'main' && (this.state === _baseStreamController.State.PARSING || this.state === _baseStreamController.State.PARSED)) {
- // reduce max buf len if current position is buffered
- if (mediaBuffered) {
- this._reduceMaxBufferLength(this.config.maxBufferLength);
- this.state = _baseStreamController.State.IDLE;
- } else {
- // current position is not buffered, but browser is still complaining about buffer full error
- // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
- // in that case flush the whole buffer to recover
- _logger.logger.warn('buffer full error also media.currentTime is not buffered, flush everything');
- this.fragCurrent = null;
- // flush everything
- this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
- }
- }
- break;
- default:
- break;
- }
- }
- }, {
- key: '_reduceMaxBufferLength',
- value: function _reduceMaxBufferLength(minLength) {
- var config = this.config;
- if (config.maxMaxBufferLength >= minLength) {
- // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
- config.maxMaxBufferLength /= 2;
- _logger.logger.warn('main:reduce max buffer length to ' + config.maxMaxBufferLength + 's');
- return true;
- }
- return false;
- }
- /**
- * Checks the health of the buffer and attempts to resolve playback stalls.
- * @private
- */
- }, {
- key: '_checkBuffer',
- value: function _checkBuffer() {
- var media = this.media;
- if (!media || media.readyState === 0) {
- // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0)
- return;
- }
- var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;
- var buffered = mediaBuffer.buffered;
- if (!this.loadedmetadata && buffered.length) {
- this.loadedmetadata = true;
- this._seekToStartPos();
- } else if (this.immediateSwitch) {
- this.immediateLevelSwitchEnd();
- } else {
- this.gapController.poll(this.lastCurrentTime, buffered);
- }
- }
- }, {
- key: 'onFragLoadEmergencyAborted',
- value: function onFragLoadEmergencyAborted() {
- this.state = _baseStreamController.State.IDLE;
- // if loadedmetadata is not set, it means that we are emergency switch down on first frag
- // in that case, reset startFragRequested flag
- if (!this.loadedmetadata) {
- this.startFragRequested = false;
- this.nextLoadPosition = this.startPosition;
- }
- this.tick();
- }
- }, {
- key: 'onBufferFlushed',
- value: function onBufferFlushed() {
- /* after successful buffer flushing, filter flushed fragments from bufferedFrags
- use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)
- */
- var media = this.mediaBuffer ? this.mediaBuffer : this.media;
- if (media) {
- // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams
- this.fragmentTracker.detectEvictedFragments(_fragment2.default.ElementaryStreamTypes.VIDEO, media.buffered);
- }
- // move to IDLE once flush complete. this should trigger new fragment loading
- this.state = _baseStreamController.State.IDLE;
- // reset reference to frag
- this.fragPrevious = null;
- }
- }, {
- key: 'swapAudioCodec',
- value: function swapAudioCodec() {
- this.audioCodecSwap = !this.audioCodecSwap;
- }
- }, {
- key: 'computeLivePosition',
- value: function computeLivePosition(sliding, levelDetails) {
- var targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration;
- return sliding + Math.max(0, levelDetails.totalduration - targetLatency);
- }
- /**
- * Seeks to the set startPosition if not equal to the mediaElement's current time.
- * @private
- */
- }, {
- key: '_seekToStartPos',
- value: function _seekToStartPos() {
- var media = this.media;
- var currentTime = media.currentTime;
- // only adjust currentTime if different from startPosition or if startPosition not buffered
- // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
- var startPosition = media.seeking ? currentTime : this.startPosition;
- // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered
- if (currentTime !== startPosition) {
- // if startPosition not buffered, let's seek to buffered.start(0)
- _logger.logger.log('target start position not buffered, seek to buffered.start(0) ' + startPosition + ' from current time ' + currentTime + ' ');
- media.currentTime = startPosition;
- }
- }
- }, {
- key: '_getAudioCodec',
- value: function _getAudioCodec(currentLevel) {
- var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
- if (this.audioCodecSwap) {
- _logger.logger.log('swapping playlist audio codec');
- if (audioCodec) {
- if (audioCodec.indexOf('mp4a.40.5') !== -1) {
- audioCodec = 'mp4a.40.2';
- } else {
- audioCodec = 'mp4a.40.5';
- }
- }
- }
- return audioCodec;
- }
- }, {
- key: 'state',
- set: function set(nextState) {
- if (this.state !== nextState) {
- var previousState = this.state;
- this._state = nextState;
- _logger.logger.log('main stream:' + previousState + '->' + nextState);
- this.hls.trigger(_events2.default.STREAM_STATE_TRANSITION, { previousState: previousState, nextState: nextState });
- }
- },
- get: function get() {
- return this._state;
- }
- }, {
- key: 'currentLevel',
- get: function get() {
- var media = this.media;
- if (media) {
- var frag = this.getBufferedFrag(media.currentTime);
- if (frag) {
- return frag.level;
- }
- }
- return -1;
- }
- }, {
- key: 'nextBufferedFrag',
- get: function get() {
- var media = this.media;
- if (media) {
- // first get end range of current fragment
- return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime));
- } else {
- return null;
- }
- }
- }, {
- key: 'nextLevel',
- get: function get() {
- var frag = this.nextBufferedFrag;
- if (frag) {
- return frag.level;
- } else {
- return -1;
- }
- }
- }, {
- key: 'liveSyncPosition',
- get: function get() {
- return this._liveSyncPosition;
- },
- set: function set(value) {
- this._liveSyncPosition = value;
- }
- }]);
- return StreamController;
- }(_baseStreamController2.default);
- exports.default = StreamController;
- module.exports = exports['default'];
- /***/ }),
- /* 41 */
- /***/ (function(module, exports, __webpack_require__) {
- function webpackBootstrapFunc (modules) {
- /******/ // The module cache
- /******/ var installedModules = {};
- /******/ // The require function
- /******/ function __webpack_require__(moduleId) {
- /******/ // Check if module is in cache
- /******/ if(installedModules[moduleId])
- /******/ return installedModules[moduleId].exports;
- /******/ // Create a new module (and put it into the cache)
- /******/ var module = installedModules[moduleId] = {
- /******/ i: moduleId,
- /******/ l: false,
- /******/ exports: {}
- /******/ };
- /******/ // Execute the module function
- /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
- /******/ // Flag the module as loaded
- /******/ module.l = true;
- /******/ // Return the exports of the module
- /******/ return module.exports;
- /******/ }
- /******/ // expose the modules object (__webpack_modules__)
- /******/ __webpack_require__.m = modules;
- /******/ // expose the module cache
- /******/ __webpack_require__.c = installedModules;
- /******/ // identity function for calling harmony imports with the correct context
- /******/ __webpack_require__.i = function(value) { return value; };
- /******/ // define getter function for harmony exports
- /******/ __webpack_require__.d = function(exports, name, getter) {
- /******/ if(!__webpack_require__.o(exports, name)) {
- /******/ Object.defineProperty(exports, name, {
- /******/ configurable: false,
- /******/ enumerable: true,
- /******/ get: getter
- /******/ });
- /******/ }
- /******/ };
- /******/ // define __esModule on exports
- /******/ __webpack_require__.r = function(exports) {
- /******/ Object.defineProperty(exports, '__esModule', { value: true });
- /******/ };
- /******/ // getDefaultExport function for compatibility with non-harmony modules
- /******/ __webpack_require__.n = function(module) {
- /******/ var getter = module && module.__esModule ?
- /******/ function getDefault() { return module['default']; } :
- /******/ function getModuleExports() { return module; };
- /******/ __webpack_require__.d(getter, 'a', getter);
- /******/ return getter;
- /******/ };
- /******/ // Object.prototype.hasOwnProperty.call
- /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
- /******/ // __webpack_public_path__
- /******/ __webpack_require__.p = "/";
- /******/ // on error function for async loading
- /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };
- var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE)
- return f.default || f // try to call default if defined to also support babel esmodule exports
- }
- var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+'
- var dependencyRegExp = '\\(\\s*(\/\\*.*?\\*\/)?\\s*.*?(' + moduleNameReqExp + ').*?\\)' // additional chars when output.pathinfo is true
- // http://stackoverflow.com/a/2593661/130442
- function quoteRegExp (str) {
- return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&')
- }
- function isNumeric(n) {
- return !isNaN(1 * n); // 1 * n converts integers, integers as string ("123"), 1e3 and "1e3" to integers and strings to NaN
- }
- function getModuleDependencies (sources, module, queueName) {
- var retval = {}
- retval[queueName] = []
- var fnString = module.toString()
- var wrapperSignature = fnString.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/)
- if (!wrapperSignature) return retval
- var webpackRequireName = wrapperSignature[1]
- // main bundle deps
- var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')
- var match
- while ((match = re.exec(fnString))) {
- if (match[3] === 'dll-reference') continue
- retval[queueName].push(match[3])
- }
- // dll deps
- re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g')
- while ((match = re.exec(fnString))) {
- if (!sources[match[2]]) {
- retval[queueName].push(match[1])
- sources[match[2]] = __webpack_require__(match[1]).m
- }
- retval[match[2]] = retval[match[2]] || []
- retval[match[2]].push(match[4])
- }
- // convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3
- var keys = Object.keys(retval);
- for (var i = 0; i < keys.length; i++) {
- for (var j = 0; j < retval[keys[i]].length; j++) {
- if (isNumeric(retval[keys[i]][j])) {
- retval[keys[i]][j] = 1 * retval[keys[i]][j];
- }
- }
- }
- return retval
- }
- function hasValuesInQueues (queues) {
- var keys = Object.keys(queues)
- return keys.reduce(function (hasValues, key) {
- return hasValues || queues[key].length > 0
- }, false)
- }
- function getRequiredModules (sources, moduleId) {
- var modulesQueue = {
- main: [moduleId]
- }
- var requiredModules = {
- main: []
- }
- var seenModules = {
- main: {}
- }
- while (hasValuesInQueues(modulesQueue)) {
- var queues = Object.keys(modulesQueue)
- for (var i = 0; i < queues.length; i++) {
- var queueName = queues[i]
- var queue = modulesQueue[queueName]
- var moduleToCheck = queue.pop()
- seenModules[queueName] = seenModules[queueName] || {}
- if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue
- seenModules[queueName][moduleToCheck] = true
- requiredModules[queueName] = requiredModules[queueName] || []
- requiredModules[queueName].push(moduleToCheck)
- var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)
- var newModulesKeys = Object.keys(newModules)
- for (var j = 0; j < newModulesKeys.length; j++) {
- modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []
- modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])
- }
- }
- }
- return requiredModules
- }
- module.exports = function (moduleId, options) {
- options = options || {}
- var sources = {
- main: __webpack_require__.m
- }
- var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId)
- var src = ''
- Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {
- var entryModule = 0
- while (requiredModules[module][entryModule]) {
- entryModule++
- }
- requiredModules[module].push(entryModule)
- sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'
- 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'
- })
- 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);'
- var blob = new window.Blob([src], { type: 'text/javascript' })
- if (options.bare) { return blob }
- var URL = window.URL || window.webkitURL || window.mozURL || window.msURL
- var workerUrl = URL.createObjectURL(blob)
- var worker = new window.Worker(workerUrl)
- worker.objectURL = workerUrl
- return worker
- }
- /***/ }),
- /* 42 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var AESCrypto = function () {
- function AESCrypto(subtle, iv) {
- _classCallCheck(this, AESCrypto);
- this.subtle = subtle;
- this.aesIV = iv;
- }
- _createClass(AESCrypto, [{
- key: 'decrypt',
- value: function decrypt(data, key) {
- return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data);
- }
- }]);
- return AESCrypto;
- }();
- exports.default = AESCrypto;
- module.exports = exports['default'];
- /***/ }),
- /* 43 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var FastAESKey = function () {
- function FastAESKey(subtle, key) {
- _classCallCheck(this, FastAESKey);
- this.subtle = subtle;
- this.key = key;
- }
- _createClass(FastAESKey, [{
- key: 'expandKey',
- value: function expandKey() {
- return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']);
- }
- }]);
- return FastAESKey;
- }();
- exports.default = FastAESKey;
- module.exports = exports['default'];
- /***/ }),
- /* 44 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- exports.removePadding = removePadding;
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- // PKCS7
- function removePadding(buffer) {
- var outputBytes = buffer.byteLength;
- var paddingBytes = outputBytes && new DataView(buffer).getUint8(outputBytes - 1);
- if (paddingBytes) {
- return buffer.slice(0, outputBytes - paddingBytes);
- } else {
- return buffer;
- }
- }
- var AESDecryptor = function () {
- function AESDecryptor() {
- _classCallCheck(this, AESDecryptor);
- // Static after running initTable
- this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
- this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
- this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
- this.sBox = new Uint32Array(256);
- this.invSBox = new Uint32Array(256);
- // Changes during runtime
- this.key = new Uint32Array(0);
- this.initTable();
- }
- // Using view.getUint32() also swaps the byte order.
- _createClass(AESDecryptor, [{
- key: 'uint8ArrayToUint32Array_',
- value: function uint8ArrayToUint32Array_(arrayBuffer) {
- var view = new DataView(arrayBuffer);
- var newArray = new Uint32Array(4);
- for (var i = 0; i < 4; i++) {
- newArray[i] = view.getUint32(i * 4);
- }
- return newArray;
- }
- }, {
- key: 'initTable',
- value: function initTable() {
- var sBox = this.sBox;
- var invSBox = this.invSBox;
- var subMix = this.subMix;
- var subMix0 = subMix[0];
- var subMix1 = subMix[1];
- var subMix2 = subMix[2];
- var subMix3 = subMix[3];
- var invSubMix = this.invSubMix;
- var invSubMix0 = invSubMix[0];
- var invSubMix1 = invSubMix[1];
- var invSubMix2 = invSubMix[2];
- var invSubMix3 = invSubMix[3];
- var d = new Uint32Array(256);
- var x = 0;
- var xi = 0;
- var i = 0;
- for (i = 0; i < 256; i++) {
- if (i < 128) {
- d[i] = i << 1;
- } else {
- d[i] = i << 1 ^ 0x11b;
- }
- }
- for (i = 0; i < 256; i++) {
- var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
- sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
- sBox[x] = sx;
- invSBox[sx] = x;
- // Compute multiplication
- var x2 = d[x];
- var x4 = d[x2];
- var x8 = d[x4];
- // Compute sub/invSub bytes, mix columns tables
- var t = d[sx] * 0x101 ^ sx * 0x1010100;
- subMix0[x] = t << 24 | t >>> 8;
- subMix1[x] = t << 16 | t >>> 16;
- subMix2[x] = t << 8 | t >>> 24;
- subMix3[x] = t;
- // Compute inv sub bytes, inv mix columns tables
- t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
- invSubMix0[sx] = t << 24 | t >>> 8;
- invSubMix1[sx] = t << 16 | t >>> 16;
- invSubMix2[sx] = t << 8 | t >>> 24;
- invSubMix3[sx] = t;
- // Compute next counter
- if (!x) {
- x = xi = 1;
- } else {
- x = x2 ^ d[d[d[x8 ^ x2]]];
- xi ^= d[d[xi]];
- }
- }
- }
- }, {
- key: 'expandKey',
- value: function expandKey(keyBuffer) {
- // convert keyBuffer to Uint32Array
- var key = this.uint8ArrayToUint32Array_(keyBuffer);
- var sameKey = true;
- var offset = 0;
- while (offset < key.length && sameKey) {
- sameKey = key[offset] === this.key[offset];
- offset++;
- }
- if (sameKey) {
- return;
- }
- this.key = key;
- var keySize = this.keySize = key.length;
- if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
- throw new Error('Invalid aes key size=' + keySize);
- }
- var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
- var ksRow = void 0;
- var invKsRow = void 0;
- var keySchedule = this.keySchedule = new Uint32Array(ksRows);
- var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
- var sbox = this.sBox;
- var rcon = this.rcon;
- var invSubMix = this.invSubMix;
- var invSubMix0 = invSubMix[0];
- var invSubMix1 = invSubMix[1];
- var invSubMix2 = invSubMix[2];
- var invSubMix3 = invSubMix[3];
- var prev = void 0;
- var t = void 0;
- for (ksRow = 0; ksRow < ksRows; ksRow++) {
- if (ksRow < keySize) {
- prev = keySchedule[ksRow] = key[ksRow];
- continue;
- }
- t = prev;
- if (ksRow % keySize === 0) {
- // Rot word
- t = t << 8 | t >>> 24;
- // Sub word
- t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
- // Mix Rcon
- t ^= rcon[ksRow / keySize | 0] << 24;
- } else if (keySize > 6 && ksRow % keySize === 4) {
- // Sub word
- t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
- }
- keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
- }
- for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
- ksRow = ksRows - invKsRow;
- if (invKsRow & 3) {
- t = keySchedule[ksRow];
- } else {
- t = keySchedule[ksRow - 4];
- }
- if (invKsRow < 4 || ksRow <= 4) {
- invKeySchedule[invKsRow] = t;
- } else {
- invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
- }
- invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
- }
- }
- // Adding this as a method greatly improves performance.
- }, {
- key: 'networkToHostOrderSwap',
- value: function networkToHostOrderSwap(word) {
- return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
- }
- }, {
- key: 'decrypt',
- value: function decrypt(inputArrayBuffer, offset, aesIV, removePKCS7Padding) {
- var nRounds = this.keySize + 6;
- var invKeySchedule = this.invKeySchedule;
- var invSBOX = this.invSBox;
- var invSubMix = this.invSubMix;
- var invSubMix0 = invSubMix[0];
- var invSubMix1 = invSubMix[1];
- var invSubMix2 = invSubMix[2];
- var invSubMix3 = invSubMix[3];
- var initVector = this.uint8ArrayToUint32Array_(aesIV);
- var initVector0 = initVector[0];
- var initVector1 = initVector[1];
- var initVector2 = initVector[2];
- var initVector3 = initVector[3];
- var inputInt32 = new Int32Array(inputArrayBuffer);
- var outputInt32 = new Int32Array(inputInt32.length);
- var t0 = void 0,
- t1 = void 0,
- t2 = void 0,
- t3 = void 0;
- var s0 = void 0,
- s1 = void 0,
- s2 = void 0,
- s3 = void 0;
- var inputWords0 = void 0,
- inputWords1 = void 0,
- inputWords2 = void 0,
- inputWords3 = void 0;
- var ksRow = void 0,
- i = void 0;
- var swapWord = this.networkToHostOrderSwap;
- while (offset < inputInt32.length) {
- inputWords0 = swapWord(inputInt32[offset]);
- inputWords1 = swapWord(inputInt32[offset + 1]);
- inputWords2 = swapWord(inputInt32[offset + 2]);
- inputWords3 = swapWord(inputInt32[offset + 3]);
- s0 = inputWords0 ^ invKeySchedule[0];
- s1 = inputWords3 ^ invKeySchedule[1];
- s2 = inputWords2 ^ invKeySchedule[2];
- s3 = inputWords1 ^ invKeySchedule[3];
- ksRow = 4;
- // Iterate through the rounds of decryption
- for (i = 1; i < nRounds; i++) {
- t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
- t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
- t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
- t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
- // Update state
- s0 = t0;
- s1 = t1;
- s2 = t2;
- s3 = t3;
- ksRow = ksRow + 4;
- }
- // Shift rows, sub bytes, add round key
- t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
- t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
- t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
- t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
- ksRow = ksRow + 3;
- // Write
- outputInt32[offset] = swapWord(t0 ^ initVector0);
- outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
- outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
- outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
- // reset initVector to last 4 unsigned int
- initVector0 = inputWords0;
- initVector1 = inputWords1;
- initVector2 = inputWords2;
- initVector3 = inputWords3;
- offset = offset + 4;
- }
- return removePKCS7Padding ? removePadding(outputInt32.buffer) : outputInt32.buffer;
- }
- }, {
- key: 'destroy',
- value: function destroy() {
- this.key = undefined;
- this.keySize = undefined;
- this.ksRows = undefined;
- this.sBox = undefined;
- this.invSBox = undefined;
- this.subMix = undefined;
- this.invSubMix = undefined;
- this.keySchedule = undefined;
- this.invKeySchedule = undefined;
- this.rcon = undefined;
- }
- }]);
- return AESDecryptor;
- }();
- exports.default = AESDecryptor;
- /***/ }),
- /* 45 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /**
- * AAC demuxer
- */
- var _adts = __webpack_require__(22);
- var ADTS = _interopRequireWildcard(_adts);
- var _logger = __webpack_require__(0);
- var _id = __webpack_require__(10);
- var _id2 = _interopRequireDefault(_id);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- 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; } }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var AACDemuxer = function () {
- function AACDemuxer(observer, remuxer, config) {
- _classCallCheck(this, AACDemuxer);
- this.observer = observer;
- this.config = config;
- this.remuxer = remuxer;
- }
- _createClass(AACDemuxer, [{
- key: 'resetInitSegment',
- value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
- this._audioTrack = { container: 'audio/adts', type: 'audio', id: 0, sequenceNumber: 0, isAAC: true, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };
- }
- }, {
- key: 'resetTimeStamp',
- value: function resetTimeStamp() {}
- }, {
- key: 'append',
- // feed incoming data to the front of the parsing pipeline
- value: function append(data, timeOffset, contiguous, accurateTimeOffset) {
- var track = this._audioTrack;
- var id3Data = _id2.default.getID3Data(data, 0) || [];
- var timestamp = _id2.default.getTimeStamp(id3Data);
- var pts = Number.isFinite(timestamp) ? timestamp * 90 : timeOffset * 90000;
- var frameIndex = 0;
- var stamp = pts;
- var length = data.length;
- var offset = id3Data.length;
- var id3Samples = [{ pts: stamp, dts: stamp, data: id3Data }];
- while (offset < length - 1) {
- if (ADTS.isHeader(data, offset) && offset + 5 < length) {
- ADTS.initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
- var frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);
- if (frame) {
- offset += frame.length;
- stamp = frame.sample.pts;
- frameIndex++;
- } else {
- _logger.logger.log('Unable to parse AAC frame');
- break;
- }
- } else if (_id2.default.isHeader(data, offset)) {
- id3Data = _id2.default.getID3Data(data, offset);
- id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });
- offset += id3Data.length;
- } else {
- // nothing found, keep looking
- offset++;
- }
- }
- this.remuxer.remux(track, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset);
- }
- }, {
- key: 'destroy',
- value: function destroy() {}
- }], [{
- key: 'probe',
- value: function probe(data) {
- if (!data) {
- return false;
- }
- // Check for the ADTS sync word
- // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
- // Layer bits (position 14 and 15) in header should be always 0 for ADTS
- // More info https://wiki.multimedia.cx/index.php?title=ADTS
- var id3Data = _id2.default.getID3Data(data, 0) || [];
- var offset = id3Data.length;
- for (var length = data.length; offset < length; offset++) {
- if (ADTS.probe(data, offset)) {
- _logger.logger.log('ADTS sync word found !');
- return true;
- }
- }
- return false;
- }
- }]);
- return AACDemuxer;
- }();
- exports.default = AACDemuxer;
- module.exports = exports['default'];
- /***/ }),
- /* 46 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /**
- * highly optimized TS demuxer:
- * parse PAT, PMT
- * extract PES packet from audio and video PIDs
- * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet
- * trigger the remuxer upon parsing completion
- * 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.
- * it also controls the remuxing process :
- * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.
- */
- // import Hex from '../utils/hex';
- var _adts = __webpack_require__(22);
- var ADTS = _interopRequireWildcard(_adts);
- var _mpegaudio = __webpack_require__(23);
- var _mpegaudio2 = _interopRequireDefault(_mpegaudio);
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _expGolomb = __webpack_require__(47);
- var _expGolomb2 = _interopRequireDefault(_expGolomb);
- var _sampleAes = __webpack_require__(48);
- var _sampleAes2 = _interopRequireDefault(_sampleAes);
- var _logger = __webpack_require__(0);
- var _errors = __webpack_require__(2);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- 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; } }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- // We are using fixed track IDs for driving the MP4 remuxer
- // instead of following the TS PIDs.
- // There is no reason not to do this and some browsers/SourceBuffer-demuxers
- // may not like if there are TrackID "switches"
- // See https://github.com/video-dev/hls.js/issues/1331
- // Here we are mapping our internal track types to constant MP4 track IDs
- // With MSE currently one can only have one track of each, and we are muxing
- // whatever video/audio rendition in them.
- var RemuxerTrackIdConfig = {
- video: 1,
- audio: 2,
- id3: 3,
- text: 4
- };
- var TSDemuxer = function () {
- function TSDemuxer(observer, remuxer, config, typeSupported) {
- _classCallCheck(this, TSDemuxer);
- this.observer = observer;
- this.config = config;
- this.typeSupported = typeSupported;
- this.remuxer = remuxer;
- this.sampleAes = null;
- }
- _createClass(TSDemuxer, [{
- key: 'setDecryptData',
- value: function setDecryptData(decryptdata) {
- if (decryptdata != null && decryptdata.key != null && decryptdata.method === 'SAMPLE-AES') {
- this.sampleAes = new _sampleAes2.default(this.observer, this.config, decryptdata, this.discardEPB);
- } else {
- this.sampleAes = null;
- }
- }
- }, {
- key: 'resetInitSegment',
- /**
- * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
- * Resets all internal track instances of the demuxer.
- *
- * @override Implements generic demuxing/remuxing interface (see DemuxerInline)
- * @param {object} initSegment
- * @param {string} audioCodec
- * @param {string} videoCodec
- * @param {number} duration (in TS timescale = 90kHz)
- */
- value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
- this.pmtParsed = false;
- this._pmtId = -1;
- this._avcTrack = TSDemuxer.createTrack('video', duration);
- this._audioTrack = TSDemuxer.createTrack('audio', duration);
- this._id3Track = TSDemuxer.createTrack('id3', duration);
- this._txtTrack = TSDemuxer.createTrack('text', duration);
- // flush any partial content
- this.aacOverFlow = null;
- this.aacLastPTS = null;
- this.avcSample = null;
- this.audioCodec = audioCodec;
- this.videoCodec = videoCodec;
- this._duration = duration;
- }
- /**
- *
- * @override
- */
- }, {
- key: 'resetTimeStamp',
- value: function resetTimeStamp() {}
- // feed incoming data to the front of the parsing pipeline
- }, {
- key: 'append',
- value: function append(data, timeOffset, contiguous, accurateTimeOffset) {
- var start = void 0,
- len = data.length,
- stt = void 0,
- pid = void 0,
- atf = void 0,
- offset = void 0,
- pes = void 0,
- unknownPIDs = false;
- this.contiguous = contiguous;
- var pmtParsed = this.pmtParsed,
- avcTrack = this._avcTrack,
- audioTrack = this._audioTrack,
- id3Track = this._id3Track,
- avcId = avcTrack.pid,
- audioId = audioTrack.pid,
- id3Id = id3Track.pid,
- pmtId = this._pmtId,
- avcData = avcTrack.pesData,
- audioData = audioTrack.pesData,
- id3Data = id3Track.pesData,
- parsePAT = this._parsePAT,
- parsePMT = this._parsePMT,
- parsePES = this._parsePES,
- parseAVCPES = this._parseAVCPES.bind(this),
- parseAACPES = this._parseAACPES.bind(this),
- parseMPEGPES = this._parseMPEGPES.bind(this),
- parseID3PES = this._parseID3PES.bind(this);
- var syncOffset = TSDemuxer._syncOffset(data);
- // don't parse last TS packet if incomplete
- len -= (len + syncOffset) % 188;
- // loop through TS packets
- for (start = syncOffset; start < len; start += 188) {
- if (data[start] === 0x47) {
- stt = !!(data[start + 1] & 0x40);
- // pid is a 13-bit field starting at the last bit of TS[1]
- pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
- atf = (data[start + 3] & 0x30) >> 4;
- // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
- if (atf > 1) {
- offset = start + 5 + data[start + 4];
- // continue if there is only adaptation field
- if (offset === start + 188) {
- continue;
- }
- } else {
- offset = start + 4;
- }
- switch (pid) {
- case avcId:
- if (stt) {
- if (avcData && (pes = parsePES(avcData)) && pes.pts !== undefined) {
- parseAVCPES(pes, false);
- }
- avcData = { data: [], size: 0 };
- }
- if (avcData) {
- avcData.data.push(data.subarray(offset, start + 188));
- avcData.size += start + 188 - offset;
- }
- break;
- case audioId:
- if (stt) {
- if (audioData && (pes = parsePES(audioData)) && pes.pts !== undefined) {
- if (audioTrack.isAAC) {
- parseAACPES(pes);
- } else {
- parseMPEGPES(pes);
- }
- }
- audioData = { data: [], size: 0 };
- }
- if (audioData) {
- audioData.data.push(data.subarray(offset, start + 188));
- audioData.size += start + 188 - offset;
- }
- break;
- case id3Id:
- if (stt) {
- if (id3Data && (pes = parsePES(id3Data)) && pes.pts !== undefined) {
- parseID3PES(pes);
- }
- id3Data = { data: [], size: 0 };
- }
- if (id3Data) {
- id3Data.data.push(data.subarray(offset, start + 188));
- id3Data.size += start + 188 - offset;
- }
- break;
- case 0:
- if (stt) {
- offset += data[offset] + 1;
- }
- pmtId = this._pmtId = parsePAT(data, offset);
- break;
- case pmtId:
- if (stt) {
- offset += data[offset] + 1;
- }
- var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, this.sampleAes != null);
- // only update track id if track PID found while parsing PMT
- // this is to avoid resetting the PID to -1 in case
- // track PID transiently disappears from the stream
- // this could happen in case of transient missing audio samples for example
- // NOTE this is only the PID of the track as found in TS,
- // but we are not using this for MP4 track IDs.
- avcId = parsedPIDs.avc;
- if (avcId > 0) {
- avcTrack.pid = avcId;
- }
- audioId = parsedPIDs.audio;
- if (audioId > 0) {
- audioTrack.pid = audioId;
- audioTrack.isAAC = parsedPIDs.isAAC;
- }
- id3Id = parsedPIDs.id3;
- if (id3Id > 0) {
- id3Track.pid = id3Id;
- }
- if (unknownPIDs && !pmtParsed) {
- _logger.logger.log('reparse from beginning');
- unknownPIDs = false;
- // we set it to -188, the += 188 in the for loop will reset start to 0
- start = syncOffset - 188;
- }
- pmtParsed = this.pmtParsed = true;
- break;
- case 17:
- case 0x1fff:
- break;
- default:
- unknownPIDs = true;
- break;
- }
- } else {
- 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' });
- }
- }
- // try to parse last PES packets
- if (avcData && (pes = parsePES(avcData)) && pes.pts !== undefined) {
- parseAVCPES(pes, true);
- avcTrack.pesData = null;
- } else {
- // either avcData null or PES truncated, keep it for next frag parsing
- avcTrack.pesData = avcData;
- }
- if (audioData && (pes = parsePES(audioData)) && pes.pts !== undefined) {
- if (audioTrack.isAAC) {
- parseAACPES(pes);
- } else {
- parseMPEGPES(pes);
- }
- audioTrack.pesData = null;
- } else {
- if (audioData && audioData.size) {
- _logger.logger.log('last AAC PES packet truncated,might overlap between fragments');
- }
- // either audioData null or PES truncated, keep it for next frag parsing
- audioTrack.pesData = audioData;
- }
- if (id3Data && (pes = parsePES(id3Data)) && pes.pts !== undefined) {
- parseID3PES(pes);
- id3Track.pesData = null;
- } else {
- // either id3Data null or PES truncated, keep it for next frag parsing
- id3Track.pesData = id3Data;
- }
- if (this.sampleAes == null) {
- this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
- } else {
- this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
- }
- }
- }, {
- key: 'decryptAndRemux',
- value: function decryptAndRemux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
- if (audioTrack.samples && audioTrack.isAAC) {
- var localthis = this;
- this.sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
- localthis.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
- });
- } else {
- this.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
- }
- }
- }, {
- key: 'decryptAndRemuxAvc',
- value: function decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
- if (videoTrack.samples) {
- var localthis = this;
- this.sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
- localthis.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
- });
- } else {
- this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
- }
- }
- }, {
- key: 'destroy',
- value: function destroy() {
- this._initPTS = this._initDTS = undefined;
- this._duration = 0;
- }
- }, {
- key: '_parsePAT',
- value: function _parsePAT(data, offset) {
- // skip the PSI header and parse the first PMT entry
- return (data[offset + 10] & 0x1F) << 8 | data[offset + 11];
- // logger.log('PMT PID:' + this._pmtId);
- }
- }, {
- key: '_parsePMT',
- value: function _parsePMT(data, offset, mpegSupported, isSampleAes) {
- var sectionLength = void 0,
- tableEnd = void 0,
- programInfoLength = void 0,
- pid = void 0,
- result = { audio: -1, avc: -1, id3: -1, isAAC: true };
- sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
- tableEnd = offset + 3 + sectionLength - 4;
- // to determine where the table is, we have to figure out how
- // long the program info descriptors are
- programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
- // advance the offset to the first entry in the mapping table
- offset += 12 + programInfoLength;
- while (offset < tableEnd) {
- pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];
- switch (data[offset]) {
- case 0xcf:
- // SAMPLE-AES AAC
- if (!isSampleAes) {
- _logger.logger.log('unkown stream type:' + data[offset]);
- break;
- }
- /* falls through */
- // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
- case 0x0f:
- // logger.log('AAC PID:' + pid);
- if (result.audio === -1) {
- result.audio = pid;
- }
- break;
- // Packetized metadata (ID3)
- case 0x15:
- // logger.log('ID3 PID:' + pid);
- if (result.id3 === -1) {
- result.id3 = pid;
- }
- break;
- case 0xdb:
- // SAMPLE-AES AVC
- if (!isSampleAes) {
- _logger.logger.log('unkown stream type:' + data[offset]);
- break;
- }
- /* falls through */
- // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
- case 0x1b:
- // logger.log('AVC PID:' + pid);
- if (result.avc === -1) {
- result.avc = pid;
- }
- break;
- // ISO/IEC 11172-3 (MPEG-1 audio)
- // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
- case 0x03:
- case 0x04:
- // logger.log('MPEG PID:' + pid);
- if (!mpegSupported) {
- _logger.logger.log('MPEG audio found, not supported in this browser for now');
- } else if (result.audio === -1) {
- result.audio = pid;
- result.isAAC = false;
- }
- break;
- case 0x24:
- _logger.logger.warn('HEVC stream type found, not supported for now');
- break;
- default:
- _logger.logger.log('unkown stream type:' + data[offset]);
- break;
- }
- // move to the next table entry
- // skip past the elementary stream descriptors, if present
- offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;
- }
- return result;
- }
- }, {
- key: '_parsePES',
- value: function _parsePES(stream) {
- var i = 0,
- frag = void 0,
- pesFlags = void 0,
- pesPrefix = void 0,
- pesLen = void 0,
- pesHdrLen = void 0,
- pesData = void 0,
- pesPts = void 0,
- pesDts = void 0,
- payloadStartOffset = void 0,
- data = stream.data;
- // safety check
- if (!stream || stream.size === 0) {
- return null;
- }
- // we might need up to 19 bytes to read PES header
- // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
- // usually only one merge is needed (and this is rare ...)
- while (data[0].length < 19 && data.length > 1) {
- var newData = new Uint8Array(data[0].length + data[1].length);
- newData.set(data[0]);
- newData.set(data[1], data[0].length);
- data[0] = newData;
- data.splice(1, 1);
- }
- // retrieve PTS/DTS from first fragment
- frag = data[0];
- pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
- if (pesPrefix === 1) {
- pesLen = (frag[4] << 8) + frag[5];
- // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
- // minus 6 : PES header size
- if (pesLen && pesLen > stream.size - 6) {
- return null;
- }
- pesFlags = frag[7];
- if (pesFlags & 0xC0) {
- /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
- as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
- as Bitwise operators treat their operands as a sequence of 32 bits */
- pesPts = (frag[9] & 0x0E) * 536870912 + // 1 << 29
- (frag[10] & 0xFF) * 4194304 + // 1 << 22
- (frag[11] & 0xFE) * 16384 + // 1 << 14
- (frag[12] & 0xFF) * 128 + // 1 << 7
- (frag[13] & 0xFE) / 2;
- // check if greater than 2^32 -1
- if (pesPts > 4294967295) {
- // decrement 2^33
- pesPts -= 8589934592;
- }
- if (pesFlags & 0x40) {
- pesDts = (frag[14] & 0x0E) * 536870912 + // 1 << 29
- (frag[15] & 0xFF) * 4194304 + // 1 << 22
- (frag[16] & 0xFE) * 16384 + // 1 << 14
- (frag[17] & 0xFF) * 128 + // 1 << 7
- (frag[18] & 0xFE) / 2;
- // check if greater than 2^32 -1
- if (pesDts > 4294967295) {
- // decrement 2^33
- pesDts -= 8589934592;
- }
- if (pesPts - pesDts > 60 * 90000) {
- _logger.logger.warn(Math.round((pesPts - pesDts) / 90000) + 's delta between PTS and DTS, align them');
- pesPts = pesDts;
- }
- } else {
- pesDts = pesPts;
- }
- }
- pesHdrLen = frag[8];
- // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
- payloadStartOffset = pesHdrLen + 9;
- stream.size -= payloadStartOffset;
- // reassemble PES packet
- pesData = new Uint8Array(stream.size);
- for (var j = 0, dataLen = data.length; j < dataLen; j++) {
- frag = data[j];
- var len = frag.byteLength;
- if (payloadStartOffset) {
- if (payloadStartOffset > len) {
- // trim full frag if PES header bigger than frag
- payloadStartOffset -= len;
- continue;
- } else {
- // trim partial frag if PES header smaller than frag
- frag = frag.subarray(payloadStartOffset);
- len -= payloadStartOffset;
- payloadStartOffset = 0;
- }
- }
- pesData.set(frag, i);
- i += len;
- }
- if (pesLen) {
- // payload size : remove PES header + PES extension
- pesLen -= pesHdrLen + 3;
- }
- return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen };
- } else {
- return null;
- }
- }
- }, {
- key: 'pushAccesUnit',
- value: function pushAccesUnit(avcSample, avcTrack) {
- if (avcSample.units.length && avcSample.frame) {
- var samples = avcTrack.samples;
- var nbSamples = samples.length;
- // only push AVC sample if starting with a keyframe is not mandatory OR
- // if keyframe already found in this fragment OR
- // keyframe found in last fragment (track.sps) AND
- // samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous
- if (!this.config.forceKeyFrameOnDiscontinuity || avcSample.key === true || avcTrack.sps && (nbSamples || this.contiguous)) {
- avcSample.id = nbSamples;
- samples.push(avcSample);
- } else {
- // dropped samples, track it
- avcTrack.dropped++;
- }
- }
- if (avcSample.debug.length) {
- _logger.logger.log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);
- }
- }
- }, {
- key: '_parseAVCPES',
- value: function _parseAVCPES(pes, last) {
- var _this = this;
- // logger.log('parse new PES');
- var track = this._avcTrack,
- units = this._parseAVCNALu(pes.data),
- debug = false,
- expGolombDecoder = void 0,
- avcSample = this.avcSample,
- push = void 0,
- spsfound = false,
- i = void 0,
- pushAccesUnit = this.pushAccesUnit.bind(this),
- createAVCSample = function createAVCSample(key, pts, dts, debug) {
- return { key: key, pts: pts, dts: dts, units: [], debug: debug };
- };
- // free pes.data to save up some memory
- pes.data = null;
- // if new NAL units found and last sample still there, let's push ...
- // this helps parsing streams with missing AUD (only do this if AUD never found)
- if (avcSample && units.length && !track.audFound) {
- pushAccesUnit(avcSample, track);
- avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');
- }
- units.forEach(function (unit) {
- switch (unit.type) {
- // NDR
- case 1:
- push = true;
- if (!avcSample) {
- avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
- }
- if (debug) {
- avcSample.debug += 'NDR ';
- }
- avcSample.frame = true;
- var data = unit.data;
- // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
- if (spsfound && data.length > 4) {
- // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
- var sliceType = new _expGolomb2.default(data).readSliceType();
- // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
- // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
- // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
- // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
- // if (sliceType === 2 || sliceType === 7) {
- if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
- avcSample.key = true;
- }
- }
- break;
- // IDR
- case 5:
- push = true;
- // handle PES not starting with AUD
- if (!avcSample) {
- avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
- }
- if (debug) {
- avcSample.debug += 'IDR ';
- }
- avcSample.key = true;
- avcSample.frame = true;
- break;
- // SEI
- case 6:
- push = true;
- if (debug && avcSample) {
- avcSample.debug += 'SEI ';
- }
- expGolombDecoder = new _expGolomb2.default(_this.discardEPB(unit.data));
- // skip frameType
- expGolombDecoder.readUByte();
- var payloadType = 0;
- var payloadSize = 0;
- var endOfCaptions = false;
- var b = 0;
- while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {
- payloadType = 0;
- do {
- b = expGolombDecoder.readUByte();
- payloadType += b;
- } while (b === 0xFF);
- // Parse payload size.
- payloadSize = 0;
- do {
- b = expGolombDecoder.readUByte();
- payloadSize += b;
- } while (b === 0xFF);
- // TODO: there can be more than one payload in an SEI packet...
- // TODO: need to read type and size in a while loop to get them all
- if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {
- endOfCaptions = true;
- var countryCode = expGolombDecoder.readUByte();
- if (countryCode === 181) {
- var providerCode = expGolombDecoder.readUShort();
- if (providerCode === 49) {
- var userStructure = expGolombDecoder.readUInt();
- if (userStructure === 0x47413934) {
- var userDataType = expGolombDecoder.readUByte();
- // Raw CEA-608 bytes wrapped in CEA-708 packet
- if (userDataType === 3) {
- var firstByte = expGolombDecoder.readUByte();
- var secondByte = expGolombDecoder.readUByte();
- var totalCCs = 31 & firstByte;
- var byteArray = [firstByte, secondByte];
- for (i = 0; i < totalCCs; i++) {
- // 3 bytes per CC
- byteArray.push(expGolombDecoder.readUByte());
- byteArray.push(expGolombDecoder.readUByte());
- byteArray.push(expGolombDecoder.readUByte());
- }
- _this._insertSampleInOrder(_this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray });
- }
- }
- }
- }
- } else if (payloadSize < expGolombDecoder.bytesAvailable) {
- for (i = 0; i < payloadSize; i++) {
- expGolombDecoder.readUByte();
- }
- }
- }
- break;
- // SPS
- case 7:
- push = true;
- spsfound = true;
- if (debug && avcSample) {
- avcSample.debug += 'SPS ';
- }
- if (!track.sps) {
- expGolombDecoder = new _expGolomb2.default(unit.data);
- var config = expGolombDecoder.readSPS();
- track.width = config.width;
- track.height = config.height;
- track.pixelRatio = config.pixelRatio;
- track.sps = [unit.data];
- track.duration = _this._duration;
- var codecarray = unit.data.subarray(1, 4);
- var codecstring = 'avc1.';
- for (i = 0; i < 3; i++) {
- var h = codecarray[i].toString(16);
- if (h.length < 2) {
- h = '0' + h;
- }
- codecstring += h;
- }
- track.codec = codecstring;
- }
- break;
- // PPS
- case 8:
- push = true;
- if (debug && avcSample) {
- avcSample.debug += 'PPS ';
- }
- if (!track.pps) {
- track.pps = [unit.data];
- }
- break;
- // AUD
- case 9:
- push = false;
- track.audFound = true;
- if (avcSample) {
- pushAccesUnit(avcSample, track);
- }
- avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');
- break;
- // Filler Data
- case 12:
- push = false;
- break;
- default:
- push = false;
- if (avcSample) {
- avcSample.debug += 'unknown NAL ' + unit.type + ' ';
- }
- break;
- }
- if (avcSample && push) {
- var _units = avcSample.units;
- _units.push(unit);
- }
- });
- // if last PES packet, push samples
- if (last && avcSample) {
- pushAccesUnit(avcSample, track);
- this.avcSample = null;
- }
- }
- }, {
- key: '_insertSampleInOrder',
- value: function _insertSampleInOrder(arr, data) {
- var len = arr.length;
- if (len > 0) {
- if (data.pts >= arr[len - 1].pts) {
- arr.push(data);
- } else {
- for (var pos = len - 1; pos >= 0; pos--) {
- if (data.pts < arr[pos].pts) {
- arr.splice(pos, 0, data);
- break;
- }
- }
- }
- } else {
- arr.push(data);
- }
- }
- }, {
- key: '_getLastNalUnit',
- value: function _getLastNalUnit() {
- var avcSample = this.avcSample,
- lastUnit = void 0;
- // try to fallback to previous sample if current one is empty
- if (!avcSample || avcSample.units.length === 0) {
- var track = this._avcTrack,
- samples = track.samples;
- avcSample = samples[samples.length - 1];
- }
- if (avcSample) {
- var units = avcSample.units;
- lastUnit = units[units.length - 1];
- }
- return lastUnit;
- }
- }, {
- key: '_parseAVCNALu',
- value: function _parseAVCNALu(array) {
- var i = 0,
- len = array.byteLength,
- value = void 0,
- overflow = void 0,
- track = this._avcTrack,
- state = track.naluState || 0,
- lastState = state;
- var units = [],
- unit = void 0,
- unitType = void 0,
- lastUnitStart = -1,
- lastUnitType = void 0;
- // logger.log('PES:' + Hex.hexDump(array));
- if (state === -1) {
- // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
- lastUnitStart = 0;
- // NALu type is value read from offset 0
- lastUnitType = array[0] & 0x1f;
- state = 0;
- i = 1;
- }
- while (i < len) {
- value = array[i++];
- // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
- if (!state) {
- state = value ? 0 : 1;
- continue;
- }
- if (state === 1) {
- state = value ? 0 : 2;
- continue;
- }
- // here we have state either equal to 2 or 3
- if (!value) {
- state = 3;
- } else if (value === 1) {
- if (lastUnitStart >= 0) {
- unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType };
- // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
- units.push(unit);
- } else {
- // lastUnitStart is undefined => this is the first start code found in this PES packet
- // first check if start code delimiter is overlapping between 2 PES packets,
- // ie it started in last packet (lastState not zero)
- // and ended at the beginning of this PES packet (i <= 4 - lastState)
- var lastUnit = this._getLastNalUnit();
- if (lastUnit) {
- if (lastState && i <= 4 - lastState) {
- // start delimiter overlapping between PES packets
- // strip start delimiter bytes from the end of last NAL unit
- // check if lastUnit had a state different from zero
- if (lastUnit.state) {
- // strip last bytes
- lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
- }
- }
- // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
- overflow = i - state - 1;
- if (overflow > 0) {
- // logger.log('first NALU found with overflow:' + overflow);
- var tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
- tmp.set(lastUnit.data, 0);
- tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
- lastUnit.data = tmp;
- }
- }
- }
- // check if we can read unit type
- if (i < len) {
- unitType = array[i] & 0x1f;
- // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
- lastUnitStart = i;
- lastUnitType = unitType;
- state = 0;
- } else {
- // not enough byte to read unit type. let's read it on next PES parsing
- state = -1;
- }
- } else {
- state = 0;
- }
- }
- if (lastUnitStart >= 0 && state >= 0) {
- unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType, state: state };
- units.push(unit);
- // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
- }
- // no NALu found
- if (units.length === 0) {
- // append pes.data to previous NAL unit
- var _lastUnit = this._getLastNalUnit();
- if (_lastUnit) {
- var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength);
- _tmp.set(_lastUnit.data, 0);
- _tmp.set(array, _lastUnit.data.byteLength);
- _lastUnit.data = _tmp;
- }
- }
- track.naluState = state;
- return units;
- }
- /**
- * remove Emulation Prevention bytes from a RBSP
- */
- }, {
- key: 'discardEPB',
- value: function discardEPB(data) {
- var length = data.byteLength,
- EPBPositions = [],
- i = 1,
- newLength = void 0,
- newData = void 0;
- // Find all `Emulation Prevention Bytes`
- while (i < length - 2) {
- if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
- EPBPositions.push(i + 2);
- i += 2;
- } else {
- i++;
- }
- }
- // If no Emulation Prevention Bytes were found just return the original
- // array
- if (EPBPositions.length === 0) {
- return data;
- }
- // Create a new array to hold the NAL unit data
- newLength = length - EPBPositions.length;
- newData = new Uint8Array(newLength);
- var sourceIndex = 0;
- for (i = 0; i < newLength; sourceIndex++, i++) {
- if (sourceIndex === EPBPositions[0]) {
- // Skip this byte
- sourceIndex++;
- // Remove this position index
- EPBPositions.shift();
- }
- newData[i] = data[sourceIndex];
- }
- return newData;
- }
- }, {
- key: '_parseAACPES',
- value: function _parseAACPES(pes) {
- var track = this._audioTrack,
- data = pes.data,
- pts = pes.pts,
- startOffset = 0,
- aacOverFlow = this.aacOverFlow,
- aacLastPTS = this.aacLastPTS,
- frameDuration = void 0,
- frameIndex = void 0,
- offset = void 0,
- stamp = void 0,
- len = void 0;
- if (aacOverFlow) {
- var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);
- tmp.set(aacOverFlow, 0);
- tmp.set(data, aacOverFlow.byteLength);
- // logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);
- data = tmp;
- }
- // look for ADTS header (0xFFFx)
- for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
- if (ADTS.isHeader(data, offset)) {
- break;
- }
- }
- // if ADTS header does not start straight from the beginning of the PES payload, raise an error
- if (offset) {
- var reason = void 0,
- fatal = void 0;
- if (offset < len - 1) {
- reason = 'AAC PES did not start with ADTS header,offset:' + offset;
- fatal = false;
- } else {
- reason = 'no ADTS header found in AAC PES';
- fatal = true;
- }
- _logger.logger.warn('parsing error:' + reason);
- this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: fatal, reason: reason });
- if (fatal) {
- return;
- }
- }
- ADTS.initTrackConfig(track, this.observer, data, offset, this.audioCodec);
- frameIndex = 0;
- frameDuration = ADTS.getFrameDuration(track.samplerate);
- // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
- // first sample PTS should be equal to last sample PTS + frameDuration
- if (aacOverFlow && aacLastPTS) {
- var newPTS = aacLastPTS + frameDuration;
- if (Math.abs(newPTS - pts) > 1) {
- _logger.logger.log('AAC: align PTS for overlapping frames by ' + Math.round((newPTS - pts) / 90));
- pts = newPTS;
- }
- }
- // scan for aac samples
- while (offset < len) {
- if (ADTS.isHeader(data, offset) && offset + 5 < len) {
- var frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);
- if (frame) {
- // logger.log(`${Math.round(frame.sample.pts)} : AAC`);
- offset += frame.length;
- stamp = frame.sample.pts;
- frameIndex++;
- } else {
- // logger.log('Unable to parse AAC frame');
- break;
- }
- } else {
- // nothing found, keep looking
- offset++;
- }
- }
- if (offset < len) {
- aacOverFlow = data.subarray(offset, len);
- // logger.log(`AAC: overflow detected:${len-offset}`);
- } else {
- aacOverFlow = null;
- }
- this.aacOverFlow = aacOverFlow;
- this.aacLastPTS = stamp;
- }
- }, {
- key: '_parseMPEGPES',
- value: function _parseMPEGPES(pes) {
- var data = pes.data;
- var length = data.length;
- var frameIndex = 0;
- var offset = 0;
- var pts = pes.pts;
- while (offset < length) {
- if (_mpegaudio2.default.isHeader(data, offset)) {
- var frame = _mpegaudio2.default.appendFrame(this._audioTrack, data, offset, pts, frameIndex);
- if (frame) {
- offset += frame.length;
- frameIndex++;
- } else {
- // logger.log('Unable to parse Mpeg audio frame');
- break;
- }
- } else {
- // nothing found, keep looking
- offset++;
- }
- }
- }
- }, {
- key: '_parseID3PES',
- value: function _parseID3PES(pes) {
- this._id3Track.samples.push(pes);
- }
- }], [{
- key: 'probe',
- value: function probe(data) {
- var syncOffset = TSDemuxer._syncOffset(data);
- if (syncOffset < 0) {
- return false;
- } else {
- if (syncOffset) {
- _logger.logger.warn('MPEG2-TS detected but first sync word found @ offset ' + syncOffset + ', junk ahead ?');
- }
- return true;
- }
- }
- }, {
- key: '_syncOffset',
- value: function _syncOffset(data) {
- // scan 1000 first bytes
- var scanwindow = Math.min(1000, data.length - 3 * 188);
- var i = 0;
- while (i < scanwindow) {
- // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
- if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {
- return i;
- } else {
- i++;
- }
- }
- return -1;
- }
- /**
- * Creates a track model internal to demuxer used to drive remuxing input
- *
- * @param {string} type 'audio' | 'video' | 'id3' | 'text'
- * @param {number} duration
- * @return {object} TSDemuxer's internal track model
- */
- }, {
- key: 'createTrack',
- value: function createTrack(type, duration) {
- return {
- container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
- type: type,
- id: RemuxerTrackIdConfig[type],
- pid: -1,
- inputTimeScale: 90000,
- sequenceNumber: 0,
- samples: [],
- len: 0,
- dropped: type === 'video' ? 0 : undefined,
- isAAC: type === 'audio' ? true : undefined,
- duration: type === 'audio' ? duration : undefined
- };
- }
- }]);
- return TSDemuxer;
- }();
- exports.default = TSDemuxer;
- module.exports = exports['default'];
- /***/ }),
- /* 47 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /**
- * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
- */
- var _logger = __webpack_require__(0);
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var ExpGolomb = function () {
- function ExpGolomb(data) {
- _classCallCheck(this, ExpGolomb);
- this.data = data;
- // the number of bytes left to examine in this.data
- this.bytesAvailable = data.byteLength;
- // the current word being examined
- this.word = 0; // :uint
- // the number of bits left to examine in the current word
- this.bitsAvailable = 0; // :uint
- }
- // ():void
- _createClass(ExpGolomb, [{
- key: 'loadWord',
- value: function loadWord() {
- var data = this.data,
- bytesAvailable = this.bytesAvailable,
- position = data.byteLength - bytesAvailable,
- workingBytes = new Uint8Array(4),
- availableBytes = Math.min(4, bytesAvailable);
- if (availableBytes === 0) {
- throw new Error('no bytes available');
- }
- workingBytes.set(data.subarray(position, position + availableBytes));
- this.word = new DataView(workingBytes.buffer).getUint32(0);
- // track the amount of this.data that has been processed
- this.bitsAvailable = availableBytes * 8;
- this.bytesAvailable -= availableBytes;
- }
- // (count:int):void
- }, {
- key: 'skipBits',
- value: function skipBits(count) {
- var skipBytes = void 0; // :int
- if (this.bitsAvailable > count) {
- this.word <<= count;
- this.bitsAvailable -= count;
- } else {
- count -= this.bitsAvailable;
- skipBytes = count >> 3;
- count -= skipBytes >> 3;
- this.bytesAvailable -= skipBytes;
- this.loadWord();
- this.word <<= count;
- this.bitsAvailable -= count;
- }
- }
- // (size:int):uint
- }, {
- key: 'readBits',
- value: function readBits(size) {
- var bits = Math.min(this.bitsAvailable, size),
- // :uint
- valu = this.word >>> 32 - bits; // :uint
- if (size > 32) {
- _logger.logger.error('Cannot read more than 32 bits at a time');
- }
- this.bitsAvailable -= bits;
- if (this.bitsAvailable > 0) {
- this.word <<= bits;
- } else if (this.bytesAvailable > 0) {
- this.loadWord();
- }
- bits = size - bits;
- if (bits > 0 && this.bitsAvailable) {
- return valu << bits | this.readBits(bits);
- } else {
- return valu;
- }
- }
- // ():uint
- }, {
- key: 'skipLZ',
- value: function skipLZ() {
- var leadingZeroCount = void 0; // :uint
- for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
- if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
- // the first bit of working word is 1
- this.word <<= leadingZeroCount;
- this.bitsAvailable -= leadingZeroCount;
- return leadingZeroCount;
- }
- }
- // we exhausted word and still have not found a 1
- this.loadWord();
- return leadingZeroCount + this.skipLZ();
- }
- // ():void
- }, {
- key: 'skipUEG',
- value: function skipUEG() {
- this.skipBits(1 + this.skipLZ());
- }
- // ():void
- }, {
- key: 'skipEG',
- value: function skipEG() {
- this.skipBits(1 + this.skipLZ());
- }
- // ():uint
- }, {
- key: 'readUEG',
- value: function readUEG() {
- var clz = this.skipLZ(); // :uint
- return this.readBits(clz + 1) - 1;
- }
- // ():int
- }, {
- key: 'readEG',
- value: function readEG() {
- var valu = this.readUEG(); // :int
- if (0x01 & valu) {
- // the number is odd if the low order bit is set
- return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
- } else {
- return -1 * (valu >>> 1); // divide by two then make it negative
- }
- }
- // Some convenience functions
- // :Boolean
- }, {
- key: 'readBoolean',
- value: function readBoolean() {
- return this.readBits(1) === 1;
- }
- // ():int
- }, {
- key: 'readUByte',
- value: function readUByte() {
- return this.readBits(8);
- }
- // ():int
- }, {
- key: 'readUShort',
- value: function readUShort() {
- return this.readBits(16);
- }
- // ():int
- }, {
- key: 'readUInt',
- value: function readUInt() {
- return this.readBits(32);
- }
- /**
- * Advance the ExpGolomb decoder past a scaling list. The scaling
- * list is optionally transmitted as part of a sequence parameter
- * set and is not relevant to transmuxing.
- * @param count {number} the number of entries in this scaling list
- * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
- */
- }, {
- key: 'skipScalingList',
- value: function skipScalingList(count) {
- var lastScale = 8,
- nextScale = 8,
- j = void 0,
- deltaScale = void 0;
- for (j = 0; j < count; j++) {
- if (nextScale !== 0) {
- deltaScale = this.readEG();
- nextScale = (lastScale + deltaScale + 256) % 256;
- }
- lastScale = nextScale === 0 ? lastScale : nextScale;
- }
- }
- /**
- * Read a sequence parameter set and return some interesting video
- * properties. A sequence parameter set is the H264 metadata that
- * describes the properties of upcoming video frames.
- * @param data {Uint8Array} the bytes of a sequence parameter set
- * @return {object} an object with configuration parsed from the
- * sequence parameter set, including the dimensions of the
- * associated video frames.
- */
- }, {
- key: 'readSPS',
- value: function readSPS() {
- var frameCropLeftOffset = 0,
- frameCropRightOffset = 0,
- frameCropTopOffset = 0,
- frameCropBottomOffset = 0,
- profileIdc = void 0,
- profileCompat = void 0,
- levelIdc = void 0,
- numRefFramesInPicOrderCntCycle = void 0,
- picWidthInMbsMinus1 = void 0,
- picHeightInMapUnitsMinus1 = void 0,
- frameMbsOnlyFlag = void 0,
- scalingListCount = void 0,
- i = void 0,
- readUByte = this.readUByte.bind(this),
- readBits = this.readBits.bind(this),
- readUEG = this.readUEG.bind(this),
- readBoolean = this.readBoolean.bind(this),
- skipBits = this.skipBits.bind(this),
- skipEG = this.skipEG.bind(this),
- skipUEG = this.skipUEG.bind(this),
- skipScalingList = this.skipScalingList.bind(this);
- readUByte();
- profileIdc = readUByte(); // profile_idc
- profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5)
- skipBits(3); // reserved_zero_3bits u(3),
- levelIdc = readUByte(); // level_idc u(8)
- skipUEG(); // seq_parameter_set_id
- // some profiles have more optional data we don't need
- if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
- var chromaFormatIdc = readUEG();
- if (chromaFormatIdc === 3) {
- skipBits(1);
- } // separate_colour_plane_flag
- skipUEG(); // bit_depth_luma_minus8
- skipUEG(); // bit_depth_chroma_minus8
- skipBits(1); // qpprime_y_zero_transform_bypass_flag
- if (readBoolean()) {
- // seq_scaling_matrix_present_flag
- scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
- for (i = 0; i < scalingListCount; i++) {
- if (readBoolean()) {
- // seq_scaling_list_present_flag[ i ]
- if (i < 6) {
- skipScalingList(16);
- } else {
- skipScalingList(64);
- }
- }
- }
- }
- }
- skipUEG(); // log2_max_frame_num_minus4
- var picOrderCntType = readUEG();
- if (picOrderCntType === 0) {
- readUEG(); // log2_max_pic_order_cnt_lsb_minus4
- } else if (picOrderCntType === 1) {
- skipBits(1); // delta_pic_order_always_zero_flag
- skipEG(); // offset_for_non_ref_pic
- skipEG(); // offset_for_top_to_bottom_field
- numRefFramesInPicOrderCntCycle = readUEG();
- for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
- skipEG();
- } // offset_for_ref_frame[ i ]
- }
- skipUEG(); // max_num_ref_frames
- skipBits(1); // gaps_in_frame_num_value_allowed_flag
- picWidthInMbsMinus1 = readUEG();
- picHeightInMapUnitsMinus1 = readUEG();
- frameMbsOnlyFlag = readBits(1);
- if (frameMbsOnlyFlag === 0) {
- skipBits(1);
- } // mb_adaptive_frame_field_flag
- skipBits(1); // direct_8x8_inference_flag
- if (readBoolean()) {
- // frame_cropping_flag
- frameCropLeftOffset = readUEG();
- frameCropRightOffset = readUEG();
- frameCropTopOffset = readUEG();
- frameCropBottomOffset = readUEG();
- }
- var pixelRatio = [1, 1];
- if (readBoolean()) {
- // vui_parameters_present_flag
- if (readBoolean()) {
- // aspect_ratio_info_present_flag
- var aspectRatioIdc = readUByte();
- switch (aspectRatioIdc) {
- case 1:
- pixelRatio = [1, 1];break;
- case 2:
- pixelRatio = [12, 11];break;
- case 3:
- pixelRatio = [10, 11];break;
- case 4:
- pixelRatio = [16, 11];break;
- case 5:
- pixelRatio = [40, 33];break;
- case 6:
- pixelRatio = [24, 11];break;
- case 7:
- pixelRatio = [20, 11];break;
- case 8:
- pixelRatio = [32, 11];break;
- case 9:
- pixelRatio = [80, 33];break;
- case 10:
- pixelRatio = [18, 11];break;
- case 11:
- pixelRatio = [15, 11];break;
- case 12:
- pixelRatio = [64, 33];break;
- case 13:
- pixelRatio = [160, 99];break;
- case 14:
- pixelRatio = [4, 3];break;
- case 15:
- pixelRatio = [3, 2];break;
- case 16:
- pixelRatio = [2, 1];break;
- case 255:
- {
- pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
- break;
- }
- }
- }
- }
- return {
- width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
- height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
- pixelRatio: pixelRatio
- };
- }
- }, {
- key: 'readSliceType',
- value: function readSliceType() {
- // skip NALu type
- this.readUByte();
- // discard first_mb_in_slice
- this.readUEG();
- // return slice_type
- return this.readUEG();
- }
- }]);
- return ExpGolomb;
- }();
- exports.default = ExpGolomb;
- module.exports = exports['default'];
- /***/ }),
- /* 48 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /**
- * SAMPLE-AES decrypter
- */
- var _decrypter = __webpack_require__(12);
- var _decrypter2 = _interopRequireDefault(_decrypter);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var SampleAesDecrypter = function () {
- function SampleAesDecrypter(observer, config, decryptdata, discardEPB) {
- _classCallCheck(this, SampleAesDecrypter);
- this.decryptdata = decryptdata;
- this.discardEPB = discardEPB;
- this.decrypter = new _decrypter2.default(observer, config, { removePKCS7Padding: false });
- }
- _createClass(SampleAesDecrypter, [{
- key: 'decryptBuffer',
- value: function decryptBuffer(encryptedData, callback) {
- this.decrypter.decrypt(encryptedData, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, callback);
- }
- // AAC - encrypt all full 16 bytes blocks starting from offset 16
- }, {
- key: 'decryptAacSample',
- value: function decryptAacSample(samples, sampleIndex, callback, sync) {
- var curUnit = samples[sampleIndex].unit;
- var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
- var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
- var localthis = this;
- this.decryptBuffer(encryptedBuffer, function (decryptedData) {
- decryptedData = new Uint8Array(decryptedData);
- curUnit.set(decryptedData, 16);
- if (!sync) {
- localthis.decryptAacSamples(samples, sampleIndex + 1, callback);
- }
- });
- }
- }, {
- key: 'decryptAacSamples',
- value: function decryptAacSamples(samples, sampleIndex, callback) {
- for (;; sampleIndex++) {
- if (sampleIndex >= samples.length) {
- callback();
- return;
- }
- if (samples[sampleIndex].unit.length < 32) {
- continue;
- }
- var sync = this.decrypter.isSync();
- this.decryptAacSample(samples, sampleIndex, callback, sync);
- if (!sync) {
- return;
- }
- }
- }
- // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
- }, {
- key: 'getAvcEncryptedData',
- value: function getAvcEncryptedData(decodedData) {
- var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
- var encryptedData = new Int8Array(encryptedDataLen);
- var outputPos = 0;
- for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {
- encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
- }
- return encryptedData;
- }
- }, {
- key: 'getAvcDecryptedUnit',
- value: function getAvcDecryptedUnit(decodedData, decryptedData) {
- decryptedData = new Uint8Array(decryptedData);
- var inputPos = 0;
- for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {
- decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos);
- }
- return decodedData;
- }
- }, {
- key: 'decryptAvcSample',
- value: function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {
- var decodedData = this.discardEPB(curUnit.data);
- var encryptedData = this.getAvcEncryptedData(decodedData);
- var localthis = this;
- this.decryptBuffer(encryptedData.buffer, function (decryptedData) {
- curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedData);
- if (!sync) {
- localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
- }
- });
- }
- }, {
- key: 'decryptAvcSamples',
- value: function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
- for (;; sampleIndex++, unitIndex = 0) {
- if (sampleIndex >= samples.length) {
- callback();
- return;
- }
- var curUnits = samples[sampleIndex].units;
- for (;; unitIndex++) {
- if (unitIndex >= curUnits.length) {
- break;
- }
- var curUnit = curUnits[unitIndex];
- if (curUnit.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
- continue;
- }
- var sync = this.decrypter.isSync();
- this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);
- if (!sync) {
- return;
- }
- }
- }
- }
- }]);
- return SampleAesDecrypter;
- }();
- exports.default = SampleAesDecrypter;
- module.exports = exports['default'];
- /***/ }),
- /* 49 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /**
- * MP3 demuxer
- */
- var _id = __webpack_require__(10);
- var _id2 = _interopRequireDefault(_id);
- var _logger = __webpack_require__(0);
- var _mpegaudio = __webpack_require__(23);
- var _mpegaudio2 = _interopRequireDefault(_mpegaudio);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var MP3Demuxer = function () {
- function MP3Demuxer(observer, remuxer, config) {
- _classCallCheck(this, MP3Demuxer);
- this.observer = observer;
- this.config = config;
- this.remuxer = remuxer;
- }
- _createClass(MP3Demuxer, [{
- key: 'resetInitSegment',
- value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
- this._audioTrack = { container: 'audio/mpeg', type: 'audio', id: -1, sequenceNumber: 0, isAAC: false, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };
- }
- }, {
- key: 'resetTimeStamp',
- value: function resetTimeStamp() {}
- }, {
- key: 'append',
- // feed incoming data to the front of the parsing pipeline
- value: function append(data, timeOffset, contiguous, accurateTimeOffset) {
- var id3Data = _id2.default.getID3Data(data, 0);
- var timestamp = _id2.default.getTimeStamp(id3Data);
- var pts = timestamp ? 90 * timestamp : timeOffset * 90000;
- var offset = id3Data.length;
- var length = data.length;
- var frameIndex = 0,
- stamp = 0;
- var track = this._audioTrack;
- var id3Samples = [{ pts: pts, dts: pts, data: id3Data }];
- while (offset < length) {
- if (_mpegaudio2.default.isHeader(data, offset)) {
- var frame = _mpegaudio2.default.appendFrame(track, data, offset, pts, frameIndex);
- if (frame) {
- offset += frame.length;
- stamp = frame.sample.pts;
- frameIndex++;
- } else {
- // logger.log('Unable to parse Mpeg audio frame');
- break;
- }
- } else if (_id2.default.isHeader(data, offset)) {
- id3Data = _id2.default.getID3Data(data, offset);
- id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });
- offset += id3Data.length;
- } else {
- // nothing found, keep looking
- offset++;
- }
- }
- this.remuxer.remux(track, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset);
- }
- }, {
- key: 'destroy',
- value: function destroy() {}
- }], [{
- key: 'probe',
- value: function probe(data) {
- // check if data contains ID3 timestamp and MPEG sync word
- var offset = void 0,
- length = void 0;
- var id3Data = _id2.default.getID3Data(data, 0);
- if (id3Data && _id2.default.getTimeStamp(id3Data) !== undefined) {
- // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
- // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
- // More info http://www.mp3-tech.org/programmer/frame_header.html
- for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) {
- if (_mpegaudio2.default.probe(data, offset)) {
- _logger.logger.log('MPEG Audio sync word found !');
- return true;
- }
- }
- }
- return false;
- }
- }]);
- return MP3Demuxer;
- }();
- exports.default = MP3Demuxer;
- module.exports = exports['default'];
- /***/ }),
- /* 50 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /**
- * fMP4 remuxer
- */
- var _aacHelper = __webpack_require__(51);
- var _aacHelper2 = _interopRequireDefault(_aacHelper);
- var _mp4Generator = __webpack_require__(52);
- var _mp4Generator2 = _interopRequireDefault(_mp4Generator);
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _errors = __webpack_require__(2);
- var _logger = __webpack_require__(0);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- // 10 seconds
- var MAX_SILENT_FRAME_DURATION = 10 * 1000;
- var MP4Remuxer = function () {
- function MP4Remuxer(observer, config, typeSupported, vendor) {
- _classCallCheck(this, MP4Remuxer);
- this.observer = observer;
- this.config = config;
- this.typeSupported = typeSupported;
- var userAgent = navigator.userAgent;
- this.isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS');
- this.ISGenerated = false;
- }
- _createClass(MP4Remuxer, [{
- key: 'destroy',
- value: function destroy() {}
- }, {
- key: 'resetTimeStamp',
- value: function resetTimeStamp(defaultTimeStamp) {
- this._initPTS = this._initDTS = defaultTimeStamp;
- }
- }, {
- key: 'resetInitSegment',
- value: function resetInitSegment() {
- this.ISGenerated = false;
- }
- }, {
- key: 'remux',
- value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
- // generate Init Segment if needed
- if (!this.ISGenerated) {
- this.generateIS(audioTrack, videoTrack, timeOffset);
- }
- if (this.ISGenerated) {
- var nbAudioSamples = audioTrack.samples.length;
- var nbVideoSamples = videoTrack.samples.length;
- var audioTimeOffset = timeOffset;
- var videoTimeOffset = timeOffset;
- if (nbAudioSamples && nbVideoSamples) {
- // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
- // if first audio DTS is not aligned with first video DTS then we need to take that into account
- // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
- // drift between audio and video streams
- var audiovideoDeltaDts = (audioTrack.samples[0].pts - videoTrack.samples[0].pts) / videoTrack.inputTimeScale;
- audioTimeOffset += Math.max(0, audiovideoDeltaDts);
- videoTimeOffset += Math.max(0, -audiovideoDeltaDts);
- }
- // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is
- // calculated in remuxAudio.
- // logger.log('nb AAC samples:' + audioTrack.samples.length);
- if (nbAudioSamples) {
- // if initSegment was generated without video samples, regenerate it again
- if (!audioTrack.timescale) {
- _logger.logger.warn('regenerate InitSegment as audio detected');
- this.generateIS(audioTrack, videoTrack, timeOffset);
- }
- var audioData = this.remuxAudio(audioTrack, audioTimeOffset, contiguous, accurateTimeOffset);
- // logger.log('nb AVC samples:' + videoTrack.samples.length);
- if (nbVideoSamples) {
- var audioTrackLength = void 0;
- if (audioData) {
- audioTrackLength = audioData.endPTS - audioData.startPTS;
- }
- // if initSegment was generated without video samples, regenerate it again
- if (!videoTrack.timescale) {
- _logger.logger.warn('regenerate InitSegment as video detected');
- this.generateIS(audioTrack, videoTrack, timeOffset);
- }
- this.remuxVideo(videoTrack, videoTimeOffset, contiguous, audioTrackLength, accurateTimeOffset);
- }
- } else {
- // logger.log('nb AVC samples:' + videoTrack.samples.length);
- if (nbVideoSamples) {
- var videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, accurateTimeOffset);
- if (videoData && audioTrack.codec) {
- this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);
- }
- }
- }
- }
- // logger.log('nb ID3 samples:' + audioTrack.samples.length);
- if (id3Track.samples.length) {
- this.remuxID3(id3Track, timeOffset);
- }
- // logger.log('nb ID3 samples:' + audioTrack.samples.length);
- if (textTrack.samples.length) {
- this.remuxText(textTrack, timeOffset);
- }
- // notify end of parsing
- this.observer.trigger(_events2.default.FRAG_PARSED);
- }
- }, {
- key: 'generateIS',
- value: function generateIS(audioTrack, videoTrack, timeOffset) {
- var observer = this.observer,
- audioSamples = audioTrack.samples,
- videoSamples = videoTrack.samples,
- typeSupported = this.typeSupported,
- container = 'audio/mp4',
- tracks = {},
- data = { tracks: tracks },
- computePTSDTS = this._initPTS === undefined,
- initPTS = void 0,
- initDTS = void 0;
- if (computePTSDTS) {
- initPTS = initDTS = Infinity;
- }
- if (audioTrack.config && audioSamples.length) {
- // let's use audio sampling rate as MP4 time scale.
- // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
- // using audio sampling rate here helps having an integer MP4 frame duration
- // this avoids potential rounding issue and AV sync issue
- audioTrack.timescale = audioTrack.samplerate;
- _logger.logger.log('audio sampling rate : ' + audioTrack.samplerate);
- if (!audioTrack.isAAC) {
- if (typeSupported.mpeg) {
- // Chrome and Safari
- container = 'audio/mpeg';
- audioTrack.codec = '';
- } else if (typeSupported.mp3) {
- // Firefox
- audioTrack.codec = 'mp3';
- }
- }
- tracks.audio = {
- container: container,
- codec: audioTrack.codec,
- initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : _mp4Generator2.default.initSegment([audioTrack]),
- metadata: {
- channelCount: audioTrack.channelCount
- }
- };
- if (computePTSDTS) {
- // remember first PTS of this demuxing context. for audio, PTS = DTS
- initPTS = initDTS = audioSamples[0].pts - audioTrack.inputTimeScale * timeOffset;
- }
- }
- if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
- // let's use input time scale as MP4 video timescale
- // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
- var inputTimeScale = videoTrack.inputTimeScale;
- videoTrack.timescale = inputTimeScale;
- tracks.video = {
- container: 'video/mp4',
- codec: videoTrack.codec,
- initSegment: _mp4Generator2.default.initSegment([videoTrack]),
- metadata: {
- width: videoTrack.width,
- height: videoTrack.height
- }
- };
- if (computePTSDTS) {
- initPTS = Math.min(initPTS, videoSamples[0].pts - inputTimeScale * timeOffset);
- initDTS = Math.min(initDTS, videoSamples[0].dts - inputTimeScale * timeOffset);
- this.observer.trigger(_events2.default.INIT_PTS_FOUND, { initPTS: initPTS });
- }
- }
- if (Object.keys(tracks).length) {
- observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, data);
- this.ISGenerated = true;
- if (computePTSDTS) {
- this._initPTS = initPTS;
- this._initDTS = initDTS;
- }
- } else {
- observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' });
- }
- }
- }, {
- key: 'remuxVideo',
- value: function remuxVideo(track, timeOffset, contiguous, audioTrackLength, accurateTimeOffset) {
- var offset = 8;
- var mp4SampleDuration = void 0;
- var mdat = void 0;
- var moof = void 0;
- var firstPTS = void 0;
- var firstDTS = void 0;
- var lastPTS = void 0;
- var lastDTS = void 0;
- var timeScale = track.timescale;
- var inputSamples = track.samples;
- var outputSamples = [];
- var nbSamples = inputSamples.length;
- var ptsNormalize = this._PTSNormalize;
- var initPTS = this._initPTS;
- // if parsed fragment is contiguous with last one, let's use last DTS value as reference
- var nextAvcDts = this.nextAvcDts;
- var isSafari = this.isSafari;
- if (nbSamples === 0) {
- return;
- }
- // Safari does not like overlapping DTS on consecutive fragments. let's use nextAvcDts to overcome this if fragments are consecutive
- if (isSafari) {
- // also consider consecutive fragments as being contiguous (even if a level switch occurs),
- // for sake of clarity:
- // consecutive fragments are frags with
- // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
- // - less than 200 ms PTS gaps (timeScale/5)
- contiguous |= inputSamples.length && nextAvcDts && (accurateTimeOffset && Math.abs(timeOffset - nextAvcDts / timeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAvcDts - initPTS) < timeScale / 5);
- }
- if (!contiguous) {
- // if not contiguous, let's use target timeOffset
- nextAvcDts = timeOffset * timeScale;
- }
- // PTS is coded on 33bits, and can loop from -2^32 to 2^32
- // ptsNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
- inputSamples.forEach(function (sample) {
- sample.pts = ptsNormalize(sample.pts - initPTS, nextAvcDts);
- sample.dts = ptsNormalize(sample.dts - initPTS, nextAvcDts);
- });
- // sort video samples by DTS then PTS then demux id order
- inputSamples.sort(function (a, b) {
- var deltadts = a.dts - b.dts;
- var deltapts = a.pts - b.pts;
- return deltadts || deltapts || a.id - b.id;
- });
- // handle broken streams with PTS < DTS, tolerance up 200ms (18000 in 90kHz timescale)
- var PTSDTSshift = inputSamples.reduce(function (prev, curr) {
- return Math.max(Math.min(prev, curr.pts - curr.dts), -18000);
- }, 0);
- if (PTSDTSshift < 0) {
- _logger.logger.warn('PTS < DTS detected in video samples, shifting DTS by ' + Math.round(PTSDTSshift / 90) + ' ms to overcome this issue');
- for (var i = 0; i < inputSamples.length; i++) {
- inputSamples[i].dts += PTSDTSshift;
- }
- }
- // compute first DTS and last DTS, normalize them against reference value
- var sample = inputSamples[0];
- firstDTS = Math.max(sample.dts, 0);
- firstPTS = Math.max(sample.pts, 0);
- // check timestamp continuity accross consecutive fragments (this is to remove inter-fragment gap/hole)
- var delta = Math.round((firstDTS - nextAvcDts) / 90);
- // if fragment are contiguous, detect hole/overlapping between fragments
- if (contiguous) {
- if (delta) {
- if (delta > 1) {
- _logger.logger.log('AVC:' + delta + ' ms hole between fragments detected,filling it');
- } else if (delta < -1) {
- _logger.logger.log('AVC:' + -delta + ' ms overlapping between fragments detected');
- }
- // remove hole/gap : set DTS to next expected DTS
- firstDTS = nextAvcDts;
- inputSamples[0].dts = firstDTS;
- // offset PTS as well, ensure that PTS is smaller or equal than new DTS
- firstPTS = Math.max(firstPTS - delta, nextAvcDts);
- inputSamples[0].pts = firstPTS;
- _logger.logger.log('Video/PTS/DTS adjusted: ' + Math.round(firstPTS / 90) + '/' + Math.round(firstDTS / 90) + ',delta:' + delta + ' ms');
- }
- }
- // compute lastPTS/lastDTS
- sample = inputSamples[inputSamples.length - 1];
- lastDTS = Math.max(sample.dts, 0);
- lastPTS = Math.max(sample.pts, 0, lastDTS);
- // on Safari let's signal the same sample duration for all samples
- // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
- // set this constant duration as being the avg delta between consecutive DTS.
- if (isSafari) {
- mp4SampleDuration = Math.round((lastDTS - firstDTS) / (inputSamples.length - 1));
- }
- var nbNalu = 0,
- naluLen = 0;
- for (var _i = 0; _i < nbSamples; _i++) {
- // compute total/avc sample length and nb of NAL units
- var _sample = inputSamples[_i],
- units = _sample.units,
- nbUnits = units.length,
- sampleLen = 0;
- for (var j = 0; j < nbUnits; j++) {
- sampleLen += units[j].data.length;
- }
- naluLen += sampleLen;
- nbNalu += nbUnits;
- _sample.length = sampleLen;
- // normalize PTS/DTS
- if (isSafari) {
- // sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples
- _sample.dts = firstDTS + _i * mp4SampleDuration;
- } else {
- // ensure sample monotonic DTS
- _sample.dts = Math.max(_sample.dts, firstDTS);
- }
- // ensure that computed value is greater or equal than sample DTS
- _sample.pts = Math.max(_sample.pts, _sample.dts);
- }
- /* concatenate the video data and construct the mdat in place
- (need 8 more bytes to fill length and mpdat type) */
- var mdatSize = naluLen + 4 * nbNalu + 8;
- try {
- mdat = new Uint8Array(mdatSize);
- } catch (err) {
- 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 });
- return;
- }
- var view = new DataView(mdat.buffer);
- view.setUint32(0, mdatSize);
- mdat.set(_mp4Generator2.default.types.mdat, 4);
- for (var _i2 = 0; _i2 < nbSamples; _i2++) {
- var avcSample = inputSamples[_i2],
- avcSampleUnits = avcSample.units,
- mp4SampleLength = 0,
- compositionTimeOffset = void 0;
- // convert NALU bitstream to MP4 format (prepend NALU with size field)
- for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) {
- var unit = avcSampleUnits[_j],
- unitData = unit.data,
- unitDataLen = unit.data.byteLength;
- view.setUint32(offset, unitDataLen);
- offset += 4;
- mdat.set(unitData, offset);
- offset += unitDataLen;
- mp4SampleLength += 4 + unitDataLen;
- }
- if (!isSafari) {
- // expected sample duration is the Decoding Timestamp diff of consecutive samples
- if (_i2 < nbSamples - 1) {
- mp4SampleDuration = inputSamples[_i2 + 1].dts - avcSample.dts;
- } else {
- var config = this.config,
- lastFrameDuration = avcSample.dts - inputSamples[_i2 > 0 ? _i2 - 1 : _i2].dts;
- if (config.stretchShortVideoTrack) {
- // In some cases, a segment's audio track duration may exceed the video track duration.
- // Since we've already remuxed audio, and we know how long the audio track is, we look to
- // see if the delta to the next segment is longer than maxBufferHole.
- // If so, playback would potentially get stuck, so we artificially inflate
- // the duration of the last frame to minimize any potential gap between segments.
- var maxBufferHole = config.maxBufferHole,
- gapTolerance = Math.floor(maxBufferHole * timeScale),
- deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;
- if (deltaToFrameEnd > gapTolerance) {
- // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
- // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
- mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
- if (mp4SampleDuration < 0) {
- mp4SampleDuration = lastFrameDuration;
- }
- _logger.logger.log('It is approximately ' + deltaToFrameEnd / 90 + ' ms to the next segment; using duration ' + mp4SampleDuration / 90 + ' ms for the last video frame.');
- } else {
- mp4SampleDuration = lastFrameDuration;
- }
- } else {
- mp4SampleDuration = lastFrameDuration;
- }
- }
- compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);
- } else {
- compositionTimeOffset = Math.max(0, mp4SampleDuration * Math.round((avcSample.pts - avcSample.dts) / mp4SampleDuration));
- }
- // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');
- // console.log(`avcSample.dts: ${avcSample.dts / 90}, avcSample.pts: ${avcSample.pts / 90}, mp4SampleDuration: ${mp4SampleDuration / 90}`, avcSample)
- outputSamples.push({
- size: mp4SampleLength,
- // constant duration
- duration: mp4SampleDuration,
- cts: compositionTimeOffset,
- flags: {
- isLeading: 0,
- isDependedOn: 0,
- hasRedundancy: 0,
- degradPrio: 0,
- dependsOn: avcSample.key ? 2 : 1,
- isNonSync: avcSample.key ? 0 : 1
- }
- });
- }
- // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
- this.nextAvcDts = lastDTS + mp4SampleDuration;
- var dropped = track.dropped;
- track.len = 0;
- track.nbNalu = 0;
- track.dropped = 0;
- if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
- var flags = outputSamples[0].flags;
- // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue
- // https://code.google.com/p/chromium/issues/detail?id=229412
- flags.dependsOn = 2;
- flags.isNonSync = 0;
- }
- track.samples = outputSamples;
- moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstDTS, track);
- track.samples = [];
- var data = {
- data1: moof,
- data2: mdat,
- startPTS: firstPTS / timeScale,
- endPTS: (lastPTS + mp4SampleDuration) / timeScale,
- startDTS: firstDTS / timeScale,
- endDTS: this.nextAvcDts / timeScale,
- type: 'video',
- hasAudio: false,
- hasVideo: true,
- nb: outputSamples.length,
- dropped: dropped
- };
- this.observer.trigger(_events2.default.FRAG_PARSING_DATA, data);
- return data;
- }
- }, {
- key: 'remuxAudio',
- value: function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset) {
- var inputTimeScale = track.inputTimeScale;
- var mp4timeScale = track.timescale;
- var scaleFactor = inputTimeScale / mp4timeScale;
- var mp4SampleDuration = track.isAAC ? 1024 : 1152;
- var inputSampleDuration = mp4SampleDuration * scaleFactor;
- var ptsNormalize = this._PTSNormalize;
- var initPTS = this._initPTS;
- var rawMPEG = !track.isAAC && this.typeSupported.mpeg;
- var offset = void 0,
- mp4Sample = void 0,
- fillFrame = void 0,
- mdat = void 0,
- moof = void 0,
- firstPTS = void 0,
- lastPTS = void 0,
- inputSamples = track.samples,
- outputSamples = [],
- nextAudioPts = this.nextAudioPts;
- // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
- // for sake of clarity:
- // consecutive fragments are frags with
- // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
- // - less than 20 audio frames distance
- // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
- // this helps ensuring audio continuity
- // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
- contiguous |= inputSamples.length && nextAudioPts && (accurateTimeOffset && Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAudioPts - initPTS) < 20 * inputSampleDuration);
- // compute normalized PTS
- inputSamples.forEach(function (sample) {
- sample.pts = sample.dts = ptsNormalize(sample.pts - initPTS, timeOffset * inputTimeScale);
- });
- // filter out sample with negative PTS that are not playable anyway
- // if we don't remove these negative samples, they will shift all audio samples forward.
- // leading to audio overlap between current / next fragment
- inputSamples = inputSamples.filter(function (sample) {
- return sample.pts >= 0;
- });
- // in case all samples have negative PTS, and have been filtered out, return now
- if (inputSamples.length === 0) {
- return;
- }
- if (!contiguous) {
- if (!accurateTimeOffset) {
- // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
- nextAudioPts = inputSamples[0].pts;
- } else {
- // if timeOffset is accurate, let's use it as predicted next audio PTS
- nextAudioPts = timeOffset * inputTimeScale;
- }
- }
- // If the audio track is missing samples, the frames seem to get "left-shifted" within the
- // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
- // In an effort to prevent this from happening, we inject frames here where there are gaps.
- // When possible, we inject a silent frame; when that's not possible, we duplicate the last
- // frame.
- if (track.isAAC) {
- var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
- for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length;) {
- // First, let's see how far off this frame is from where we expect it to be
- var sample = inputSamples[i],
- delta;
- var pts = sample.pts;
- delta = pts - nextPts;
- var duration = Math.abs(1000 * delta / inputTimeScale);
- // If we're overlapping by more than a duration, drop this sample
- if (delta <= -maxAudioFramesDrift * inputSampleDuration) {
- _logger.logger.warn('Dropping 1 audio frame @ ' + (nextPts / inputTimeScale).toFixed(3) + 's due to ' + Math.round(duration) + ' ms overlap.');
- inputSamples.splice(i, 1);
- track.len -= sample.unit.length;
- // Don't touch nextPtsNorm or i
- } // eslint-disable-line brace-style
- // Insert missing frames if:
- // 1: We're more than maxAudioFramesDrift frame away
- // 2: Not more than MAX_SILENT_FRAME_DURATION away
- // 3: currentTime (aka nextPtsNorm) is not 0
- else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && nextPts) {
- var missing = Math.round(delta / inputSampleDuration);
- _logger.logger.warn('Injecting ' + missing + ' audio frame @ ' + (nextPts / inputTimeScale).toFixed(3) + 's due to ' + Math.round(1000 * delta / inputTimeScale) + ' ms gap.');
- for (var j = 0; j < missing; j++) {
- var newStamp = Math.max(nextPts, 0);
- fillFrame = _aacHelper2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
- if (!fillFrame) {
- _logger.logger.log('Unable to get silent frame for given audio codec; duplicating last frame instead.');
- fillFrame = sample.unit.subarray();
- }
- inputSamples.splice(i, 0, { unit: fillFrame, pts: newStamp, dts: newStamp });
- track.len += fillFrame.length;
- nextPts += inputSampleDuration;
- i++;
- }
- // Adjust sample to next expected pts
- sample.pts = sample.dts = nextPts;
- nextPts += inputSampleDuration;
- i++;
- } else {
- // Otherwise, just adjust pts
- if (Math.abs(delta) > 0.1 * inputSampleDuration) {
- // logger.log(`Invalid frame delta ${Math.round(delta + inputSampleDuration)} at PTS ${Math.round(pts / 90)} (should be ${Math.round(inputSampleDuration)}).`);
- }
- sample.pts = sample.dts = nextPts;
- nextPts += inputSampleDuration;
- i++;
- }
- }
- }
- for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
- var audioSample = inputSamples[_j2];
- var unit = audioSample.unit;
- var _pts = audioSample.pts;
- // logger.log(`Audio/PTS:${Math.round(pts/90)}`);
- // if not first sample
- if (lastPTS !== undefined) {
- mp4Sample.duration = Math.round((_pts - lastPTS) / scaleFactor);
- } else {
- var _delta = Math.round(1000 * (_pts - nextAudioPts) / inputTimeScale),
- numMissingFrames = 0;
- // if fragment are contiguous, detect hole/overlapping between fragments
- // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
- if (contiguous && track.isAAC) {
- // log delta
- if (_delta) {
- if (_delta > 0 && _delta < MAX_SILENT_FRAME_DURATION) {
- numMissingFrames = Math.round((_pts - nextAudioPts) / inputSampleDuration);
- _logger.logger.log(_delta + ' ms hole between AAC samples detected,filling it');
- if (numMissingFrames > 0) {
- fillFrame = _aacHelper2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
- if (!fillFrame) {
- fillFrame = unit.subarray();
- }
- track.len += numMissingFrames * fillFrame.length;
- }
- // if we have frame overlap, overlapping for more than half a frame duraion
- } else if (_delta < -12) {
- // drop overlapping audio frames... browser will deal with it
- _logger.logger.log('drop overlapping AAC sample, expected/parsed/delta:' + (nextAudioPts / inputTimeScale).toFixed(3) + 's/' + (_pts / inputTimeScale).toFixed(3) + 's/' + -_delta + 'ms');
- track.len -= unit.byteLength;
- continue;
- }
- // set PTS/DTS to expected PTS/DTS
- _pts = nextAudioPts;
- }
- }
- // remember first PTS of our audioSamples
- firstPTS = _pts;
- if (track.len > 0) {
- /* concatenate the audio data and construct the mdat in place
- (need 8 more bytes to fill length and mdat type) */
- var mdatSize = rawMPEG ? track.len : track.len + 8;
- offset = rawMPEG ? 0 : 8;
- try {
- mdat = new Uint8Array(mdatSize);
- } catch (err) {
- 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 });
- return;
- }
- if (!rawMPEG) {
- var view = new DataView(mdat.buffer);
- view.setUint32(0, mdatSize);
- mdat.set(_mp4Generator2.default.types.mdat, 4);
- }
- } else {
- // no audio samples
- return;
- }
- for (var _i3 = 0; _i3 < numMissingFrames; _i3++) {
- fillFrame = _aacHelper2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
- if (!fillFrame) {
- _logger.logger.log('Unable to get silent frame for given audio codec; duplicating this frame instead.');
- fillFrame = unit.subarray();
- }
- mdat.set(fillFrame, offset);
- offset += fillFrame.byteLength;
- mp4Sample = {
- size: fillFrame.byteLength,
- cts: 0,
- duration: 1024,
- flags: {
- isLeading: 0,
- isDependedOn: 0,
- hasRedundancy: 0,
- degradPrio: 0,
- dependsOn: 1
- }
- };
- outputSamples.push(mp4Sample);
- }
- }
- mdat.set(unit, offset);
- var unitLen = unit.byteLength;
- offset += unitLen;
- // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${audioSample.pts}/${audioSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(audioSample.pts/4294967296).toFixed(3)}');
- mp4Sample = {
- size: unitLen,
- cts: 0,
- duration: 0,
- flags: {
- isLeading: 0,
- isDependedOn: 0,
- hasRedundancy: 0,
- degradPrio: 0,
- dependsOn: 1
- }
- };
- outputSamples.push(mp4Sample);
- lastPTS = _pts;
- }
- var lastSampleDuration = 0;
- var nbSamples = outputSamples.length;
- // set last sample duration as being identical to previous sample
- if (nbSamples >= 2) {
- lastSampleDuration = outputSamples[nbSamples - 2].duration;
- mp4Sample.duration = lastSampleDuration;
- }
- if (nbSamples) {
- // next audio sample PTS should be equal to last sample PTS + duration
- this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSampleDuration;
- // logger.log('Audio/PTS/PTSend:' + audioSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));
- track.len = 0;
- track.samples = outputSamples;
- if (rawMPEG) {
- moof = new Uint8Array();
- } else {
- moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstPTS / scaleFactor, track);
- }
- track.samples = [];
- var start = firstPTS / inputTimeScale;
- var end = nextAudioPts / inputTimeScale;
- var audioData = {
- data1: moof,
- data2: mdat,
- startPTS: start,
- endPTS: end,
- startDTS: start,
- endDTS: end,
- type: 'audio',
- hasAudio: true,
- hasVideo: false,
- nb: nbSamples
- };
- this.observer.trigger(_events2.default.FRAG_PARSING_DATA, audioData);
- return audioData;
- }
- return null;
- }
- }, {
- key: 'remuxEmptyAudio',
- value: function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
- var inputTimeScale = track.inputTimeScale,
- mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale,
- scaleFactor = inputTimeScale / mp4timeScale,
- nextAudioPts = this.nextAudioPts,
- // sync with video's timestamp
- startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS,
- endDTS = videoData.endDTS * inputTimeScale + this._initDTS,
- // one sample's duration value
- sampleDuration = 1024,
- frameDuration = scaleFactor * sampleDuration,
- // samples count of this segment's duration
- nbSamples = Math.ceil((endDTS - startDTS) / frameDuration),
- // silent frame
- silentFrame = _aacHelper2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
- _logger.logger.warn('remux empty Audio');
- // Can't remux if we can't generate a silent frame...
- if (!silentFrame) {
- _logger.logger.trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');
- return;
- }
- var samples = [];
- for (var i = 0; i < nbSamples; i++) {
- var stamp = startDTS + i * frameDuration;
- samples.push({ unit: silentFrame, pts: stamp, dts: stamp });
- track.len += silentFrame.length;
- }
- track.samples = samples;
- this.remuxAudio(track, timeOffset, contiguous);
- }
- }, {
- key: 'remuxID3',
- value: function remuxID3(track) {
- var length = track.samples.length,
- sample = void 0;
- var inputTimeScale = track.inputTimeScale;
- var initPTS = this._initPTS;
- var initDTS = this._initDTS;
- // consume samples
- if (length) {
- for (var index = 0; index < length; index++) {
- sample = track.samples[index];
- // setting id3 pts, dts to relative time
- // using this._initPTS and this._initDTS to calculate relative time
- sample.pts = (sample.pts - initPTS) / inputTimeScale;
- sample.dts = (sample.dts - initDTS) / inputTimeScale;
- }
- this.observer.trigger(_events2.default.FRAG_PARSING_METADATA, {
- samples: track.samples
- });
- }
- track.samples = [];
- }
- }, {
- key: 'remuxText',
- value: function remuxText(track) {
- track.samples.sort(function (a, b) {
- return a.pts - b.pts;
- });
- var length = track.samples.length,
- sample = void 0;
- var inputTimeScale = track.inputTimeScale;
- var initPTS = this._initPTS;
- // consume samples
- if (length) {
- for (var index = 0; index < length; index++) {
- sample = track.samples[index];
- // setting text pts, dts to relative time
- // using this._initPTS and this._initDTS to calculate relative time
- sample.pts = (sample.pts - initPTS) / inputTimeScale;
- }
- this.observer.trigger(_events2.default.FRAG_PARSING_USERDATA, {
- samples: track.samples
- });
- }
- track.samples = [];
- }
- }, {
- key: '_PTSNormalize',
- value: function _PTSNormalize(value, reference) {
- var offset = void 0;
- if (reference === undefined) {
- return value;
- }
- if (reference < value) {
- // - 2^33
- offset = -8589934592;
- } else {
- // + 2^33
- offset = 8589934592;
- }
- /* PTS is 33bit (from 0 to 2^33 -1)
- if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
- PTS looping occured. fill the gap */
- while (Math.abs(value - reference) > 4294967296) {
- value += offset;
- }
- return value;
- }
- }]);
- return MP4Remuxer;
- }();
- exports.default = MP4Remuxer;
- module.exports = exports['default'];
- /***/ }),
- /* 51 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /**
- * AAC helper
- */
- var AAC = function () {
- function AAC() {
- _classCallCheck(this, AAC);
- }
- _createClass(AAC, null, [{
- key: 'getSilentFrame',
- value: function getSilentFrame(codec, channelCount) {
- switch (codec) {
- case 'mp4a.40.2':
- if (channelCount === 1) {
- return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
- } else if (channelCount === 2) {
- return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
- } else if (channelCount === 3) {
- return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
- } else if (channelCount === 4) {
- return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
- } else if (channelCount === 5) {
- return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
- } else if (channelCount === 6) {
- 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]);
- }
- break;
- // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
- default:
- if (channelCount === 1) {
- // 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
- 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]);
- } else if (channelCount === 2) {
- // 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
- 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]);
- } else if (channelCount === 3) {
- // 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
- 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]);
- }
- break;
- }
- return null;
- }
- }]);
- return AAC;
- }();
- exports.default = AAC;
- module.exports = exports['default'];
- /***/ }),
- /* 52 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /**
- * Generate MP4 Box
- */
- var UINT32_MAX = Math.pow(2, 32) - 1;
- var MP4 = function () {
- function MP4() {
- _classCallCheck(this, MP4);
- }
- _createClass(MP4, null, [{
- key: 'init',
- value: function init() {
- MP4.types = {
- avc1: [], // codingname
- avcC: [],
- btrt: [],
- dinf: [],
- dref: [],
- esds: [],
- ftyp: [],
- hdlr: [],
- mdat: [],
- mdhd: [],
- mdia: [],
- mfhd: [],
- minf: [],
- moof: [],
- moov: [],
- mp4a: [],
- '.mp3': [],
- mvex: [],
- mvhd: [],
- pasp: [],
- sdtp: [],
- stbl: [],
- stco: [],
- stsc: [],
- stsd: [],
- stsz: [],
- stts: [],
- tfdt: [],
- tfhd: [],
- traf: [],
- trak: [],
- trun: [],
- trex: [],
- tkhd: [],
- vmhd: [],
- smhd: []
- };
- var i = void 0;
- for (i in MP4.types) {
- if (MP4.types.hasOwnProperty(i)) {
- MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
- }
- }
- var videoHdlr = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
- ]);
- var audioHdlr = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
- ]);
- MP4.HDLR_TYPES = {
- 'video': videoHdlr,
- 'audio': audioHdlr
- };
- var dref = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x01, // entry_count
- 0x00, 0x00, 0x00, 0x0c, // entry_size
- 0x75, 0x72, 0x6c, 0x20, // 'url' type
- 0x00, // version 0
- 0x00, 0x00, 0x01 // entry_flags
- ]);
- var stco = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00 // entry_count
- ]);
- MP4.STTS = MP4.STSC = MP4.STCO = stco;
- MP4.STSZ = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // sample_size
- 0x00, 0x00, 0x00, 0x00 // sample_count
- ]);
- MP4.VMHD = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x01, // flags
- 0x00, 0x00, // graphicsmode
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
- ]);
- MP4.SMHD = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, // balance
- 0x00, 0x00 // reserved
- ]);
- MP4.STSD = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x01]); // entry_count
- var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
- var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
- var minorVersion = new Uint8Array([0, 0, 0, 1]);
- MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
- MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
- }
- }, {
- key: 'box',
- value: function box(type) {
- var payload = Array.prototype.slice.call(arguments, 1),
- size = 8,
- i = payload.length,
- len = i,
- result = void 0;
- // calculate the total size we need to allocate
- while (i--) {
- size += payload[i].byteLength;
- }
- result = new Uint8Array(size);
- result[0] = size >> 24 & 0xff;
- result[1] = size >> 16 & 0xff;
- result[2] = size >> 8 & 0xff;
- result[3] = size & 0xff;
- result.set(type, 4);
- // copy the payload into the result
- for (i = 0, size = 8; i < len; i++) {
- // copy payload[i] array @ offset size
- result.set(payload[i], size);
- size += payload[i].byteLength;
- }
- return result;
- }
- }, {
- key: 'hdlr',
- value: function hdlr(type) {
- return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
- }
- }, {
- key: 'mdat',
- value: function mdat(data) {
- return MP4.box(MP4.types.mdat, data);
- }
- }, {
- key: 'mdhd',
- value: function mdhd(timescale, duration) {
- duration *= timescale;
- var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
- var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
- return MP4.box(MP4.types.mdhd, new Uint8Array([0x01, // version 1
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
- timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
- 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)
- 0x00, 0x00]));
- }
- }, {
- key: 'mdia',
- value: function mdia(track) {
- return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
- }
- }, {
- key: 'mfhd',
- value: function mfhd(sequenceNumber) {
- return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
- sequenceNumber >> 24, sequenceNumber >> 16 & 0xFF, sequenceNumber >> 8 & 0xFF, sequenceNumber & 0xFF // sequence_number
- ]));
- }
- }, {
- key: 'minf',
- value: function minf(track) {
- if (track.type === 'audio') {
- return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
- } else {
- return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
- }
- }
- }, {
- key: 'moof',
- value: function moof(sn, baseMediaDecodeTime, track) {
- return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
- }
- /**
- * @param tracks... (optional) {array} the tracks associated with this movie
- */
- }, {
- key: 'moov',
- value: function moov(tracks) {
- var i = tracks.length,
- boxes = [];
- while (i--) {
- boxes[i] = MP4.trak(tracks[i]);
- }
- return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
- }
- }, {
- key: 'mvex',
- value: function mvex(tracks) {
- var i = tracks.length,
- boxes = [];
- while (i--) {
- boxes[i] = MP4.trex(tracks[i]);
- }
- return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
- }
- }, {
- key: 'mvhd',
- value: function mvhd(timescale, duration) {
- duration *= timescale;
- var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
- var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
- var bytes = new Uint8Array([0x01, // version 1
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
- timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
- 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
- 0x01, 0x00, // 1.0 volume
- 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 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
- 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
- 0xff, 0xff, 0xff, 0xff // next_track_ID
- ]);
- return MP4.box(MP4.types.mvhd, bytes);
- }
- }, {
- key: 'sdtp',
- value: function sdtp(track) {
- var samples = track.samples || [],
- bytes = new Uint8Array(4 + samples.length),
- flags = void 0,
- i = void 0;
- // leave the full box header (4 bytes) all zero
- // write the sample table
- for (i = 0; i < samples.length; i++) {
- flags = samples[i].flags;
- bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
- }
- return MP4.box(MP4.types.sdtp, bytes);
- }
- }, {
- key: 'stbl',
- value: function stbl(track) {
- 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));
- }
- }, {
- key: 'avc1',
- value: function avc1(track) {
- var sps = [],
- pps = [],
- i = void 0,
- data = void 0,
- len = void 0;
- // assemble the SPSs
- for (i = 0; i < track.sps.length; i++) {
- data = track.sps[i];
- len = data.byteLength;
- sps.push(len >>> 8 & 0xFF);
- sps.push(len & 0xFF);
- // SPS
- sps = sps.concat(Array.prototype.slice.call(data));
- }
- // assemble the PPSs
- for (i = 0; i < track.pps.length; i++) {
- data = track.pps[i];
- len = data.byteLength;
- pps.push(len >>> 8 & 0xFF);
- pps.push(len & 0xFF);
- pps = pps.concat(Array.prototype.slice.call(data));
- }
- var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version
- sps[3], // profile
- sps[4], // profile compat
- sps[5], // level
- 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes
- 0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
- ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
- ]).concat(pps))),
- // "PPS"
- width = track.width,
- height = track.height,
- hSpacing = track.pixelRatio[0],
- vSpacing = track.pixelRatio[1];
- return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // data_reference_index
- 0x00, 0x00, // pre_defined
- 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
- width >> 8 & 0xFF, width & 0xff, // width
- height >> 8 & 0xFF, height & 0xff, // height
- 0x00, 0x48, 0x00, 0x00, // horizresolution
- 0x00, 0x48, 0x00, 0x00, // vertresolution
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // frame_count
- 0x12, 0x64, 0x61, 0x69, 0x6C, // dailymotion/hls.js
- 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
- 0x00, 0x18, // depth = 24
- 0x11, 0x11]), // pre_defined = -1
- avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
- 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
- 0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate
- MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24, // hSpacing
- hSpacing >> 16 & 0xFF, hSpacing >> 8 & 0xFF, hSpacing & 0xFF, vSpacing >> 24, // vSpacing
- vSpacing >> 16 & 0xFF, vSpacing >> 8 & 0xFF, vSpacing & 0xFF])));
- }
- }, {
- key: 'esds',
- value: function esds(track) {
- var configlen = track.config.length;
- return new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x03, // descriptor_type
- 0x17 + configlen, // length
- 0x00, 0x01, // es_id
- 0x00, // stream_priority
- 0x04, // descriptor_type
- 0x0f + configlen, // length
- 0x40, // codec : mpeg4_audio
- 0x15, // stream_type
- 0x00, 0x00, 0x00, // buffer_size
- 0x00, 0x00, 0x00, 0x00, // maxBitrate
- 0x00, 0x00, 0x00, 0x00, // avgBitrate
- 0x05 // descriptor_type
- ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
- }
- }, {
- key: 'mp4a',
- value: function mp4a(track) {
- var samplerate = track.samplerate;
- return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // data_reference_index
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, track.channelCount, // channelcount
- 0x00, 0x10, // sampleSize:16bits
- 0x00, 0x00, 0x00, 0x00, // reserved2
- samplerate >> 8 & 0xFF, samplerate & 0xff, //
- 0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
- }
- }, {
- key: 'mp3',
- value: function mp3(track) {
- var samplerate = track.samplerate;
- return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // data_reference_index
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, track.channelCount, // channelcount
- 0x00, 0x10, // sampleSize:16bits
- 0x00, 0x00, 0x00, 0x00, // reserved2
- samplerate >> 8 & 0xFF, samplerate & 0xff, //
- 0x00, 0x00]));
- }
- }, {
- key: 'stsd',
- value: function stsd(track) {
- if (track.type === 'audio') {
- if (!track.isAAC && track.codec === 'mp3') {
- return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
- }
- return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
- } else {
- return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
- }
- }
- }, {
- key: 'tkhd',
- value: function tkhd(track) {
- var id = track.id,
- duration = track.duration * track.timescale,
- width = track.width,
- height = track.height,
- upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)),
- lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
- return MP4.box(MP4.types.tkhd, new Uint8Array([0x01, // version 1
- 0x00, 0x00, 0x07, // flags
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
- id >> 24 & 0xFF, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID
- 0x00, 0x00, 0x00, 0x00, // reserved
- 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
- 0x00, 0x00, // layer
- 0x00, 0x00, // alternate_group
- 0x00, 0x00, // non-audio track volume
- 0x00, 0x00, // reserved
- 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
- width >> 8 & 0xFF, width & 0xFF, 0x00, 0x00, // width
- height >> 8 & 0xFF, height & 0xFF, 0x00, 0x00 // height
- ]));
- }
- }, {
- key: 'traf',
- value: function traf(track, baseMediaDecodeTime) {
- var sampleDependencyTable = MP4.sdtp(track),
- id = track.id,
- upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)),
- lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
- return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF]) // track_ID
- ), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1
- 0x00, 0x00, 0x00, // flags
- 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
- 20 + // tfdt
- 8 + // traf header
- 16 + // mfhd
- 8 + // moof header
- 8), // mdat header
- sampleDependencyTable);
- }
- /**
- * Generate a track box.
- * @param track {object} a track definition
- * @return {Uint8Array} the track box
- */
- }, {
- key: 'trak',
- value: function trak(track) {
- track.duration = track.duration || 0xffffffff;
- return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
- }
- }, {
- key: 'trex',
- value: function trex(track) {
- var id = track.id;
- return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF, // track_ID
- 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
- 0x00, 0x00, 0x00, 0x00, // default_sample_duration
- 0x00, 0x00, 0x00, 0x00, // default_sample_size
- 0x00, 0x01, 0x00, 0x01 // default_sample_flags
- ]));
- }
- }, {
- key: 'trun',
- value: function trun(track, offset) {
- var samples = track.samples || [],
- len = samples.length,
- arraylen = 12 + 16 * len,
- array = new Uint8Array(arraylen),
- i = void 0,
- sample = void 0,
- duration = void 0,
- size = void 0,
- flags = void 0,
- cts = void 0;
- offset += 8 + arraylen;
- array.set([0x00, // version 0
- 0x00, 0x0f, 0x01, // flags
- len >>> 24 & 0xFF, len >>> 16 & 0xFF, len >>> 8 & 0xFF, len & 0xFF, // sample_count
- offset >>> 24 & 0xFF, offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF // data_offset
- ], 0);
- for (i = 0; i < len; i++) {
- sample = samples[i];
- duration = sample.duration;
- size = sample.size;
- flags = sample.flags;
- cts = sample.cts;
- array.set([duration >>> 24 & 0xFF, duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, // sample_duration
- size >>> 24 & 0xFF, size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, // sample_size
- 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
- cts >>> 24 & 0xFF, cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF // sample_composition_time_offset
- ], 12 + 16 * i);
- }
- return MP4.box(MP4.types.trun, array);
- }
- }, {
- key: 'initSegment',
- value: function initSegment(tracks) {
- if (!MP4.types) {
- MP4.init();
- }
- var movie = MP4.moov(tracks),
- result = void 0;
- result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
- result.set(MP4.FTYP);
- result.set(movie, MP4.FTYP.byteLength);
- return result;
- }
- }]);
- return MP4;
- }();
- exports.default = MP4;
- module.exports = exports['default'];
- /***/ }),
- /* 53 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /**
- * passthrough remuxer
- */
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var PassThroughRemuxer = function () {
- function PassThroughRemuxer(observer) {
- _classCallCheck(this, PassThroughRemuxer);
- this.observer = observer;
- }
- _createClass(PassThroughRemuxer, [{
- key: 'destroy',
- value: function destroy() {}
- }, {
- key: 'resetTimeStamp',
- value: function resetTimeStamp() {}
- }, {
- key: 'resetInitSegment',
- value: function resetInitSegment() {}
- }, {
- key: 'remux',
- value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset, rawData) {
- var observer = this.observer;
- var streamType = '';
- if (audioTrack) {
- streamType += 'audio';
- }
- if (videoTrack) {
- streamType += 'video';
- }
- observer.trigger(_events2.default.FRAG_PARSING_DATA, {
- data1: rawData,
- startPTS: timeOffset,
- startDTS: timeOffset,
- type: streamType,
- hasAudio: !!audioTrack,
- hasVideo: !!videoTrack,
- nb: 1,
- dropped: 0
- });
- // notify end of parsing
- observer.trigger(_events2.default.FRAG_PARSED);
- }
- }]);
- return PassThroughRemuxer;
- }();
- exports.default = PassThroughRemuxer;
- module.exports = exports['default'];
- /***/ }),
- /* 54 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- var has = Object.prototype.hasOwnProperty
- , prefix = '~';
- /**
- * Constructor to create a storage for our `EE` objects.
- * An `Events` instance is a plain object whose properties are event names.
- *
- * @constructor
- * @private
- */
- function Events() {}
- //
- // We try to not inherit from `Object.prototype`. In some engines creating an
- // instance in this way is faster than calling `Object.create(null)` directly.
- // If `Object.create(null)` is not supported we prefix the event names with a
- // character to make sure that the built-in object properties are not
- // overridden or used as an attack vector.
- //
- if (Object.create) {
- Events.prototype = Object.create(null);
- //
- // This hack is needed because the `__proto__` property is still inherited in
- // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
- //
- if (!new Events().__proto__) prefix = false;
- }
- /**
- * Representation of a single event listener.
- *
- * @param {Function} fn The listener function.
- * @param {*} context The context to invoke the listener with.
- * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
- * @constructor
- * @private
- */
- function EE(fn, context, once) {
- this.fn = fn;
- this.context = context;
- this.once = once || false;
- }
- /**
- * Add a listener for a given event.
- *
- * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn The listener function.
- * @param {*} context The context to invoke the listener with.
- * @param {Boolean} once Specify if the listener is a one-time listener.
- * @returns {EventEmitter}
- * @private
- */
- function addListener(emitter, event, fn, context, once) {
- if (typeof fn !== 'function') {
- throw new TypeError('The listener must be a function');
- }
- var listener = new EE(fn, context || emitter, once)
- , evt = prefix ? prefix + event : event;
- if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
- else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
- else emitter._events[evt] = [emitter._events[evt], listener];
- return emitter;
- }
- /**
- * Clear event by name.
- *
- * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
- * @param {(String|Symbol)} evt The Event name.
- * @private
- */
- function clearEvent(emitter, evt) {
- if (--emitter._eventsCount === 0) emitter._events = new Events();
- else delete emitter._events[evt];
- }
- /**
- * Minimal `EventEmitter` interface that is molded against the Node.js
- * `EventEmitter` interface.
- *
- * @constructor
- * @public
- */
- function EventEmitter() {
- this._events = new Events();
- this._eventsCount = 0;
- }
- /**
- * Return an array listing the events for which the emitter has registered
- * listeners.
- *
- * @returns {Array}
- * @public
- */
- EventEmitter.prototype.eventNames = function eventNames() {
- var names = []
- , events
- , name;
- if (this._eventsCount === 0) return names;
- for (name in (events = this._events)) {
- if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
- }
- if (Object.getOwnPropertySymbols) {
- return names.concat(Object.getOwnPropertySymbols(events));
- }
- return names;
- };
- /**
- * Return the listeners registered for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @returns {Array} The registered listeners.
- * @public
- */
- EventEmitter.prototype.listeners = function listeners(event) {
- var evt = prefix ? prefix + event : event
- , handlers = this._events[evt];
- if (!handlers) return [];
- if (handlers.fn) return [handlers.fn];
- for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
- ee[i] = handlers[i].fn;
- }
- return ee;
- };
- /**
- * Return the number of listeners listening to a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @returns {Number} The number of listeners.
- * @public
- */
- EventEmitter.prototype.listenerCount = function listenerCount(event) {
- var evt = prefix ? prefix + event : event
- , listeners = this._events[evt];
- if (!listeners) return 0;
- if (listeners.fn) return 1;
- return listeners.length;
- };
- /**
- * Calls each of the listeners registered for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @returns {Boolean} `true` if the event had listeners, else `false`.
- * @public
- */
- EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
- var evt = prefix ? prefix + event : event;
- if (!this._events[evt]) return false;
- var listeners = this._events[evt]
- , len = arguments.length
- , args
- , i;
- if (listeners.fn) {
- if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
- switch (len) {
- case 1: return listeners.fn.call(listeners.context), true;
- case 2: return listeners.fn.call(listeners.context, a1), true;
- case 3: return listeners.fn.call(listeners.context, a1, a2), true;
- case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
- case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
- case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
- }
- for (i = 1, args = new Array(len -1); i < len; i++) {
- args[i - 1] = arguments[i];
- }
- listeners.fn.apply(listeners.context, args);
- } else {
- var length = listeners.length
- , j;
- for (i = 0; i < length; i++) {
- if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
- switch (len) {
- case 1: listeners[i].fn.call(listeners[i].context); break;
- case 2: listeners[i].fn.call(listeners[i].context, a1); break;
- case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
- case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
- default:
- if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
- args[j - 1] = arguments[j];
- }
- listeners[i].fn.apply(listeners[i].context, args);
- }
- }
- }
- return true;
- };
- /**
- * Add a listener for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn The listener function.
- * @param {*} [context=this] The context to invoke the listener with.
- * @returns {EventEmitter} `this`.
- * @public
- */
- EventEmitter.prototype.on = function on(event, fn, context) {
- return addListener(this, event, fn, context, false);
- };
- /**
- * Add a one-time listener for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn The listener function.
- * @param {*} [context=this] The context to invoke the listener with.
- * @returns {EventEmitter} `this`.
- * @public
- */
- EventEmitter.prototype.once = function once(event, fn, context) {
- return addListener(this, event, fn, context, true);
- };
- /**
- * Remove the listeners of a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn Only remove the listeners that match this function.
- * @param {*} context Only remove the listeners that have this context.
- * @param {Boolean} once Only remove one-time listeners.
- * @returns {EventEmitter} `this`.
- * @public
- */
- EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
- var evt = prefix ? prefix + event : event;
- if (!this._events[evt]) return this;
- if (!fn) {
- clearEvent(this, evt);
- return this;
- }
- var listeners = this._events[evt];
- if (listeners.fn) {
- if (
- listeners.fn === fn &&
- (!once || listeners.once) &&
- (!context || listeners.context === context)
- ) {
- clearEvent(this, evt);
- }
- } else {
- for (var i = 0, events = [], length = listeners.length; i < length; i++) {
- if (
- listeners[i].fn !== fn ||
- (once && !listeners[i].once) ||
- (context && listeners[i].context !== context)
- ) {
- events.push(listeners[i]);
- }
- }
- //
- // Reset the array, or remove it completely if we have no more listeners.
- //
- if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
- else clearEvent(this, evt);
- }
- return this;
- };
- /**
- * Remove all listeners, or those of the specified event.
- *
- * @param {(String|Symbol)} [event] The event name.
- * @returns {EventEmitter} `this`.
- * @public
- */
- EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
- var evt;
- if (event) {
- evt = prefix ? prefix + event : event;
- if (this._events[evt]) clearEvent(this, evt);
- } else {
- this._events = new Events();
- this._eventsCount = 0;
- }
- return this;
- };
- //
- // Alias methods names because people roll like that.
- //
- EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
- EventEmitter.prototype.addListener = EventEmitter.prototype.on;
- //
- // Expose the prefix.
- //
- EventEmitter.prefixed = prefix;
- //
- // Allow `EventEmitter` to be imported as module namespace.
- //
- EventEmitter.EventEmitter = EventEmitter;
- //
- // Expose the module.
- //
- if (true) {
- module.exports = EventEmitter;
- }
- /***/ }),
- /* 55 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var _demuxerInline = __webpack_require__(21);
- var _demuxerInline2 = _interopRequireDefault(_demuxerInline);
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _logger = __webpack_require__(0);
- var _events3 = __webpack_require__(20);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /* demuxer web worker.
- * - listen to worker message, and trigger DemuxerInline upon reception of Fragments.
- * - 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.
- */
- var DemuxerWorker = function DemuxerWorker(self) {
- // observer setup
- var observer = new _events3.EventEmitter();
- observer.trigger = function trigger(event) {
- for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- data[_key - 1] = arguments[_key];
- }
- observer.emit.apply(observer, [event, event].concat(data));
- };
- observer.off = function off(event) {
- for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
- data[_key2 - 1] = arguments[_key2];
- }
- observer.removeListener.apply(observer, [event].concat(data));
- };
- var forwardMessage = function forwardMessage(ev, data) {
- self.postMessage({ event: ev, data: data });
- };
- self.addEventListener('message', function (ev) {
- var data = ev.data;
- // console.log('demuxer cmd:' + data.cmd);
- switch (data.cmd) {
- case 'init':
- var config = JSON.parse(data.config);
- self.demuxer = new _demuxerInline2.default(observer, data.typeSupported, config, data.vendor);
- (0, _logger.enableLogs)(config.debug);
- // signal end of worker init
- forwardMessage('init', null);
- break;
- case 'demux':
- 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);
- break;
- default:
- break;
- }
- });
- // forward events to main thread
- observer.on(_events2.default.FRAG_DECRYPTED, forwardMessage);
- observer.on(_events2.default.FRAG_PARSING_INIT_SEGMENT, forwardMessage);
- observer.on(_events2.default.FRAG_PARSED, forwardMessage);
- observer.on(_events2.default.ERROR, forwardMessage);
- observer.on(_events2.default.FRAG_PARSING_METADATA, forwardMessage);
- observer.on(_events2.default.FRAG_PARSING_USERDATA, forwardMessage);
- observer.on(_events2.default.INIT_PTS_FOUND, forwardMessage);
- // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy)
- observer.on(_events2.default.FRAG_PARSING_DATA, function (ev, data) {
- var transferable = [];
- var message = { event: ev, data: data };
- if (data.data1) {
- message.data1 = data.data1.buffer;
- transferable.push(data.data1.buffer);
- delete data.data1;
- }
- if (data.data2) {
- message.data2 = data.data2.buffer;
- transferable.push(data.data2.buffer);
- delete data.data2;
- }
- self.postMessage(message, transferable);
- });
- };
- exports.default = DemuxerWorker;
- module.exports = exports['default'];
- /***/ }),
- /* 56 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _bufferHelper = __webpack_require__(4);
- var _errors = __webpack_require__(2);
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _logger = __webpack_require__(0);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var stallDebounceInterval = 1000;
- var jumpThreshold = 0.5; // tolerance needed as some browsers stalls playback before reaching buffered range end
- var GapController = function () {
- function GapController(config, media, fragmentTracker, hls) {
- _classCallCheck(this, GapController);
- this.config = config;
- this.media = media;
- this.fragmentTracker = fragmentTracker;
- this.hls = hls;
- this.stallReported = false;
- }
- /**
- * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
- * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
- * @param lastCurrentTime
- * @param buffered
- */
- _createClass(GapController, [{
- key: 'poll',
- value: function poll(lastCurrentTime, buffered) {
- var config = this.config,
- media = this.media;
- var currentTime = media.currentTime;
- var tnow = window.performance.now();
- if (currentTime !== lastCurrentTime) {
- // The playhead is now moving, but was previously stalled
- if (this.stallReported) {
- _logger.logger.warn('playback not stuck anymore @' + currentTime + ', after ' + Math.round(tnow - this.stalled) + 'ms');
- this.stallReported = false;
- }
- this.stalled = null;
- this.nudgeRetry = 0;
- return;
- }
- if (media.ended || !media.buffered.length || media.readyState > 2) {
- return;
- }
- if (media.seeking && _bufferHelper.BufferHelper.isBuffered(media, currentTime)) {
- return;
- }
- // The playhead isn't moving but it should be
- // Allow some slack time to for small stalls to resolve themselves
- var stalledDuration = tnow - this.stalled;
- var bufferInfo = _bufferHelper.BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
- if (!this.stalled) {
- this.stalled = tnow;
- return;
- } else if (stalledDuration >= stallDebounceInterval) {
- // Report stalling after trying to fix
- this._reportStall(bufferInfo.len);
- }
- this._tryFixBufferStall(bufferInfo, stalledDuration);
- }
- /**
- * Detects and attempts to fix known buffer stalling issues.
- * @param bufferInfo - The properties of the current buffer.
- * @param stalledDuration - The amount of time Hls.js has been stalling for.
- * @private
- */
- }, {
- key: '_tryFixBufferStall',
- value: function _tryFixBufferStall(bufferInfo, stalledDuration) {
- var config = this.config,
- fragmentTracker = this.fragmentTracker,
- media = this.media;
- var currentTime = media.currentTime;
- var partial = fragmentTracker.getPartialFragment(currentTime);
- if (partial) {
- // Try to skip over the buffer hole caused by a partial fragment
- // This method isn't limited by the size of the gap between buffered ranges
- this._trySkipBufferHole(partial);
- }
- if (bufferInfo.len > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {
- // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
- // We only try to jump the hole if it's under the configured size
- // Reset stalled so to rearm watchdog timer
- this.stalled = null;
- this._tryNudgeBuffer();
- }
- }
- /**
- * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
- * @param bufferLen - The playhead distance from the end of the current buffer segment.
- * @private
- */
- }, {
- key: '_reportStall',
- value: function _reportStall(bufferLen) {
- var hls = this.hls,
- media = this.media,
- stallReported = this.stallReported;
- if (!stallReported) {
- // Report stalled error once
- this.stallReported = true;
- _logger.logger.warn('Playback stalling at @' + media.currentTime + ' due to low buffer');
- hls.trigger(_events2.default.ERROR, {
- type: _errors.ErrorTypes.MEDIA_ERROR,
- details: _errors.ErrorDetails.BUFFER_STALLED_ERROR,
- fatal: false,
- buffer: bufferLen
- });
- }
- }
- /**
- * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
- * @param partial - The partial fragment found at the current time (where playback is stalling).
- * @private
- */
- }, {
- key: '_trySkipBufferHole',
- value: function _trySkipBufferHole(partial) {
- var hls = this.hls,
- media = this.media;
- var currentTime = media.currentTime;
- var lastEndTime = 0;
- // Check if currentTime is between unbuffered regions of partial fragments
- for (var i = 0; i < media.buffered.length; i++) {
- var startTime = media.buffered.start(i);
- if (currentTime >= lastEndTime && currentTime < startTime) {
- media.currentTime = Math.max(startTime, media.currentTime + 0.1);
- _logger.logger.warn('skipping hole, adjusting currentTime from ' + currentTime + ' to ' + media.currentTime);
- this.stalled = null;
- hls.trigger(_events2.default.ERROR, {
- type: _errors.ErrorTypes.MEDIA_ERROR,
- details: _errors.ErrorDetails.BUFFER_SEEK_OVER_HOLE,
- fatal: false,
- reason: 'fragment loaded with buffer holes, seeking from ' + currentTime + ' to ' + media.currentTime,
- frag: partial
- });
- return;
- }
- lastEndTime = media.buffered.end(i);
- }
- }
- /**
- * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
- * @private
- */
- }, {
- key: '_tryNudgeBuffer',
- value: function _tryNudgeBuffer() {
- var config = this.config,
- hls = this.hls,
- media = this.media;
- var currentTime = media.currentTime;
- var nudgeRetry = (this.nudgeRetry || 0) + 1;
- this.nudgeRetry = nudgeRetry;
- if (nudgeRetry < config.nudgeMaxRetry) {
- var targetTime = currentTime + nudgeRetry * config.nudgeOffset;
- _logger.logger.log('adjust currentTime from ' + currentTime + ' to ' + targetTime);
- // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
- media.currentTime = targetTime;
- hls.trigger(_events2.default.ERROR, {
- type: _errors.ErrorTypes.MEDIA_ERROR,
- details: _errors.ErrorDetails.BUFFER_NUDGE_ON_STALL,
- fatal: false
- });
- } else {
- _logger.logger.error('still stuck in high buffer @' + currentTime + ' after ' + config.nudgeMaxRetry + ', raise fatal error');
- hls.trigger(_events2.default.ERROR, {
- type: _errors.ErrorTypes.MEDIA_ERROR,
- details: _errors.ErrorDetails.BUFFER_STALLED_ERROR,
- fatal: true
- });
- }
- }
- }]);
- return GapController;
- }();
- exports.default = GapController;
- module.exports = exports['default'];
- /***/ }),
- /* 57 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; };
- 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; }; }();
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _eventHandler = __webpack_require__(3);
- var _eventHandler2 = _interopRequireDefault(_eventHandler);
- var _logger = __webpack_require__(0);
- var _errors = __webpack_require__(2);
- var _codecs = __webpack_require__(18);
- var _levelHelper = __webpack_require__(7);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /*
- * Level Controller
- */
- var _window = window,
- performance = _window.performance;
- var chromeOrFirefox = void 0;
- var LevelController = function (_EventHandler) {
- _inherits(LevelController, _EventHandler);
- function LevelController(hls) {
- _classCallCheck(this, LevelController);
- 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));
- _this.canload = false;
- _this.currentLevelIndex = null;
- _this.manualLevelIndex = -1;
- _this.timer = null;
- chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());
- return _this;
- }
- _createClass(LevelController, [{
- key: 'onHandlerDestroying',
- value: function onHandlerDestroying() {
- this.clearTimer();
- this.manualLevelIndex = -1;
- }
- }, {
- key: 'clearTimer',
- value: function clearTimer() {
- if (this.timer !== null) {
- clearTimeout(this.timer);
- this.timer = null;
- }
- }
- }, {
- key: 'startLoad',
- value: function startLoad() {
- var levels = this._levels;
- this.canload = true;
- this.levelRetryCount = 0;
- // clean up live level details to force reload them, and reset load errors
- if (levels) {
- levels.forEach(function (level) {
- level.loadError = 0;
- var levelDetails = level.details;
- if (levelDetails && levelDetails.live) {
- level.details = undefined;
- }
- });
- }
- // speed up live playlist refresh if timer exists
- if (this.timer !== null) {
- this.loadLevel();
- }
- }
- }, {
- key: 'stopLoad',
- value: function stopLoad() {
- this.canload = false;
- }
- }, {
- key: 'onManifestLoaded',
- value: function onManifestLoaded(data) {
- var levels = [];
- var audioTracks = [];
- var bitrateStart = void 0;
- var levelSet = {};
- var levelFromSet = null;
- var videoCodecFound = false;
- var audioCodecFound = false;
- // regroup redundant levels together
- data.levels.forEach(function (level) {
- var attributes = level.attrs;
- level.loadError = 0;
- level.fragmentError = false;
- videoCodecFound = videoCodecFound || !!level.videoCodec;
- audioCodecFound = audioCodecFound || !!level.audioCodec;
- // erase audio codec info if browser does not support mp4a.40.34.
- // demuxer will autodetect codec and fallback to mpeg/audio
- if (chromeOrFirefox && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {
- level.audioCodec = undefined;
- }
- levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here
- if (!levelFromSet) {
- level.url = [level.url];
- level.urlId = 0;
- levelSet[level.bitrate] = level;
- levels.push(level);
- } else {
- levelFromSet.url.push(level.url);
- }
- if (attributes) {
- if (attributes.AUDIO) {
- audioCodecFound = true;
- (0, _levelHelper.addGroupId)(levelFromSet || level, 'audio', attributes.AUDIO);
- }
- if (attributes.SUBTITLES) {
- (0, _levelHelper.addGroupId)(levelFromSet || level, 'text', attributes.SUBTITLES);
- }
- }
- });
- // remove audio-only level if we also have levels with audio+video codecs signalled
- if (videoCodecFound && audioCodecFound) {
- levels = levels.filter(function (_ref) {
- var videoCodec = _ref.videoCodec;
- return !!videoCodec;
- });
- }
- // only keep levels with supported audio/video codecs
- levels = levels.filter(function (_ref2) {
- var audioCodec = _ref2.audioCodec,
- videoCodec = _ref2.videoCodec;
- return (!audioCodec || (0, _codecs.isCodecSupportedInMp4)(audioCodec, 'audio')) && (!videoCodec || (0, _codecs.isCodecSupportedInMp4)(videoCodec, 'video'));
- });
- if (data.audioTracks) {
- audioTracks = data.audioTracks.filter(function (track) {
- return !track.audioCodec || (0, _codecs.isCodecSupportedInMp4)(track.audioCodec, 'audio');
- });
- // Reassign id's after filtering since they're used as array indices
- audioTracks.forEach(function (track, index) {
- track.id = index;
- });
- }
- if (levels.length > 0) {
- // start bitrate is the first bitrate of the manifest
- bitrateStart = levels[0].bitrate;
- // sort level on bitrate
- levels.sort(function (a, b) {
- return a.bitrate - b.bitrate;
- });
- this._levels = levels;
- // find index of first level in sorted levels
- for (var i = 0; i < levels.length; i++) {
- if (levels[i].bitrate === bitrateStart) {
- this._firstLevel = i;
- _logger.logger.log('manifest loaded,' + levels.length + ' level(s) found, first bitrate:' + bitrateStart);
- break;
- }
- }
- // Audio is only alternate if manifest include a URI along with the audio group tag
- this.hls.trigger(_events2.default.MANIFEST_PARSED, {
- levels: levels,
- audioTracks: audioTracks,
- firstLevel: this._firstLevel,
- stats: data.stats,
- audio: audioCodecFound,
- video: videoCodecFound,
- altAudio: audioTracks.some(function (t) {
- return !!t.url;
- })
- });
- } else {
- this.hls.trigger(_events2.default.ERROR, {
- type: _errors.ErrorTypes.MEDIA_ERROR,
- details: _errors.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
- fatal: true,
- url: this.hls.url,
- reason: 'no level with compatible codecs found in manifest'
- });
- }
- }
- }, {
- key: 'setLevelInternal',
- value: function setLevelInternal(newLevel) {
- var levels = this._levels;
- var hls = this.hls;
- // check if level idx is valid
- if (newLevel >= 0 && newLevel < levels.length) {
- // stopping live reloading timer if any
- this.clearTimer();
- if (this.currentLevelIndex !== newLevel) {
- _logger.logger.log('switching to level ' + newLevel);
- this.currentLevelIndex = newLevel;
- var levelProperties = levels[newLevel];
- levelProperties.level = newLevel;
- hls.trigger(_events2.default.LEVEL_SWITCHING, levelProperties);
- }
- var level = levels[newLevel];
- var levelDetails = level.details;
- // check if we need to load playlist for this level
- if (!levelDetails || levelDetails.live) {
- // level not retrieved yet, or live playlist we need to (re)load it
- var urlId = level.urlId;
- hls.trigger(_events2.default.LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId });
- }
- } else {
- // invalid level id given, trigger error
- hls.trigger(_events2.default.ERROR, {
- type: _errors.ErrorTypes.OTHER_ERROR,
- details: _errors.ErrorDetails.LEVEL_SWITCH_ERROR,
- level: newLevel,
- fatal: false,
- reason: 'invalid level idx'
- });
- }
- }
- }, {
- key: 'onError',
- value: function onError(data) {
- if (data.fatal) {
- if (data.type === _errors.ErrorTypes.NETWORK_ERROR) {
- this.clearTimer();
- }
- return;
- }
- var levelError = false,
- fragmentError = false;
- var levelIndex = void 0;
- // try to recover not fatal errors
- switch (data.details) {
- case _errors.ErrorDetails.FRAG_LOAD_ERROR:
- case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
- case _errors.ErrorDetails.KEY_LOAD_ERROR:
- case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
- levelIndex = data.frag.level;
- fragmentError = true;
- break;
- case _errors.ErrorDetails.LEVEL_LOAD_ERROR:
- case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT:
- levelIndex = data.context.level;
- levelError = true;
- break;
- case _errors.ErrorDetails.REMUX_ALLOC_ERROR:
- levelIndex = data.level;
- levelError = true;
- break;
- }
- if (levelIndex !== undefined) {
- this.recoverLevel(data, levelIndex, levelError, fragmentError);
- }
- }
- /**
- * Switch to a redundant stream if any available.
- * If redundant stream is not available, emergency switch down if ABR mode is enabled.
- *
- * @param {Object} errorEvent
- * @param {Number} levelIndex current level index
- * @param {Boolean} levelError
- * @param {Boolean} fragmentError
- */
- // FIXME Find a better abstraction where fragment/level retry management is well decoupled
- }, {
- key: 'recoverLevel',
- value: function recoverLevel(errorEvent, levelIndex, levelError, fragmentError) {
- var _this2 = this;
- var config = this.hls.config;
- var errorDetails = errorEvent.details;
- var level = this._levels[levelIndex];
- var redundantLevels = void 0,
- delay = void 0,
- nextLevel = void 0;
- level.loadError++;
- level.fragmentError = fragmentError;
- if (levelError) {
- if (this.levelRetryCount + 1 <= config.levelLoadingMaxRetry) {
- // exponential backoff capped to max retry timeout
- delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);
- // Schedule level reload
- this.timer = setTimeout(function () {
- return _this2.loadLevel();
- }, delay);
- // boolean used to inform stream controller not to switch back to IDLE on non fatal error
- errorEvent.levelRetry = true;
- this.levelRetryCount++;
- _logger.logger.warn('level controller, ' + errorDetails + ', retry in ' + delay + ' ms, current retry count is ' + this.levelRetryCount);
- } else {
- _logger.logger.error('level controller, cannot recover from ' + errorDetails + ' error');
- this.currentLevelIndex = null;
- // stopping live reloading timer if any
- this.clearTimer();
- // switch error to fatal
- errorEvent.fatal = true;
- return;
- }
- }
- // Try any redundant streams if available for both errors: level and fragment
- // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down
- if (levelError || fragmentError) {
- redundantLevels = level.url.length;
- if (redundantLevels > 1 && level.loadError < redundantLevels) {
- level.urlId = (level.urlId + 1) % redundantLevels;
- level.details = undefined;
- _logger.logger.warn('level controller, ' + errorDetails + ' for level ' + levelIndex + ': switching to redundant URL-id ' + level.urlId);
- // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
- // console.log('New video quality level audio group id:', level.attrs.AUDIO);
- } else {
- // Search for available level
- if (this.manualLevelIndex === -1) {
- // When lowest level has been reached, let's start hunt from the top
- nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1;
- _logger.logger.warn('level controller, ' + errorDetails + ': switch to ' + nextLevel);
- this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;
- } else if (fragmentError) {
- // Allow fragment retry as long as configuration allows.
- // reset this._level so that another call to set level() will trigger again a frag load
- _logger.logger.warn('level controller, ' + errorDetails + ': reload a fragment');
- this.currentLevelIndex = null;
- }
- }
- }
- }
- // reset errors on the successful load of a fragment
- }, {
- key: 'onFragLoaded',
- value: function onFragLoaded(_ref3) {
- var frag = _ref3.frag;
- if (frag !== undefined && frag.type === 'main') {
- var level = this._levels[frag.level];
- if (level !== undefined) {
- level.fragmentError = false;
- level.loadError = 0;
- this.levelRetryCount = 0;
- }
- }
- }
- }, {
- key: 'onLevelLoaded',
- value: function onLevelLoaded(data) {
- var _this3 = this;
- var level = data.level,
- details = data.details;
- // only process level loaded events matching with expected level
- if (level !== this.currentLevelIndex) {
- return;
- }
- var curLevel = this._levels[level];
- // reset level load error counter on successful level loaded only if there is no issues with fragments
- if (!curLevel.fragmentError) {
- curLevel.loadError = 0;
- this.levelRetryCount = 0;
- }
- // if current playlist is a live playlist, arm a timer to reload it
- if (details.live) {
- var reloadInterval = (0, _levelHelper.computeReloadInterval)(curLevel.details, details, data.stats.trequest);
- _logger.logger.log('live playlist, reload in ' + Math.round(reloadInterval) + ' ms');
- this.timer = setTimeout(function () {
- return _this3.loadLevel();
- }, reloadInterval);
- } else {
- this.clearTimer();
- }
- }
- }, {
- key: 'onAudioTrackSwitched',
- value: function onAudioTrackSwitched(data) {
- var audioGroupId = this.hls.audioTracks[data.id].groupId;
- var currentLevel = this.hls.levels[this.currentLevelIndex];
- if (!currentLevel) {
- return;
- }
- if (currentLevel.audioGroupIds) {
- var urlId = -1;
- for (var i = 0; i < currentLevel.audioGroupIds.length; i++) {
- if (currentLevel.audioGroupIds[i] === audioGroupId) {
- urlId = i;
- break;
- }
- }
- if (urlId !== currentLevel.urlId) {
- currentLevel.urlId = urlId;
- this.startLoad();
- }
- }
- }
- }, {
- key: 'loadLevel',
- value: function loadLevel() {
- _logger.logger.debug('call to loadLevel');
- if (this.currentLevelIndex !== null && this.canload) {
- var levelObject = this._levels[this.currentLevelIndex];
- if ((typeof levelObject === 'undefined' ? 'undefined' : _typeof(levelObject)) === 'object' && levelObject.url.length > 0) {
- var level = this.currentLevelIndex;
- var id = levelObject.urlId;
- var url = levelObject.url[id];
- _logger.logger.log('Attempt loading level index ' + level + ' with URL-id ' + id);
- // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
- // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
- this.hls.trigger(_events2.default.LEVEL_LOADING, { url: url, level: level, id: id });
- }
- }
- }
- }, {
- key: 'levels',
- get: function get() {
- return this._levels;
- }
- }, {
- key: 'level',
- get: function get() {
- return this.currentLevelIndex;
- },
- set: function set(newLevel) {
- var levels = this._levels;
- if (levels) {
- newLevel = Math.min(newLevel, levels.length - 1);
- if (this.currentLevelIndex !== newLevel || !levels[newLevel].details) {
- this.setLevelInternal(newLevel);
- }
- }
- }
- }, {
- key: 'manualLevel',
- get: function get() {
- return this.manualLevelIndex;
- },
- set: function set(newLevel) {
- this.manualLevelIndex = newLevel;
- if (this._startLevel === undefined) {
- this._startLevel = newLevel;
- }
- if (newLevel !== -1) {
- this.level = newLevel;
- }
- }
- }, {
- key: 'firstLevel',
- get: function get() {
- return this._firstLevel;
- },
- set: function set(newLevel) {
- this._firstLevel = newLevel;
- }
- }, {
- key: 'startLevel',
- get: function get() {
- // hls.startLevel takes precedence over config.startLevel
- // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)
- if (this._startLevel === undefined) {
- var configStartLevel = this.hls.config.startLevel;
- if (configStartLevel !== undefined) {
- return configStartLevel;
- } else {
- return this._firstLevel;
- }
- } else {
- return this._startLevel;
- }
- },
- set: function set(newLevel) {
- this._startLevel = newLevel;
- }
- }, {
- key: 'nextLoadLevel',
- get: function get() {
- if (this.manualLevelIndex !== -1) {
- return this.manualLevelIndex;
- } else {
- return this.hls.nextAutoLevel;
- }
- },
- set: function set(nextLevel) {
- this.level = nextLevel;
- if (this.manualLevelIndex === -1) {
- this.hls.nextAutoLevel = nextLevel;
- }
- }
- }]);
- return LevelController;
- }(_eventHandler2.default);
- exports.default = LevelController;
- module.exports = exports['default'];
- /***/ }),
- /* 58 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _eventHandler = __webpack_require__(3);
- var _eventHandler2 = _interopRequireDefault(_eventHandler);
- var _id = __webpack_require__(10);
- var _id2 = _interopRequireDefault(_id);
- var _texttrackUtils = __webpack_require__(29);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /*
- * id3 metadata track controller
- */
- var ID3TrackController = function (_EventHandler) {
- _inherits(ID3TrackController, _EventHandler);
- function ID3TrackController(hls) {
- _classCallCheck(this, ID3TrackController);
- 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));
- _this.id3Track = undefined;
- _this.media = undefined;
- return _this;
- }
- _createClass(ID3TrackController, [{
- key: 'destroy',
- value: function destroy() {
- _eventHandler2.default.prototype.destroy.call(this);
- }
- // Add ID3 metatadata text track.
- }, {
- key: 'onMediaAttached',
- value: function onMediaAttached(data) {
- this.media = data.media;
- if (!this.media) {}
- }
- }, {
- key: 'onMediaDetaching',
- value: function onMediaDetaching() {
- (0, _texttrackUtils.clearCurrentCues)(this.id3Track);
- this.id3Track = undefined;
- this.media = undefined;
- }
- }, {
- key: 'getID3Track',
- value: function getID3Track(textTracks) {
- for (var i = 0; i < textTracks.length; i++) {
- var textTrack = textTracks[i];
- if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
- // send 'addtrack' when reusing the textTrack for metadata,
- // same as what we do for captions
- (0, _texttrackUtils.sendAddTrackEvent)(textTrack, this.media);
- return textTrack;
- }
- }
- return this.media.addTextTrack('metadata', 'id3');
- }
- }, {
- key: 'onFragParsingMetadata',
- value: function onFragParsingMetadata(data) {
- var fragment = data.frag;
- var samples = data.samples;
- // create track dynamically
- if (!this.id3Track) {
- this.id3Track = this.getID3Track(this.media.textTracks);
- this.id3Track.mode = 'hidden';
- }
- // Attempt to recreate Safari functionality by creating
- // WebKitDataCue objects when available and store the decoded
- // ID3 data in the value property of the cue
- var Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;
- for (var i = 0; i < samples.length; i++) {
- var frames = _id2.default.getID3Frames(samples[i].data);
- if (frames) {
- var startTime = samples[i].pts;
- var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.endPTS;
- // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
- if (startTime === endTime) {
- endTime += 0.0001;
- }
- for (var j = 0; j < frames.length; j++) {
- var frame = frames[j];
- // Safari doesn't put the timestamp frame in the TextTrack
- if (!_id2.default.isTimeStampFrame(frame)) {
- var cue = new Cue(startTime, endTime, '');
- cue.value = frame;
- this.id3Track.addCue(cue);
- }
- }
- }
- }
- }
- }]);
- return ID3TrackController;
- }(_eventHandler2.default);
- exports.default = ID3TrackController;
- module.exports = exports['default'];
- /***/ }),
- /* 59 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isSupported = isSupported;
- var _mediasourceHelper = __webpack_require__(13);
- function isSupported() {
- var mediaSource = (0, _mediasourceHelper.getMediaSource)();
- var sourceBuffer = window.SourceBuffer || window.WebKitSourceBuffer;
- var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
- // if SourceBuffer is exposed ensure its API is valid
- // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
- var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
- return !!isTypeSupported && !!sourceBufferValidAPI;
- }
- /***/ }),
- /* 60 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.hlsDefaultConfig = undefined;
- var _abrController = __webpack_require__(61);
- var _abrController2 = _interopRequireDefault(_abrController);
- var _bufferController = __webpack_require__(64);
- var _bufferController2 = _interopRequireDefault(_bufferController);
- var _capLevelController = __webpack_require__(65);
- var _capLevelController2 = _interopRequireDefault(_capLevelController);
- var _fpsController = __webpack_require__(66);
- var _fpsController2 = _interopRequireDefault(_fpsController);
- var _xhrLoader = __webpack_require__(67);
- var _xhrLoader2 = _interopRequireDefault(_xhrLoader);
- var _audioTrackController = __webpack_require__(68);
- var _audioTrackController2 = _interopRequireDefault(_audioTrackController);
- var _audioStreamController = __webpack_require__(69);
- var _audioStreamController2 = _interopRequireDefault(_audioStreamController);
- var _cues = __webpack_require__(70);
- var Cues = _interopRequireWildcard(_cues);
- var _timelineController = __webpack_require__(72);
- var _timelineController2 = _interopRequireDefault(_timelineController);
- var _subtitleTrackController = __webpack_require__(76);
- var _subtitleTrackController2 = _interopRequireDefault(_subtitleTrackController);
- var _subtitleStreamController = __webpack_require__(77);
- var _emeController = __webpack_require__(78);
- var _emeController2 = _interopRequireDefault(_emeController);
- var _mediakeysHelper = __webpack_require__(79);
- 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; } }
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- // import FetchLoader from './utils/fetch-loader';
- var hlsDefaultConfig = exports.hlsDefaultConfig = {
- autoStartLoad: true, // used by stream-controller
- startPosition: -1, // used by stream-controller
- defaultAudioCodec: undefined, // used by stream-controller
- debug: false, // used by logger
- capLevelOnFPSDrop: false, // used by fps-controller
- capLevelToPlayerSize: false, // used by cap-level-controller
- initialLiveManifestSize: 1, // used by stream-controller
- maxBufferLength: 30, // used by stream-controller
- maxBufferSize: 60 * 1000 * 1000, // used by stream-controller
- maxBufferHole: 0.5, // used by stream-controller
- lowBufferWatchdogPeriod: 0.5, // used by stream-controller
- highBufferWatchdogPeriod: 3, // used by stream-controller
- nudgeOffset: 0.1, // used by stream-controller
- nudgeMaxRetry: 3, // used by stream-controller
- maxFragLookUpTolerance: 0.25, // used by stream-controller
- liveSyncDurationCount: 3, // used by stream-controller
- liveMaxLatencyDurationCount: Infinity, // used by stream-controller
- liveSyncDuration: undefined, // used by stream-controller
- liveMaxLatencyDuration: undefined, // used by stream-controller
- liveDurationInfinity: false, // used by buffer-controller
- liveBackBufferLength: Infinity, // used by buffer-controller
- maxMaxBufferLength: 600, // used by stream-controller
- enableWorker: true, // used by demuxer
- enableSoftwareAES: true, // used by decrypter
- manifestLoadingTimeOut: 10000, // used by playlist-loader
- manifestLoadingMaxRetry: 1, // used by playlist-loader
- manifestLoadingRetryDelay: 1000, // used by playlist-loader
- manifestLoadingMaxRetryTimeout: 64000, // used by playlist-loader
- startLevel: undefined, // used by level-controller
- levelLoadingTimeOut: 10000, // used by playlist-loader
- levelLoadingMaxRetry: 4, // used by playlist-loader
- levelLoadingRetryDelay: 1000, // used by playlist-loader
- levelLoadingMaxRetryTimeout: 64000, // used by playlist-loader
- fragLoadingTimeOut: 20000, // used by fragment-loader
- fragLoadingMaxRetry: 6, // used by fragment-loader
- fragLoadingRetryDelay: 1000, // used by fragment-loader
- fragLoadingMaxRetryTimeout: 64000, // used by fragment-loader
- startFragPrefetch: false, // used by stream-controller
- fpsDroppedMonitoringPeriod: 5000, // used by fps-controller
- fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller
- appendErrorMaxRetry: 3, // used by buffer-controller
- loader: _xhrLoader2.default,
- // loader: FetchLoader,
- fLoader: undefined, // used by fragment-loader
- pLoader: undefined, // used by playlist-loader
- xhrSetup: undefined, // used by xhr-loader
- licenseXhrSetup: undefined, // used by eme-controller
- // fetchSetup: undefined,
- abrController: _abrController2.default,
- bufferController: _bufferController2.default,
- capLevelController: _capLevelController2.default,
- fpsController: _fpsController2.default,
- stretchShortVideoTrack: false, // used by mp4-remuxer
- maxAudioFramesDrift: 1, // used by mp4-remuxer
- forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer
- abrEwmaFastLive: 3, // used by abr-controller
- abrEwmaSlowLive: 9, // used by abr-controller
- abrEwmaFastVoD: 3, // used by abr-controller
- abrEwmaSlowVoD: 9, // used by abr-controller
- abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller
- abrBandWidthFactor: 0.95, // used by abr-controller
- abrBandWidthUpFactor: 0.7, // used by abr-controller
- abrMaxWithRealBitrate: false, // used by abr-controller
- maxStarvationDelay: 4, // used by abr-controller
- maxLoadingDelay: 4, // used by abr-controller
- minAutoBitrate: 0, // used by hls
- emeEnabled: false, // used by eme-controller
- widevineLicenseUrl: undefined, // used by eme-controller
- requestMediaKeySystemAccessFunc: _mediakeysHelper.requestMediaKeySystemAccess // used by eme-controller
- }; /**
- * HLS config
- */
- hlsDefaultConfig.subtitleStreamController = _subtitleStreamController.SubtitleStreamController;
- hlsDefaultConfig.subtitleTrackController = _subtitleTrackController2.default;
- hlsDefaultConfig.timelineController = _timelineController2.default;
- hlsDefaultConfig.cueHandler = Cues; // used by timeline-controller
- hlsDefaultConfig.enableCEA708Captions = true; // used by timeline-controller
- hlsDefaultConfig.enableWebVTT = true; // used by timeline-controller
- hlsDefaultConfig.captionsTextTrack1Label = 'English'; // used by timeline-controller
- hlsDefaultConfig.captionsTextTrack1LanguageCode = 'en'; // used by timeline-controller
- hlsDefaultConfig.captionsTextTrack2Label = 'Spanish'; // used by timeline-controller
- hlsDefaultConfig.captionsTextTrack2LanguageCode = 'es'; // used by timeline-controller
- hlsDefaultConfig.audioStreamController = _audioStreamController2.default;
- hlsDefaultConfig.audioTrackController = _audioTrackController2.default;
- hlsDefaultConfig.emeController = _emeController2.default;
- /***/ }),
- /* 61 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _eventHandler = __webpack_require__(3);
- var _eventHandler2 = _interopRequireDefault(_eventHandler);
- var _bufferHelper = __webpack_require__(4);
- var _errors = __webpack_require__(2);
- var _logger = __webpack_require__(0);
- var _ewmaBandwidthEstimator = __webpack_require__(62);
- var _ewmaBandwidthEstimator2 = _interopRequireDefault(_ewmaBandwidthEstimator);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /*
- * simple ABR Controller
- * - compute next level based on last fragment bw heuristics
- * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling
- */
- var _window = window,
- performance = _window.performance;
- var AbrController = function (_EventHandler) {
- _inherits(AbrController, _EventHandler);
- function AbrController(hls) {
- _classCallCheck(this, AbrController);
- 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));
- _this.lastLoadedFragLevel = 0;
- _this._nextAutoLevel = -1;
- _this.hls = hls;
- _this.timer = null;
- _this._bwEstimator = null;
- _this.onCheck = _this._abandonRulesCheck.bind(_this);
- return _this;
- }
- _createClass(AbrController, [{
- key: 'destroy',
- value: function destroy() {
- this.clearTimer();
- _eventHandler2.default.prototype.destroy.call(this);
- }
- }, {
- key: 'onFragLoading',
- value: function onFragLoading(data) {
- var frag = data.frag;
- if (frag.type === 'main') {
- if (!this.timer) {
- this.fragCurrent = frag;
- this.timer = setInterval(this.onCheck, 100);
- }
- // lazy init of BwEstimator, rationale is that we use different params for Live/VoD
- // so we need to wait for stream manifest / playlist type to instantiate it.
- if (!this._bwEstimator) {
- var hls = this.hls;
- var config = hls.config;
- var level = frag.level;
- var isLive = hls.levels[level].details.live;
- var ewmaFast = void 0,
- ewmaSlow = void 0;
- if (isLive) {
- ewmaFast = config.abrEwmaFastLive;
- ewmaSlow = config.abrEwmaSlowLive;
- } else {
- ewmaFast = config.abrEwmaFastVoD;
- ewmaSlow = config.abrEwmaSlowVoD;
- }
- this._bwEstimator = new _ewmaBandwidthEstimator2.default(hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate);
- }
- }
- }
- }, {
- key: '_abandonRulesCheck',
- value: function _abandonRulesCheck() {
- /*
- monitor fragment retrieval time...
- we compute expected time of arrival of the complete fragment.
- we compare it to expected time of buffer starvation
- */
- var hls = this.hls;
- var video = hls.media;
- var frag = this.fragCurrent;
- if (!frag) {
- return;
- }
- var loader = frag.loader;
- var minAutoLevel = hls.minAutoLevel;
- // if loader has been destroyed or loading has been aborted, stop timer and return
- if (!loader || loader.stats && loader.stats.aborted) {
- _logger.logger.warn('frag loader destroy or aborted, disarm abandonRules');
- this.clearTimer();
- // reset forced auto level value so that next level will be selected
- this._nextAutoLevel = -1;
- return;
- }
- var stats = loader.stats;
- /* only monitor frag retrieval time if
- (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) */
- if (video && stats && (!video.paused && video.playbackRate !== 0 || !video.readyState) && frag.autoLevel && frag.level) {
- var requestDelay = performance.now() - stats.trequest,
- playbackRate = Math.abs(video.playbackRate);
- // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate
- if (requestDelay > 500 * frag.duration / playbackRate) {
- var levels = hls.levels,
- loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay),
- // byte/s; at least 1 byte/s to avoid division by zero
- // compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size
- level = levels[frag.level],
- levelBitrate = level.realBitrate ? Math.max(level.realBitrate, level.bitrate) : level.bitrate,
- expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8)),
- pos = video.currentTime,
- fragLoadedDelay = (expectedLen - stats.loaded) / loadRate,
- bufferStarvationDelay = (_bufferHelper.BufferHelper.bufferInfo(video, pos, hls.config.maxBufferHole).end - pos) / playbackRate;
- // consider emergency switch down only if we have less than 2 frag buffered AND
- // time to finish loading current fragment is bigger than buffer starvation delay
- // ie if we risk buffer starvation if bw does not increase quickly
- if (bufferStarvationDelay < 2 * frag.duration / playbackRate && fragLoadedDelay > bufferStarvationDelay) {
- var fragLevelNextLoadedDelay = void 0,
- nextLoadLevel = void 0;
- // lets iterate through lower level and try to find the biggest one that could avoid rebuffering
- // we start from current level - 1 and we step down , until we find a matching level
- for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
- // compute time to load next fragment at lower level
- // 0.8 : consider only 80% of current bw to be conservative
- // 8 = bits per byte (bps/Bps)
- var levelNextBitrate = levels[nextLoadLevel].realBitrate ? Math.max(levels[nextLoadLevel].realBitrate, levels[nextLoadLevel].bitrate) : levels[nextLoadLevel].bitrate;
- fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate);
- if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
- // we found a lower level that be rebuffering free with current estimated bw !
- break;
- }
- }
- // only emergency switch down if it takes less time to load new fragment at lowest level instead
- // of finishing loading current one ...
- if (fragLevelNextLoadedDelay < fragLoadedDelay) {
- _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));
- // force next load level in auto mode
- hls.nextLoadLevel = nextLoadLevel;
- // update bw estimate for this fragment before cancelling load (this will help reducing the bw)
- this._bwEstimator.sample(requestDelay, stats.loaded);
- // abort fragment loading
- loader.abort();
- // stop abandon rules timer
- this.clearTimer();
- hls.trigger(_events2.default.FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag, stats: stats });
- }
- }
- }
- }
- }
- }, {
- key: 'onFragLoaded',
- value: function onFragLoaded(data) {
- var frag = data.frag;
- if (frag.type === 'main' && Number.isFinite(frag.sn)) {
- // stop monitoring bw once frag loaded
- this.clearTimer();
- // store level id after successful fragment load
- this.lastLoadedFragLevel = frag.level;
- // reset forced auto level value so that next level will be selected
- this._nextAutoLevel = -1;
- // compute level average bitrate
- if (this.hls.config.abrMaxWithRealBitrate) {
- var level = this.hls.levels[frag.level];
- var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;
- var loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration;
- level.loaded = { bytes: loadedBytes, duration: loadedDuration };
- level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
- }
- // if fragment has been loaded to perform a bitrate test,
- if (data.frag.bitrateTest) {
- var stats = data.stats;
- stats.tparsed = stats.tbuffered = stats.tload;
- this.onFragBuffered(data);
- }
- }
- }
- }, {
- key: 'onFragBuffered',
- value: function onFragBuffered(data) {
- var stats = data.stats;
- var frag = data.frag;
- // only update stats on first frag buffering
- // if same frag is loaded multiple times, it might be in browser cache, and loaded quickly
- // and leading to wrong bw estimation
- // on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED)
- if (stats.aborted !== true && frag.type === 'main' && Number.isFinite(frag.sn) && (!frag.bitrateTest || stats.tload === stats.tbuffered)) {
- // use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached
- // 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
- // as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation
- var fragLoadingProcessingMs = stats.tparsed - stats.trequest;
- _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)));
- this._bwEstimator.sample(fragLoadingProcessingMs, stats.loaded);
- stats.bwEstimate = this._bwEstimator.getEstimate();
- // if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration
- if (frag.bitrateTest) {
- this.bitrateTestDelay = fragLoadingProcessingMs / 1000;
- } else {
- this.bitrateTestDelay = 0;
- }
- }
- }
- }, {
- key: 'onError',
- value: function onError(data) {
- // stop timer in case of frag loading error
- switch (data.details) {
- case _errors.ErrorDetails.FRAG_LOAD_ERROR:
- case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
- this.clearTimer();
- break;
- default:
- break;
- }
- }
- }, {
- key: 'clearTimer',
- value: function clearTimer() {
- clearInterval(this.timer);
- this.timer = null;
- }
- // return next auto level
- }, {
- key: '_findBestLevel',
- value: function _findBestLevel(currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) {
- for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
- var levelInfo = levels[i];
- if (!levelInfo) {
- continue;
- }
- var levelDetails = levelInfo.details,
- avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration,
- live = levelDetails ? levelDetails.live : false,
- adjustedbw = void 0;
- // follow algorithm captured from stagefright :
- // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
- // Pick the highest bandwidth stream below or equal to estimated bandwidth.
- // consider only 80% of the available bandwidth, but if we are switching up,
- // be even more conservative (70%) to avoid overestimating and immediately
- // switching back.
- if (i <= currentLevel) {
- adjustedbw = bwFactor * currentBw;
- } else {
- adjustedbw = bwUpFactor * currentBw;
- }
- var bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate,
- fetchDuration = bitrate * avgDuration / adjustedbw;
- _logger.logger.trace('level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: ' + i + '/' + Math.round(adjustedbw) + '/' + bitrate + '/' + avgDuration + '/' + maxFetchDuration + '/' + fetchDuration);
- // if adjusted bw is greater than level bitrate AND
- if (adjustedbw > bitrate && (
- // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
- // 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 ...
- // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that _findBestLevel will return -1
- !fetchDuration || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) {
- // as we are looping from highest to lowest, this will return the best achievable quality level
- return i;
- }
- }
- // not enough time budget even with quality level 0 ... rebuffering might happen
- return -1;
- }
- }, {
- key: 'nextAutoLevel',
- get: function get() {
- var forcedAutoLevel = this._nextAutoLevel;
- var bwEstimator = this._bwEstimator;
- // in case next auto level has been forced, and bw not available or not reliable, return forced value
- if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {
- return forcedAutoLevel;
- }
- // compute next level using ABR logic
- var nextABRAutoLevel = this._nextABRAutoLevel;
- // if forced auto level has been defined, use it to cap ABR computed quality level
- if (forcedAutoLevel !== -1) {
- nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);
- }
- return nextABRAutoLevel;
- },
- set: function set(nextLevel) {
- this._nextAutoLevel = nextLevel;
- }
- }, {
- key: '_nextABRAutoLevel',
- get: function get() {
- var hls = this.hls,
- maxAutoLevel = hls.maxAutoLevel,
- levels = hls.levels,
- config = hls.config,
- minAutoLevel = hls.minAutoLevel;
- var video = hls.media,
- currentLevel = this.lastLoadedFragLevel,
- currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0,
- pos = video ? video.currentTime : 0,
- // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as
- // if we're playing back at the normal rate.
- playbackRate = video && video.playbackRate !== 0 ? Math.abs(video.playbackRate) : 1.0,
- avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate,
- // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
- bufferStarvationDelay = (_bufferHelper.BufferHelper.bufferInfo(video, pos, config.maxBufferHole).end - pos) / playbackRate;
- // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
- var bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor, levels);
- if (bestLevel >= 0) {
- return bestLevel;
- } else {
- _logger.logger.trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering');
- // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering
- // if no matching level found, logic will return 0
- var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay,
- bwFactor = config.abrBandWidthFactor,
- bwUpFactor = config.abrBandWidthUpFactor;
- if (bufferStarvationDelay === 0) {
- // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
- var bitrateTestDelay = this.bitrateTestDelay;
- if (bitrateTestDelay) {
- // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
- // max video loading delay used in automatic start level selection :
- // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
- // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
- // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
- var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
- maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
- _logger.logger.trace('bitrate test took ' + Math.round(1000 * bitrateTestDelay) + 'ms, set first fragment max fetchDuration to ' + Math.round(1000 * maxStarvationDelay) + ' ms');
- // don't use conservative factor on bitrate test
- bwFactor = bwUpFactor = 1;
- }
- }
- bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor, levels);
- return Math.max(bestLevel, 0);
- }
- }
- }]);
- return AbrController;
- }(_eventHandler2.default);
- exports.default = AbrController;
- module.exports = exports['default'];
- /***/ }),
- /* 62 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /*
- * EWMA Bandwidth Estimator
- * - heavily inspired from shaka-player
- * Tracks bandwidth samples and estimates available bandwidth.
- * Based on the minimum of two exponentially-weighted moving averages with
- * different half-lives.
- */
- var _ewma = __webpack_require__(63);
- var _ewma2 = _interopRequireDefault(_ewma);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var EwmaBandWidthEstimator = function () {
- function EwmaBandWidthEstimator(hls, slow, fast, defaultEstimate) {
- _classCallCheck(this, EwmaBandWidthEstimator);
- this.hls = hls;
- this.defaultEstimate_ = defaultEstimate;
- this.minWeight_ = 0.001;
- this.minDelayMs_ = 50;
- this.slow_ = new _ewma2.default(slow);
- this.fast_ = new _ewma2.default(fast);
- }
- _createClass(EwmaBandWidthEstimator, [{
- key: 'sample',
- value: function sample(durationMs, numBytes) {
- durationMs = Math.max(durationMs, this.minDelayMs_);
- var bandwidth = 8000 * numBytes / durationMs,
- // console.log('instant bw:'+ Math.round(bandwidth));
- // we weight sample using loading duration....
- weight = durationMs / 1000;
- this.fast_.sample(weight, bandwidth);
- this.slow_.sample(weight, bandwidth);
- }
- }, {
- key: 'canEstimate',
- value: function canEstimate() {
- var fast = this.fast_;
- return fast && fast.getTotalWeight() >= this.minWeight_;
- }
- }, {
- key: 'getEstimate',
- value: function getEstimate() {
- if (this.canEstimate()) {
- // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
- // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
- // Take the minimum of these two estimates. This should have the effect of
- // adapting down quickly, but up more slowly.
- return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
- } else {
- return this.defaultEstimate_;
- }
- }
- }, {
- key: 'destroy',
- value: function destroy() {}
- }]);
- return EwmaBandWidthEstimator;
- }();
- exports.default = EwmaBandWidthEstimator;
- module.exports = exports['default'];
- /***/ }),
- /* 63 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /*
- * compute an Exponential Weighted moving average
- * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
- * - heavily inspired from shaka-player
- */
- var EWMA = function () {
- // About half of the estimated value will be from the last |halfLife| samples by weight.
- function EWMA(halfLife) {
- _classCallCheck(this, EWMA);
- // Larger values of alpha expire historical data more slowly.
- this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
- this.estimate_ = 0;
- this.totalWeight_ = 0;
- }
- _createClass(EWMA, [{
- key: "sample",
- value: function sample(weight, value) {
- var adjAlpha = Math.pow(this.alpha_, weight);
- this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
- this.totalWeight_ += weight;
- }
- }, {
- key: "getTotalWeight",
- value: function getTotalWeight() {
- return this.totalWeight_;
- }
- }, {
- key: "getEstimate",
- value: function getEstimate() {
- if (this.alpha_) {
- var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
- return this.estimate_ / zeroFactor;
- } else {
- return this.estimate_;
- }
- }
- }]);
- return EWMA;
- }();
- exports.default = EWMA;
- module.exports = exports["default"];
- /***/ }),
- /* 64 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _eventHandler = __webpack_require__(3);
- var _eventHandler2 = _interopRequireDefault(_eventHandler);
- var _logger = __webpack_require__(0);
- var _errors = __webpack_require__(2);
- var _mediasourceHelper = __webpack_require__(13);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /*
- * Buffer Controller
- */
- var MediaSource = (0, _mediasourceHelper.getMediaSource)();
- var BufferController = function (_EventHandler) {
- _inherits(BufferController, _EventHandler);
- function BufferController(hls) {
- _classCallCheck(this, BufferController);
- // the value that we have set mediasource.duration to
- // (the actual duration may be tweaked slighly by the browser)
- 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));
- _this._msDuration = null;
- // the value that we want to set mediaSource.duration to
- _this._levelDuration = null;
- // the target duration of the current media playlist
- _this._levelTargetDuration = 10;
- // current stream state: true - for live broadcast, false - for VoD content
- _this._live = null;
- // cache the self generated object url to detect hijack of video tag
- _this._objectUrl = null;
- // The number of BUFFER_CODEC events received before any sourceBuffers are created
- _this.bufferCodecEventsExpected = 0;
- // Source Buffer listeners
- _this.onsbue = _this.onSBUpdateEnd.bind(_this);
- _this.onsbe = _this.onSBUpdateError.bind(_this);
- _this.pendingTracks = {};
- _this.tracks = {};
- return _this;
- }
- _createClass(BufferController, [{
- key: 'destroy',
- value: function destroy() {
- _eventHandler2.default.prototype.destroy.call(this);
- }
- }, {
- key: 'onLevelPtsUpdated',
- value: function onLevelPtsUpdated(data) {
- var type = data.type;
- var audioTrack = this.tracks.audio;
- // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
- // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
- // 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
- // `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend`
- // event if SB is in updating state.
- // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
- if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') {
- // Chrome audio mp3 track
- var audioBuffer = this.sourceBuffer.audio;
- var delta = Math.abs(audioBuffer.timestampOffset - data.start);
- // adjust timestamp offset if time delta is greater than 100ms
- if (delta > 0.1) {
- var updating = audioBuffer.updating;
- try {
- audioBuffer.abort();
- } catch (err) {
- _logger.logger.warn('can not abort audio buffer: ' + err);
- }
- if (!updating) {
- _logger.logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.start);
- audioBuffer.timestampOffset = data.start;
- } else {
- this.audioTimestampOffset = data.start;
- }
- }
- }
- }
- }, {
- key: 'onManifestParsed',
- value: function onManifestParsed(data) {
- // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
- // sourcebuffers will be created all at once when the expected nb of tracks will be reached
- // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
- // it will contain the expected nb of source buffers, no need to compute it
- this.bufferCodecEventsExpected = data.altAudio ? 2 : 1;
- _logger.logger.log(this.bufferCodecEventsExpected + ' bufferCodec event(s) expected');
- }
- }, {
- key: 'onMediaAttaching',
- value: function onMediaAttaching(data) {
- var media = this.media = data.media;
- if (media) {
- // setup the media source
- var ms = this.mediaSource = new MediaSource();
- // Media Source listeners
- this.onmso = this.onMediaSourceOpen.bind(this);
- this.onmse = this.onMediaSourceEnded.bind(this);
- this.onmsc = this.onMediaSourceClose.bind(this);
- ms.addEventListener('sourceopen', this.onmso);
- ms.addEventListener('sourceended', this.onmse);
- ms.addEventListener('sourceclose', this.onmsc);
- // link video and media Source
- media.src = window.URL.createObjectURL(ms);
- // cache the locally generated object url
- this._objectUrl = media.src;
- }
- }
- }, {
- key: 'onMediaDetaching',
- value: function onMediaDetaching() {
- _logger.logger.log('media source detaching');
- var ms = this.mediaSource;
- if (ms) {
- if (ms.readyState === 'open') {
- try {
- // endOfStream could trigger exception if any sourcebuffer is in updating state
- // we don't really care about checking sourcebuffer state here,
- // as we are anyway detaching the MediaSource
- // let's just avoid this exception to propagate
- ms.endOfStream();
- } catch (err) {
- _logger.logger.warn('onMediaDetaching:' + err.message + ' while calling endOfStream');
- }
- }
- ms.removeEventListener('sourceopen', this.onmso);
- ms.removeEventListener('sourceended', this.onmse);
- ms.removeEventListener('sourceclose', this.onmsc);
- // Detach properly the MediaSource from the HTMLMediaElement as
- // suggested in https://github.com/w3c/media-source/issues/53.
- if (this.media) {
- window.URL.revokeObjectURL(this._objectUrl);
- // clean up video tag src only if it's our own url. some external libraries might
- // hijack the video tag and change its 'src' without destroying the Hls instance first
- if (this.media.src === this._objectUrl) {
- this.media.removeAttribute('src');
- this.media.load();
- } else {
- _logger.logger.warn('media.src was changed by a third party - skip cleanup');
- }
- }
- this.mediaSource = null;
- this.media = null;
- this._objectUrl = null;
- this.pendingTracks = {};
- this.tracks = {};
- this.sourceBuffer = {};
- this.flushRange = [];
- this.segments = [];
- this.appended = 0;
- }
- this.onmso = this.onmse = this.onmsc = null;
- this.hls.trigger(_events2.default.MEDIA_DETACHED);
- }
- }, {
- key: 'onMediaSourceOpen',
- value: function onMediaSourceOpen() {
- _logger.logger.log('media source opened');
- this.hls.trigger(_events2.default.MEDIA_ATTACHED, { media: this.media });
- var mediaSource = this.mediaSource;
- if (mediaSource) {
- // once received, don't listen anymore to sourceopen event
- mediaSource.removeEventListener('sourceopen', this.onmso);
- }
- this.checkPendingTracks();
- }
- }, {
- key: 'checkPendingTracks',
- value: function checkPendingTracks() {
- var bufferCodecEventsExpected = this.bufferCodecEventsExpected,
- pendingTracks = this.pendingTracks;
- // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
- // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
- // data has been appended to existing ones.
- // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
- var pendingTracksCount = Object.keys(pendingTracks).length;
- if (pendingTracksCount && !bufferCodecEventsExpected || pendingTracksCount === 2) {
- // ok, let's create them now !
- this.createSourceBuffers(pendingTracks);
- this.pendingTracks = {};
- // append any pending segments now !
- this.doAppending();
- }
- }
- }, {
- key: 'onMediaSourceClose',
- value: function onMediaSourceClose() {
- _logger.logger.log('media source closed');
- }
- }, {
- key: 'onMediaSourceEnded',
- value: function onMediaSourceEnded() {
- _logger.logger.log('media source ended');
- }
- }, {
- key: 'onSBUpdateEnd',
- value: function onSBUpdateEnd() {
- // update timestampOffset
- if (this.audioTimestampOffset) {
- var audioBuffer = this.sourceBuffer.audio;
- _logger.logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + this.audioTimestampOffset);
- audioBuffer.timestampOffset = this.audioTimestampOffset;
- delete this.audioTimestampOffset;
- }
- if (this._needsFlush) {
- this.doFlush();
- }
- if (this._needsEos) {
- this.checkEos();
- }
- this.appending = false;
- var parent = this.parent;
- // count nb of pending segments waiting for appending on this sourcebuffer
- var pending = this.segments.reduce(function (counter, segment) {
- return segment.parent === parent ? counter + 1 : counter;
- }, 0);
- // this.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments
- var timeRanges = {};
- var sourceBuffer = this.sourceBuffer;
- for (var streamType in sourceBuffer) {
- timeRanges[streamType] = sourceBuffer[streamType].buffered;
- }
- // 寻找可播放的起始点。如果没有自动播放,需要手动Seek
- if (this._paused === false && timeRanges["video"] && timeRanges["video"].length > 0 && timeRanges["audio"] && timeRanges["audio"].length > 0) {
- if (timeRanges["video"].end(0) - timeRanges["video"].start(0) > 1 && timeRanges["audio"].end(0) - timeRanges["audio"].start(0) > 1) {
- // Seek to the point that can play;
- var startTime = Math.max(timeRanges["video"].start(0), timeRanges["audio"].start(0));
- this.media.currentTime = startTime;
- this.media.play();
- delete this["_paused"];
- } else {
- // Try to seek more
- var endTime = Math.max(timeRanges["video"].end(0), timeRanges["audio"].end(0));
- this.media.currentTime = endTime;
- this.media.play();
- }
- }
- this.hls.trigger(_events2.default.BUFFER_APPENDED, { parent: parent, pending: pending, timeRanges: timeRanges });
- // don't append in flushing mode
- if (!this._needsFlush) {
- this.doAppending();
- }
- this.updateMediaElementDuration();
- // appending goes first
- if (pending === 0) {
- this.flushLiveBackBuffer();
- }
- }
- }, {
- key: 'onSBUpdateError',
- value: function onSBUpdateError(event) {
- _logger.logger.error('sourceBuffer error:', event);
- // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
- // this error might not always be fatal (it is fatal if decode error is set, in that case
- // it will be followed by a mediaElement error ...)
- this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false });
- // we don't need to do more than that, as accordin to the spec, updateend will be fired just after
- }
- }, {
- key: 'onBufferReset',
- value: function onBufferReset() {
- var sourceBuffer = this.sourceBuffer;
- for (var type in sourceBuffer) {
- var sb = sourceBuffer[type];
- try {
- this.mediaSource.removeSourceBuffer(sb);
- sb.removeEventListener('updateend', this.onsbue);
- sb.removeEventListener('error', this.onsbe);
- } catch (err) {}
- }
- this.sourceBuffer = {};
- this.flushRange = [];
- this.segments = [];
- this.appended = 0;
- }
- }, {
- key: 'onBufferCodecs',
- value: function onBufferCodecs(tracks) {
- var _this2 = this;
- // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
- // if sourcebuffers already created, do nothing ...
- /** 需要放过tracks, 有新的track需要重新加buffer 使得画面到达时,可以播放画面
- if (Object.keys(this.sourceBuffer).length) {
- return;
- }*/
- Object.keys(tracks).forEach(function (trackName) {
- _this2.pendingTracks[trackName] = tracks[trackName];
- });
- var mediaSource = this.mediaSource;
- this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
- if (mediaSource && mediaSource.readyState === 'open') {
- this.checkPendingTracks();
- }
- }
- }, {
- key: 'createSourceBuffers',
- value: function createSourceBuffers(tracks) {
- var sourceBuffer = this.sourceBuffer,
- mediaSource = this.mediaSource;
- for (var trackName in tracks) {
- if (!sourceBuffer[trackName]) {
- var track = tracks[trackName];
- // use levelCodec as first priority
- var codec = track.levelCodec || track.codec;
- var mimeType = track.container + ';codecs=' + codec;
- _logger.logger.log('creating sourceBuffer(' + mimeType + ')');
- try {
- var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
- sb.addEventListener('updateend', this.onsbue);
- sb.addEventListener('error', this.onsbe);
- this.tracks[trackName] = { codec: codec, container: track.container };
- track.buffer = sb;
- } catch (err) {
- if (err.code == 22) {
- _logger.logger.log("Found new track, try to rebuild");
- this._paused = false;
- // setup the media source
- var ms = this.mediaSource = new MediaSource();
- // Media Source listeners
- this.onmso = this.onMediaSourceOpen.bind(this);
- this.onmse = this.onMediaSourceEnded.bind(this);
- this.onmsc = this.onMediaSourceClose.bind(this);
- for (var i = 0; i < Object.keys(this.tracks).length; i++) {
- var _track = this.tracks[Object.keys(this.tracks)[i]];
- this.pendingTracks[Object.keys(this.tracks)[i]] = _track;
- }
- this.tracks = {};
- this.sourceBuffer = {};
- ms.addEventListener('sourceopen', this.onmso);
- ms.addEventListener('sourceended', this.onmse);
- ms.addEventListener('sourceclose', this.onmsc);
- // link video and media Source
- this.media.src = window.URL.createObjectURL(ms);
- // cache the locally generated object url
- this._objectUrl = media.src;
- } else {
- _logger.logger.error('error while trying to add sourceBuffer:' + err.message);
- this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType });
- }
- }
- }
- }
- this.hls.trigger(_events2.default.BUFFER_CREATED, { tracks: tracks });
- }
- }, {
- key: 'onBufferAppending',
- value: function onBufferAppending(data) {
- if (!this._needsFlush) {
- if (!this.segments) {
- this.segments = [data];
- } else {
- this.segments.push(data);
- }
- this.doAppending();
- }
- }
- }, {
- key: 'onBufferAppendFail',
- value: function onBufferAppendFail(data) {
- _logger.logger.error('sourceBuffer error:', data.event);
- // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
- // this error might not always be fatal (it is fatal if decode error is set, in that case
- // it will be followed by a mediaElement error ...)
- this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false });
- }
- // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
- }, {
- key: 'onBufferEos',
- value: function onBufferEos(data) {
- var sb = this.sourceBuffer;
- var dataType = data.type;
- for (var type in sb) {
- if (!dataType || type === dataType) {
- if (!sb[type].ended) {
- sb[type].ended = true;
- _logger.logger.log(type + ' sourceBuffer now EOS');
- }
- }
- }
- this.checkEos();
- }
- // if all source buffers are marked as ended, signal endOfStream() to MediaSource.
- }, {
- key: 'checkEos',
- value: function checkEos() {
- var sb = this.sourceBuffer,
- mediaSource = this.mediaSource;
- if (!mediaSource || mediaSource.readyState !== 'open') {
- this._needsEos = false;
- return;
- }
- for (var type in sb) {
- var sbobj = sb[type];
- if (!sbobj.ended) {
- return;
- }
- if (sbobj.updating) {
- this._needsEos = true;
- return;
- }
- }
- _logger.logger.log('all media data are available, signal endOfStream() to MediaSource and stop loading fragment');
- // Notify the media element that it now has all of the media data
- try {
- mediaSource.endOfStream();
- } catch (e) {
- _logger.logger.warn('exception while calling mediaSource.endOfStream()');
- }
- this._needsEos = false;
- }
- }, {
- key: 'onBufferFlushing',
- value: function onBufferFlushing(data) {
- this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });
- // attempt flush immediately
- this.flushBufferCounter = 0;
- this.doFlush();
- }
- }, {
- key: 'flushLiveBackBuffer',
- value: function flushLiveBackBuffer() {
- // clear back buffer for live only
- if (!this._live) {
- return;
- }
- var liveBackBufferLength = this.hls.config.liveBackBufferLength;
- if (!isFinite(liveBackBufferLength) || liveBackBufferLength < 0) {
- return;
- }
- var currentTime = this.media.currentTime;
- var sourceBuffer = this.sourceBuffer;
- var bufferTypes = Object.keys(sourceBuffer);
- var targetBackBufferPosition = currentTime - Math.max(liveBackBufferLength, this._levelTargetDuration);
- for (var index = bufferTypes.length - 1; index >= 0; index--) {
- var bufferType = bufferTypes[index],
- buffered = sourceBuffer[bufferType].buffered;
- // when target buffer start exceeds actual buffer start
- if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
- // remove buffer up until current time minus minimum back buffer length (removing buffer too close to current
- // time will lead to playback freezing)
- // credits for level target duration - https://github.com/videojs/http-streaming/blob/3132933b6aa99ddefab29c10447624efd6fd6e52/src/segment-loader.js#L91
- this.removeBufferRange(bufferType, sourceBuffer[bufferType], 0, targetBackBufferPosition);
- }
- }
- }
- }, {
- key: 'onLevelUpdated',
- value: function onLevelUpdated(_ref) {
- var details = _ref.details;
- if (details.fragments.length > 0) {
- this._levelDuration = details.totalduration + details.fragments[0].start;
- this._levelTargetDuration = details.averagetargetduration || details.targetduration || 10;
- this._live = details.live;
- this.updateMediaElementDuration();
- }
- }
- /**
- * Update Media Source duration to current level duration or override to Infinity if configuration parameter
- * 'liveDurationInfinity` is set to `true`
- * More details: https://github.com/video-dev/hls.js/issues/355
- */
- }, {
- key: 'updateMediaElementDuration',
- value: function updateMediaElementDuration() {
- var config = this.hls.config;
- var duration = void 0;
- if (this._levelDuration === null || !this.media || !this.mediaSource || !this.sourceBuffer || this.media.readyState === 0 || this.mediaSource.readyState !== 'open') {
- return;
- }
- for (var type in this.sourceBuffer) {
- if (this.sourceBuffer[type].updating === true) {
- // can't set duration whilst a buffer is updating
- return;
- }
- }
- duration = this.media.duration;
- // initialise to the value that the media source is reporting
- if (this._msDuration === null) {
- this._msDuration = this.mediaSource.duration;
- }
- if (this._live === true && config.liveDurationInfinity === true) {
- // Override duration to Infinity
- _logger.logger.log('Media Source duration is set to Infinity');
- this._msDuration = this.mediaSource.duration = Infinity;
- } else if (this._levelDuration > this._msDuration && this._levelDuration > duration || !Number.isFinite(duration)) {
- // levelDuration was the last value we set.
- // not using mediaSource.duration as the browser may tweak this value
- // only update Media Source duration if its value increase, this is to avoid
- // flushing already buffered portion when switching between quality level
- _logger.logger.log('Updating Media Source duration to ' + this._levelDuration.toFixed(3));
- this._msDuration = this.mediaSource.duration = this._levelDuration;
- }
- }
- }, {
- key: 'doFlush',
- value: function doFlush() {
- // loop through all buffer ranges to flush
- while (this.flushRange.length) {
- var range = this.flushRange[0];
- // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer
- if (this.flushBuffer(range.start, range.end, range.type)) {
- // range flushed, remove from flush array
- this.flushRange.shift();
- this.flushBufferCounter = 0;
- } else {
- this._needsFlush = true;
- // avoid looping, wait for SB update end to retrigger a flush
- return;
- }
- }
- if (this.flushRange.length === 0) {
- // everything flushed
- this._needsFlush = false;
- // let's recompute this.appended, which is used to avoid flush looping
- var appended = 0;
- var sourceBuffer = this.sourceBuffer;
- try {
- for (var type in sourceBuffer) {
- appended += sourceBuffer[type].buffered.length;
- }
- } catch (error) {
- // error could be thrown while accessing buffered, in case sourcebuffer has already been removed from MediaSource
- // this is harmess at this stage, catch this to avoid reporting an internal exception
- _logger.logger.error('error while accessing sourceBuffer.buffered');
- }
- this.appended = appended;
- this.hls.trigger(_events2.default.BUFFER_FLUSHED);
- }
- }
- }, {
- key: 'doAppending',
- value: function doAppending() {
- var hls = this.hls,
- segments = this.segments,
- sourceBuffer = this.sourceBuffer;
- if (Object.keys(sourceBuffer).length) {
- if (this.media.error) {
- this.segments = [];
- _logger.logger.error('trying to append although a media error occured, flush segment and abort');
- return;
- }
- if (this.appending) {
- // logger.log(`sb appending in progress`);
- return;
- }
- if (segments && segments.length) {
- var segment = segments.shift();
- try {
- var type = segment.type,
- sb = sourceBuffer[type];
- if (sb) {
- if (!sb.updating) {
- // reset sourceBuffer ended flag before appending segment
- sb.ended = false;
- // logger.log(`appending ${segment.content} ${type} SB, size:${segment.data.length}, ${segment.parent}`);
- this.parent = segment.parent;
- // console.log('append buffer ', segment)
- sb.appendBuffer(segment.data);
- this.appendError = 0;
- this.appended++;
- this.appending = true;
- } else {
- segments.unshift(segment);
- }
- } else {
- // in case we don't have any source buffer matching with this segment type,
- // it means that Mediasource fails to create sourcebuffer
- // discard this segment, and trigger update end
- this.onSBUpdateEnd();
- }
- } catch (err) {
- // in case any error occured while appending, put back segment in segments table
- _logger.logger.error('error while trying to append buffer:' + err.message);
- segments.unshift(segment);
- var event = { type: _errors.ErrorTypes.MEDIA_ERROR, parent: segment.parent };
- if (err.code !== 22) {
- if (this.appendError) {
- this.appendError++;
- } else {
- this.appendError = 1;
- }
- event.details = _errors.ErrorDetails.BUFFER_APPEND_ERROR;
- /* with UHD content, we could get loop of quota exceeded error until
- browser is able to evict some data from sourcebuffer. retrying help recovering this
- */
- if (this.appendError > hls.config.appendErrorMaxRetry) {
- _logger.logger.log('fail ' + hls.config.appendErrorMaxRetry + ' times to append segment in sourceBuffer');
- this.segments = [];
- event.fatal = true;
- hls.trigger(_events2.default.ERROR, event);
- } else {
- event.fatal = false;
- hls.trigger(_events2.default.ERROR, event);
- }
- } else {
- // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
- // let's stop appending any segments, and report BUFFER_FULL_ERROR error
- this.segments = [];
- event.details = _errors.ErrorDetails.BUFFER_FULL_ERROR;
- event.fatal = false;
- hls.trigger(_events2.default.ERROR, event);
- }
- }
- }
- }
- }
- /*
- flush specified buffered range,
- return true once range has been flushed.
- as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end
- */
- }, {
- key: 'flushBuffer',
- value: function flushBuffer(startOffset, endOffset, typeIn) {
- var sb = void 0;
- var sourceBuffer = this.sourceBuffer;
- if (Object.keys(sourceBuffer).length) {
- _logger.logger.log('flushBuffer,pos/start/end: ' + this.media.currentTime.toFixed(3) + '/' + startOffset + '/' + endOffset);
- // safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments
- if (this.flushBufferCounter < this.appended) {
- for (var type in sourceBuffer) {
- // check if sourcebuffer type is defined (typeIn): if yes, let's only flush this one
- // if no, let's flush all sourcebuffers
- if (typeIn && type !== typeIn) {
- continue;
- }
- sb = sourceBuffer[type];
- // we are going to flush buffer, mark source buffer as 'not ended'
- sb.ended = false;
- if (!sb.updating) {
- if (this.removeBufferRange(type, sb, startOffset, endOffset)) {
- this.flushBufferCounter++;
- return false;
- }
- } else {
- _logger.logger.warn('cannot flush, sb updating in progress');
- return false;
- }
- }
- } else {
- _logger.logger.warn('abort flushing too many retries');
- }
- _logger.logger.log('buffer flushed');
- }
- // everything flushed !
- return true;
- }
- /**
- * Removes first buffered range from provided source buffer that lies within given start and end offsets.
- *
- * @param type Type of the source buffer, logging purposes only.
- * @param sb Target SourceBuffer instance.
- * @param startOffset
- * @param endOffset
- *
- * @returns {boolean} True when source buffer remove requested.
- */
- }, {
- key: 'removeBufferRange',
- value: function removeBufferRange(type, sb, startOffset, endOffset) {
- try {
- for (var i = 0; i < sb.buffered.length; i++) {
- var bufStart = sb.buffered.start(i);
- var bufEnd = sb.buffered.end(i);
- var removeStart = Math.max(bufStart, startOffset);
- var removeEnd = Math.min(bufEnd, endOffset);
- /* sometimes sourcebuffer.remove() does not flush
- the exact expected time range.
- to avoid rounding issues/infinite loop,
- only flush buffer range of length greater than 500ms.
- */
- if (Math.min(removeEnd, bufEnd) - removeStart > 0.5) {
- _logger.logger.log('sb remove ' + type + ' [' + removeStart + ',' + removeEnd + '], of [' + bufStart + ',' + bufEnd + '], pos:' + this.media.currentTime);
- sb.remove(removeStart, removeEnd);
- return true;
- }
- }
- } catch (error) {
- _logger.logger.warn('removeBufferRange failed', error);
- }
- return false;
- }
- }]);
- return BufferController;
- }(_eventHandler2.default);
- exports.default = BufferController;
- module.exports = exports['default'];
- /***/ }),
- /* 65 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _eventHandler = __webpack_require__(3);
- var _eventHandler2 = _interopRequireDefault(_eventHandler);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /*
- * cap stream level to media size dimension controller
- */
- var CapLevelController = function (_EventHandler) {
- _inherits(CapLevelController, _EventHandler);
- function CapLevelController(hls) {
- _classCallCheck(this, CapLevelController);
- 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));
- _this.autoLevelCapping = Number.POSITIVE_INFINITY;
- _this.firstLevel = null;
- _this.levels = [];
- _this.media = null;
- _this.restrictedLevels = [];
- _this.timer = null;
- return _this;
- }
- _createClass(CapLevelController, [{
- key: 'destroy',
- value: function destroy() {
- if (this.hls.config.capLevelToPlayerSize) {
- this.media = null;
- this._stopCapping();
- }
- }
- }, {
- key: 'onFpsDropLevelCapping',
- value: function onFpsDropLevelCapping(data) {
- // Don't add a restricted level more than once
- if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {
- this.restrictedLevels.push(data.droppedLevel);
- }
- }
- }, {
- key: 'onMediaAttaching',
- value: function onMediaAttaching(data) {
- this.media = data.media instanceof window.HTMLVideoElement ? data.media : null;
- }
- }, {
- key: 'onManifestParsed',
- value: function onManifestParsed(data) {
- var hls = this.hls;
- this.restrictedLevels = [];
- this.levels = data.levels;
- this.firstLevel = data.firstLevel;
- if (hls.config.capLevelToPlayerSize && data.video) {
- // Start capping immediately if the manifest has signaled video codecs
- this._startCapping();
- }
- }
- // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
- // to the first level
- }, {
- key: 'onBufferCodecs',
- value: function onBufferCodecs(data) {
- var hls = this.hls;
- if (hls.config.capLevelToPlayerSize && data.video) {
- // If the manifest did not signal a video codec capping has been deferred until we're certain video is present
- this._startCapping();
- }
- }
- }, {
- key: 'onLevelsUpdated',
- value: function onLevelsUpdated(data) {
- this.levels = data.levels;
- }
- }, {
- key: 'onMediaDetaching',
- value: function onMediaDetaching() {
- this._stopCapping();
- }
- }, {
- key: 'detectPlayerSize',
- value: function detectPlayerSize() {
- if (this.media) {
- var levelsLength = this.levels ? this.levels.length : 0;
- if (levelsLength) {
- var hls = this.hls;
- hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);
- if (hls.autoLevelCapping > this.autoLevelCapping) {
- // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
- // usually happen when the user go to the fullscreen mode.
- hls.streamController.nextLevelSwitch();
- }
- this.autoLevelCapping = hls.autoLevelCapping;
- }
- }
- }
- /*
- * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
- */
- }, {
- key: 'getMaxLevel',
- value: function getMaxLevel(capLevelIndex) {
- var _this2 = this;
- if (!this.levels) {
- return -1;
- }
- var validLevels = this.levels.filter(function (level, index) {
- return CapLevelController.isLevelAllowed(index, _this2.restrictedLevels) && index <= capLevelIndex;
- });
- return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
- }
- }, {
- key: '_startCapping',
- value: function _startCapping() {
- if (this.timer) {
- // Don't reset capping if started twice; this can happen if the manifest signals a video codec
- return;
- }
- this.autoLevelCapping = Number.POSITIVE_INFINITY;
- this.hls.firstLevel = this.getMaxLevel(this.firstLevel);
- clearInterval(this.timer);
- this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);
- this.detectPlayerSize();
- }
- }, {
- key: '_stopCapping',
- value: function _stopCapping() {
- this.restrictedLevels = [];
- this.firstLevel = null;
- this.autoLevelCapping = Number.POSITIVE_INFINITY;
- if (this.timer) {
- this.timer = clearInterval(this.timer);
- this.timer = null;
- }
- }
- }, {
- key: 'mediaWidth',
- get: function get() {
- var width = void 0;
- var media = this.media;
- if (media) {
- width = media.width || media.clientWidth || media.offsetWidth;
- width *= CapLevelController.contentScaleFactor;
- }
- return width;
- }
- }, {
- key: 'mediaHeight',
- get: function get() {
- var height = void 0;
- var media = this.media;
- if (media) {
- height = media.height || media.clientHeight || media.offsetHeight;
- height *= CapLevelController.contentScaleFactor;
- }
- return height;
- }
- }], [{
- key: 'isLevelAllowed',
- value: function isLevelAllowed(level) {
- var restrictedLevels = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
- return restrictedLevels.indexOf(level) === -1;
- }
- }, {
- key: 'getMaxLevelByMediaSize',
- value: function getMaxLevelByMediaSize(levels, width, height) {
- if (!levels || levels && !levels.length) {
- return -1;
- }
- // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
- // to determine whether we've chosen the greatest bandwidth for the media's dimensions
- var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) {
- if (!nextLevel) {
- return true;
- }
- return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
- };
- // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
- // the max level
- var maxLevelIndex = levels.length - 1;
- for (var i = 0; i < levels.length; i += 1) {
- var level = levels[i];
- if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {
- maxLevelIndex = i;
- break;
- }
- }
- return maxLevelIndex;
- }
- }, {
- key: 'contentScaleFactor',
- get: function get() {
- var pixelRatio = 1;
- try {
- pixelRatio = window.devicePixelRatio;
- } catch (e) {}
- return pixelRatio;
- }
- }]);
- return CapLevelController;
- }(_eventHandler2.default);
- exports.default = CapLevelController;
- module.exports = exports['default'];
- /***/ }),
- /* 66 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _eventHandler = __webpack_require__(3);
- var _eventHandler2 = _interopRequireDefault(_eventHandler);
- var _logger = __webpack_require__(0);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /*
- * FPS Controller
- */
- var _window = window,
- performance = _window.performance;
- var FPSController = function (_EventHandler) {
- _inherits(FPSController, _EventHandler);
- function FPSController(hls) {
- _classCallCheck(this, FPSController);
- return _possibleConstructorReturn(this, (FPSController.__proto__ || Object.getPrototypeOf(FPSController)).call(this, hls, _events2.default.MEDIA_ATTACHING));
- }
- _createClass(FPSController, [{
- key: 'destroy',
- value: function destroy() {
- if (this.timer) {
- clearInterval(this.timer);
- }
- this.isVideoPlaybackQualityAvailable = false;
- }
- }, {
- key: 'onMediaAttaching',
- value: function onMediaAttaching(data) {
- var config = this.hls.config;
- if (config.capLevelOnFPSDrop) {
- var video = this.video = data.media instanceof window.HTMLVideoElement ? data.media : null;
- if (typeof video.getVideoPlaybackQuality === 'function') {
- this.isVideoPlaybackQualityAvailable = true;
- }
- clearInterval(this.timer);
- this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
- }
- }
- }, {
- key: 'checkFPS',
- value: function checkFPS(video, decodedFrames, droppedFrames) {
- var currentTime = performance.now();
- if (decodedFrames) {
- if (this.lastTime) {
- var currentPeriod = currentTime - this.lastTime,
- currentDropped = droppedFrames - this.lastDroppedFrames,
- currentDecoded = decodedFrames - this.lastDecodedFrames,
- droppedFPS = 1000 * currentDropped / currentPeriod,
- hls = this.hls;
- hls.trigger(_events2.default.FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames });
- if (droppedFPS > 0) {
- // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
- if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
- var currentLevel = hls.currentLevel;
- _logger.logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
- if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
- currentLevel = currentLevel - 1;
- hls.trigger(_events2.default.FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: hls.currentLevel });
- hls.autoLevelCapping = currentLevel;
- hls.streamController.nextLevelSwitch();
- }
- }
- }
- }
- this.lastTime = currentTime;
- this.lastDroppedFrames = droppedFrames;
- this.lastDecodedFrames = decodedFrames;
- }
- }
- }, {
- key: 'checkFPSInterval',
- value: function checkFPSInterval() {
- var video = this.video;
- if (video) {
- if (this.isVideoPlaybackQualityAvailable) {
- var videoPlaybackQuality = video.getVideoPlaybackQuality();
- this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
- } else {
- this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
- }
- }
- }
- }]);
- return FPSController;
- }(_eventHandler2.default);
- exports.default = FPSController;
- module.exports = exports['default'];
- /***/ }),
- /* 67 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /**
- * XHR based logger
- */
- var _logger = __webpack_require__(0);
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var _window = window,
- performance = _window.performance,
- XMLHttpRequest = _window.XMLHttpRequest;
- var XhrLoader = function () {
- function XhrLoader(config) {
- _classCallCheck(this, XhrLoader);
- if (config && config.xhrSetup) {
- this.xhrSetup = config.xhrSetup;
- }
- }
- _createClass(XhrLoader, [{
- key: 'destroy',
- value: function destroy() {
- this.abort();
- this.loader = null;
- }
- }, {
- key: 'abort',
- value: function abort() {
- var loader = this.loader;
- if (loader && loader.readyState !== 4) {
- this.stats.aborted = true;
- loader.abort();
- }
- window.clearTimeout(this.requestTimeout);
- this.requestTimeout = null;
- window.clearTimeout(this.retryTimeout);
- this.retryTimeout = null;
- }
- }, {
- key: 'load',
- value: function load(context, config, callbacks) {
- this.context = context;
- this.config = config;
- this.callbacks = callbacks;
- this.stats = { trequest: performance.now(), retry: 0 };
- this.retryDelay = config.retryDelay;
- this.loadInternal();
- }
- }, {
- key: 'loadInternal',
- value: function loadInternal() {
- var xhr = void 0,
- context = this.context;
- xhr = this.loader = new XMLHttpRequest();
- var stats = this.stats;
- stats.tfirst = 0;
- stats.loaded = 0;
- var xhrSetup = this.xhrSetup;
- try {
- if (xhrSetup) {
- try {
- xhrSetup(xhr, context.url);
- } catch (e) {
- // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");}
- // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN
- xhr.open('GET', context.url, true);
- xhrSetup(xhr, context.url);
- }
- }
- if (!xhr.readyState) {
- xhr.open('GET', context.url, true);
- }
- } catch (e) {
- // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
- this.callbacks.onError({ code: xhr.status, text: e.message }, context, xhr);
- return;
- }
- if (context.rangeEnd) {
- xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
- }
- xhr.onreadystatechange = this.readystatechange.bind(this);
- xhr.onprogress = this.loadprogress.bind(this);
- xhr.responseType = context.responseType;
- // setup timeout before we perform request
- this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout);
- xhr.send();
- }
- }, {
- key: 'readystatechange',
- value: function readystatechange(event) {
- var xhr = event.currentTarget,
- readyState = xhr.readyState,
- stats = this.stats,
- context = this.context,
- config = this.config;
- // don't proceed if xhr has been aborted
- if (stats.aborted) {
- return;
- }
- // >= HEADERS_RECEIVED
- if (readyState >= 2) {
- // clear xhr timeout and rearm it if readyState less than 4
- window.clearTimeout(this.requestTimeout);
- if (stats.tfirst === 0) {
- stats.tfirst = Math.max(performance.now(), stats.trequest);
- }
- if (readyState === 4) {
- var status = xhr.status;
- // http status between 200 to 299 are all successful
- if (status >= 200 && status < 300) {
- stats.tload = Math.max(stats.tfirst, performance.now());
- var data = void 0,
- len = void 0;
- if (context.responseType === 'arraybuffer') {
- data = xhr.response;
- len = data.byteLength;
- } else {
- data = xhr.responseText;
- len = data.length;
- }
- stats.loaded = stats.total = len;
- var response = { url: xhr.responseURL, data: data };
- this.callbacks.onSuccess(response, stats, context, xhr);
- } else {
- // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
- if (stats.retry >= config.maxRetry || status >= 400 && status < 499) {
- _logger.logger.error(status + ' while loading ' + context.url);
- this.callbacks.onError({ code: status, text: xhr.statusText }, context, xhr);
- } else {
- // retry
- _logger.logger.warn(status + ' while loading ' + context.url + ', retrying in ' + this.retryDelay + '...');
- // aborts and resets internal state
- this.destroy();
- // schedule retry
- this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay);
- // set exponential backoff
- this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);
- stats.retry++;
- }
- }
- } else {
- // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
- this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout);
- }
- }
- }
- }, {
- key: 'loadtimeout',
- value: function loadtimeout() {
- _logger.logger.warn('timeout while loading ' + this.context.url);
- this.callbacks.onTimeout(this.stats, this.context, null);
- }
- }, {
- key: 'loadprogress',
- value: function loadprogress(event) {
- var xhr = event.currentTarget,
- stats = this.stats;
- stats.loaded = event.loaded;
- if (event.lengthComputable) {
- stats.total = event.total;
- }
- var onProgress = this.callbacks.onProgress;
- if (onProgress) {
- // third arg is to provide on progress data
- onProgress(stats, this.context, null, xhr);
- }
- }
- }]);
- return XhrLoader;
- }();
- exports.default = XhrLoader;
- module.exports = exports['default'];
- /***/ }),
- /* 68 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _taskLoop = __webpack_require__(28);
- var _taskLoop2 = _interopRequireDefault(_taskLoop);
- var _logger = __webpack_require__(0);
- var _errors = __webpack_require__(2);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; }
- /**
- * @class AudioTrackController
- * @implements {EventHandler}
- *
- * Handles main manifest and audio-track metadata loaded,
- * owns and exposes the selectable audio-tracks data-models.
- *
- * Exposes internal interface to select available audio-tracks.
- *
- * Handles errors on loading audio-track playlists. Manages fallback mechanism
- * with redundants tracks (group-IDs).
- *
- * Handles level-loading and group-ID switches for video (fallback on video levels),
- * and eventually adapts the audio-track group-ID to match.
- *
- * @fires AUDIO_TRACK_LOADING
- * @fires AUDIO_TRACK_SWITCHING
- * @fires AUDIO_TRACKS_UPDATED
- * @fires ERROR
- *
- */
- var AudioTrackController = function (_TaskLoop) {
- _inherits(AudioTrackController, _TaskLoop);
- function AudioTrackController(hls) {
- _classCallCheck(this, AudioTrackController);
- /**
- * @private
- * Currently selected index in `tracks`
- * @member {number} trackId
- */
- 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));
- _this._trackId = -1;
- /**
- * @private
- * If should select tracks according to default track attribute
- * @member {boolean} _selectDefaultTrack
- */
- _this._selectDefaultTrack = true;
- /**
- * @public
- * All tracks available
- * @member {AudioTrack[]}
- */
- _this.tracks = [];
- /**
- * @public
- * List of blacklisted audio track IDs (that have caused failure)
- * @member {number[]}
- */
- _this.trackIdBlacklist = Object.create(null);
- /**
- * @public
- * The currently running group ID for audio
- * (we grab this on manifest-parsed and new level-loaded)
- * @member {string}
- */
- _this.audioGroupId = null;
- return _this;
- }
- /**
- * Reset audio tracks on new manifest loading.
- */
- _createClass(AudioTrackController, [{
- key: 'onManifestLoading',
- value: function onManifestLoading() {
- this.tracks = [];
- this._trackId = -1;
- this._selectDefaultTrack = true;
- }
- /**
- * Store tracks data from manifest parsed data.
- *
- * Trigger AUDIO_TRACKS_UPDATED event.
- *
- * @param {*} data
- */
- }, {
- key: 'onManifestParsed',
- value: function onManifestParsed(data) {
- var tracks = this.tracks = data.audioTracks || [];
- this.hls.trigger(_events2.default.AUDIO_TRACKS_UPDATED, { audioTracks: tracks });
- }
- /**
- * Store track details of loaded track in our data-model.
- *
- * Set-up metadata update interval task for live-mode streams.
- *
- * @param {} data
- */
- }, {
- key: 'onAudioTrackLoaded',
- value: function onAudioTrackLoaded(data) {
- if (data.id >= this.tracks.length) {
- _logger.logger.warn('Invalid audio track id:', data.id);
- return;
- }
- _logger.logger.log('audioTrack ' + data.id + ' loaded');
- this.tracks[data.id].details = data.details;
- // check if current playlist is a live playlist
- // and if we have already our reload interval setup
- if (data.details.live && !this.hasInterval()) {
- // if live playlist we will have to reload it periodically
- // set reload period to playlist target duration
- var updatePeriodMs = data.details.targetduration * 1000;
- this.setInterval(updatePeriodMs);
- }
- if (!data.details.live && this.hasInterval()) {
- // playlist is not live and timer is scheduled: cancel it
- this.clearInterval();
- }
- }
- /**
- * Update the internal group ID to any audio-track we may have set manually
- * or because of a failure-handling fallback.
- *
- * Quality-levels should update to that group ID in this case.
- *
- * @param {*} data
- */
- }, {
- key: 'onAudioTrackSwitched',
- value: function onAudioTrackSwitched(data) {
- var audioGroupId = this.tracks[data.id].groupId;
- if (audioGroupId && this.audioGroupId !== audioGroupId) {
- this.audioGroupId = audioGroupId;
- }
- }
- /**
- * When a level gets loaded, if it has redundant audioGroupIds (in the same ordinality as it's redundant URLs)
- * we are setting our audio-group ID internally to the one set, if it is different from the group ID currently set.
- *
- * If group-ID got update, we re-select the appropriate audio-track with this group-ID matching the currently
- * selected one (based on NAME property).
- *
- * @param {*} data
- */
- }, {
- key: 'onLevelLoaded',
- value: function onLevelLoaded(data) {
- // FIXME: crashes because currentLevel is undefined
- // const levelInfo = this.hls.levels[this.hls.currentLevel];
- var levelInfo = this.hls.levels[data.level];
- if (!levelInfo.audioGroupIds) {
- return;
- }
- var audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];
- if (this.audioGroupId !== audioGroupId) {
- this.audioGroupId = audioGroupId;
- this._selectInitialAudioTrack();
- }
- }
- /**
- * Handle network errors loading audio track manifests
- * and also pausing on any netwok errors.
- *
- * @param {ErrorEventData} data
- */
- }, {
- key: 'onError',
- value: function onError(data) {
- // Only handle network errors
- if (data.type !== _errors.ErrorTypes.NETWORK_ERROR) {
- return;
- }
- // If fatal network error, cancel update task
- if (data.fatal) {
- this.clearInterval();
- }
- // If not an audio-track loading error don't handle further
- if (data.details !== _errors.ErrorDetails.AUDIO_TRACK_LOAD_ERROR) {
- return;
- }
- _logger.logger.warn('Network failure on audio-track id:', data.context.id);
- this._handleLoadError();
- }
- /**
- * @type {AudioTrack[]} Audio-track list we own
- */
- }, {
- key: '_setAudioTrack',
- /**
- * @private
- * @param {number} newId
- */
- value: function _setAudioTrack(newId) {
- // noop on same audio track id as already set
- if (this._trackId === newId && this.tracks[this._trackId].details) {
- _logger.logger.debug('Same id as current audio-track passed, and track details available -> no-op');
- return;
- }
- // check if level idx is valid
- if (newId < 0 || newId >= this.tracks.length) {
- _logger.logger.warn('Invalid id passed to audio-track controller');
- return;
- }
- var audioTrack = this.tracks[newId];
- _logger.logger.log('Now switching to audio-track index ' + newId);
- // stopping live reloading timer if any
- this.clearInterval();
- this._trackId = newId;
- var url = audioTrack.url,
- type = audioTrack.type,
- id = audioTrack.id;
- this.hls.trigger(_events2.default.AUDIO_TRACK_SWITCHING, { id: id, type: type, url: url });
- this._loadTrackDetailsIfNeeded(audioTrack);
- }
- /**
- * @override
- */
- }, {
- key: 'doTick',
- value: function doTick() {
- this._updateTrack(this._trackId);
- }
- /**
- * Select initial track
- * @private
- */
- }, {
- key: '_selectInitialAudioTrack',
- value: function _selectInitialAudioTrack() {
- var _this2 = this;
- var tracks = this.tracks;
- if (!tracks.length) {
- return;
- }
- var currentAudioTrack = this.tracks[this._trackId];
- var name = null;
- if (currentAudioTrack) {
- name = currentAudioTrack.name;
- }
- // Pre-select default tracks if there are any
- if (this._selectDefaultTrack) {
- var defaultTracks = tracks.filter(function (track) {
- return track.default;
- });
- if (defaultTracks.length) {
- tracks = defaultTracks;
- } else {
- _logger.logger.warn('No default audio tracks defined');
- }
- }
- var trackFound = false;
- var traverseTracks = function traverseTracks() {
- // Select track with right group ID
- tracks.forEach(function (track) {
- if (trackFound) {
- return;
- }
- // We need to match the (pre-)selected group ID
- // and the NAME of the current track.
- if ((!_this2.audioGroupId || track.groupId === _this2.audioGroupId) && (!name || name === track.name)) {
- // If there was a previous track try to stay with the same `NAME`.
- // It should be unique across tracks of same group, and consistent through redundant track groups.
- _this2._setAudioTrack(track.id);
- trackFound = true;
- }
- });
- };
- traverseTracks();
- if (!trackFound) {
- name = null;
- traverseTracks();
- }
- if (!trackFound) {
- _logger.logger.error('No track found for running audio group-ID: ' + this.audioGroupId);
- this.hls.trigger(_events2.default.ERROR, {
- type: _errors.ErrorTypes.MEDIA_ERROR,
- details: _errors.ErrorDetails.AUDIO_TRACK_LOAD_ERROR,
- fatal: true
- });
- }
- }
- /**
- * @private
- * @param {AudioTrack} audioTrack
- * @returns {boolean}
- */
- }, {
- key: '_needsTrackLoading',
- value: function _needsTrackLoading(audioTrack) {
- var details = audioTrack.details,
- url = audioTrack.url;
- if (!details || details.live) {
- // check if we face an audio track embedded in main playlist (audio track without URI attribute)
- return !!url;
- }
- return false;
- }
- /**
- * @private
- * @param {AudioTrack} audioTrack
- */
- }, {
- key: '_loadTrackDetailsIfNeeded',
- value: function _loadTrackDetailsIfNeeded(audioTrack) {
- if (this._needsTrackLoading(audioTrack)) {
- var url = audioTrack.url,
- id = audioTrack.id;
- // track not retrieved yet, or live playlist we need to (re)load it
- _logger.logger.log('loading audio-track playlist for id: ' + id);
- this.hls.trigger(_events2.default.AUDIO_TRACK_LOADING, { url: url, id: id });
- }
- }
- /**
- * @private
- * @param {number} newId
- */
- }, {
- key: '_updateTrack',
- value: function _updateTrack(newId) {
- // check if level idx is valid
- if (newId < 0 || newId >= this.tracks.length) {
- return;
- }
- // stopping live reloading timer if any
- this.clearInterval();
- this._trackId = newId;
- _logger.logger.log('trying to update audio-track ' + newId);
- var audioTrack = this.tracks[newId];
- this._loadTrackDetailsIfNeeded(audioTrack);
- }
- /**
- * @private
- */
- }, {
- key: '_handleLoadError',
- value: function _handleLoadError() {
- // First, let's black list current track id
- this.trackIdBlacklist[this._trackId] = true;
- // Let's try to fall back on a functional audio-track with the same group ID
- var previousId = this._trackId;
- var _tracks$previousId = this.tracks[previousId],
- name = _tracks$previousId.name,
- language = _tracks$previousId.language,
- groupId = _tracks$previousId.groupId;
- _logger.logger.warn('Loading failed on audio track id: ' + previousId + ', group-id: ' + groupId + ', name/language: "' + name + '" / "' + language + '"');
- // Find a non-blacklisted track ID with the same NAME
- // At least a track that is not blacklisted, thus on another group-ID.
- var newId = previousId;
- for (var i = 0; i < this.tracks.length; i++) {
- if (this.trackIdBlacklist[i]) {
- continue;
- }
- var newTrack = this.tracks[i];
- if (newTrack.name === name) {
- newId = i;
- break;
- }
- }
- if (newId === previousId) {
- _logger.logger.warn('No fallback audio-track found for name/language: "' + name + '" / "' + language + '"');
- return;
- }
- _logger.logger.log('Attempting audio-track fallback id:', newId, 'group-id:', this.tracks[newId].groupId);
- this._setAudioTrack(newId);
- }
- }, {
- key: 'audioTracks',
- get: function get() {
- return this.tracks;
- }
- /**
- * @type {number} Index into audio-tracks list of currently selected track.
- */
- }, {
- key: 'audioTrack',
- get: function get() {
- return this._trackId;
- }
- /**
- * Select current track by index
- */
- ,
- set: function set(newId) {
- this._setAudioTrack(newId);
- // If audio track is selected from API then don't choose from the manifest default track
- this._selectDefaultTrack = false;
- }
- }]);
- return AudioTrackController;
- }(_taskLoop2.default);
- exports.default = AudioTrackController;
- module.exports = exports['default'];
- /***/ }),
- /* 69 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _binarySearch = __webpack_require__(9);
- var _binarySearch2 = _interopRequireDefault(_binarySearch);
- var _bufferHelper = __webpack_require__(4);
- var _demuxer = __webpack_require__(19);
- var _demuxer2 = _interopRequireDefault(_demuxer);
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _levelHelper = __webpack_require__(7);
- var LevelHelper = _interopRequireWildcard(_levelHelper);
- var _timeRanges = __webpack_require__(25);
- var _timeRanges2 = _interopRequireDefault(_timeRanges);
- var _errors = __webpack_require__(2);
- var _logger = __webpack_require__(0);
- var _discontinuities = __webpack_require__(26);
- var _fragmentTracker = __webpack_require__(6);
- var _fragment = __webpack_require__(11);
- var _fragment2 = _interopRequireDefault(_fragment);
- var _baseStreamController = __webpack_require__(14);
- var _baseStreamController2 = _interopRequireDefault(_baseStreamController);
- 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; } }
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /*
- * Audio Stream Controller
- */
- var _window = window,
- performance = _window.performance;
- var TICK_INTERVAL = 100; // how often to tick in ms
- var AudioStreamController = function (_BaseStreamController) {
- _inherits(AudioStreamController, _BaseStreamController);
- function AudioStreamController(hls, fragmentTracker) {
- _classCallCheck(this, AudioStreamController);
- 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));
- _this.fragmentTracker = fragmentTracker;
- _this.config = hls.config;
- _this.audioCodecSwap = false;
- _this._state = _baseStreamController.State.STOPPED;
- _this.initPTS = [];
- _this.waitingFragment = null;
- _this.videoTrackCC = null;
- return _this;
- }
- // Signal that video PTS was found
- _createClass(AudioStreamController, [{
- key: 'onInitPtsFound',
- value: function onInitPtsFound(data) {
- var demuxerId = data.id,
- cc = data.frag.cc,
- initPTS = data.initPTS;
- if (demuxerId === 'main') {
- // Always update the new INIT PTS
- // Can change due level switch
- this.initPTS[cc] = initPTS;
- this.videoTrackCC = cc;
- _logger.logger.log('InitPTS for cc: ' + cc + ' found from video track: ' + initPTS);
- // If we are waiting we need to demux/remux the waiting frag
- // With the new initPTS
- if (this.state === _baseStreamController.State.WAITING_INIT_PTS) {
- this.tick();
- }
- }
- }
- }, {
- key: 'startLoad',
- value: function startLoad(startPosition) {
- if (this.tracks) {
- var lastCurrentTime = this.lastCurrentTime;
- this.stopLoad();
- this.setInterval(TICK_INTERVAL);
- this.fragLoadError = 0;
- if (lastCurrentTime > 0 && startPosition === -1) {
- _logger.logger.log('audio:override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3));
- this.state = _baseStreamController.State.IDLE;
- } else {
- this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition;
- this.state = _baseStreamController.State.STARTING;
- }
- this.nextLoadPosition = this.startPosition = this.lastCurrentTime;
- this.tick();
- } else {
- this.startPosition = startPosition;
- this.state = _baseStreamController.State.STOPPED;
- }
- }
- }, {
- key: 'doTick',
- value: function doTick() {
- var pos = void 0,
- track = void 0,
- trackDetails = void 0,
- hls = this.hls,
- config = hls.config;
- // logger.log('audioStream:' + this.state);
- switch (this.state) {
- case _baseStreamController.State.ERROR:
- // don't do anything in error state to avoid breaking further ...
- case _baseStreamController.State.PAUSED:
- // don't do anything in paused state either ...
- case _baseStreamController.State.BUFFER_FLUSHING:
- break;
- case _baseStreamController.State.STARTING:
- this.state = _baseStreamController.State.WAITING_TRACK;
- this.loadedmetadata = false;
- break;
- case _baseStreamController.State.IDLE:
- var tracks = this.tracks;
- // audio tracks not received => exit loop
- if (!tracks) {
- break;
- }
- // if video not attached AND
- // start fragment already requested OR start frag prefetch disable
- // exit loop
- // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
- if (!this.media && (this.startFragRequested || !config.startFragPrefetch)) {
- break;
- }
- // determine next candidate fragment to be loaded, based on current position and
- // end of buffer position
- // if we have not yet loaded any fragment, start loading from start position
- if (this.loadedmetadata) {
- pos = this.media.currentTime;
- } else {
- pos = this.nextLoadPosition;
- if (pos === undefined) {
- break;
- }
- }
- var media = this.mediaBuffer ? this.mediaBuffer : this.media,
- videoBuffer = this.videoBuffer ? this.videoBuffer : this.media,
- bufferInfo = _bufferHelper.BufferHelper.bufferInfo(media, pos, config.maxBufferHole),
- mainBufferInfo = _bufferHelper.BufferHelper.bufferInfo(videoBuffer, pos, config.maxBufferHole),
- bufferLen = bufferInfo.len,
- bufferEnd = bufferInfo.end,
- fragPrevious = this.fragPrevious,
- // ensure we buffer at least config.maxBufferLength (default 30s) or config.maxMaxBufferLength (default: 600s)
- // whichever is smaller.
- // once we reach that threshold, don't buffer more than video (mainBufferInfo.len)
- maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength),
- maxBufLen = Math.max(maxConfigBuffer, mainBufferInfo.len),
- audioSwitch = this.audioSwitch,
- trackId = this.trackId;
- // if buffer length is less than maxBufLen try to load a new fragment
- if ((bufferLen < maxBufLen || audioSwitch) && trackId < tracks.length) {
- trackDetails = tracks[trackId].details;
- // if track info not retrieved yet, switch state and wait for track retrieval
- if (typeof trackDetails === 'undefined') {
- this.state = _baseStreamController.State.WAITING_TRACK;
- break;
- }
- if (!audioSwitch && this._streamEnded(bufferInfo, trackDetails)) {
- this.hls.trigger(_events2.default.BUFFER_EOS, { type: 'audio' });
- this.state = _baseStreamController.State.ENDED;
- return;
- }
- // find fragment index, contiguous with end of buffer position
- var fragments = trackDetails.fragments,
- fragLen = fragments.length,
- start = fragments[0].start,
- end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
- frag = void 0;
- // When switching audio track, reload audio as close as possible to currentTime
- if (audioSwitch) {
- if (trackDetails.live && !trackDetails.PTSKnown) {
- _logger.logger.log('switching audiotrack, live stream, unknown PTS,load first fragment');
- bufferEnd = 0;
- } else {
- bufferEnd = pos;
- // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime
- if (trackDetails.PTSKnown && pos < start) {
- // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start
- if (bufferInfo.end > start || bufferInfo.nextStart) {
- _logger.logger.log('alt audio track ahead of main track, seek to start of alt audio track');
- this.media.currentTime = start + 0.05;
- } else {
- return;
- }
- }
- }
- }
- if (trackDetails.initSegment && !trackDetails.initSegment.data) {
- frag = trackDetails.initSegment;
- } // eslint-disable-line brace-style
- // if bufferEnd before start of playlist, load first fragment
- else if (bufferEnd <= start) {
- frag = fragments[0];
- if (this.videoTrackCC !== null && frag.cc !== this.videoTrackCC) {
- // Ensure we find a fragment which matches the continuity of the video track
- frag = (0, _discontinuities.findFragWithCC)(fragments, this.videoTrackCC);
- }
- if (trackDetails.live && frag.loadIdx && frag.loadIdx === this.fragLoadIdx) {
- // we just loaded this first fragment, and we are still lagging behind the start of the live playlist
- // let's force seek to start
- var nextBuffered = bufferInfo.nextStart ? bufferInfo.nextStart : start;
- _logger.logger.log('no alt audio available @currentTime:' + this.media.currentTime + ', seeking @' + (nextBuffered + 0.05));
- this.media.currentTime = nextBuffered + 0.05;
- return;
- }
- } else {
- var foundFrag = void 0;
- var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
- var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;
- var fragmentWithinToleranceTest = function fragmentWithinToleranceTest(candidate) {
- // offset should be within fragment boundary - config.maxFragLookUpTolerance
- // this is to cope with situations like
- // bufferEnd = 9.991
- // frag[Ø] : [0,10]
- // frag[1] : [10,20]
- // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
- // frag start frag start+duration
- // |-----------------------------|
- // <---> <--->
- // ...--------><-----------------------------><---------....
- // previous frag matching fragment next frag
- // return -1 return 0 return 1
- // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
- // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
- var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration);
- if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
- return 1;
- } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
- // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
- return -1;
- }
- return 0;
- };
- if (bufferEnd < end) {
- if (bufferEnd > end - maxFragLookUpTolerance) {
- maxFragLookUpTolerance = 0;
- }
- // Prefer the next fragment if it's within tolerance
- if (fragNext && !fragmentWithinToleranceTest(fragNext)) {
- foundFrag = fragNext;
- } else {
- foundFrag = _binarySearch2.default.search(fragments, fragmentWithinToleranceTest);
- }
- } else {
- // reach end of playlist
- foundFrag = fragments[fragLen - 1];
- }
- if (foundFrag) {
- frag = foundFrag;
- start = foundFrag.start;
- // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
- if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) {
- if (frag.sn < trackDetails.endSN) {
- frag = fragments[frag.sn + 1 - trackDetails.startSN];
- _logger.logger.log('SN just loaded, load next one: ' + frag.sn);
- } else {
- frag = null;
- }
- }
- }
- }
- if (frag) {
- // logger.log(' loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));
- if (frag.encrypted) {
- _logger.logger.log('Loading key for ' + frag.sn + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId);
- this.state = _baseStreamController.State.KEY_LOADING;
- hls.trigger(_events2.default.KEY_LOADING, { frag: frag });
- } else {
- _logger.logger.log('Loading ' + frag.sn + ', cc: ' + frag.cc + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId + ', currentTime:' + pos + ',bufferEnd:' + bufferEnd.toFixed(3));
- // only load if fragment is not loaded or if in audio switch
- // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch
- this.fragCurrent = frag;
- if (audioSwitch || this.fragmentTracker.getState(frag) === _fragmentTracker.FragmentState.NOT_LOADED) {
- this.startFragRequested = true;
- if (Number.isFinite(frag.sn)) {
- this.nextLoadPosition = frag.start + frag.duration;
- }
- hls.trigger(_events2.default.FRAG_LOADING, { frag: frag });
- this.state = _baseStreamController.State.FRAG_LOADING;
- }
- }
- }
- }
- break;
- case _baseStreamController.State.WAITING_TRACK:
- track = this.tracks[this.trackId];
- // check if playlist is already loaded
- if (track && track.details) {
- this.state = _baseStreamController.State.IDLE;
- }
- break;
- case _baseStreamController.State.FRAG_LOADING_WAITING_RETRY:
- var now = performance.now();
- var retryDate = this.retryDate;
- media = this.media;
- var isSeeking = media && media.seeking;
- // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
- if (!retryDate || now >= retryDate || isSeeking) {
- _logger.logger.log('audioStreamController: retryDate reached, switch back to IDLE state');
- this.state = _baseStreamController.State.IDLE;
- }
- break;
- case _baseStreamController.State.WAITING_INIT_PTS:
- var videoTrackCC = this.videoTrackCC;
- if (this.initPTS[videoTrackCC] === undefined) {
- break;
- }
- // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS
- var waitingFrag = this.waitingFragment;
- if (waitingFrag) {
- var waitingFragCC = waitingFrag.frag.cc;
- if (videoTrackCC !== waitingFragCC) {
- track = this.tracks[this.trackId];
- if (track.details && track.details.live) {
- _logger.logger.warn('Waiting fragment CC (' + waitingFragCC + ') does not match video track CC (' + videoTrackCC + ')');
- this.waitingFragment = null;
- this.state = _baseStreamController.State.IDLE;
- }
- } else {
- this.state = _baseStreamController.State.FRAG_LOADING;
- this.onFragLoaded(this.waitingFragment);
- this.waitingFragment = null;
- }
- } else {
- this.state = _baseStreamController.State.IDLE;
- }
- break;
- case _baseStreamController.State.STOPPED:
- case _baseStreamController.State.FRAG_LOADING:
- case _baseStreamController.State.PARSING:
- case _baseStreamController.State.PARSED:
- case _baseStreamController.State.ENDED:
- break;
- default:
- break;
- }
- }
- }, {
- key: 'onMediaAttached',
- value: function onMediaAttached(data) {
- var media = this.media = this.mediaBuffer = data.media;
- this.onvseeking = this.onMediaSeeking.bind(this);
- this.onvended = this.onMediaEnded.bind(this);
- media.addEventListener('seeking', this.onvseeking);
- media.addEventListener('ended', this.onvended);
- var config = this.config;
- if (this.tracks && config.autoStartLoad) {
- this.startLoad(config.startPosition);
- }
- }
- }, {
- key: 'onMediaDetaching',
- value: function onMediaDetaching() {
- var media = this.media;
- if (media && media.ended) {
- _logger.logger.log('MSE detaching and video ended, reset startPosition');
- this.startPosition = this.lastCurrentTime = 0;
- }
- // remove video listeners
- if (media) {
- media.removeEventListener('seeking', this.onvseeking);
- media.removeEventListener('ended', this.onvended);
- this.onvseeking = this.onvseeked = this.onvended = null;
- }
- this.media = this.mediaBuffer = this.videoBuffer = null;
- this.loadedmetadata = false;
- this.stopLoad();
- }
- }, {
- key: 'onAudioTracksUpdated',
- value: function onAudioTracksUpdated(data) {
- _logger.logger.log('audio tracks updated');
- this.tracks = data.audioTracks;
- }
- }, {
- key: 'onAudioTrackSwitching',
- value: function onAudioTrackSwitching(data) {
- // if any URL found on new audio track, it is an alternate audio track
- var altAudio = !!data.url;
- this.trackId = data.id;
- this.fragCurrent = null;
- this.state = _baseStreamController.State.PAUSED;
- this.waitingFragment = null;
- // destroy useless demuxer when switching audio to main
- if (!altAudio) {
- if (this.demuxer) {
- this.demuxer.destroy();
- this.demuxer = null;
- }
- } else {
- // switching to audio track, start timer if not already started
- this.setInterval(TICK_INTERVAL);
- }
- // should we switch tracks ?
- if (altAudio) {
- this.audioSwitch = true;
- // main audio track are handled by stream-controller, just do something if switching to alt audio track
- this.state = _baseStreamController.State.IDLE;
- }
- this.tick();
- }
- }, {
- key: 'onAudioTrackLoaded',
- value: function onAudioTrackLoaded(data) {
- var newDetails = data.details,
- trackId = data.id,
- track = this.tracks[trackId],
- duration = newDetails.totalduration,
- sliding = 0;
- _logger.logger.log('track ' + trackId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration);
- if (newDetails.live) {
- var curDetails = track.details;
- if (curDetails && newDetails.fragments.length > 0) {
- // we already have details for that level, merge them
- LevelHelper.mergeDetails(curDetails, newDetails);
- sliding = newDetails.fragments[0].start;
- // TODO
- // this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
- if (newDetails.PTSKnown) {
- _logger.logger.log('live audio playlist sliding:' + sliding.toFixed(3));
- } else {
- _logger.logger.log('live audio playlist - outdated PTS, unknown sliding');
- }
- } else {
- newDetails.PTSKnown = false;
- _logger.logger.log('live audio playlist - first load, unknown sliding');
- }
- } else {
- newDetails.PTSKnown = false;
- }
- track.details = newDetails;
- // compute start position
- if (!this.startFragRequested) {
- // compute start position if set to -1. use it straight away if value is defined
- if (this.startPosition === -1) {
- // first, check if start time offset has been set in playlist, if yes, use this value
- var startTimeOffset = newDetails.startTimeOffset;
- if (Number.isFinite(startTimeOffset)) {
- _logger.logger.log('start time offset found in playlist, adjust startPosition to ' + startTimeOffset);
- this.startPosition = startTimeOffset;
- } else {
- this.startPosition = 0;
- }
- }
- this.nextLoadPosition = this.startPosition;
- }
- // only switch batck to IDLE state if we were waiting for track to start downloading a new fragment
- if (this.state === _baseStreamController.State.WAITING_TRACK) {
- this.state = _baseStreamController.State.IDLE;
- }
- // trigger handler right now
- this.tick();
- }
- }, {
- key: 'onKeyLoaded',
- value: function onKeyLoaded() {
- if (this.state === _baseStreamController.State.KEY_LOADING) {
- this.state = _baseStreamController.State.IDLE;
- this.tick();
- }
- }
- }, {
- key: 'onFragLoaded',
- value: function onFragLoaded(data) {
- var fragCurrent = this.fragCurrent,
- fragLoaded = data.frag;
- if (this.state === _baseStreamController.State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'audio' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
- var track = this.tracks[this.trackId],
- details = track.details,
- duration = details.totalduration,
- trackId = fragCurrent.level,
- sn = fragCurrent.sn,
- cc = fragCurrent.cc,
- audioCodec = this.config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2',
- stats = this.stats = data.stats;
- if (sn === 'initSegment') {
- this.state = _baseStreamController.State.IDLE;
- stats.tparsed = stats.tbuffered = performance.now();
- details.initSegment.data = data.payload;
- this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'audio' });
- this.tick();
- } else {
- this.state = _baseStreamController.State.PARSING;
- // transmux the MPEG-TS data to ISO-BMFF segments
- this.appended = false;
- if (!this.demuxer) {
- this.demuxer = new _demuxer2.default(this.hls, 'audio');
- }
- // Check if we have video initPTS
- // If not we need to wait for it
- var initPTS = this.initPTS[cc];
- var initSegmentData = details.initSegment ? details.initSegment.data : [];
- if (details.initSegment || initPTS !== undefined) {
- this.pendingBuffering = true;
- _logger.logger.log('Demuxing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],track ' + trackId);
- // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
- var accurateTimeOffset = false; // details.PTSKnown || !details.live;
- this.demuxer.push(data.payload, initSegmentData, audioCodec, null, fragCurrent, duration, accurateTimeOffset, initPTS);
- } else {
- _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);
- this.waitingFragment = data;
- this.state = _baseStreamController.State.WAITING_INIT_PTS;
- }
- }
- }
- this.fragLoadError = 0;
- }
- }, {
- key: 'onFragParsingInitSegment',
- value: function onFragParsingInitSegment(data) {
- var fragCurrent = this.fragCurrent;
- var fragNew = data.frag;
- if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === _baseStreamController.State.PARSING) {
- var tracks = data.tracks,
- track = void 0;
- // delete any video track found on audio demuxer
- if (tracks.video) {
- delete tracks.video;
- }
- // include levelCodec in audio and video tracks
- track = tracks.audio;
- if (track) {
- track.levelCodec = track.codec;
- track.id = data.id;
- this.hls.trigger(_events2.default.BUFFER_CODECS, tracks);
- _logger.logger.log('audio track:audio,container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']');
- var initSegment = track.initSegment;
- if (initSegment) {
- var appendObj = { type: 'audio', data: initSegment, parent: 'audio', content: 'initSegment' };
- if (this.audioSwitch) {
- this.pendingData = [appendObj];
- } else {
- this.appended = true;
- // arm pending Buffering flag before appending a segment
- this.pendingBuffering = true;
- this.hls.trigger(_events2.default.BUFFER_APPENDING, appendObj);
- }
- }
- // trigger handler right now
- this.tick();
- }
- }
- }
- }, {
- key: 'onFragParsingData',
- value: function onFragParsingData(data) {
- var _this2 = this;
- var fragCurrent = this.fragCurrent;
- var fragNew = data.frag;
- if (fragCurrent && data.id === 'audio' && data.type === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === _baseStreamController.State.PARSING) {
- var trackId = this.trackId,
- track = this.tracks[trackId],
- hls = this.hls;
- if (!Number.isFinite(data.endPTS)) {
- data.endPTS = data.startPTS + fragCurrent.duration;
- data.endDTS = data.startDTS + fragCurrent.duration;
- }
- fragCurrent.addElementaryStream(_fragment2.default.ElementaryStreamTypes.AUDIO);
- _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);
- LevelHelper.updateFragPTSDTS(track.details, fragCurrent, data.startPTS, data.endPTS);
- var audioSwitch = this.audioSwitch,
- media = this.media,
- appendOnBufferFlush = false;
- // Only flush audio from old audio tracks when PTS is known on new audio track
- if (audioSwitch && media) {
- if (media.readyState) {
- var currentTime = media.currentTime;
- _logger.logger.log('switching audio track : currentTime:' + currentTime);
- if (currentTime >= data.startPTS) {
- _logger.logger.log('switching audio track : flushing all audio');
- this.state = _baseStreamController.State.BUFFER_FLUSHING;
- hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
- appendOnBufferFlush = true;
- // Lets announce that the initial audio track switch flush occur
- this.audioSwitch = false;
- hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: trackId });
- }
- } else {
- // Lets announce that the initial audio track switch flush occur
- this.audioSwitch = false;
- hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: trackId });
- }
- }
- var pendingData = this.pendingData;
- if (!pendingData) {
- _logger.logger.warn('Apparently attempt to enqueue media payload without codec initialization data upfront');
- hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: null, fatal: true });
- return;
- }
- if (!this.audioSwitch) {
- [data.data1, data.data2].forEach(function (buffer) {
- if (buffer && buffer.length) {
- pendingData.push({ type: data.type, data: buffer, parent: 'audio', content: 'data' });
- }
- });
- if (!appendOnBufferFlush && pendingData.length) {
- pendingData.forEach(function (appendObj) {
- // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
- // in that case it is useless to append following segments
- if (_this2.state === _baseStreamController.State.PARSING) {
- // arm pending Buffering flag before appending a segment
- _this2.pendingBuffering = true;
- _this2.hls.trigger(_events2.default.BUFFER_APPENDING, appendObj);
- }
- });
- this.pendingData = [];
- this.appended = true;
- }
- }
- // trigger handler right now
- this.tick();
- }
- }
- }, {
- key: 'onFragParsed',
- value: function onFragParsed(data) {
- var fragCurrent = this.fragCurrent;
- var fragNew = data.frag;
- if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === _baseStreamController.State.PARSING) {
- this.stats.tparsed = performance.now();
- this.state = _baseStreamController.State.PARSED;
- this._checkAppendedParsed();
- }
- }
- }, {
- key: 'onBufferReset',
- value: function onBufferReset() {
- // reset reference to sourcebuffers
- this.mediaBuffer = this.videoBuffer = null;
- this.loadedmetadata = false;
- }
- }, {
- key: 'onBufferCreated',
- value: function onBufferCreated(data) {
- var audioTrack = data.tracks.audio;
- if (audioTrack) {
- this.mediaBuffer = audioTrack.buffer;
- this.loadedmetadata = true;
- }
- if (data.tracks.video) {
- this.videoBuffer = data.tracks.video.buffer;
- }
- }
- }, {
- key: 'onBufferAppended',
- value: function onBufferAppended(data) {
- if (data.parent === 'audio') {
- var state = this.state;
- if (state === _baseStreamController.State.PARSING || state === _baseStreamController.State.PARSED) {
- // check if all buffers have been appended
- this.pendingBuffering = data.pending > 0;
- this._checkAppendedParsed();
- }
- }
- }
- }, {
- key: '_checkAppendedParsed',
- value: function _checkAppendedParsed() {
- // trigger handler right now
- if (this.state === _baseStreamController.State.PARSED && (!this.appended || !this.pendingBuffering)) {
- var frag = this.fragCurrent,
- stats = this.stats,
- hls = this.hls;
- if (frag) {
- this.fragPrevious = frag;
- stats.tbuffered = performance.now();
- hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'audio' });
- var media = this.mediaBuffer ? this.mediaBuffer : this.media;
- _logger.logger.log('audio buffered : ' + _timeRanges2.default.toString(media.buffered));
- if (this.audioSwitch && this.appended) {
- this.audioSwitch = false;
- hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: this.trackId });
- }
- this.state = _baseStreamController.State.IDLE;
- }
- this.tick();
- }
- }
- }, {
- key: 'onError',
- value: function onError(data) {
- var frag = data.frag;
- // don't handle frag error not related to audio fragment
- if (frag && frag.type !== 'audio') {
- return;
- }
- switch (data.details) {
- case _errors.ErrorDetails.FRAG_LOAD_ERROR:
- case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
- var _frag = data.frag;
- // don't handle frag error not related to audio fragment
- if (_frag && _frag.type !== 'audio') {
- break;
- }
- if (!data.fatal) {
- var loadError = this.fragLoadError;
- if (loadError) {
- loadError++;
- } else {
- loadError = 1;
- }
- var config = this.config;
- if (loadError <= config.fragLoadingMaxRetry) {
- this.fragLoadError = loadError;
- // exponential backoff capped to config.fragLoadingMaxRetryTimeout
- var delay = Math.min(Math.pow(2, loadError - 1) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);
- _logger.logger.warn('AudioStreamController: frag loading failed, retry in ' + delay + ' ms');
- this.retryDate = performance.now() + delay;
- // retry loading state
- this.state = _baseStreamController.State.FRAG_LOADING_WAITING_RETRY;
- } else {
- _logger.logger.error('AudioStreamController: ' + data.details + ' reaches max retry, redispatch as fatal ...');
- // switch error to fatal
- data.fatal = true;
- this.state = _baseStreamController.State.ERROR;
- }
- }
- break;
- case _errors.ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
- case _errors.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
- case _errors.ErrorDetails.KEY_LOAD_ERROR:
- case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
- // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received
- if (this.state !== _baseStreamController.State.ERROR) {
- // if fatal error, stop processing, otherwise move to IDLE to retry loading
- this.state = data.fatal ? _baseStreamController.State.ERROR : _baseStreamController.State.IDLE;
- _logger.logger.warn('AudioStreamController: ' + data.details + ' while loading frag, now switching to ' + this.state + ' state ...');
- }
- break;
- case _errors.ErrorDetails.BUFFER_FULL_ERROR:
- // if in appending state
- if (data.parent === 'audio' && (this.state === _baseStreamController.State.PARSING || this.state === _baseStreamController.State.PARSED)) {
- var media = this.mediaBuffer,
- currentTime = this.media.currentTime,
- mediaBuffered = media && _bufferHelper.BufferHelper.isBuffered(media, currentTime) && _bufferHelper.BufferHelper.isBuffered(media, currentTime + 0.5);
- // reduce max buf len if current position is buffered
- if (mediaBuffered) {
- var _config = this.config;
- if (_config.maxMaxBufferLength >= _config.maxBufferLength) {
- // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
- _config.maxMaxBufferLength /= 2;
- _logger.logger.warn('AudioStreamController: reduce max buffer length to ' + _config.maxMaxBufferLength + 's');
- }
- this.state = _baseStreamController.State.IDLE;
- } else {
- // current position is not buffered, but browser is still complaining about buffer full error
- // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
- // in that case flush the whole audio buffer to recover
- _logger.logger.warn('AudioStreamController: buffer full error also media.currentTime is not buffered, flush audio buffer');
- this.fragCurrent = null;
- // flush everything
- this.state = _baseStreamController.State.BUFFER_FLUSHING;
- this.hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
- }
- }
- break;
- default:
- break;
- }
- }
- }, {
- key: 'onBufferFlushed',
- value: function onBufferFlushed() {
- var _this3 = this;
- var pendingData = this.pendingData;
- if (pendingData && pendingData.length) {
- _logger.logger.log('AudioStreamController: appending pending audio data after buffer flushed');
- pendingData.forEach(function (appendObj) {
- _this3.hls.trigger(_events2.default.BUFFER_APPENDING, appendObj);
- });
- this.appended = true;
- this.pendingData = [];
- this.state = _baseStreamController.State.PARSED;
- } else {
- // move to IDLE once flush complete. this should trigger new fragment loading
- this.state = _baseStreamController.State.IDLE;
- // reset reference to frag
- this.fragPrevious = null;
- this.tick();
- }
- }
- }, {
- key: 'state',
- set: function set(nextState) {
- if (this.state !== nextState) {
- var previousState = this.state;
- this._state = nextState;
- _logger.logger.log('audio stream:' + previousState + '->' + nextState);
- }
- },
- get: function get() {
- return this._state;
- }
- }]);
- return AudioStreamController;
- }(_baseStreamController2.default);
- exports.default = AudioStreamController;
- module.exports = exports['default'];
- /***/ }),
- /* 70 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.newCue = newCue;
- var _vttparser = __webpack_require__(30);
- function newCue(track, startTime, endTime, captionScreen) {
- var row = void 0;
- var cue = void 0;
- var indenting = void 0;
- var indent = void 0;
- var text = void 0;
- var VTTCue = window.VTTCue || window.TextTrackCue;
- for (var r = 0; r < captionScreen.rows.length; r++) {
- row = captionScreen.rows[r];
- indenting = true;
- indent = 0;
- text = '';
- if (!row.isEmpty()) {
- for (var c = 0; c < row.chars.length; c++) {
- if (row.chars[c].uchar.match(/\s/) && indenting) {
- indent++;
- } else {
- text += row.chars[c].uchar;
- indenting = false;
- }
- }
- // To be used for cleaning-up orphaned roll-up captions
- row.cueStartTime = startTime;
- // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
- if (startTime === endTime) {
- endTime += 0.0001;
- }
- cue = new VTTCue(startTime, endTime, (0, _vttparser.fixLineBreaks)(text.trim()));
- if (indent >= 16) {
- indent--;
- } else {
- indent++;
- }
- // VTTCue.line get's flakey when using controls, so let's now include line 13&14
- // also, drop line 1 since it's to close to the top
- if (navigator.userAgent.match(/Firefox\//)) {
- cue.line = r + 1;
- } else {
- cue.line = r > 7 ? r - 2 : r + 1;
- }
- cue.align = 'left';
- // Clamp the position between 0 and 100 - if out of these bounds, Firefox throws an exception and captions break
- cue.position = Math.max(0, Math.min(100, 100 * (indent / 32) + (navigator.userAgent.match(/Firefox\//) ? 50 : 0)));
- track.addCue(cue);
- }
- }
- }
- /***/ }),
- /* 71 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- /**
- * Copyright 2013 vtt.js Contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- exports.default = function () {
- if (typeof window !== 'undefined' && window.VTTCue) {
- return window.VTTCue;
- }
- var autoKeyword = 'auto';
- var directionSetting = {
- '': true,
- lr: true,
- rl: true
- };
- var alignSetting = {
- start: true,
- middle: true,
- end: true,
- left: true,
- right: true
- };
- function findDirectionSetting(value) {
- if (typeof value !== 'string') {
- return false;
- }
- var dir = directionSetting[value.toLowerCase()];
- return dir ? value.toLowerCase() : false;
- }
- function findAlignSetting(value) {
- if (typeof value !== 'string') {
- return false;
- }
- var align = alignSetting[value.toLowerCase()];
- return align ? value.toLowerCase() : false;
- }
- function extend(obj) {
- var i = 1;
- for (; i < arguments.length; i++) {
- var cobj = arguments[i];
- for (var p in cobj) {
- obj[p] = cobj[p];
- }
- }
- return obj;
- }
- function VTTCue(startTime, endTime, text) {
- var cue = this;
- var isIE8 = function () {
- if (typeof navigator === 'undefined') {
- return;
- }
- return (/MSIE\s8\.0/.test(navigator.userAgent)
- );
- }();
- var baseObj = {};
- if (isIE8) {
- cue = document.createElement('custom');
- } else {
- baseObj.enumerable = true;
- }
- /**
- * Shim implementation specific properties. These properties are not in
- * the spec.
- */
- // Lets us know when the VTTCue's data has changed in such a way that we need
- // to recompute its display state. This lets us compute its display state
- // lazily.
- cue.hasBeenReset = false;
- /**
- * VTTCue and TextTrackCue properties
- * http://dev.w3.org/html5/webvtt/#vttcue-interface
- */
- var _id = '';
- var _pauseOnExit = false;
- var _startTime = startTime;
- var _endTime = endTime;
- var _text = text;
- var _region = null;
- var _vertical = '';
- var _snapToLines = true;
- var _line = 'auto';
- var _lineAlign = 'start';
- var _position = 50;
- var _positionAlign = 'middle';
- var _size = 50;
- var _align = 'middle';
- Object.defineProperty(cue, 'id', extend({}, baseObj, {
- get: function get() {
- return _id;
- },
- set: function set(value) {
- _id = '' + value;
- }
- }));
- Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {
- get: function get() {
- return _pauseOnExit;
- },
- set: function set(value) {
- _pauseOnExit = !!value;
- }
- }));
- Object.defineProperty(cue, 'startTime', extend({}, baseObj, {
- get: function get() {
- return _startTime;
- },
- set: function set(value) {
- if (typeof value !== 'number') {
- throw new TypeError('Start time must be set to a number.');
- }
- _startTime = value;
- this.hasBeenReset = true;
- }
- }));
- Object.defineProperty(cue, 'endTime', extend({}, baseObj, {
- get: function get() {
- return _endTime;
- },
- set: function set(value) {
- if (typeof value !== 'number') {
- throw new TypeError('End time must be set to a number.');
- }
- _endTime = value;
- this.hasBeenReset = true;
- }
- }));
- Object.defineProperty(cue, 'text', extend({}, baseObj, {
- get: function get() {
- return _text;
- },
- set: function set(value) {
- _text = '' + value;
- this.hasBeenReset = true;
- }
- }));
- Object.defineProperty(cue, 'region', extend({}, baseObj, {
- get: function get() {
- return _region;
- },
- set: function set(value) {
- _region = value;
- this.hasBeenReset = true;
- }
- }));
- Object.defineProperty(cue, 'vertical', extend({}, baseObj, {
- get: function get() {
- return _vertical;
- },
- set: function set(value) {
- var setting = findDirectionSetting(value);
- // Have to check for false because the setting an be an empty string.
- if (setting === false) {
- throw new SyntaxError('An invalid or illegal string was specified.');
- }
- _vertical = setting;
- this.hasBeenReset = true;
- }
- }));
- Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {
- get: function get() {
- return _snapToLines;
- },
- set: function set(value) {
- _snapToLines = !!value;
- this.hasBeenReset = true;
- }
- }));
- Object.defineProperty(cue, 'line', extend({}, baseObj, {
- get: function get() {
- return _line;
- },
- set: function set(value) {
- if (typeof value !== 'number' && value !== autoKeyword) {
- throw new SyntaxError('An invalid number or illegal string was specified.');
- }
- _line = value;
- this.hasBeenReset = true;
- }
- }));
- Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {
- get: function get() {
- return _lineAlign;
- },
- set: function set(value) {
- var setting = findAlignSetting(value);
- if (!setting) {
- throw new SyntaxError('An invalid or illegal string was specified.');
- }
- _lineAlign = setting;
- this.hasBeenReset = true;
- }
- }));
- Object.defineProperty(cue, 'position', extend({}, baseObj, {
- get: function get() {
- return _position;
- },
- set: function set(value) {
- if (value < 0 || value > 100) {
- throw new Error('Position must be between 0 and 100.');
- }
- _position = value;
- this.hasBeenReset = true;
- }
- }));
- Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {
- get: function get() {
- return _positionAlign;
- },
- set: function set(value) {
- var setting = findAlignSetting(value);
- if (!setting) {
- throw new SyntaxError('An invalid or illegal string was specified.');
- }
- _positionAlign = setting;
- this.hasBeenReset = true;
- }
- }));
- Object.defineProperty(cue, 'size', extend({}, baseObj, {
- get: function get() {
- return _size;
- },
- set: function set(value) {
- if (value < 0 || value > 100) {
- throw new Error('Size must be between 0 and 100.');
- }
- _size = value;
- this.hasBeenReset = true;
- }
- }));
- Object.defineProperty(cue, 'align', extend({}, baseObj, {
- get: function get() {
- return _align;
- },
- set: function set(value) {
- var setting = findAlignSetting(value);
- if (!setting) {
- throw new SyntaxError('An invalid or illegal string was specified.');
- }
- _align = setting;
- this.hasBeenReset = true;
- }
- }));
- /**
- * Other <track> spec defined properties
- */
- // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
- cue.displayState = undefined;
- if (isIE8) {
- return cue;
- }
- }
- /**
- * VTTCue methods
- */
- VTTCue.prototype.getCueAsHTML = function () {
- // Assume WebVTT.convertCueToDOMTree is on the global.
- var WebVTT = window.WebVTT;
- return WebVTT.convertCueToDOMTree(window, this.text);
- };
- return VTTCue;
- }();
- module.exports = exports['default'];
- /***/ }),
- /* 72 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _eventHandler = __webpack_require__(3);
- var _eventHandler2 = _interopRequireDefault(_eventHandler);
- var _cea608Parser = __webpack_require__(73);
- var _cea608Parser2 = _interopRequireDefault(_cea608Parser);
- var _outputFilter = __webpack_require__(74);
- var _outputFilter2 = _interopRequireDefault(_outputFilter);
- var _webvttParser = __webpack_require__(75);
- var _webvttParser2 = _interopRequireDefault(_webvttParser);
- var _logger = __webpack_require__(0);
- var _texttrackUtils = __webpack_require__(29);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /*
- * Timeline Controller
- */
- function canReuseVttTextTrack(inUseTrack, manifestTrack) {
- return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);
- }
- function intersection(x1, x2, y1, y2) {
- return Math.min(x2, y2) - Math.max(x1, y1);
- }
- var TimelineController = function (_EventHandler) {
- _inherits(TimelineController, _EventHandler);
- function TimelineController(hls) {
- _classCallCheck(this, TimelineController);
- 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));
- _this.hls = hls;
- _this.config = hls.config;
- _this.enabled = true;
- _this.Cues = hls.config.cueHandler;
- _this.textTracks = [];
- _this.tracks = [];
- _this.unparsedVttFrags = [];
- _this.initPTS = [];
- _this.cueRanges = [];
- _this.captionsTracks = {};
- _this.captionsProperties = {
- textTrack1: {
- label: _this.config.captionsTextTrack1Label,
- languageCode: _this.config.captionsTextTrack1LanguageCode
- },
- textTrack2: {
- label: _this.config.captionsTextTrack2Label,
- languageCode: _this.config.captionsTextTrack2LanguageCode
- }
- };
- if (_this.config.enableCEA708Captions) {
- var channel1 = new _outputFilter2.default(_this, 'textTrack1');
- var channel2 = new _outputFilter2.default(_this, 'textTrack2');
- _this.cea608Parser = new _cea608Parser2.default(0, channel1, channel2);
- }
- return _this;
- }
- _createClass(TimelineController, [{
- key: 'addCues',
- value: function addCues(trackName, startTime, endTime, screen) {
- // skip cues which overlap more than 50% with previously parsed time ranges
- var ranges = this.cueRanges;
- var merged = false;
- for (var i = ranges.length; i--;) {
- var cueRange = ranges[i];
- var overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
- if (overlap >= 0) {
- cueRange[0] = Math.min(cueRange[0], startTime);
- cueRange[1] = Math.max(cueRange[1], endTime);
- merged = true;
- if (overlap / (endTime - startTime) > 0.5) {
- return;
- }
- }
- }
- if (!merged) {
- ranges.push([startTime, endTime]);
- }
- this.Cues.newCue(this.captionsTracks[trackName], startTime, endTime, screen);
- }
- // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
- }, {
- key: 'onInitPtsFound',
- value: function onInitPtsFound(data) {
- var _this2 = this;
- if (data.id === 'main') {
- this.initPTS[data.frag.cc] = data.initPTS;
- }
- // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.
- // Parse any unparsed fragments upon receiving the initial PTS.
- if (this.unparsedVttFrags.length) {
- var unparsedVttFrags = this.unparsedVttFrags;
- this.unparsedVttFrags = [];
- unparsedVttFrags.forEach(function (frag) {
- _this2.onFragLoaded(frag);
- });
- }
- }
- }, {
- key: 'getExistingTrack',
- value: function getExistingTrack(trackName) {
- var media = this.media;
- if (media) {
- for (var i = 0; i < media.textTracks.length; i++) {
- var textTrack = media.textTracks[i];
- if (textTrack[trackName]) {
- return textTrack;
- }
- }
- }
- return null;
- }
- }, {
- key: 'createCaptionsTrack',
- value: function createCaptionsTrack(trackName) {
- var _captionsProperties$t = this.captionsProperties[trackName],
- label = _captionsProperties$t.label,
- languageCode = _captionsProperties$t.languageCode;
- var captionsTracks = this.captionsTracks;
- if (!captionsTracks[trackName]) {
- // Enable reuse of existing text track.
- var existingTrack = this.getExistingTrack(trackName);
- if (!existingTrack) {
- var textTrack = this.createTextTrack('captions', label, languageCode);
- if (textTrack) {
- // Set a special property on the track so we know it's managed by Hls.js
- textTrack[trackName] = true;
- captionsTracks[trackName] = textTrack;
- }
- } else {
- captionsTracks[trackName] = existingTrack;
- (0, _texttrackUtils.clearCurrentCues)(captionsTracks[trackName]);
- (0, _texttrackUtils.sendAddTrackEvent)(captionsTracks[trackName], this.media);
- }
- }
- }
- }, {
- key: 'createTextTrack',
- value: function createTextTrack(kind, label, lang) {
- var media = this.media;
- if (media) {
- return media.addTextTrack(kind, label, lang);
- }
- }
- }, {
- key: 'destroy',
- value: function destroy() {
- _eventHandler2.default.prototype.destroy.call(this);
- }
- }, {
- key: 'onMediaAttaching',
- value: function onMediaAttaching(data) {
- this.media = data.media;
- this._cleanTracks();
- }
- }, {
- key: 'onMediaDetaching',
- value: function onMediaDetaching() {
- var captionsTracks = this.captionsTracks;
- Object.keys(captionsTracks).forEach(function (trackName) {
- (0, _texttrackUtils.clearCurrentCues)(captionsTracks[trackName]);
- delete captionsTracks[trackName];
- });
- }
- }, {
- key: 'onManifestLoading',
- value: function onManifestLoading() {
- this.lastSn = -1; // Detect discontiguity in fragment parsing
- this.prevCC = -1;
- this.vttCCs = { // Detect discontinuity in subtitle manifests
- ccOffset: 0,
- presentationOffset: 0,
- 0: {
- start: 0, prevCC: -1, new: false
- }
- };
- this._cleanTracks();
- }
- }, {
- key: '_cleanTracks',
- value: function _cleanTracks() {
- // clear outdated subtitles
- var media = this.media;
- if (media) {
- var textTracks = media.textTracks;
- if (textTracks) {
- for (var i = 0; i < textTracks.length; i++) {
- (0, _texttrackUtils.clearCurrentCues)(textTracks[i]);
- }
- }
- }
- }
- }, {
- key: 'onManifestLoaded',
- value: function onManifestLoaded(data) {
- var _this3 = this;
- this.textTracks = [];
- this.unparsedVttFrags = this.unparsedVttFrags || [];
- this.initPTS = [];
- this.cueRanges = [];
- if (this.config.enableWebVTT) {
- this.tracks = data.subtitles || [];
- var inUseTracks = this.media ? this.media.textTracks : [];
- this.tracks.forEach(function (track, index) {
- var textTrack = void 0;
- if (index < inUseTracks.length) {
- var inUseTrack = null;
- for (var i = 0; i < inUseTracks.length; i++) {
- if (canReuseVttTextTrack(inUseTracks[i], track)) {
- inUseTrack = inUseTracks[i];
- break;
- }
- }
- // Reuse tracks with the same label, but do not reuse 608/708 tracks
- if (inUseTrack) {
- textTrack = inUseTrack;
- }
- }
- if (!textTrack) {
- textTrack = _this3.createTextTrack('subtitles', track.name, track.lang);
- }
- if (track.default) {
- textTrack.mode = _this3.hls.subtitleDisplay ? 'showing' : 'hidden';
- } else {
- textTrack.mode = 'disabled';
- }
- _this3.textTracks.push(textTrack);
- });
- }
- }
- }, {
- key: 'onLevelSwitching',
- value: function onLevelSwitching() {
- this.enabled = this.hls.currentLevel.closedCaptions !== 'NONE';
- }
- }, {
- key: 'onFragLoaded',
- value: function onFragLoaded(data) {
- var frag = data.frag,
- payload = data.payload;
- if (frag.type === 'main') {
- var sn = frag.sn;
- // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
- if (sn !== this.lastSn + 1) {
- var cea608Parser = this.cea608Parser;
- if (cea608Parser) {
- cea608Parser.reset();
- }
- }
- this.lastSn = sn;
- } // eslint-disable-line brace-style
- // If fragment is subtitle type, parse as WebVTT.
- else if (frag.type === 'subtitle') {
- if (payload.byteLength) {
- // We need an initial synchronisation PTS. Store fragments as long as none has arrived.
- if (!Number.isFinite(this.initPTS[frag.cc])) {
- this.unparsedVttFrags.push(data);
- if (this.initPTS.length) {
- // finish unsuccessfully, otherwise the subtitle-stream-controller could be blocked from loading new frags.
- this.hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
- }
- return;
- }
- var decryptData = frag.decryptdata;
- // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.
- if (decryptData == null || decryptData.key == null || decryptData.method !== 'AES-128') {
- this._parseVTTs(frag, payload);
- }
- } else {
- // In case there is no payload, finish unsuccessfully.
- this.hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
- }
- }
- }
- }, {
- key: '_parseVTTs',
- value: function _parseVTTs(frag, payload) {
- var vttCCs = this.vttCCs;
- if (!vttCCs[frag.cc]) {
- vttCCs[frag.cc] = { start: frag.start, prevCC: this.prevCC, new: true };
- this.prevCC = frag.cc;
- }
- var textTracks = this.textTracks,
- hls = this.hls;
- // Parse the WebVTT file contents.
- _webvttParser2.default.parse(payload, this.initPTS[frag.cc], vttCCs, frag.cc, function (cues) {
- var currentTrack = textTracks[frag.level];
- // WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled"
- // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null
- // and trying to access getCueById method of cues will throw an exception
- if (currentTrack.mode === 'disabled') {
- hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
- return;
- }
- // Add cues and trigger event with success true.
- cues.forEach(function (cue) {
- // Sometimes there are cue overlaps on segmented vtts so the same
- // cue can appear more than once in different vtt files.
- // This avoid showing duplicated cues with same timecode and text.
- if (!currentTrack.cues.getCueById(cue.id)) {
- try {
- currentTrack.addCue(cue);
- } catch (err) {
- var textTrackCue = new window.TextTrackCue(cue.startTime, cue.endTime, cue.text);
- textTrackCue.id = cue.id;
- currentTrack.addCue(textTrackCue);
- }
- }
- });
- hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: true, frag: frag });
- }, function (e) {
- // Something went wrong while parsing. Trigger event with success false.
- _logger.logger.log('Failed to parse VTT cue: ' + e);
- hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
- });
- }
- }, {
- key: 'onFragDecrypted',
- value: function onFragDecrypted(data) {
- var decryptedData = data.payload,
- frag = data.frag;
- if (frag.type === 'subtitle') {
- if (!Number.isFinite(this.initPTS[frag.cc])) {
- this.unparsedVttFrags.push(data);
- return;
- }
- this._parseVTTs(frag, decryptedData);
- }
- }
- }, {
- key: 'onFragParsingUserdata',
- value: function onFragParsingUserdata(data) {
- // push all of the CEA-708 messages into the interpreter
- // immediately. It will create the proper timestamps based on our PTS value
- if (this.enabled && this.config.enableCEA708Captions) {
- for (var i = 0; i < data.samples.length; i++) {
- var ccdatas = this.extractCea608Data(data.samples[i].bytes);
- this.cea608Parser.addData(data.samples[i].pts, ccdatas);
- }
- }
- }
- }, {
- key: 'extractCea608Data',
- value: function extractCea608Data(byteArray) {
- var count = byteArray[0] & 31;
- var position = 2;
- var tmpByte = void 0,
- ccbyte1 = void 0,
- ccbyte2 = void 0,
- ccValid = void 0,
- ccType = void 0;
- var actualCCBytes = [];
- for (var j = 0; j < count; j++) {
- tmpByte = byteArray[position++];
- ccbyte1 = 0x7F & byteArray[position++];
- ccbyte2 = 0x7F & byteArray[position++];
- ccValid = (4 & tmpByte) !== 0;
- ccType = 3 & tmpByte;
- if (ccbyte1 === 0 && ccbyte2 === 0) {
- continue;
- }
- if (ccValid) {
- if (ccType === 0) {
- // || ccType === 1
- actualCCBytes.push(ccbyte1);
- actualCCBytes.push(ccbyte2);
- }
- }
- }
- return actualCCBytes;
- }
- }]);
- return TimelineController;
- }(_eventHandler2.default);
- exports.default = TimelineController;
- module.exports = exports['default'];
- /***/ }),
- /* 73 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /**
- *
- * This code was ported from the dash.js project at:
- * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
- * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
- *
- * The original copyright appears below:
- *
- * The copyright in this software is being made available under the BSD License,
- * included below. This software may be subject to other third party and contributor
- * rights, including patent rights, and no such rights are granted under this license.
- *
- * Copyright (c) 2015-2016, DASH Industry Forum.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without modification,
- * are permitted provided that the following conditions are met:
- * 1. Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation and/or
- * other materials provided with the distribution.
- * 2. Neither the name of Dash Industry Forum nor the names of its
- * contributors may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
- /**
- * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes
- */
- var specialCea608CharsCodes = {
- 0x2a: 0xe1, // lowercase a, acute accent
- 0x5c: 0xe9, // lowercase e, acute accent
- 0x5e: 0xed, // lowercase i, acute accent
- 0x5f: 0xf3, // lowercase o, acute accent
- 0x60: 0xfa, // lowercase u, acute accent
- 0x7b: 0xe7, // lowercase c with cedilla
- 0x7c: 0xf7, // division symbol
- 0x7d: 0xd1, // uppercase N tilde
- 0x7e: 0xf1, // lowercase n tilde
- 0x7f: 0x2588, // Full block
- // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
- // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
- // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
- 0x80: 0xae, // Registered symbol (R)
- 0x81: 0xb0, // degree sign
- 0x82: 0xbd, // 1/2 symbol
- 0x83: 0xbf, // Inverted (open) question mark
- 0x84: 0x2122, // Trademark symbol (TM)
- 0x85: 0xa2, // Cents symbol
- 0x86: 0xa3, // Pounds sterling
- 0x87: 0x266a, // Music 8'th note
- 0x88: 0xe0, // lowercase a, grave accent
- 0x89: 0x20, // transparent space (regular)
- 0x8a: 0xe8, // lowercase e, grave accent
- 0x8b: 0xe2, // lowercase a, circumflex accent
- 0x8c: 0xea, // lowercase e, circumflex accent
- 0x8d: 0xee, // lowercase i, circumflex accent
- 0x8e: 0xf4, // lowercase o, circumflex accent
- 0x8f: 0xfb, // lowercase u, circumflex accent
- // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
- // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
- 0x90: 0xc1, // capital letter A with acute
- 0x91: 0xc9, // capital letter E with acute
- 0x92: 0xd3, // capital letter O with acute
- 0x93: 0xda, // capital letter U with acute
- 0x94: 0xdc, // capital letter U with diaresis
- 0x95: 0xfc, // lowercase letter U with diaeresis
- 0x96: 0x2018, // opening single quote
- 0x97: 0xa1, // inverted exclamation mark
- 0x98: 0x2a, // asterisk
- 0x99: 0x2019, // closing single quote
- 0x9a: 0x2501, // box drawings heavy horizontal
- 0x9b: 0xa9, // copyright sign
- 0x9c: 0x2120, // Service mark
- 0x9d: 0x2022, // (round) bullet
- 0x9e: 0x201c, // Left double quotation mark
- 0x9f: 0x201d, // Right double quotation mark
- 0xa0: 0xc0, // uppercase A, grave accent
- 0xa1: 0xc2, // uppercase A, circumflex
- 0xa2: 0xc7, // uppercase C with cedilla
- 0xa3: 0xc8, // uppercase E, grave accent
- 0xa4: 0xca, // uppercase E, circumflex
- 0xa5: 0xcb, // capital letter E with diaresis
- 0xa6: 0xeb, // lowercase letter e with diaresis
- 0xa7: 0xce, // uppercase I, circumflex
- 0xa8: 0xcf, // uppercase I, with diaresis
- 0xa9: 0xef, // lowercase i, with diaresis
- 0xaa: 0xd4, // uppercase O, circumflex
- 0xab: 0xd9, // uppercase U, grave accent
- 0xac: 0xf9, // lowercase u, grave accent
- 0xad: 0xdb, // uppercase U, circumflex
- 0xae: 0xab, // left-pointing double angle quotation mark
- 0xaf: 0xbb, // right-pointing double angle quotation mark
- // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
- // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
- 0xb0: 0xc3, // Uppercase A, tilde
- 0xb1: 0xe3, // Lowercase a, tilde
- 0xb2: 0xcd, // Uppercase I, acute accent
- 0xb3: 0xcc, // Uppercase I, grave accent
- 0xb4: 0xec, // Lowercase i, grave accent
- 0xb5: 0xd2, // Uppercase O, grave accent
- 0xb6: 0xf2, // Lowercase o, grave accent
- 0xb7: 0xd5, // Uppercase O, tilde
- 0xb8: 0xf5, // Lowercase o, tilde
- 0xb9: 0x7b, // Open curly brace
- 0xba: 0x7d, // Closing curly brace
- 0xbb: 0x5c, // Backslash
- 0xbc: 0x5e, // Caret
- 0xbd: 0x5f, // Underscore
- 0xbe: 0x7c, // Pipe (vertical line)
- 0xbf: 0x223c, // Tilde operator
- 0xc0: 0xc4, // Uppercase A, umlaut
- 0xc1: 0xe4, // Lowercase A, umlaut
- 0xc2: 0xd6, // Uppercase O, umlaut
- 0xc3: 0xf6, // Lowercase o, umlaut
- 0xc4: 0xdf, // Esszett (sharp S)
- 0xc5: 0xa5, // Yen symbol
- 0xc6: 0xa4, // Generic currency sign
- 0xc7: 0x2503, // Box drawings heavy vertical
- 0xc8: 0xc5, // Uppercase A, ring
- 0xc9: 0xe5, // Lowercase A, ring
- 0xca: 0xd8, // Uppercase O, stroke
- 0xcb: 0xf8, // Lowercase o, strok
- 0xcc: 0x250f, // Box drawings heavy down and right
- 0xcd: 0x2513, // Box drawings heavy down and left
- 0xce: 0x2517, // Box drawings heavy up and right
- 0xcf: 0x251b // Box drawings heavy up and left
- };
- /**
- * Utils
- */
- var getCharForByte = function getCharForByte(byte) {
- var charCode = byte;
- if (specialCea608CharsCodes.hasOwnProperty(byte)) {
- charCode = specialCea608CharsCodes[byte];
- }
- return String.fromCharCode(charCode);
- };
- var NR_ROWS = 15,
- NR_COLS = 100;
- // Tables to look up row from PAC data
- var rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 };
- var rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 };
- var rowsLowCh2 = { 0x19: 1, 0x1A: 3, 0x1D: 5, 0x1E: 7, 0x1F: 9, 0x18: 11, 0x1B: 12, 0x1C: 14 };
- var rowsHighCh2 = { 0x19: 2, 0x1A: 4, 0x1D: 6, 0x1E: 8, 0x1F: 10, 0x1B: 13, 0x1C: 15 };
- var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];
- /**
- * Simple logger class to be able to write with time-stamps and filter on level.
- */
- var logger = {
- verboseFilter: { 'DATA': 3, 'DEBUG': 3, 'INFO': 2, 'WARNING': 2, 'TEXT': 1, 'ERROR': 0 },
- time: null,
- verboseLevel: 0, // Only write errors
- setTime: function setTime(newTime) {
- this.time = newTime;
- },
- log: function log(severity, msg) {
- var minLevel = this.verboseFilter[severity];
- if (this.verboseLevel >= minLevel) {
- // console.log(this.time + ' [' + severity + '] ' + msg);
- }
- }
- };
- var numArrayToHexArray = function numArrayToHexArray(numArray) {
- var hexArray = [];
- for (var j = 0; j < numArray.length; j++) {
- hexArray.push(numArray[j].toString(16));
- }
- return hexArray;
- };
- var PenState = function () {
- function PenState(foreground, underline, italics, background, flash) {
- _classCallCheck(this, PenState);
- this.foreground = foreground || 'white';
- this.underline = underline || false;
- this.italics = italics || false;
- this.background = background || 'black';
- this.flash = flash || false;
- }
- _createClass(PenState, [{
- key: 'reset',
- value: function reset() {
- this.foreground = 'white';
- this.underline = false;
- this.italics = false;
- this.background = 'black';
- this.flash = false;
- }
- }, {
- key: 'setStyles',
- value: function setStyles(styles) {
- var attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];
- for (var i = 0; i < attribs.length; i++) {
- var style = attribs[i];
- if (styles.hasOwnProperty(style)) {
- this[style] = styles[style];
- }
- }
- }
- }, {
- key: 'isDefault',
- value: function isDefault() {
- return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;
- }
- }, {
- key: 'equals',
- value: function equals(other) {
- return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
- }
- }, {
- key: 'copy',
- value: function copy(newPenState) {
- this.foreground = newPenState.foreground;
- this.underline = newPenState.underline;
- this.italics = newPenState.italics;
- this.background = newPenState.background;
- this.flash = newPenState.flash;
- }
- }, {
- key: 'toString',
- value: function toString() {
- return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;
- }
- }]);
- return PenState;
- }();
- /**
- * Unicode character with styling and background.
- * @constructor
- */
- var StyledUnicodeChar = function () {
- function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) {
- _classCallCheck(this, StyledUnicodeChar);
- this.uchar = uchar || ' '; // unicode character
- this.penState = new PenState(foreground, underline, italics, background, flash);
- }
- _createClass(StyledUnicodeChar, [{
- key: 'reset',
- value: function reset() {
- this.uchar = ' ';
- this.penState.reset();
- }
- }, {
- key: 'setChar',
- value: function setChar(uchar, newPenState) {
- this.uchar = uchar;
- this.penState.copy(newPenState);
- }
- }, {
- key: 'setPenState',
- value: function setPenState(newPenState) {
- this.penState.copy(newPenState);
- }
- }, {
- key: 'equals',
- value: function equals(other) {
- return this.uchar === other.uchar && this.penState.equals(other.penState);
- }
- }, {
- key: 'copy',
- value: function copy(newChar) {
- this.uchar = newChar.uchar;
- this.penState.copy(newChar.penState);
- }
- }, {
- key: 'isEmpty',
- value: function isEmpty() {
- return this.uchar === ' ' && this.penState.isDefault();
- }
- }]);
- return StyledUnicodeChar;
- }();
- /**
- * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
- * @constructor
- */
- var Row = function () {
- function Row() {
- _classCallCheck(this, Row);
- this.chars = [];
- for (var i = 0; i < NR_COLS; i++) {
- this.chars.push(new StyledUnicodeChar());
- }
- this.pos = 0;
- this.currPenState = new PenState();
- }
- _createClass(Row, [{
- key: 'equals',
- value: function equals(other) {
- var equal = true;
- for (var i = 0; i < NR_COLS; i++) {
- if (!this.chars[i].equals(other.chars[i])) {
- equal = false;
- break;
- }
- }
- return equal;
- }
- }, {
- key: 'copy',
- value: function copy(other) {
- for (var i = 0; i < NR_COLS; i++) {
- this.chars[i].copy(other.chars[i]);
- }
- }
- }, {
- key: 'isEmpty',
- value: function isEmpty() {
- var empty = true;
- for (var i = 0; i < NR_COLS; i++) {
- if (!this.chars[i].isEmpty()) {
- empty = false;
- break;
- }
- }
- return empty;
- }
- /**
- * Set the cursor to a valid column.
- */
- }, {
- key: 'setCursor',
- value: function setCursor(absPos) {
- if (this.pos !== absPos) {
- this.pos = absPos;
- }
- if (this.pos < 0) {
- logger.log('ERROR', 'Negative cursor position ' + this.pos);
- this.pos = 0;
- } else if (this.pos > NR_COLS) {
- logger.log('ERROR', 'Too large cursor position ' + this.pos);
- this.pos = NR_COLS;
- }
- }
- /**
- * Move the cursor relative to current position.
- */
- }, {
- key: 'moveCursor',
- value: function moveCursor(relPos) {
- var newPos = this.pos + relPos;
- if (relPos > 1) {
- for (var i = this.pos + 1; i < newPos + 1; i++) {
- this.chars[i].setPenState(this.currPenState);
- }
- }
- this.setCursor(newPos);
- }
- /**
- * Backspace, move one step back and clear character.
- */
- }, {
- key: 'backSpace',
- value: function backSpace() {
- this.moveCursor(-1);
- this.chars[this.pos].setChar(' ', this.currPenState);
- }
- }, {
- key: 'insertChar',
- value: function insertChar(byte) {
- if (byte >= 0x90) {
- // Extended char
- this.backSpace();
- }
- var char = getCharForByte(byte);
- if (this.pos >= NR_COLS) {
- logger.log('ERROR', 'Cannot insert ' + byte.toString(16) + ' (' + char + ') at position ' + this.pos + '. Skipping it!');
- return;
- }
- this.chars[this.pos].setChar(char, this.currPenState);
- this.moveCursor(1);
- }
- }, {
- key: 'clearFromPos',
- value: function clearFromPos(startPos) {
- var i = void 0;
- for (i = startPos; i < NR_COLS; i++) {
- this.chars[i].reset();
- }
- }
- }, {
- key: 'clear',
- value: function clear() {
- this.clearFromPos(0);
- this.pos = 0;
- this.currPenState.reset();
- }
- }, {
- key: 'clearToEndOfRow',
- value: function clearToEndOfRow() {
- this.clearFromPos(this.pos);
- }
- }, {
- key: 'getTextString',
- value: function getTextString() {
- var chars = [];
- var empty = true;
- for (var i = 0; i < NR_COLS; i++) {
- var char = this.chars[i].uchar;
- if (char !== ' ') {
- empty = false;
- }
- chars.push(char);
- }
- if (empty) {
- return '';
- } else {
- return chars.join('');
- }
- }
- }, {
- key: 'setPenStyles',
- value: function setPenStyles(styles) {
- this.currPenState.setStyles(styles);
- var currChar = this.chars[this.pos];
- currChar.setPenState(this.currPenState);
- }
- }]);
- return Row;
- }();
- /**
- * Keep a CEA-608 screen of 32x15 styled characters
- * @constructor
- */
- var CaptionScreen = function () {
- function CaptionScreen() {
- _classCallCheck(this, CaptionScreen);
- this.rows = [];
- for (var i = 0; i < NR_ROWS; i++) {
- this.rows.push(new Row());
- } // Note that we use zero-based numbering (0-14)
- this.currRow = NR_ROWS - 1;
- this.nrRollUpRows = null;
- this.reset();
- }
- _createClass(CaptionScreen, [{
- key: 'reset',
- value: function reset() {
- for (var i = 0; i < NR_ROWS; i++) {
- this.rows[i].clear();
- }
- this.currRow = NR_ROWS - 1;
- }
- }, {
- key: 'equals',
- value: function equals(other) {
- var equal = true;
- for (var i = 0; i < NR_ROWS; i++) {
- if (!this.rows[i].equals(other.rows[i])) {
- equal = false;
- break;
- }
- }
- return equal;
- }
- }, {
- key: 'copy',
- value: function copy(other) {
- for (var i = 0; i < NR_ROWS; i++) {
- this.rows[i].copy(other.rows[i]);
- }
- }
- }, {
- key: 'isEmpty',
- value: function isEmpty() {
- var empty = true;
- for (var i = 0; i < NR_ROWS; i++) {
- if (!this.rows[i].isEmpty()) {
- empty = false;
- break;
- }
- }
- return empty;
- }
- }, {
- key: 'backSpace',
- value: function backSpace() {
- var row = this.rows[this.currRow];
- row.backSpace();
- }
- }, {
- key: 'clearToEndOfRow',
- value: function clearToEndOfRow() {
- var row = this.rows[this.currRow];
- row.clearToEndOfRow();
- }
- /**
- * Insert a character (without styling) in the current row.
- */
- }, {
- key: 'insertChar',
- value: function insertChar(char) {
- var row = this.rows[this.currRow];
- row.insertChar(char);
- }
- }, {
- key: 'setPen',
- value: function setPen(styles) {
- var row = this.rows[this.currRow];
- row.setPenStyles(styles);
- }
- }, {
- key: 'moveCursor',
- value: function moveCursor(relPos) {
- var row = this.rows[this.currRow];
- row.moveCursor(relPos);
- }
- }, {
- key: 'setCursor',
- value: function setCursor(absPos) {
- logger.log('INFO', 'setCursor: ' + absPos);
- var row = this.rows[this.currRow];
- row.setCursor(absPos);
- }
- }, {
- key: 'setPAC',
- value: function setPAC(pacData) {
- logger.log('INFO', 'pacData = ' + JSON.stringify(pacData));
- var newRow = pacData.row - 1;
- if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
- newRow = this.nrRollUpRows - 1;
- }
- // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows
- if (this.nrRollUpRows && this.currRow !== newRow) {
- // clear all rows first
- for (var i = 0; i < NR_ROWS; i++) {
- this.rows[i].clear();
- }
- // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location
- // topRowIndex - the start of rows to copy (inclusive index)
- var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
- // We only copy if the last position was already shown.
- // We use the cueStartTime value to check this.
- var lastOutputScreen = this.lastOutputScreen;
- if (lastOutputScreen) {
- var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
- if (prevLineTime && prevLineTime < logger.time) {
- for (var _i = 0; _i < this.nrRollUpRows; _i++) {
- this.rows[newRow - this.nrRollUpRows + _i + 1].copy(lastOutputScreen.rows[topRowIndex + _i]);
- }
- }
- }
- }
- this.currRow = newRow;
- var row = this.rows[this.currRow];
- if (pacData.indent !== null) {
- var indent = pacData.indent;
- var prevPos = Math.max(indent - 1, 0);
- row.setCursor(pacData.indent);
- pacData.color = row.chars[prevPos].penState.foreground;
- }
- var styles = { foreground: pacData.color, underline: pacData.underline, italics: pacData.italics, background: 'black', flash: false };
- this.setPen(styles);
- }
- /**
- * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
- */
- }, {
- key: 'setBkgData',
- value: function setBkgData(bkgData) {
- logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData));
- this.backSpace();
- this.setPen(bkgData);
- this.insertChar(0x20); // Space
- }
- }, {
- key: 'setRollUpRows',
- value: function setRollUpRows(nrRows) {
- this.nrRollUpRows = nrRows;
- }
- }, {
- key: 'rollUp',
- value: function rollUp() {
- if (this.nrRollUpRows === null) {
- logger.log('DEBUG', 'roll_up but nrRollUpRows not set yet');
- return; // Not properly setup
- }
- logger.log('TEXT', this.getDisplayText());
- var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
- var topRow = this.rows.splice(topRowIndex, 1)[0];
- topRow.clear();
- this.rows.splice(this.currRow, 0, topRow);
- logger.log('INFO', 'Rolling up');
- // logger.log('TEXT', this.get_display_text())
- }
- /**
- * Get all non-empty rows with as unicode text.
- */
- }, {
- key: 'getDisplayText',
- value: function getDisplayText(asOneRow) {
- asOneRow = asOneRow || false;
- var displayText = [];
- var text = '';
- var rowNr = -1;
- for (var i = 0; i < NR_ROWS; i++) {
- var rowText = this.rows[i].getTextString();
- if (rowText) {
- rowNr = i + 1;
- if (asOneRow) {
- displayText.push('Row ' + rowNr + ': \'' + rowText + '\'');
- } else {
- displayText.push(rowText.trim());
- }
- }
- }
- if (displayText.length > 0) {
- if (asOneRow) {
- text = '[' + displayText.join(' | ') + ']';
- } else {
- text = displayText.join('\n');
- }
- }
- return text;
- }
- }, {
- key: 'getTextAndFormat',
- value: function getTextAndFormat() {
- return this.rows;
- }
- }]);
- return CaptionScreen;
- }();
- // var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
- var Cea608Channel = function () {
- function Cea608Channel(channelNumber, outputFilter) {
- _classCallCheck(this, Cea608Channel);
- this.chNr = channelNumber;
- this.outputFilter = outputFilter;
- this.mode = null;
- this.verbose = 0;
- this.displayedMemory = new CaptionScreen();
- this.nonDisplayedMemory = new CaptionScreen();
- this.lastOutputScreen = new CaptionScreen();
- this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
- this.writeScreen = this.displayedMemory;
- this.mode = null;
- this.cueStartTime = null; // Keeps track of where a cue started.
- }
- _createClass(Cea608Channel, [{
- key: 'reset',
- value: function reset() {
- this.mode = null;
- this.displayedMemory.reset();
- this.nonDisplayedMemory.reset();
- this.lastOutputScreen.reset();
- this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
- this.writeScreen = this.displayedMemory;
- this.mode = null;
- this.cueStartTime = null;
- this.lastCueEndTime = null;
- }
- }, {
- key: 'getHandler',
- value: function getHandler() {
- return this.outputFilter;
- }
- }, {
- key: 'setHandler',
- value: function setHandler(newHandler) {
- this.outputFilter = newHandler;
- }
- }, {
- key: 'setPAC',
- value: function setPAC(pacData) {
- this.writeScreen.setPAC(pacData);
- }
- }, {
- key: 'setBkgData',
- value: function setBkgData(bkgData) {
- this.writeScreen.setBkgData(bkgData);
- }
- }, {
- key: 'setMode',
- value: function setMode(newMode) {
- if (newMode === this.mode) {
- return;
- }
- this.mode = newMode;
- logger.log('INFO', 'MODE=' + newMode);
- if (this.mode === 'MODE_POP-ON') {
- this.writeScreen = this.nonDisplayedMemory;
- } else {
- this.writeScreen = this.displayedMemory;
- this.writeScreen.reset();
- }
- if (this.mode !== 'MODE_ROLL-UP') {
- this.displayedMemory.nrRollUpRows = null;
- this.nonDisplayedMemory.nrRollUpRows = null;
- }
- this.mode = newMode;
- }
- }, {
- key: 'insertChars',
- value: function insertChars(chars) {
- for (var i = 0; i < chars.length; i++) {
- this.writeScreen.insertChar(chars[i]);
- }
- var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';
- logger.log('INFO', screen + ': ' + this.writeScreen.getDisplayText(true));
- if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
- logger.log('TEXT', 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));
- this.outputDataUpdate();
- }
- }
- }, {
- key: 'ccRCL',
- value: function ccRCL() {
- // Resume Caption Loading (switch mode to Pop On)
- logger.log('INFO', 'RCL - Resume Caption Loading');
- this.setMode('MODE_POP-ON');
- }
- }, {
- key: 'ccBS',
- value: function ccBS() {
- // BackSpace
- logger.log('INFO', 'BS - BackSpace');
- if (this.mode === 'MODE_TEXT') {
- return;
- }
- this.writeScreen.backSpace();
- if (this.writeScreen === this.displayedMemory) {
- this.outputDataUpdate();
- }
- }
- }, {
- key: 'ccAOF',
- value: function ccAOF() {// Reserved (formerly Alarm Off)
- }
- }, {
- key: 'ccAON',
- value: function ccAON() {// Reserved (formerly Alarm On)
- }
- }, {
- key: 'ccDER',
- value: function ccDER() {
- // Delete to End of Row
- logger.log('INFO', 'DER- Delete to End of Row');
- this.writeScreen.clearToEndOfRow();
- this.outputDataUpdate();
- }
- }, {
- key: 'ccRU',
- value: function ccRU(nrRows) {
- // Roll-Up Captions-2,3,or 4 Rows
- logger.log('INFO', 'RU(' + nrRows + ') - Roll Up');
- this.writeScreen = this.displayedMemory;
- this.setMode('MODE_ROLL-UP');
- this.writeScreen.setRollUpRows(nrRows);
- }
- }, {
- key: 'ccFON',
- value: function ccFON() {
- // Flash On
- logger.log('INFO', 'FON - Flash On');
- this.writeScreen.setPen({ flash: true });
- }
- }, {
- key: 'ccRDC',
- value: function ccRDC() {
- // Resume Direct Captioning (switch mode to PaintOn)
- logger.log('INFO', 'RDC - Resume Direct Captioning');
- this.setMode('MODE_PAINT-ON');
- }
- }, {
- key: 'ccTR',
- value: function ccTR() {
- // Text Restart in text mode (not supported, however)
- logger.log('INFO', 'TR');
- this.setMode('MODE_TEXT');
- }
- }, {
- key: 'ccRTD',
- value: function ccRTD() {
- // Resume Text Display in Text mode (not supported, however)
- logger.log('INFO', 'RTD');
- this.setMode('MODE_TEXT');
- }
- }, {
- key: 'ccEDM',
- value: function ccEDM() {
- // Erase Displayed Memory
- logger.log('INFO', 'EDM - Erase Displayed Memory');
- this.displayedMemory.reset();
- this.outputDataUpdate(true);
- }
- }, {
- key: 'ccCR',
- value: function ccCR() {
- // Carriage Return
- logger.log('CR - Carriage Return');
- this.writeScreen.rollUp();
- this.outputDataUpdate(true);
- }
- }, {
- key: 'ccENM',
- value: function ccENM() {
- // Erase Non-Displayed Memory
- logger.log('INFO', 'ENM - Erase Non-displayed Memory');
- this.nonDisplayedMemory.reset();
- }
- }, {
- key: 'ccEOC',
- value: function ccEOC() {
- // End of Caption (Flip Memories)
- logger.log('INFO', 'EOC - End Of Caption');
- if (this.mode === 'MODE_POP-ON') {
- var tmp = this.displayedMemory;
- this.displayedMemory = this.nonDisplayedMemory;
- this.nonDisplayedMemory = tmp;
- this.writeScreen = this.nonDisplayedMemory;
- logger.log('TEXT', 'DISP: ' + this.displayedMemory.getDisplayText());
- }
- this.outputDataUpdate(true);
- }
- }, {
- key: 'ccTO',
- value: function ccTO(nrCols) {
- // Tab Offset 1,2, or 3 columns
- logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset');
- this.writeScreen.moveCursor(nrCols);
- }
- }, {
- key: 'ccMIDROW',
- value: function ccMIDROW(secondByte) {
- // Parse MIDROW command
- var styles = { flash: false };
- styles.underline = secondByte % 2 === 1;
- styles.italics = secondByte >= 0x2e;
- if (!styles.italics) {
- var colorIndex = Math.floor(secondByte / 2) - 0x10;
- var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];
- styles.foreground = colors[colorIndex];
- } else {
- styles.foreground = 'white';
- }
- logger.log('INFO', 'MIDROW: ' + JSON.stringify(styles));
- this.writeScreen.setPen(styles);
- }
- }, {
- key: 'outputDataUpdate',
- value: function outputDataUpdate() {
- var dispatch = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
- var t = logger.time;
- if (t === null) {
- return;
- }
- if (this.outputFilter) {
- if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
- // Start of a new cue
- this.cueStartTime = t;
- } else {
- if (!this.displayedMemory.equals(this.lastOutputScreen)) {
- if (this.outputFilter.newCue) {
- this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen);
- if (dispatch === true && this.outputFilter.dispatchCue) {
- this.outputFilter.dispatchCue();
- }
- }
- this.cueStartTime = this.displayedMemory.isEmpty() ? null : t;
- }
- }
- this.lastOutputScreen.copy(this.displayedMemory);
- }
- }
- }, {
- key: 'cueSplitAtTime',
- value: function cueSplitAtTime(t) {
- if (this.outputFilter) {
- if (!this.displayedMemory.isEmpty()) {
- if (this.outputFilter.newCue) {
- this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
- }
- this.cueStartTime = t;
- }
- }
- }
- }]);
- return Cea608Channel;
- }();
- var Cea608Parser = function () {
- function Cea608Parser(field, out1, out2) {
- _classCallCheck(this, Cea608Parser);
- this.field = field || 1;
- this.outputs = [out1, out2];
- this.channels = [new Cea608Channel(1, out1), new Cea608Channel(2, out2)];
- this.currChNr = -1; // Will be 1 or 2
- this.lastCmdA = null; // First byte of last command
- this.lastCmdB = null; // Second byte of last command
- this.bufferedData = [];
- this.startTime = null;
- this.lastTime = null;
- this.dataCounters = { 'padding': 0, 'char': 0, 'cmd': 0, 'other': 0 };
- }
- _createClass(Cea608Parser, [{
- key: 'getHandler',
- value: function getHandler(index) {
- return this.channels[index].getHandler();
- }
- }, {
- key: 'setHandler',
- value: function setHandler(index, newHandler) {
- this.channels[index].setHandler(newHandler);
- }
- /**
- * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
- */
- }, {
- key: 'addData',
- value: function addData(t, byteList) {
- var cmdFound = void 0,
- a = void 0,
- b = void 0,
- charsFound = false;
- this.lastTime = t;
- logger.setTime(t);
- for (var i = 0; i < byteList.length; i += 2) {
- a = byteList[i] & 0x7f;
- b = byteList[i + 1] & 0x7f;
- if (a === 0 && b === 0) {
- this.dataCounters.padding += 2;
- continue;
- } else {
- logger.log('DATA', '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');
- }
- cmdFound = this.parseCmd(a, b);
- if (!cmdFound) {
- cmdFound = this.parseMidrow(a, b);
- }
- if (!cmdFound) {
- cmdFound = this.parsePAC(a, b);
- }
- if (!cmdFound) {
- cmdFound = this.parseBackgroundAttributes(a, b);
- }
- if (!cmdFound) {
- charsFound = this.parseChars(a, b);
- if (charsFound) {
- if (this.currChNr && this.currChNr >= 0) {
- var channel = this.channels[this.currChNr - 1];
- channel.insertChars(charsFound);
- } else {
- logger.log('WARNING', 'No channel found yet. TEXT-MODE?');
- }
- }
- }
- if (cmdFound) {
- this.dataCounters.cmd += 2;
- } else if (charsFound) {
- this.dataCounters.char += 2;
- } else {
- this.dataCounters.other += 2;
- logger.log('WARNING', 'Couldn\'t parse cleaned data ' + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));
- }
- }
- }
- /**
- * Parse Command.
- * @returns {Boolean} Tells if a command was found
- */
- }, {
- key: 'parseCmd',
- value: function parseCmd(a, b) {
- var chNr = null;
- var cond1 = (a === 0x14 || a === 0x1C) && b >= 0x20 && b <= 0x2F;
- var cond2 = (a === 0x17 || a === 0x1F) && b >= 0x21 && b <= 0x23;
- if (!(cond1 || cond2)) {
- return false;
- }
- if (a === this.lastCmdA && b === this.lastCmdB) {
- this.lastCmdA = null;
- this.lastCmdB = null; // Repeated commands are dropped (once)
- logger.log('DEBUG', 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');
- return true;
- }
- if (a === 0x14 || a === 0x17) {
- chNr = 1;
- } else {
- chNr = 2;
- } // (a === 0x1C || a=== 0x1f)
- var channel = this.channels[chNr - 1];
- if (a === 0x14 || a === 0x1C) {
- if (b === 0x20) {
- channel.ccRCL();
- } else if (b === 0x21) {
- channel.ccBS();
- } else if (b === 0x22) {
- channel.ccAOF();
- } else if (b === 0x23) {
- channel.ccAON();
- } else if (b === 0x24) {
- channel.ccDER();
- } else if (b === 0x25) {
- channel.ccRU(2);
- } else if (b === 0x26) {
- channel.ccRU(3);
- } else if (b === 0x27) {
- channel.ccRU(4);
- } else if (b === 0x28) {
- channel.ccFON();
- } else if (b === 0x29) {
- channel.ccRDC();
- } else if (b === 0x2A) {
- channel.ccTR();
- } else if (b === 0x2B) {
- channel.ccRTD();
- } else if (b === 0x2C) {
- channel.ccEDM();
- } else if (b === 0x2D) {
- channel.ccCR();
- } else if (b === 0x2E) {
- channel.ccENM();
- } else if (b === 0x2F) {
- channel.ccEOC();
- }
- } else {
- // a == 0x17 || a == 0x1F
- channel.ccTO(b - 0x20);
- }
- this.lastCmdA = a;
- this.lastCmdB = b;
- this.currChNr = chNr;
- return true;
- }
- /**
- * Parse midrow styling command
- * @returns {Boolean}
- */
- }, {
- key: 'parseMidrow',
- value: function parseMidrow(a, b) {
- var chNr = null;
- if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {
- if (a === 0x11) {
- chNr = 1;
- } else {
- chNr = 2;
- }
- if (chNr !== this.currChNr) {
- logger.log('ERROR', 'Mismatch channel in midrow parsing');
- return false;
- }
- var channel = this.channels[chNr - 1];
- channel.ccMIDROW(b);
- logger.log('DEBUG', 'MIDROW (' + numArrayToHexArray([a, b]) + ')');
- return true;
- }
- return false;
- }
- /**
- * Parse Preable Access Codes (Table 53).
- * @returns {Boolean} Tells if PAC found
- */
- }, {
- key: 'parsePAC',
- value: function parsePAC(a, b) {
- var chNr = null;
- var row = null;
- var case1 = (a >= 0x11 && a <= 0x17 || a >= 0x19 && a <= 0x1F) && b >= 0x40 && b <= 0x7F;
- var case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5F;
- if (!(case1 || case2)) {
- return false;
- }
- if (a === this.lastCmdA && b === this.lastCmdB) {
- this.lastCmdA = null;
- this.lastCmdB = null;
- return true; // Repeated commands are dropped (once)
- }
- chNr = a <= 0x17 ? 1 : 2;
- if (b >= 0x40 && b <= 0x5F) {
- row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
- } else {
- // 0x60 <= b <= 0x7F
- row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
- }
- var pacData = this.interpretPAC(row, b);
- var channel = this.channels[chNr - 1];
- channel.setPAC(pacData);
- this.lastCmdA = a;
- this.lastCmdB = b;
- this.currChNr = chNr;
- return true;
- }
- /**
- * Interpret the second byte of the pac, and return the information.
- * @returns {Object} pacData with style parameters.
- */
- }, {
- key: 'interpretPAC',
- value: function interpretPAC(row, byte) {
- var pacIndex = byte;
- var pacData = { color: null, italics: false, indent: null, underline: false, row: row };
- if (byte > 0x5F) {
- pacIndex = byte - 0x60;
- } else {
- pacIndex = byte - 0x40;
- }
- pacData.underline = (pacIndex & 1) === 1;
- if (pacIndex <= 0xd) {
- pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];
- } else if (pacIndex <= 0xf) {
- pacData.italics = true;
- pacData.color = 'white';
- } else {
- pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;
- }
- return pacData; // Note that row has zero offset. The spec uses 1.
- }
- /**
- * Parse characters.
- * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
- */
- }, {
- key: 'parseChars',
- value: function parseChars(a, b) {
- var channelNr = null,
- charCodes = null,
- charCode1 = null;
- if (a >= 0x19) {
- channelNr = 2;
- charCode1 = a - 8;
- } else {
- channelNr = 1;
- charCode1 = a;
- }
- if (charCode1 >= 0x11 && charCode1 <= 0x13) {
- // Special character
- var oneCode = b;
- if (charCode1 === 0x11) {
- oneCode = b + 0x50;
- } else if (charCode1 === 0x12) {
- oneCode = b + 0x70;
- } else {
- oneCode = b + 0x90;
- }
- logger.log('INFO', 'Special char \'' + getCharForByte(oneCode) + '\' in channel ' + channelNr);
- charCodes = [oneCode];
- } else if (a >= 0x20 && a <= 0x7f) {
- charCodes = b === 0 ? [a] : [a, b];
- }
- if (charCodes) {
- var hexCodes = numArrayToHexArray(charCodes);
- logger.log('DEBUG', 'Char codes = ' + hexCodes.join(','));
- this.lastCmdA = null;
- this.lastCmdB = null;
- }
- return charCodes;
- }
- /**
- * Parse extended background attributes as well as new foreground color black.
- * @returns{Boolean} Tells if background attributes are found
- */
- }, {
- key: 'parseBackgroundAttributes',
- value: function parseBackgroundAttributes(a, b) {
- var bkgData = void 0,
- index = void 0,
- chNr = void 0,
- channel = void 0;
- var case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;
- var case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;
- if (!(case1 || case2)) {
- return false;
- }
- bkgData = {};
- if (a === 0x10 || a === 0x18) {
- index = Math.floor((b - 0x20) / 2);
- bkgData.background = backgroundColors[index];
- if (b % 2 === 1) {
- bkgData.background = bkgData.background + '_semi';
- }
- } else if (b === 0x2d) {
- bkgData.background = 'transparent';
- } else {
- bkgData.foreground = 'black';
- if (b === 0x2f) {
- bkgData.underline = true;
- }
- }
- chNr = a < 0x18 ? 1 : 2;
- channel = this.channels[chNr - 1];
- channel.setBkgData(bkgData);
- this.lastCmdA = null;
- this.lastCmdB = null;
- return true;
- }
- /**
- * Reset state of parser and its channels.
- */
- }, {
- key: 'reset',
- value: function reset() {
- for (var i = 0; i < this.channels.length; i++) {
- if (this.channels[i]) {
- this.channels[i].reset();
- }
- }
- this.lastCmdA = null;
- this.lastCmdB = null;
- }
- /**
- * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
- */
- }, {
- key: 'cueSplitAtTime',
- value: function cueSplitAtTime(t) {
- for (var i = 0; i < this.channels.length; i++) {
- if (this.channels[i]) {
- this.channels[i].cueSplitAtTime(t);
- }
- }
- }
- }]);
- return Cea608Parser;
- }();
- exports.default = Cea608Parser;
- module.exports = exports['default'];
- /***/ }),
- /* 74 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var OutputFilter = function () {
- function OutputFilter(timelineController, trackName) {
- _classCallCheck(this, OutputFilter);
- this.timelineController = timelineController;
- this.trackName = trackName;
- this.startTime = null;
- this.endTime = null;
- this.screen = null;
- }
- _createClass(OutputFilter, [{
- key: "dispatchCue",
- value: function dispatchCue() {
- if (this.startTime === null) {
- return;
- }
- this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen);
- this.startTime = null;
- }
- }, {
- key: "newCue",
- value: function newCue(startTime, endTime, screen) {
- if (this.startTime === null || this.startTime > startTime) {
- this.startTime = startTime;
- }
- this.endTime = endTime;
- this.screen = screen;
- this.timelineController.createCaptionsTrack(this.trackName);
- }
- }]);
- return OutputFilter;
- }();
- exports.default = OutputFilter;
- module.exports = exports["default"];
- /***/ }),
- /* 75 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var _vttparser = __webpack_require__(30);
- var _vttparser2 = _interopRequireDefault(_vttparser);
- var _id = __webpack_require__(10);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- // String.prototype.startsWith is not supported in IE11
- var startsWith = function startsWith(inputString, searchString, position) {
- return inputString.substr(position || 0, searchString.length) === searchString;
- };
- var cueString2millis = function cueString2millis(timeString) {
- var ts = parseInt(timeString.substr(-3));
- var secs = parseInt(timeString.substr(-6, 2));
- var mins = parseInt(timeString.substr(-9, 2));
- var hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;
- if (!Number.isFinite(ts) || !Number.isFinite(secs) || !Number.isFinite(mins) || !Number.isFinite(hours)) {
- return -1;
- }
- ts += 1000 * secs;
- ts += 60 * 1000 * mins;
- ts += 60 * 60 * 1000 * hours;
- return ts;
- };
- // From https://github.com/darkskyapp/string-hash
- var hash = function hash(text) {
- var hash = 5381;
- var i = text.length;
- while (i) {
- hash = hash * 33 ^ text.charCodeAt(--i);
- }
- return (hash >>> 0).toString();
- };
- var calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {
- var currCC = vttCCs[cc];
- var prevCC = vttCCs[currCC.prevCC];
- // This is the first discontinuity or cues have been processed since the last discontinuity
- // Offset = current discontinuity time
- if (!prevCC || !prevCC.new && currCC.new) {
- vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
- currCC.new = false;
- return;
- }
- // There have been discontinuities since cues were last parsed.
- // Offset = time elapsed
- while (prevCC && prevCC.new) {
- vttCCs.ccOffset += currCC.start - prevCC.start;
- currCC.new = false;
- currCC = prevCC;
- prevCC = vttCCs[currCC.prevCC];
- }
- vttCCs.presentationOffset = presentationTime;
- };
- var WebVTTParser = {
- parse: function parse(vttByteArray, syncPTS, vttCCs, cc, callBack, errorCallBack) {
- // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character.
- var re = /\r\n|\n\r|\n|\r/g;
- // Uint8Array.prototype.reduce is not implemented in IE11
- var vttLines = (0, _id.utf8ArrayToStr)(new Uint8Array(vttByteArray)).trim().replace(re, '\n').split('\n');
- var cueTime = '00:00.000';
- var mpegTs = 0;
- var localTime = 0;
- var presentationTime = 0;
- var cues = [];
- var parsingError = void 0;
- var inHeader = true;
- // let VTTCue = VTTCue || window.TextTrackCue;
- // Create parser object using VTTCue with TextTrackCue fallback on certain browsers.
- var parser = new _vttparser2.default();
- parser.oncue = function (cue) {
- // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.
- var currCC = vttCCs[cc];
- var cueOffset = vttCCs.ccOffset;
- // Update offsets for new discontinuities
- if (currCC && currCC.new) {
- if (localTime !== undefined) {
- // When local time is provided, offset = discontinuity start time - local time
- cueOffset = vttCCs.ccOffset = currCC.start;
- } else {
- calculateOffset(vttCCs, cc, presentationTime);
- }
- }
- if (presentationTime) {
- // If we have MPEGTS, offset = presentation time + discontinuity offset
- cueOffset = presentationTime - vttCCs.presentationOffset;
- }
- cue.startTime += cueOffset - localTime;
- cue.endTime += cueOffset - localTime;
- // Create a unique hash id for a cue based on start/end times and text.
- // This helps timeline-controller to avoid showing repeated captions.
- cue.id = hash(cue.startTime.toString()) + hash(cue.endTime.toString()) + hash(cue.text);
- // Fix encoding of special characters. TODO: Test with all sorts of weird characters.
- cue.text = decodeURIComponent(encodeURIComponent(cue.text));
- if (cue.endTime > 0) {
- cues.push(cue);
- }
- };
- parser.onparsingerror = function (e) {
- parsingError = e;
- };
- parser.onflush = function () {
- if (parsingError && errorCallBack) {
- errorCallBack(parsingError);
- return;
- }
- callBack(cues);
- };
- // Go through contents line by line.
- vttLines.forEach(function (line) {
- if (inHeader) {
- // Look for X-TIMESTAMP-MAP in header.
- if (startsWith(line, 'X-TIMESTAMP-MAP=')) {
- // Once found, no more are allowed anyway, so stop searching.
- inHeader = false;
- // Extract LOCAL and MPEGTS.
- line.substr(16).split(',').forEach(function (timestamp) {
- if (startsWith(timestamp, 'LOCAL:')) {
- cueTime = timestamp.substr(6);
- } else if (startsWith(timestamp, 'MPEGTS:')) {
- mpegTs = parseInt(timestamp.substr(7));
- }
- });
- try {
- // Calculate subtitle offset in milliseconds.
- if (syncPTS + (vttCCs[cc].start * 90000 || 0) < 0) {
- syncPTS += 8589934592;
- }
- // Adjust MPEGTS by sync PTS.
- mpegTs -= syncPTS;
- // Convert cue time to seconds
- localTime = cueString2millis(cueTime) / 1000;
- // Convert MPEGTS to seconds from 90kHz.
- presentationTime = mpegTs / 90000;
- if (localTime === -1) {
- parsingError = new Error('Malformed X-TIMESTAMP-MAP: ' + line);
- }
- } catch (e) {
- parsingError = new Error('Malformed X-TIMESTAMP-MAP: ' + line);
- }
- // Return without parsing X-TIMESTAMP-MAP line.
- return;
- } else if (line === '') {
- inHeader = false;
- }
- }
- // Parse line by default.
- parser.parse(line + '\n');
- });
- parser.flush();
- }
- };
- exports.default = WebVTTParser;
- module.exports = exports['default'];
- /***/ }),
- /* 76 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _eventHandler = __webpack_require__(3);
- var _eventHandler2 = _interopRequireDefault(_eventHandler);
- var _logger = __webpack_require__(0);
- var _levelHelper = __webpack_require__(7);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; }
- var SubtitleTrackController = function (_EventHandler) {
- _inherits(SubtitleTrackController, _EventHandler);
- function SubtitleTrackController(hls) {
- _classCallCheck(this, SubtitleTrackController);
- 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));
- _this.tracks = [];
- _this.trackId = -1;
- _this.media = null;
- _this.stopped = true;
- /**
- * @member {boolean} subtitleDisplay Enable/disable subtitle display rendering
- */
- _this.subtitleDisplay = true;
- return _this;
- }
- _createClass(SubtitleTrackController, [{
- key: 'destroy',
- value: function destroy() {
- _eventHandler2.default.prototype.destroy.call(this);
- }
- // Listen for subtitle track change, then extract the current track ID.
- }, {
- key: 'onMediaAttached',
- value: function onMediaAttached(data) {
- var _this2 = this;
- this.media = data.media;
- if (!this.media) {
- return;
- }
- if (this.queuedDefaultTrack) {
- this.subtitleTrack = this.queuedDefaultTrack;
- delete this.queuedDefaultTrack;
- }
- this.trackChangeListener = this._onTextTracksChanged.bind(this);
- this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);
- if (this.useTextTrackPolling) {
- this.subtitlePollingInterval = setInterval(function () {
- _this2.trackChangeListener();
- }, 500);
- } else {
- this.media.textTracks.addEventListener('change', this.trackChangeListener);
- }
- }
- }, {
- key: 'onMediaDetaching',
- value: function onMediaDetaching() {
- if (!this.media) {
- return;
- }
- if (this.useTextTrackPolling) {
- clearInterval(this.subtitlePollingInterval);
- } else {
- this.media.textTracks.removeEventListener('change', this.trackChangeListener);
- }
- this.media = null;
- }
- // Fired whenever a new manifest is loaded.
- }, {
- key: 'onManifestLoaded',
- value: function onManifestLoaded(data) {
- var _this3 = this;
- var tracks = data.subtitles || [];
- this.tracks = tracks;
- this.hls.trigger(_events2.default.SUBTITLE_TRACKS_UPDATED, { subtitleTracks: tracks });
- // loop through available subtitle tracks and autoselect default if needed
- // TODO: improve selection logic to handle forced, etc
- tracks.forEach(function (track) {
- if (track.default) {
- // setting this.subtitleTrack will trigger internal logic
- // if media has not been attached yet, it will fail
- // we keep a reference to the default track id
- // and we'll set subtitleTrack when onMediaAttached is triggered
- if (_this3.media) {
- _this3.subtitleTrack = track.id;
- } else {
- _this3.queuedDefaultTrack = track.id;
- }
- }
- });
- }
- }, {
- key: 'onSubtitleTrackLoaded',
- value: function onSubtitleTrackLoaded(data) {
- var _this4 = this;
- var id = data.id,
- details = data.details;
- var trackId = this.trackId,
- tracks = this.tracks;
- var currentTrack = tracks[trackId];
- if (id >= tracks.length || id !== trackId || !currentTrack || this.stopped) {
- this._clearReloadTimer();
- return;
- }
- _logger.logger.log('subtitle track ' + id + ' loaded');
- if (details.live) {
- var reloadInterval = (0, _levelHelper.computeReloadInterval)(currentTrack.details, details, data.stats.trequest);
- _logger.logger.log('Reloading live subtitle playlist in ' + reloadInterval + 'ms');
- this.timer = setTimeout(function () {
- _this4._loadCurrentTrack();
- }, reloadInterval);
- } else {
- this._clearReloadTimer();
- }
- }
- }, {
- key: 'startLoad',
- value: function startLoad() {
- this.stopped = false;
- this._loadCurrentTrack();
- }
- }, {
- key: 'stopLoad',
- value: function stopLoad() {
- this.stopped = true;
- this._clearReloadTimer();
- }
- /** get alternate subtitle tracks list from playlist **/
- }, {
- key: '_clearReloadTimer',
- value: function _clearReloadTimer() {
- if (this.timer) {
- clearTimeout(this.timer);
- this.timer = null;
- }
- }
- }, {
- key: '_loadCurrentTrack',
- value: function _loadCurrentTrack() {
- var trackId = this.trackId,
- tracks = this.tracks,
- hls = this.hls;
- var currentTrack = tracks[trackId];
- if (trackId < 0 || !currentTrack || currentTrack.details && !currentTrack.details.live) {
- return;
- }
- _logger.logger.log('Loading subtitle track ' + trackId);
- hls.trigger(_events2.default.SUBTITLE_TRACK_LOADING, { url: currentTrack.url, id: trackId });
- }
- /**
- * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
- * This operates on the DOM textTracks.
- * A value of -1 will disable all subtitle tracks.
- * @param newId - The id of the next track to enable
- * @private
- */
- }, {
- key: '_toggleTrackModes',
- value: function _toggleTrackModes(newId) {
- var media = this.media,
- subtitleDisplay = this.subtitleDisplay,
- trackId = this.trackId;
- if (!media) {
- return;
- }
- var textTracks = filterSubtitleTracks(media.textTracks);
- if (newId === -1) {
- [].slice.call(textTracks).forEach(function (track) {
- track.mode = 'disabled';
- });
- } else {
- var oldTrack = textTracks[trackId];
- if (oldTrack) {
- oldTrack.mode = 'disabled';
- }
- }
- var nextTrack = textTracks[newId];
- if (nextTrack) {
- nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden';
- }
- }
- /**
- * This method is responsible for validating the subtitle index and periodically reloading if live.
- * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
- * @param newId - The id of the subtitle track to activate.
- */
- }, {
- key: '_setSubtitleTrackInternal',
- value: function _setSubtitleTrackInternal(newId) {
- var hls = this.hls,
- tracks = this.tracks;
- if (!Number.isFinite(newId) || newId < -1 || newId >= tracks.length) {
- return;
- }
- this.trackId = newId;
- _logger.logger.log('Switching to subtitle track ' + newId);
- hls.trigger(_events2.default.SUBTITLE_TRACK_SWITCH, { id: newId });
- this._loadCurrentTrack();
- }
- }, {
- key: '_onTextTracksChanged',
- value: function _onTextTracksChanged() {
- // Media is undefined when switching streams via loadSource()
- if (!this.media) {
- return;
- }
- var trackId = -1;
- var tracks = filterSubtitleTracks(this.media.textTracks);
- for (var id = 0; id < tracks.length; id++) {
- if (tracks[id].mode === 'hidden') {
- // Do not break in case there is a following track with showing.
- trackId = id;
- } else if (tracks[id].mode === 'showing') {
- trackId = id;
- break;
- }
- }
- // Setting current subtitleTrack will invoke code.
- this.subtitleTrack = trackId;
- }
- }, {
- key: 'subtitleTracks',
- get: function get() {
- return this.tracks;
- }
- /** get index of the selected subtitle track (index in subtitle track lists) **/
- }, {
- key: 'subtitleTrack',
- get: function get() {
- return this.trackId;
- }
- /** select a subtitle track, based on its index in subtitle track lists**/
- ,
- set: function set(subtitleTrackId) {
- if (this.trackId !== subtitleTrackId) {
- this._toggleTrackModes(subtitleTrackId);
- this._setSubtitleTrackInternal(subtitleTrackId);
- }
- }
- }]);
- return SubtitleTrackController;
- }(_eventHandler2.default);
- function filterSubtitleTracks(textTrackList) {
- var tracks = [];
- for (var i = 0; i < textTrackList.length; i++) {
- var track = textTrackList[i];
- // Edge adds a track without a label; we don't want to use it
- if (track.kind === 'subtitles' && track.label) {
- tracks.push(textTrackList[i]);
- }
- }
- return tracks;
- }
- exports.default = SubtitleTrackController;
- module.exports = exports['default'];
- /***/ }),
- /* 77 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.SubtitleStreamController = undefined;
- 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; }; }();
- 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); } };
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _logger = __webpack_require__(0);
- var _decrypter = __webpack_require__(12);
- var _decrypter2 = _interopRequireDefault(_decrypter);
- var _bufferHelper = __webpack_require__(4);
- var _fragmentFinders = __webpack_require__(27);
- var _fragmentTracker = __webpack_require__(6);
- var _baseStreamController = __webpack_require__(14);
- var _baseStreamController2 = _interopRequireDefault(_baseStreamController);
- var _levelHelper = __webpack_require__(7);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /**
- * @class SubtitleStreamController
- */
- var _window = window,
- performance = _window.performance;
- var TICK_INTERVAL = 500; // how often to tick in ms
- var SubtitleStreamController = exports.SubtitleStreamController = function (_BaseStreamController) {
- _inherits(SubtitleStreamController, _BaseStreamController);
- function SubtitleStreamController(hls, fragmentTracker) {
- _classCallCheck(this, SubtitleStreamController);
- 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));
- _this.fragmentTracker = fragmentTracker;
- _this.config = hls.config;
- _this.state = _baseStreamController.State.STOPPED;
- _this.tracks = [];
- _this.tracksBuffered = [];
- _this.currentTrackId = -1;
- _this.decrypter = new _decrypter2.default(hls, hls.config);
- // lastAVStart stores the time in seconds for the start time of a level load
- _this.lastAVStart = 0;
- _this._onMediaSeeking = _this.onMediaSeeking.bind(_this);
- return _this;
- }
- _createClass(SubtitleStreamController, [{
- key: 'onSubtitleFragProcessed',
- value: function onSubtitleFragProcessed(data) {
- var frag = data.frag,
- success = data.success;
- this.fragPrevious = frag;
- this.state = _baseStreamController.State.IDLE;
- if (!success) {
- return;
- }
- var buffered = this.tracksBuffered[this.currentTrackId];
- if (!buffered) {
- return;
- }
- // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo
- // so we can re-use the logic used to detect how much have been buffered
- var timeRange = void 0;
- var fragStart = frag.start;
- for (var i = 0; i < buffered.length; i++) {
- if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
- timeRange = buffered[i];
- break;
- }
- }
- var fragEnd = frag.start + frag.duration;
- if (timeRange) {
- timeRange.end = fragEnd;
- } else {
- timeRange = {
- start: fragStart,
- end: fragEnd
- };
- buffered.push(timeRange);
- }
- }
- }, {
- key: 'onMediaAttached',
- value: function onMediaAttached(_ref) {
- var media = _ref.media;
- this.media = media;
- media.addEventListener('seeking', this._onMediaSeeking);
- this.state = _baseStreamController.State.IDLE;
- }
- }, {
- key: 'onMediaDetaching',
- value: function onMediaDetaching() {
- this.media.removeEventListener('seeking', this._onMediaSeeking);
- this.media = null;
- this.state = _baseStreamController.State.STOPPED;
- }
- // If something goes wrong, proceed to next frag, if we were processing one.
- }, {
- key: 'onError',
- value: function onError(data) {
- var frag = data.frag;
- // don't handle error not related to subtitle fragment
- if (!frag || frag.type !== 'subtitle') {
- return;
- }
- this.state = _baseStreamController.State.IDLE;
- }
- // Got all new subtitle tracks.
- }, {
- key: 'onSubtitleTracksUpdated',
- value: function onSubtitleTracksUpdated(data) {
- var _this2 = this;
- _logger.logger.log('subtitle tracks updated');
- this.tracksBuffered = [];
- this.tracks = data.subtitleTracks;
- this.tracks.forEach(function (track) {
- _this2.tracksBuffered[track.id] = [];
- });
- }
- }, {
- key: 'onSubtitleTrackSwitch',
- value: function onSubtitleTrackSwitch(data) {
- this.currentTrackId = data.id;
- if (!this.tracks || this.currentTrackId === -1) {
- this.clearInterval();
- return;
- }
- // Check if track has the necessary details to load fragments
- var currentTrack = this.tracks[this.currentTrackId];
- if (currentTrack && currentTrack.details) {
- this.setInterval(TICK_INTERVAL);
- }
- }
- // Got a new set of subtitle fragments.
- }, {
- key: 'onSubtitleTrackLoaded',
- value: function onSubtitleTrackLoaded(data) {
- var id = data.id,
- details = data.details;
- var currentTrackId = this.currentTrackId,
- tracks = this.tracks;
- var currentTrack = tracks[currentTrackId];
- if (id >= tracks.length || id !== currentTrackId || !currentTrack) {
- return;
- }
- if (details.live) {
- (0, _levelHelper.mergeSubtitlePlaylists)(currentTrack.details, details, this.lastAVStart);
- }
- currentTrack.details = details;
- this.setInterval(TICK_INTERVAL);
- }
- }, {
- key: 'onKeyLoaded',
- value: function onKeyLoaded() {
- if (this.state === _baseStreamController.State.KEY_LOADING) {
- this.state = _baseStreamController.State.IDLE;
- }
- }
- }, {
- key: 'onFragLoaded',
- value: function onFragLoaded(data) {
- var fragCurrent = this.fragCurrent;
- var decryptData = data.frag.decryptdata;
- var fragLoaded = data.frag;
- var hls = this.hls;
- if (this.state === _baseStreamController.State.FRAG_LOADING && fragCurrent && data.frag.type === 'subtitle' && fragCurrent.sn === data.frag.sn) {
- // check to see if the payload needs to be decrypted
- if (data.payload.byteLength > 0 && decryptData && decryptData.key && decryptData.method === 'AES-128') {
- var startTime = performance.now();
- // decrypt the subtitles
- this.decrypter.decrypt(data.payload, decryptData.key.buffer, decryptData.iv.buffer, function (decryptedData) {
- var endTime = performance.now();
- hls.trigger(_events2.default.FRAG_DECRYPTED, { frag: fragLoaded, payload: decryptedData, stats: { tstart: startTime, tdecrypt: endTime } });
- });
- }
- }
- }
- }, {
- key: 'onLevelUpdated',
- value: function onLevelUpdated(_ref2) {
- var details = _ref2.details;
- var frags = details.fragments;
- this.lastAVStart = frags.length ? frags[0].start : 0;
- }
- }, {
- key: 'doTick',
- value: function doTick() {
- if (!this.media) {
- this.state = _baseStreamController.State.IDLE;
- return;
- }
- switch (this.state) {
- case _baseStreamController.State.IDLE:
- {
- var config = this.config,
- currentTrackId = this.currentTrackId,
- fragmentTracker = this.fragmentTracker,
- media = this.media,
- tracks = this.tracks;
- if (!tracks || !tracks[currentTrackId] || !tracks[currentTrackId].details) {
- break;
- }
- var maxBufferHole = config.maxBufferHole,
- maxFragLookUpTolerance = config.maxFragLookUpTolerance;
- var maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);
- var bufferedInfo = _bufferHelper.BufferHelper.bufferedInfo(this._getBuffered(), media.currentTime, maxBufferHole);
- var bufferEnd = bufferedInfo.end,
- bufferLen = bufferedInfo.len;
- var trackDetails = tracks[currentTrackId].details;
- var fragments = trackDetails.fragments;
- var fragLen = fragments.length;
- var end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration;
- if (bufferLen > maxConfigBuffer) {
- return;
- }
- var foundFrag = void 0;
- var fragPrevious = this.fragPrevious;
- if (bufferEnd < end) {
- if (fragPrevious && trackDetails.hasProgramDateTime) {
- foundFrag = (0, _fragmentFinders.findFragmentByPDT)(fragments, fragPrevious.endProgramDateTime, maxFragLookUpTolerance);
- }
- if (!foundFrag) {
- foundFrag = (0, _fragmentFinders.findFragmentByPTS)(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance);
- }
- } else {
- foundFrag = fragments[fragLen - 1];
- }
- if (foundFrag && foundFrag.encrypted) {
- _logger.logger.log('Loading key for ' + foundFrag.sn);
- this.state = _baseStreamController.State.KEY_LOADING;
- this.hls.trigger(_events2.default.KEY_LOADING, { frag: foundFrag });
- } else if (foundFrag && fragmentTracker.getState(foundFrag) === _fragmentTracker.FragmentState.NOT_LOADED) {
- // only load if fragment is not loaded
- this.fragCurrent = foundFrag;
- this.state = _baseStreamController.State.FRAG_LOADING;
- this.hls.trigger(_events2.default.FRAG_LOADING, { frag: foundFrag });
- }
- }
- }
- }
- }, {
- key: 'stopLoad',
- value: function stopLoad() {
- this.lastAVStart = 0;
- _get(SubtitleStreamController.prototype.__proto__ || Object.getPrototypeOf(SubtitleStreamController.prototype), 'stopLoad', this).call(this);
- }
- }, {
- key: '_getBuffered',
- value: function _getBuffered() {
- return this.tracksBuffered[this.currentTrackId] || [];
- }
- }, {
- key: 'onMediaSeeking',
- value: function onMediaSeeking() {
- this.fragPrevious = null;
- }
- }]);
- return SubtitleStreamController;
- }(_baseStreamController2.default);
- /***/ }),
- /* 78 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _eventHandler = __webpack_require__(3);
- var _eventHandler2 = _interopRequireDefault(_eventHandler);
- var _events = __webpack_require__(1);
- var _events2 = _interopRequireDefault(_events);
- var _errors = __webpack_require__(2);
- var _logger = __webpack_require__(0);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /**
- * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>
- *
- * DRM support for Hls.js
- */
- var _window = window,
- XMLHttpRequest = _window.XMLHttpRequest;
- var MAX_LICENSE_REQUEST_FAILURES = 3;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess
- */
- var KeySystems = {
- WIDEVINE: 'com.widevine.alpha',
- PLAYREADY: 'com.microsoft.playready'
- };
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration
- * @param {Array<string>} audioCodecs List of required audio codecs to support
- * @param {Array<string>} videoCodecs List of required video codecs to support
- * @param {object} drmSystemOptions Optional parameters/requirements for the key-system
- * @returns {Array<MediaSystemConfiguration>} An array of supported configurations
- */
- var createWidevineMediaKeySystemConfigurations = function createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions) {
- /* jshint ignore:line */
- var baseConfig = {
- // initDataTypes: ['keyids', 'mp4'],
- // label: "",
- // persistentState: "not-allowed", // or "required" ?
- // distinctiveIdentifier: "not-allowed", // or "required" ?
- // sessionTypes: ['temporary'],
- videoCapabilities: [
- // { contentType: 'video/mp4; codecs="avc1.42E01E"' }
- ]
- };
- videoCodecs.forEach(function (codec) {
- baseConfig.videoCapabilities.push({
- contentType: 'video/mp4; codecs="' + codec + '"'
- });
- });
- return [baseConfig];
- };
- /**
- * The idea here is to handle key-system (and their respective platforms) specific configuration differences
- * in order to work with the local requestMediaKeySystemAccess method.
- *
- * We can also rule-out platform-related key-system support at this point by throwing an error or returning null.
- *
- * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
- * @param {Array<string>} audioCodecs List of required audio codecs to support
- * @param {Array<string>} videoCodecs List of required video codecs to support
- * @returns {Array<MediaSystemConfiguration> | null} A non-empty Array of MediaKeySystemConfiguration objects or `null`
- */
- var getSupportedMediaKeySystemConfigurations = function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs) {
- switch (keySystem) {
- case KeySystems.WIDEVINE:
- return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs);
- default:
- throw Error('Unknown key-system: ' + keySystem);
- }
- };
- /**
- * Controller to deal with encrypted media extensions (EME)
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API
- *
- * @class
- * @constructor
- */
- var EMEController = function (_EventHandler) {
- _inherits(EMEController, _EventHandler);
- /**
- * @constructs
- * @param {Hls} hls Our Hls.js instance
- */
- function EMEController(hls) {
- _classCallCheck(this, EMEController);
- var _this = _possibleConstructorReturn(this, (EMEController.__proto__ || Object.getPrototypeOf(EMEController)).call(this, hls, _events2.default.MEDIA_ATTACHED, _events2.default.MANIFEST_PARSED));
- _this._widevineLicenseUrl = hls.config.widevineLicenseUrl;
- _this._licenseXhrSetup = hls.config.licenseXhrSetup;
- _this._emeEnabled = hls.config.emeEnabled;
- _this._requestMediaKeySystemAccess = hls.config.requestMediaKeySystemAccessFunc;
- _this._mediaKeysList = [];
- _this._media = null;
- _this._hasSetMediaKeys = false;
- _this._isMediaEncrypted = false;
- _this._requestLicenseFailureCount = 0;
- return _this;
- }
- /**
- *
- * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
- * @returns {string} License server URL for key-system (if any configured, otherwise causes error)
- */
- _createClass(EMEController, [{
- key: 'getLicenseServerUrl',
- value: function getLicenseServerUrl(keySystem) {
- var url = void 0;
- switch (keySystem) {
- case KeySystems.WIDEVINE:
- url = this._widevineLicenseUrl;
- break;
- default:
- url = null;
- break;
- }
- if (!url) {
- _logger.logger.error('No license server URL configured for key-system "' + keySystem + '"');
- this.hls.trigger(_events2.default.ERROR, {
- type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
- details: _errors.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
- fatal: true
- });
- }
- return url;
- }
- /**
- * Requests access object and adds it to our list upon success
- * @private
- * @param {string} keySystem System ID (see `KeySystems`)
- * @param {Array<string>} audioCodecs List of required audio codecs to support
- * @param {Array<string>} videoCodecs List of required video codecs to support
- */
- }, {
- key: '_attemptKeySystemAccess',
- value: function _attemptKeySystemAccess(keySystem, audioCodecs, videoCodecs) {
- var _this2 = this;
- // TODO: add other DRM "options"
- var mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs);
- if (!mediaKeySystemConfigs) {
- _logger.logger.warn('Can not create config for key-system (maybe because platform is not supported):', keySystem);
- return;
- }
- _logger.logger.log('Requesting encrypted media key-system access');
- // expecting interface like window.navigator.requestMediaKeySystemAccess
- this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs).then(function (mediaKeySystemAccess) {
- _this2._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);
- }).catch(function (err) {
- _logger.logger.error('Failed to obtain key-system "' + keySystem + '" access:', err);
- });
- }
- }, {
- key: '_onMediaKeySystemAccessObtained',
- /**
- * Handles obtaining access to a key-system
- *
- * @param {string} keySystem
- * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess
- */
- value: function _onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess) {
- var _this3 = this;
- _logger.logger.log('Access for key-system "' + keySystem + '" obtained');
- var mediaKeysListItem = {
- mediaKeys: null,
- mediaKeysSession: null,
- mediaKeysSessionInitialized: false,
- mediaKeySystemAccess: mediaKeySystemAccess,
- mediaKeySystemDomain: keySystem
- };
- this._mediaKeysList.push(mediaKeysListItem);
- mediaKeySystemAccess.createMediaKeys().then(function (mediaKeys) {
- mediaKeysListItem.mediaKeys = mediaKeys;
- _logger.logger.log('Media-keys created for key-system "' + keySystem + '"');
- _this3._onMediaKeysCreated();
- }).catch(function (err) {
- _logger.logger.error('Failed to create media-keys:', err);
- });
- }
- /**
- * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this
- * for all existing keys where no session exists yet.
- */
- }, {
- key: '_onMediaKeysCreated',
- value: function _onMediaKeysCreated() {
- var _this4 = this;
- // check for all key-list items if a session exists, otherwise, create one
- this._mediaKeysList.forEach(function (mediaKeysListItem) {
- if (!mediaKeysListItem.mediaKeysSession) {
- mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession();
- _this4._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);
- }
- });
- }
- /**
- *
- * @param {*} keySession
- */
- }, {
- key: '_onNewMediaKeySession',
- value: function _onNewMediaKeySession(keySession) {
- var _this5 = this;
- _logger.logger.log('New key-system session ' + keySession.sessionId);
- keySession.addEventListener('message', function (event) {
- _this5._onKeySessionMessage(keySession, event.message);
- }, false);
- }
- }, {
- key: '_onKeySessionMessage',
- value: function _onKeySessionMessage(keySession, message) {
- _logger.logger.log('Got EME message event, creating license request');
- this._requestLicense(message, function (data) {
- _logger.logger.log('Received license data, updating key-session');
- keySession.update(data);
- });
- }
- }, {
- key: '_onMediaEncrypted',
- value: function _onMediaEncrypted(initDataType, initData) {
- _logger.logger.log('Media is encrypted using "' + initDataType + '" init data type');
- this._isMediaEncrypted = true;
- this._mediaEncryptionInitDataType = initDataType;
- this._mediaEncryptionInitData = initData;
- this._attemptSetMediaKeys();
- this._generateRequestWithPreferredKeySession();
- }
- }, {
- key: '_attemptSetMediaKeys',
- value: function _attemptSetMediaKeys() {
- if (!this._hasSetMediaKeys) {
- // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
- var keysListItem = this._mediaKeysList[0];
- if (!keysListItem || !keysListItem.mediaKeys) {
- _logger.logger.error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');
- this.hls.trigger(_events2.default.ERROR, {
- type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
- details: _errors.ErrorDetails.KEY_SYSTEM_NO_KEYS,
- fatal: true
- });
- return;
- }
- _logger.logger.log('Setting keys for encrypted media');
- this._media.setMediaKeys(keysListItem.mediaKeys);
- this._hasSetMediaKeys = true;
- }
- }
- }, {
- key: '_generateRequestWithPreferredKeySession',
- value: function _generateRequestWithPreferredKeySession() {
- var _this6 = this;
- // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
- var keysListItem = this._mediaKeysList[0];
- if (!keysListItem) {
- _logger.logger.error('Fatal: Media is encrypted but not any key-system access has been obtained yet');
- this.hls.trigger(_events2.default.ERROR, {
- type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
- details: _errors.ErrorDetails.KEY_SYSTEM_NO_ACCESS,
- fatal: true
- });
- return;
- }
- if (keysListItem.mediaKeysSessionInitialized) {
- _logger.logger.warn('Key-Session already initialized but requested again');
- return;
- }
- var keySession = keysListItem.mediaKeysSession;
- if (!keySession) {
- _logger.logger.error('Fatal: Media is encrypted but no key-session existing');
- this.hls.trigger(_events2.default.ERROR, {
- type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
- details: _errors.ErrorDetails.KEY_SYSTEM_NO_SESSION,
- fatal: true
- });
- }
- var initDataType = this._mediaEncryptionInitDataType;
- var initData = this._mediaEncryptionInitData;
- _logger.logger.log('Generating key-session request for "' + initDataType + '" init data type');
- keysListItem.mediaKeysSessionInitialized = true;
- keySession.generateRequest(initDataType, initData).then(function () {
- _logger.logger.debug('Key-session generation succeeded');
- }).catch(function (err) {
- _logger.logger.error('Error generating key-session request:', err);
- _this6.hls.trigger(_events2.default.ERROR, {
- type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
- details: _errors.ErrorDetails.KEY_SYSTEM_NO_SESSION,
- fatal: false
- });
- });
- }
- /**
- * @param {string} url License server URL
- * @param {ArrayBuffer} keyMessage Message data issued by key-system
- * @param {function} callback Called when XHR has succeeded
- * @returns {XMLHttpRequest} Unsent (but opened state) XHR object
- */
- }, {
- key: '_createLicenseXhr',
- value: function _createLicenseXhr(url, keyMessage, callback) {
- var xhr = new XMLHttpRequest();
- var licenseXhrSetup = this._licenseXhrSetup;
- try {
- if (licenseXhrSetup) {
- try {
- licenseXhrSetup(xhr, url);
- } catch (e) {
- // let's try to open before running setup
- xhr.open('POST', url, true);
- licenseXhrSetup(xhr, url);
- }
- }
- // if licenseXhrSetup did not yet call open, let's do it now
- if (!xhr.readyState) {
- xhr.open('POST', url, true);
- }
- } catch (e) {
- // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
- _logger.logger.error('Error setting up key-system license XHR', e);
- this.hls.trigger(_events2.default.ERROR, {
- type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
- details: _errors.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
- fatal: true
- });
- return;
- }
- xhr.responseType = 'arraybuffer';
- xhr.onreadystatechange = this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);
- return xhr;
- }
- /**
- * @param {XMLHttpRequest} xhr
- * @param {string} url License server URL
- * @param {ArrayBuffer} keyMessage Message data issued by key-system
- * @param {function} callback Called when XHR has succeeded
- *
- */
- }, {
- key: '_onLicenseRequestReadyStageChange',
- value: function _onLicenseRequestReadyStageChange(xhr, url, keyMessage, callback) {
- switch (xhr.readyState) {
- case 4:
- if (xhr.status === 200) {
- this._requestLicenseFailureCount = 0;
- _logger.logger.log('License request succeeded');
- callback(xhr.response);
- } else {
- _logger.logger.error('License Request XHR failed (' + url + '). Status: ' + xhr.status + ' (' + xhr.statusText + ')');
- this._requestLicenseFailureCount++;
- if (this._requestLicenseFailureCount <= MAX_LICENSE_REQUEST_FAILURES) {
- var attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;
- _logger.logger.warn('Retrying license request, ' + attemptsLeft + ' attempts left');
- this._requestLicense(keyMessage, callback);
- return;
- }
- this.hls.trigger(_events2.default.ERROR, {
- type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
- details: _errors.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
- fatal: true
- });
- }
- break;
- }
- }
- /**
- * @param {object} keysListItem
- * @param {ArrayBuffer} keyMessage
- * @returns {ArrayBuffer} Challenge data posted to license server
- */
- }, {
- key: '_generateLicenseRequestChallenge',
- value: function _generateLicenseRequestChallenge(keysListItem, keyMessage) {
- var challenge = void 0;
- if (keysListItem.mediaKeySystemDomain === KeySystems.PLAYREADY) {
- _logger.logger.error('PlayReady is not supported (yet)');
- // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js
- /*
- if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {
- // For PlayReady CDMs, we need to dig the Challenge out of the XML.
- var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');
- if (keyMessageXml.getElementsByTagName('Challenge')[0]) {
- challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);
- } else {
- throw 'Cannot find <Challenge> in key message';
- }
- var headerNames = keyMessageXml.getElementsByTagName('name');
- var headerValues = keyMessageXml.getElementsByTagName('value');
- if (headerNames.length !== headerValues.length) {
- throw 'Mismatched header <name>/<value> pair in key message';
- }
- for (var i = 0; i < headerNames.length; i++) {
- xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);
- }
- }
- */
- } else if (keysListItem.mediaKeySystemDomain === KeySystems.WIDEVINE) {
- // For Widevine CDMs, the challenge is the keyMessage.
- challenge = keyMessage;
- } else {
- _logger.logger.error('Unsupported key-system:', keysListItem.mediaKeySystemDomain);
- }
- return challenge;
- }
- }, {
- key: '_requestLicense',
- value: function _requestLicense(keyMessage, callback) {
- _logger.logger.log('Requesting content license for key-system');
- var keysListItem = this._mediaKeysList[0];
- if (!keysListItem) {
- _logger.logger.error('Fatal error: Media is encrypted but no key-system access has been obtained yet');
- this.hls.trigger(_events2.default.ERROR, {
- type: _errors.ErrorTypes.KEY_SYSTEM_ERROR,
- details: _errors.ErrorDetails.KEY_SYSTEM_NO_ACCESS,
- fatal: true
- });
- return;
- }
- var url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);
- var xhr = this._createLicenseXhr(url, keyMessage, callback);
- _logger.logger.log('Sending license request to URL: ' + url);
- xhr.send(this._generateLicenseRequestChallenge(keysListItem, keyMessage));
- }
- }, {
- key: 'onMediaAttached',
- value: function onMediaAttached(data) {
- var _this7 = this;
- if (!this._emeEnabled) {
- return;
- }
- var media = data.media;
- // keep reference of media
- this._media = media;
- // FIXME: also handle detaching media !
- media.addEventListener('encrypted', function (e) {
- _this7._onMediaEncrypted(e.initDataType, e.initData);
- });
- }
- }, {
- key: 'onManifestParsed',
- value: function onManifestParsed(data) {
- if (!this._emeEnabled) {
- return;
- }
- var audioCodecs = data.levels.map(function (level) {
- return level.audioCodec;
- });
- var videoCodecs = data.levels.map(function (level) {
- return level.videoCodec;
- });
- this._attemptKeySystemAccess(KeySystems.WIDEVINE, audioCodecs, videoCodecs);
- }
- }, {
- key: 'requestMediaKeySystemAccess',
- get: function get() {
- if (!this._requestMediaKeySystemAccess) {
- throw new Error('No requestMediaKeySystemAccess function configured');
- }
- return this._requestMediaKeySystemAccess;
- }
- }]);
- return EMEController;
- }(_eventHandler2.default);
- exports.default = EMEController;
- module.exports = exports['default'];
- /***/ }),
- /* 79 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var requestMediaKeySystemAccess = function () {
- if (typeof window !== 'undefined' && window.navigator && window.navigator.requestMediaKeySystemAccess) {
- return window.navigator.requestMediaKeySystemAccess.bind(window.navigator);
- } else {
- return null;
- }
- }();
- exports.requestMediaKeySystemAccess = requestMediaKeySystemAccess;
- /***/ }),
- /* 80 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var util = {};
- util.getBrowserVersion = function () {
- var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
- if (userAgent.toLowerCase().indexOf("mobile") > -1) {
- return "Unknown";
- }
- if (userAgent.indexOf("Firefox") > -1) {
- var version = userAgent.match(/firefox\/[\d.]+/gi)[0].match(/[\d]+/)[0];
- return "Firefox " + version;
- } else if (userAgent.indexOf("Edge") > -1) {
- var _version = userAgent.match(/edge\/[\d.]+/gi)[0].match(/[\d]+/)[0];
- return "Edge " + _version;
- } else if (userAgent.indexOf("rv:11") > -1) {
- return "IE 11";
- } else if (userAgent.indexOf("Opera") > -1 || userAgent.indexOf("OPR") > -1) {
- if (userAgent.indexOf("Opera") > -1) {
- var _version2 = userAgent.match(/opera\/[\d.]+/gi)[0].match(/[\d]+/)[0];
- return "Opera " + _version2;
- }
- if (userAgent.indexOf("OPR") > -1) {
- var _version3 = userAgent.match(/opr\/[\d.]+/gi)[0].match(/[\d]+/)[0];
- return "Opera " + _version3;
- }
- } else if (userAgent.indexOf("Chrome") > -1) {
- var _version4 = userAgent.match(/chrome\/[\d.]+/gi)[0].match(/[\d]+/)[0];
- return "Chrome " + _version4;
- } else if (userAgent.indexOf("Safari") > -1) {
- var _version5 = userAgent.match(/safari\/[\d.]+/gi)[0].match(/[\d]+/)[0];
- return "Safari " + _version5;
- } else if (userAgent.indexOf("MSIE") > -1 || userAgent.indexOf("Trident") > -1) {
- if (userAgent.indexOf("MSIE") > -1) {
- var _version6 = userAgent.match(/msie [\d.]+/gi)[0].match(/[\d]+/)[0];
- return "IE " + _version6;
- }
- if (userAgent.indexOf("Trident") > -1) {
- var versionTrident = userAgent.match(/trident\/[\d.]+/gi)[0].match(/[\d]+/)[0];
- var _version7 = parseInt(versionTrident) + 4;
- return "IE " + _version7;
- }
- } else {
- return "Unknown";
- }
- };
- exports.default = util;
- module.exports = exports["default"];
- /***/ })
- /******/ ]);
- });
- /***/ }),
- /***/ "90e3":
- /***/ (function(module, exports) {
- var id = 0;
- var postfix = Math.random();
- module.exports = function (key) {
- return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);
- };
- /***/ }),
- /***/ "9112":
- /***/ (function(module, exports, __webpack_require__) {
- var DESCRIPTORS = __webpack_require__("83ab");
- var definePropertyModule = __webpack_require__("9bf2");
- var createPropertyDescriptor = __webpack_require__("5c6c");
- module.exports = DESCRIPTORS ? function (object, key, value) {
- return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
- } : function (object, key, value) {
- object[key] = value;
- return object;
- };
- /***/ }),
- /***/ "94ca":
- /***/ (function(module, exports, __webpack_require__) {
- var fails = __webpack_require__("d039");
- var replacement = /#|\.prototype\./;
- var isForced = function (feature, detection) {
- var value = data[normalize(feature)];
- return value == POLYFILL ? true
- : value == NATIVE ? false
- : typeof detection == 'function' ? fails(detection)
- : !!detection;
- };
- var normalize = isForced.normalize = function (string) {
- return String(string).replace(replacement, '.').toLowerCase();
- };
- var data = isForced.data = {};
- var NATIVE = isForced.NATIVE = 'N';
- var POLYFILL = isForced.POLYFILL = 'P';
- module.exports = isForced;
- /***/ }),
- /***/ "9bf2":
- /***/ (function(module, exports, __webpack_require__) {
- var DESCRIPTORS = __webpack_require__("83ab");
- var IE8_DOM_DEFINE = __webpack_require__("0cfb");
- var anObject = __webpack_require__("825a");
- var toPrimitive = __webpack_require__("c04e");
- var nativeDefineProperty = Object.defineProperty;
- // `Object.defineProperty` method
- // https://tc39.github.io/ecma262/#sec-object.defineproperty
- exports.f = DESCRIPTORS ? nativeDefineProperty : function defineProperty(O, P, Attributes) {
- anObject(O);
- P = toPrimitive(P, true);
- anObject(Attributes);
- if (IE8_DOM_DEFINE) try {
- return nativeDefineProperty(O, P, Attributes);
- } catch (error) { /* empty */ }
- if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
- if ('value' in Attributes) O[P] = Attributes.value;
- return O;
- };
- /***/ }),
- /***/ "a691":
- /***/ (function(module, exports) {
- var ceil = Math.ceil;
- var floor = Math.floor;
- // `ToInteger` abstract operation
- // https://tc39.github.io/ecma262/#sec-tointeger
- module.exports = function (argument) {
- return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);
- };
- /***/ }),
- /***/ "b402":
- /***/ (function(module, exports, __webpack_require__) {
- (function webpackUniversalModuleDefinition(root, factory) {
- if(true)
- module.exports = factory(__webpack_require__("5392"));
- else {}
- })(window, function(__WEBPACK_EXTERNAL_MODULE__20__) {
- return /******/ (function(modules) { // webpackBootstrap
- /******/ // The module cache
- /******/ var installedModules = {};
- /******/
- /******/ // The require function
- /******/ function __webpack_require__(moduleId) {
- /******/
- /******/ // Check if module is in cache
- /******/ if(installedModules[moduleId]) {
- /******/ return installedModules[moduleId].exports;
- /******/ }
- /******/ // Create a new module (and put it into the cache)
- /******/ var module = installedModules[moduleId] = {
- /******/ i: moduleId,
- /******/ l: false,
- /******/ exports: {}
- /******/ };
- /******/
- /******/ // Execute the module function
- /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
- /******/
- /******/ // Flag the module as loaded
- /******/ module.l = true;
- /******/
- /******/ // Return the exports of the module
- /******/ return module.exports;
- /******/ }
- /******/
- /******/
- /******/ // expose the modules object (__webpack_modules__)
- /******/ __webpack_require__.m = modules;
- /******/
- /******/ // expose the module cache
- /******/ __webpack_require__.c = installedModules;
- /******/
- /******/ // define getter function for harmony exports
- /******/ __webpack_require__.d = function(exports, name, getter) {
- /******/ if(!__webpack_require__.o(exports, name)) {
- /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
- /******/ }
- /******/ };
- /******/
- /******/ // define __esModule on exports
- /******/ __webpack_require__.r = function(exports) {
- /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
- /******/ }
- /******/ Object.defineProperty(exports, '__esModule', { value: true });
- /******/ };
- /******/
- /******/ // create a fake namespace object
- /******/ // mode & 1: value is a module id, require it
- /******/ // mode & 2: merge all properties of value into the ns
- /******/ // mode & 4: return value when already ns object
- /******/ // mode & 8|1: behave like require
- /******/ __webpack_require__.t = function(value, mode) {
- /******/ if(mode & 1) value = __webpack_require__(value);
- /******/ if(mode & 8) return value;
- /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
- /******/ var ns = Object.create(null);
- /******/ __webpack_require__.r(ns);
- /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
- /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
- /******/ return ns;
- /******/ };
- /******/
- /******/ // getDefaultExport function for compatibility with non-harmony modules
- /******/ __webpack_require__.n = function(module) {
- /******/ var getter = module && module.__esModule ?
- /******/ function getDefault() { return module['default']; } :
- /******/ function getModuleExports() { return module; };
- /******/ __webpack_require__.d(getter, 'a', getter);
- /******/ return getter;
- /******/ };
- /******/
- /******/ // Object.prototype.hasOwnProperty.call
- /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
- /******/
- /******/ // __webpack_public_path__
- /******/ __webpack_require__.p = "";
- /******/
- /******/
- /******/ // Load entry module and return exports
- /******/ return __webpack_require__(__webpack_require__.s = 18);
- /******/ })
- /************************************************************************/
- /******/ ([
- /* 0 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var _events = __webpack_require__(2);
- var _events2 = _interopRequireDefault(_events);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var Log = function () {
- function Log() {
- _classCallCheck(this, Log);
- }
- _createClass(Log, null, [{
- key: 'e',
- value: function e(tag, msg) {
- if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
- var str = '[' + tag + '] > ' + msg;
- if (Log.ENABLE_CALLBACK) {
- Log.emitter.emit('log', 'error', str);
- }
- if (!Log.ENABLE_ERROR) {
- return;
- }
- }
- }, {
- key: 'i',
- value: function i(tag, msg) {
- if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
- var str = '[' + tag + '] > ' + msg;
- if (Log.ENABLE_CALLBACK) {
- Log.emitter.emit('log', 'info', str);
- }
- if (!Log.ENABLE_INFO) {
- return;
- }
- }
- }, {
- key: 'w',
- value: function w(tag, msg) {
- if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
- var str = '[' + tag + '] > ' + msg;
- if (Log.ENABLE_CALLBACK) {
- Log.emitter.emit('log', 'warn', str);
- }
- if (!Log.ENABLE_WARN) {
- return;
- }
- }
- }, {
- key: 'd',
- value: function d(tag, msg) {
- if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
- var str = '[' + tag + '] > ' + msg;
- if (Log.ENABLE_CALLBACK) {
- Log.emitter.emit('log', 'debug', str);
- }
- if (!Log.ENABLE_DEBUG) {
- return;
- }
- }
- }, {
- key: 'v',
- value: function v(tag, msg) {
- if (!tag || Log.FORCE_GLOBAL_TAG) tag = Log.GLOBAL_TAG;
- var str = '[' + tag + '] > ' + msg;
- if (Log.ENABLE_CALLBACK) {
- Log.emitter.emit('log', 'verbose', str);
- }
- if (!Log.ENABLE_VERBOSE) {
- return;
- }
- }
- }]);
- return Log;
- }();
- Log.GLOBAL_TAG = 'flv.js';
- Log.FORCE_GLOBAL_TAG = false;
- Log.ENABLE_ERROR = true;
- Log.ENABLE_INFO = true;
- Log.ENABLE_WARN = true;
- Log.ENABLE_DEBUG = true;
- Log.ENABLE_VERBOSE = true;
- Log.ENABLE_CALLBACK = false;
- Log.emitter = new _events2.default();
- exports.default = Log;
- module.exports = exports['default'];
- /***/ }),
- /* 1 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- 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; }
- 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; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var RuntimeException = exports.RuntimeException = function () {
- function RuntimeException(message) {
- _classCallCheck(this, RuntimeException);
- this._message = message;
- }
- _createClass(RuntimeException, [{
- key: 'toString',
- value: function toString() {
- return this.name + ': ' + this.message;
- }
- }, {
- key: 'name',
- get: function get() {
- return 'RuntimeException';
- }
- }, {
- key: 'message',
- get: function get() {
- return this._message;
- }
- }]);
- return RuntimeException;
- }();
- var IllegalStateException = exports.IllegalStateException = function (_RuntimeException) {
- _inherits(IllegalStateException, _RuntimeException);
- function IllegalStateException(message) {
- _classCallCheck(this, IllegalStateException);
- return _possibleConstructorReturn(this, (IllegalStateException.__proto__ || Object.getPrototypeOf(IllegalStateException)).call(this, message));
- }
- _createClass(IllegalStateException, [{
- key: 'name',
- get: function get() {
- return 'IllegalStateException';
- }
- }]);
- return IllegalStateException;
- }(RuntimeException);
- var InvalidArgumentException = exports.InvalidArgumentException = function (_RuntimeException2) {
- _inherits(InvalidArgumentException, _RuntimeException2);
- function InvalidArgumentException(message) {
- _classCallCheck(this, InvalidArgumentException);
- return _possibleConstructorReturn(this, (InvalidArgumentException.__proto__ || Object.getPrototypeOf(InvalidArgumentException)).call(this, message));
- }
- _createClass(InvalidArgumentException, [{
- key: 'name',
- get: function get() {
- return 'InvalidArgumentException';
- }
- }]);
- return InvalidArgumentException;
- }(RuntimeException);
- var NotImplementedException = exports.NotImplementedException = function (_RuntimeException3) {
- _inherits(NotImplementedException, _RuntimeException3);
- function NotImplementedException(message) {
- _classCallCheck(this, NotImplementedException);
- return _possibleConstructorReturn(this, (NotImplementedException.__proto__ || Object.getPrototypeOf(NotImplementedException)).call(this, message));
- }
- _createClass(NotImplementedException, [{
- key: 'name',
- get: function get() {
- return 'NotImplementedException';
- }
- }]);
- return NotImplementedException;
- }(RuntimeException);
- /***/ }),
- /* 2 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- var R = typeof Reflect === 'object' ? Reflect : null
- var ReflectApply = R && typeof R.apply === 'function'
- ? R.apply
- : function ReflectApply(target, receiver, args) {
- return Function.prototype.apply.call(target, receiver, args);
- }
- var ReflectOwnKeys
- if (R && typeof R.ownKeys === 'function') {
- ReflectOwnKeys = R.ownKeys
- } else if (Object.getOwnPropertySymbols) {
- ReflectOwnKeys = function ReflectOwnKeys(target) {
- return Object.getOwnPropertyNames(target)
- .concat(Object.getOwnPropertySymbols(target));
- };
- } else {
- ReflectOwnKeys = function ReflectOwnKeys(target) {
- return Object.getOwnPropertyNames(target);
- };
- }
- function ProcessEmitWarning(warning) {
- if (console && console.warn) console.warn(warning);
- }
- var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
- return value !== value;
- }
- function EventEmitter() {
- EventEmitter.init.call(this);
- }
- module.exports = EventEmitter;
- // Backwards-compat with node 0.10.x
- EventEmitter.EventEmitter = EventEmitter;
- EventEmitter.prototype._events = undefined;
- EventEmitter.prototype._eventsCount = 0;
- EventEmitter.prototype._maxListeners = undefined;
- // By default EventEmitters will print a warning if more than 10 listeners are
- // added to it. This is a useful default which helps finding memory leaks.
- var defaultMaxListeners = 10;
- function checkListener(listener) {
- if (typeof listener !== 'function') {
- throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
- }
- }
- Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
- enumerable: true,
- get: function() {
- return defaultMaxListeners;
- },
- set: function(arg) {
- if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
- throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
- }
- defaultMaxListeners = arg;
- }
- });
- EventEmitter.init = function() {
- if (this._events === undefined ||
- this._events === Object.getPrototypeOf(this)._events) {
- this._events = Object.create(null);
- this._eventsCount = 0;
- }
- this._maxListeners = this._maxListeners || undefined;
- };
- // Obviously not all Emitters should be limited to 10. This function allows
- // that to be increased. Set to zero for unlimited.
- EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
- if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
- throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
- }
- this._maxListeners = n;
- return this;
- };
- function _getMaxListeners(that) {
- if (that._maxListeners === undefined)
- return EventEmitter.defaultMaxListeners;
- return that._maxListeners;
- }
- EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
- return _getMaxListeners(this);
- };
- EventEmitter.prototype.emit = function emit(type) {
- var args = [];
- for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
- var doError = (type === 'error');
- var events = this._events;
- if (events !== undefined)
- doError = (doError && events.error === undefined);
- else if (!doError)
- return false;
- // If there is no 'error' event listener then throw.
- if (doError) {
- var er;
- if (args.length > 0)
- er = args[0];
- if (er instanceof Error) {
- // Note: The comments on the `throw` lines are intentional, they show
- // up in Node's output if this results in an unhandled exception.
- throw er; // Unhandled 'error' event
- }
- // At least give some kind of context to the user
- var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
- err.context = er;
- throw err; // Unhandled 'error' event
- }
- var handler = events[type];
- if (handler === undefined)
- return false;
- if (typeof handler === 'function') {
- ReflectApply(handler, this, args);
- } else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- ReflectApply(listeners[i], this, args);
- }
- return true;
- };
- function _addListener(target, type, listener, prepend) {
- var m;
- var events;
- var existing;
- checkListener(listener);
- events = target._events;
- if (events === undefined) {
- events = target._events = Object.create(null);
- target._eventsCount = 0;
- } else {
- // To avoid recursion in the case that type === "newListener"! Before
- // adding it to the listeners, first emit "newListener".
- if (events.newListener !== undefined) {
- target.emit('newListener', type,
- listener.listener ? listener.listener : listener);
- // Re-assign `events` because a newListener handler could have caused the
- // this._events to be assigned to a new object
- events = target._events;
- }
- existing = events[type];
- }
- if (existing === undefined) {
- // Optimize the case of one listener. Don't need the extra array object.
- existing = events[type] = listener;
- ++target._eventsCount;
- } else {
- if (typeof existing === 'function') {
- // Adding the second element, need to change to array.
- existing = events[type] =
- prepend ? [listener, existing] : [existing, listener];
- // If we've already got an array, just append.
- } else if (prepend) {
- existing.unshift(listener);
- } else {
- existing.push(listener);
- }
- // Check for listener leak
- m = _getMaxListeners(target);
- if (m > 0 && existing.length > m && !existing.warned) {
- existing.warned = true;
- // No error code for this since it is a Warning
- // eslint-disable-next-line no-restricted-syntax
- var w = new Error('Possible EventEmitter memory leak detected. ' +
- existing.length + ' ' + String(type) + ' listeners ' +
- 'added. Use emitter.setMaxListeners() to ' +
- 'increase limit');
- w.name = 'MaxListenersExceededWarning';
- w.emitter = target;
- w.type = type;
- w.count = existing.length;
- ProcessEmitWarning(w);
- }
- }
- return target;
- }
- EventEmitter.prototype.addListener = function addListener(type, listener) {
- return _addListener(this, type, listener, false);
- };
- EventEmitter.prototype.on = EventEmitter.prototype.addListener;
- EventEmitter.prototype.prependListener =
- function prependListener(type, listener) {
- return _addListener(this, type, listener, true);
- };
- function onceWrapper() {
- if (!this.fired) {
- this.target.removeListener(this.type, this.wrapFn);
- this.fired = true;
- if (arguments.length === 0)
- return this.listener.call(this.target);
- return this.listener.apply(this.target, arguments);
- }
- }
- function _onceWrap(target, type, listener) {
- var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
- var wrapped = onceWrapper.bind(state);
- wrapped.listener = listener;
- state.wrapFn = wrapped;
- return wrapped;
- }
- EventEmitter.prototype.once = function once(type, listener) {
- checkListener(listener);
- this.on(type, _onceWrap(this, type, listener));
- return this;
- };
- EventEmitter.prototype.prependOnceListener =
- function prependOnceListener(type, listener) {
- checkListener(listener);
- this.prependListener(type, _onceWrap(this, type, listener));
- return this;
- };
- // Emits a 'removeListener' event if and only if the listener was removed.
- EventEmitter.prototype.removeListener =
- function removeListener(type, listener) {
- var list, events, position, i, originalListener;
- checkListener(listener);
- events = this._events;
- if (events === undefined)
- return this;
- list = events[type];
- if (list === undefined)
- return this;
- if (list === listener || list.listener === listener) {
- if (--this._eventsCount === 0)
- this._events = Object.create(null);
- else {
- delete events[type];
- if (events.removeListener)
- this.emit('removeListener', type, list.listener || listener);
- }
- } else if (typeof list !== 'function') {
- position = -1;
- for (i = list.length - 1; i >= 0; i--) {
- if (list[i] === listener || list[i].listener === listener) {
- originalListener = list[i].listener;
- position = i;
- break;
- }
- }
- if (position < 0)
- return this;
- if (position === 0)
- list.shift();
- else {
- spliceOne(list, position);
- }
- if (list.length === 1)
- events[type] = list[0];
- if (events.removeListener !== undefined)
- this.emit('removeListener', type, originalListener || listener);
- }
- return this;
- };
- EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
- EventEmitter.prototype.removeAllListeners =
- function removeAllListeners(type) {
- var listeners, events, i;
- events = this._events;
- if (events === undefined)
- return this;
- // not listening for removeListener, no need to emit
- if (events.removeListener === undefined) {
- if (arguments.length === 0) {
- this._events = Object.create(null);
- this._eventsCount = 0;
- } else if (events[type] !== undefined) {
- if (--this._eventsCount === 0)
- this._events = Object.create(null);
- else
- delete events[type];
- }
- return this;
- }
- // emit removeListener for all listeners on all events
- if (arguments.length === 0) {
- var keys = Object.keys(events);
- var key;
- for (i = 0; i < keys.length; ++i) {
- key = keys[i];
- if (key === 'removeListener') continue;
- this.removeAllListeners(key);
- }
- this.removeAllListeners('removeListener');
- this._events = Object.create(null);
- this._eventsCount = 0;
- return this;
- }
- listeners = events[type];
- if (typeof listeners === 'function') {
- this.removeListener(type, listeners);
- } else if (listeners !== undefined) {
- // LIFO order
- for (i = listeners.length - 1; i >= 0; i--) {
- this.removeListener(type, listeners[i]);
- }
- }
- return this;
- };
- function _listeners(target, type, unwrap) {
- var events = target._events;
- if (events === undefined)
- return [];
- var evlistener = events[type];
- if (evlistener === undefined)
- return [];
- if (typeof evlistener === 'function')
- return unwrap ? [evlistener.listener || evlistener] : [evlistener];
- return unwrap ?
- unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
- }
- EventEmitter.prototype.listeners = function listeners(type) {
- return _listeners(this, type, true);
- };
- EventEmitter.prototype.rawListeners = function rawListeners(type) {
- return _listeners(this, type, false);
- };
- EventEmitter.listenerCount = function(emitter, type) {
- if (typeof emitter.listenerCount === 'function') {
- return emitter.listenerCount(type);
- } else {
- return listenerCount.call(emitter, type);
- }
- };
- EventEmitter.prototype.listenerCount = listenerCount;
- function listenerCount(type) {
- var events = this._events;
- if (events !== undefined) {
- var evlistener = events[type];
- if (typeof evlistener === 'function') {
- return 1;
- } else if (evlistener !== undefined) {
- return evlistener.length;
- }
- }
- return 0;
- }
- EventEmitter.prototype.eventNames = function eventNames() {
- return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
- };
- function arrayClone(arr, n) {
- var copy = new Array(n);
- for (var i = 0; i < n; ++i)
- copy[i] = arr[i];
- return copy;
- }
- function spliceOne(list, index) {
- for (; index + 1 < list.length; index++)
- list[index] = list[index + 1];
- list.pop();
- }
- function unwrapListeners(arr) {
- var ret = new Array(arr.length);
- for (var i = 0; i < ret.length; ++i) {
- ret[i] = arr[i].listener || arr[i];
- }
- return ret;
- }
- /***/ }),
- /* 3 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.BaseLoader = exports.LoaderErrors = exports.LoaderStatus = undefined;
- 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; }; }(); /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var _exception = __webpack_require__(1);
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var LoaderStatus = exports.LoaderStatus = {
- kIdle: 0,
- kConnecting: 1,
- kBuffering: 2,
- kError: 3,
- kComplete: 4
- };
- var LoaderErrors = exports.LoaderErrors = {
- OK: 'OK',
- EXCEPTION: 'Exception',
- HTTP_STATUS_CODE_INVALID: 'HttpStatusCodeInvalid',
- CONNECTING_TIMEOUT: 'ConnectingTimeout',
- EARLY_EOF: 'EarlyEof',
- UNRECOVERABLE_EARLY_EOF: 'UnrecoverableEarlyEof'
- };
- /* Loader has callbacks which have following prototypes:
- * function onContentLengthKnown(contentLength: number): void
- * function onURLRedirect(url: string): void
- * function onDataArrival(chunk: ArrayBuffer, byteStart: number, receivedLength: number): void
- * function onError(errorType: number, errorInfo: {code: number, msg: string}): void
- * function onComplete(rangeFrom: number, rangeTo: number): void
- */
- var BaseLoader = exports.BaseLoader = function () {
- function BaseLoader(typeName) {
- _classCallCheck(this, BaseLoader);
- this._type = typeName || 'undefined';
- this._status = LoaderStatus.kIdle;
- this._needStash = false;
- // callbacks
- this._onContentLengthKnown = null;
- this._onURLRedirect = null;
- this._onDataArrival = null;
- this._onError = null;
- this._onComplete = null;
- }
- _createClass(BaseLoader, [{
- key: 'destroy',
- value: function destroy() {
- this._status = LoaderStatus.kIdle;
- this._onContentLengthKnown = null;
- this._onURLRedirect = null;
- this._onDataArrival = null;
- this._onError = null;
- this._onComplete = null;
- }
- }, {
- key: 'isWorking',
- value: function isWorking() {
- return this._status === LoaderStatus.kConnecting || this._status === LoaderStatus.kBuffering;
- }
- }, {
- key: 'open',
- // pure virtual
- value: function open(dataSource, range) {
- throw new _exception.NotImplementedException('Unimplemented abstract function!');
- }
- }, {
- key: 'abort',
- value: function abort() {
- throw new _exception.NotImplementedException('Unimplemented abstract function!');
- }
- }, {
- key: 'type',
- get: function get() {
- return this._type;
- }
- }, {
- key: 'status',
- get: function get() {
- return this._status;
- }
- }, {
- key: 'needStashBuffer',
- get: function get() {
- return this._needStash;
- }
- }, {
- key: 'onContentLengthKnown',
- get: function get() {
- return this._onContentLengthKnown;
- },
- set: function set(callback) {
- this._onContentLengthKnown = callback;
- }
- }, {
- key: 'onURLRedirect',
- get: function get() {
- return this._onURLRedirect;
- },
- set: function set(callback) {
- this._onURLRedirect = callback;
- }
- }, {
- key: 'onDataArrival',
- get: function get() {
- return this._onDataArrival;
- },
- set: function set(callback) {
- this._onDataArrival = callback;
- }
- }, {
- key: 'onError',
- get: function get() {
- return this._onError;
- },
- set: function set(callback) {
- this._onError = callback;
- }
- }, {
- key: 'onComplete',
- get: function get() {
- return this._onComplete;
- },
- set: function set(callback) {
- this._onComplete = callback;
- }
- }]);
- return BaseLoader;
- }();
- /***/ }),
- /* 4 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var Browser = {};
- function detect() {
- // modified from jquery-browser-plugin
- var ua = self.navigator.userAgent.toLowerCase();
- 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) || [];
- 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) || [];
- var matched = {
- browser: match[5] || match[3] || match[1] || '',
- version: match[2] || match[4] || '0',
- majorVersion: match[4] || match[2] || '0',
- platform: platform_match[0] || ''
- };
- var browser = {};
- if (matched.browser) {
- browser[matched.browser] = true;
- var versionArray = matched.majorVersion.split('.');
- browser.version = {
- major: parseInt(matched.majorVersion, 10),
- string: matched.version
- };
- if (versionArray.length > 1) {
- browser.version.minor = parseInt(versionArray[1], 10);
- }
- if (versionArray.length > 2) {
- browser.version.build = parseInt(versionArray[2], 10);
- }
- }
- if (matched.platform) {
- browser[matched.platform] = true;
- }
- if (browser.chrome || browser.opr || browser.safari) {
- browser.webkit = true;
- }
- // MSIE. IE11 has 'rv' identifer
- if (browser.rv || browser.iemobile) {
- if (browser.rv) {
- delete browser.rv;
- }
- var msie = 'msie';
- matched.browser = msie;
- browser[msie] = true;
- }
- // Microsoft Edge
- if (browser.edge) {
- delete browser.edge;
- var msedge = 'msedge';
- matched.browser = msedge;
- browser[msedge] = true;
- }
- // Opera 15+
- if (browser.opr) {
- var opera = 'opera';
- matched.browser = opera;
- browser[opera] = true;
- }
- // Stock android browsers are marked as Safari
- if (browser.safari && browser.android) {
- var android = 'android';
- matched.browser = android;
- browser[android] = true;
- }
- browser.name = matched.browser;
- browser.platform = matched.platform;
- for (var key in Browser) {
- if (Browser.hasOwnProperty(key)) {
- delete Browser[key];
- }
- }
- Object.assign(Browser, browser);
- }
- detect();
- exports.default = Browser;
- module.exports = exports['default'];
- /***/ }),
- /* 5 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var TransmuxingEvents = {
- IO_ERROR: 'io_error',
- DEMUX_ERROR: 'demux_error',
- INIT_SEGMENT: 'init_segment',
- MEDIA_SEGMENT: 'media_segment',
- LOADING_COMPLETE: 'loading_complete',
- RECOVERED_EARLY_EOF: 'recovered_early_eof',
- MEDIA_INFO: 'media_info',
- STATISTICS_INFO: 'statistics_info',
- RECOMMEND_SEEKPOINT: 'recommend_seekpoint',
- LOADED_SEI: 'loaded_sei'
- };
- exports.default = TransmuxingEvents;
- module.exports = exports['default'];
- /***/ }),
- /* 6 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.createDefaultConfig = createDefaultConfig;
- /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var defaultConfig = exports.defaultConfig = {
- enableWorker: false,
- enableStashBuffer: true,
- stashInitialSize: undefined,
- isLive: false,
- lazyLoad: true,
- lazyLoadMaxDuration: 3 * 60,
- lazyLoadRecoverDuration: 30,
- deferLoadAfterSourceOpen: true,
- // autoCleanupSourceBuffer: default as false, leave unspecified
- autoCleanupMaxBackwardDuration: 3 * 60,
- autoCleanupMinBackwardDuration: 2 * 60,
- statisticsInfoReportInterval: 600,
- fixAudioTimestampGap: true,
- accurateSeek: false,
- seekType: 'range', // [range, param, custom]
- seekParamStart: 'bstart',
- seekParamEnd: 'bend',
- rangeLoadZeroStart: false,
- customSeekHandler: undefined,
- reuseRedirectedURL: false
- // referrerPolicy: leave as unspecified
- };
- function createDefaultConfig() {
- return Object.assign({}, defaultConfig);
- }
- /***/ }),
- /* 7 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var PlayerEvents = {
- ERROR: 'error',
- LOADING_COMPLETE: 'loading_complete',
- RECOVERED_EARLY_EOF: 'recovered_early_eof',
- MEDIA_INFO: 'media_info',
- STATISTICS_INFO: 'statistics_info',
- LOADED_SEI: 'loaded_sei'
- };
- exports.default = PlayerEvents;
- module.exports = exports['default'];
- /***/ }),
- /* 8 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var _events = __webpack_require__(2);
- var _events2 = _interopRequireDefault(_events);
- var _logger = __webpack_require__(0);
- var _logger2 = _interopRequireDefault(_logger);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var LoggingControl = function () {
- function LoggingControl() {
- _classCallCheck(this, LoggingControl);
- }
- _createClass(LoggingControl, null, [{
- key: 'getConfig',
- value: function getConfig() {
- return {
- globalTag: _logger2.default.GLOBAL_TAG,
- forceGlobalTag: _logger2.default.FORCE_GLOBAL_TAG,
- enableVerbose: _logger2.default.ENABLE_VERBOSE,
- enableDebug: _logger2.default.ENABLE_DEBUG,
- enableInfo: _logger2.default.ENABLE_INFO,
- enableWarn: _logger2.default.ENABLE_WARN,
- enableError: _logger2.default.ENABLE_ERROR,
- enableCallback: _logger2.default.ENABLE_CALLBACK
- };
- }
- }, {
- key: 'applyConfig',
- value: function applyConfig(config) {
- _logger2.default.GLOBAL_TAG = config.globalTag;
- _logger2.default.FORCE_GLOBAL_TAG = config.forceGlobalTag;
- _logger2.default.ENABLE_VERBOSE = config.enableVerbose;
- _logger2.default.ENABLE_DEBUG = config.enableDebug;
- _logger2.default.ENABLE_INFO = config.enableInfo;
- _logger2.default.ENABLE_WARN = config.enableWarn;
- _logger2.default.ENABLE_ERROR = config.enableError;
- _logger2.default.ENABLE_CALLBACK = config.enableCallback;
- }
- }, {
- key: '_notifyChange',
- value: function _notifyChange() {
- var emitter = LoggingControl.emitter;
- if (emitter.listenerCount('change') > 0) {
- var config = LoggingControl.getConfig();
- emitter.emit('change', config);
- }
- }
- }, {
- key: 'registerListener',
- value: function registerListener(listener) {
- LoggingControl.emitter.addListener('change', listener);
- }
- }, {
- key: 'removeListener',
- value: function removeListener(listener) {
- LoggingControl.emitter.removeListener('change', listener);
- }
- }, {
- key: 'addLogListener',
- value: function addLogListener(listener) {
- _logger2.default.emitter.addListener('log', listener);
- if (_logger2.default.emitter.listenerCount('log') > 0) {
- _logger2.default.ENABLE_CALLBACK = true;
- LoggingControl._notifyChange();
- }
- }
- }, {
- key: 'removeLogListener',
- value: function removeLogListener(listener) {
- _logger2.default.emitter.removeListener('log', listener);
- if (_logger2.default.emitter.listenerCount('log') === 0) {
- _logger2.default.ENABLE_CALLBACK = false;
- LoggingControl._notifyChange();
- }
- }
- }, {
- key: 'forceGlobalTag',
- get: function get() {
- return _logger2.default.FORCE_GLOBAL_TAG;
- },
- set: function set(enable) {
- _logger2.default.FORCE_GLOBAL_TAG = enable;
- LoggingControl._notifyChange();
- }
- }, {
- key: 'globalTag',
- get: function get() {
- return _logger2.default.GLOBAL_TAG;
- },
- set: function set(tag) {
- _logger2.default.GLOBAL_TAG = tag;
- LoggingControl._notifyChange();
- }
- }, {
- key: 'enableAll',
- get: function get() {
- return _logger2.default.ENABLE_VERBOSE && _logger2.default.ENABLE_DEBUG && _logger2.default.ENABLE_INFO && _logger2.default.ENABLE_WARN && _logger2.default.ENABLE_ERROR;
- },
- set: function set(enable) {
- _logger2.default.ENABLE_VERBOSE = enable;
- _logger2.default.ENABLE_DEBUG = enable;
- _logger2.default.ENABLE_INFO = enable;
- _logger2.default.ENABLE_WARN = enable;
- _logger2.default.ENABLE_ERROR = enable;
- LoggingControl._notifyChange();
- }
- }, {
- key: 'enableDebug',
- get: function get() {
- return _logger2.default.ENABLE_DEBUG;
- },
- set: function set(enable) {
- _logger2.default.ENABLE_DEBUG = enable;
- LoggingControl._notifyChange();
- }
- }, {
- key: 'enableVerbose',
- get: function get() {
- return _logger2.default.ENABLE_VERBOSE;
- },
- set: function set(enable) {
- _logger2.default.ENABLE_VERBOSE = enable;
- LoggingControl._notifyChange();
- }
- }, {
- key: 'enableInfo',
- get: function get() {
- return _logger2.default.ENABLE_INFO;
- },
- set: function set(enable) {
- _logger2.default.ENABLE_INFO = enable;
- LoggingControl._notifyChange();
- }
- }, {
- key: 'enableWarn',
- get: function get() {
- return _logger2.default.ENABLE_WARN;
- },
- set: function set(enable) {
- _logger2.default.ENABLE_WARN = enable;
- LoggingControl._notifyChange();
- }
- }, {
- key: 'enableError',
- get: function get() {
- return _logger2.default.ENABLE_ERROR;
- },
- set: function set(enable) {
- _logger2.default.ENABLE_ERROR = enable;
- LoggingControl._notifyChange();
- }
- }]);
- return LoggingControl;
- }();
- LoggingControl.emitter = new _events2.default();
- exports.default = LoggingControl;
- module.exports = exports['default'];
- /***/ }),
- /* 9 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var MediaInfo = function () {
- function MediaInfo() {
- _classCallCheck(this, MediaInfo);
- this.mimeType = null;
- this.duration = null;
- this.hasAudio = null;
- this.hasVideo = null;
- this.audioCodec = null;
- this.videoCodec = null;
- this.audioDataRate = null;
- this.videoDataRate = null;
- this.audioSampleRate = null;
- this.audioChannelCount = 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;
- this.metadata = null;
- this.segments = null; // MediaInfo[]
- this.segmentCount = null;
- this.hasKeyframesIndex = null;
- this.keyframesIndex = null;
- }
- _createClass(MediaInfo, [{
- key: "isComplete",
- value: function isComplete() {
- var audioInfoComplete = this.hasAudio === false || this.hasAudio === true && this.audioCodec != null && this.audioSampleRate != null && this.audioChannelCount != null;
- 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;
- // keyframesIndex may not be present
- return this.mimeType != null && this.duration != null && this.metadata != null && this.hasKeyframesIndex != null && audioInfoComplete && videoInfoComplete;
- }
- }, {
- key: "isSeekable",
- value: function isSeekable() {
- return this.hasKeyframesIndex === true;
- }
- }, {
- key: "getNearestKeyframe",
- value: function getNearestKeyframe(milliseconds) {
- if (this.keyframesIndex == null) {
- return null;
- }
- var table = this.keyframesIndex;
- var keyframeIdx = this._search(table.times, milliseconds);
- return {
- index: keyframeIdx,
- milliseconds: table.times[keyframeIdx],
- fileposition: table.filepositions[keyframeIdx]
- };
- }
- }, {
- key: "_search",
- value: function _search(list, value) {
- var idx = 0;
- var last = list.length - 1;
- var mid = 0;
- var lbound = 0;
- var ubound = last;
- if (value < list[0]) {
- idx = 0;
- lbound = ubound + 1; // skip search
- }
- while (lbound <= ubound) {
- mid = lbound + Math.floor((ubound - lbound) / 2);
- if (mid === last || value >= list[mid] && value < list[mid + 1]) {
- idx = mid;
- break;
- } else if (list[mid] < value) {
- lbound = mid + 1;
- } else {
- ubound = mid - 1;
- }
- }
- return idx;
- }
- }]);
- return MediaInfo;
- }();
- exports.default = MediaInfo;
- module.exports = exports["default"];
- /***/ }),
- /* 10 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var DemuxErrors = {
- OK: 'OK',
- FORMAT_ERROR: 'FormatError',
- FORMAT_UNSUPPORTED: 'FormatUnsupported',
- CODEC_UNSUPPORTED: 'CodecUnsupported'
- };
- exports.default = DemuxErrors;
- module.exports = exports['default'];
- /***/ }),
- /* 11 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var Polyfill = function () {
- function Polyfill() {
- _classCallCheck(this, Polyfill);
- }
- _createClass(Polyfill, null, [{
- key: 'install',
- value: function install() {
- // ES6 Object.setPrototypeOf
- Object.setPrototypeOf = Object.setPrototypeOf || function (obj, proto) {
- obj.__proto__ = proto;
- return obj;
- };
- // ES6 Object.assign
- Object.assign = Object.assign || function (target) {
- if (target === undefined || target === null) {
- throw new TypeError('Cannot convert undefined or null to object');
- }
- var output = Object(target);
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i];
- if (source !== undefined && source !== null) {
- for (var key in source) {
- if (source.hasOwnProperty(key)) {
- output[key] = source[key];
- }
- }
- }
- }
- return output;
- };
- // ES6 Promise (missing support in IE11)
- if (typeof self.Promise !== 'function') {
- __webpack_require__(22).polyfill();
- }
- }
- }]);
- return Polyfill;
- }();
- Polyfill.install();
- exports.default = Polyfill;
- module.exports = exports['default'];
- /***/ }),
- /* 12 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var _logger = __webpack_require__(0);
- var _logger2 = _interopRequireDefault(_logger);
- var _speedSampler = __webpack_require__(13);
- var _speedSampler2 = _interopRequireDefault(_speedSampler);
- var _loader = __webpack_require__(3);
- var _fetchStreamLoader = __webpack_require__(26);
- var _fetchStreamLoader2 = _interopRequireDefault(_fetchStreamLoader);
- var _xhrMozChunkedLoader = __webpack_require__(27);
- var _xhrMozChunkedLoader2 = _interopRequireDefault(_xhrMozChunkedLoader);
- var _xhrMsstreamLoader = __webpack_require__(28);
- var _xhrMsstreamLoader2 = _interopRequireDefault(_xhrMsstreamLoader);
- var _xhrRangeLoader = __webpack_require__(29);
- var _xhrRangeLoader2 = _interopRequireDefault(_xhrRangeLoader);
- var _websocketLoader = __webpack_require__(30);
- var _websocketLoader2 = _interopRequireDefault(_websocketLoader);
- var _rangeSeekHandler = __webpack_require__(31);
- var _rangeSeekHandler2 = _interopRequireDefault(_rangeSeekHandler);
- var _paramSeekHandler = __webpack_require__(32);
- var _paramSeekHandler2 = _interopRequireDefault(_paramSeekHandler);
- var _exception = __webpack_require__(1);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /**
- * DataSource: {
- * url: string,
- * filesize: number,
- * cors: boolean,
- * withCredentials: boolean
- * }
- *
- */
- // Manage IO Loaders
- var IOController = function () {
- function IOController(dataSource, config, extraData) {
- _classCallCheck(this, IOController);
- this.TAG = 'IOController';
- this._config = config;
- this._extraData = extraData;
- this._stashInitialSize = 1024 * 384; // default initial size: 384KB
- if (config.stashInitialSize != undefined && config.stashInitialSize > 0) {
- // apply from config
- this._stashInitialSize = config.stashInitialSize;
- }
- this._stashUsed = 0;
- this._stashSize = this._stashInitialSize;
- this._bufferSize = 1024 * 1024 * 3; // initial size: 3MB
- this._stashBuffer = new ArrayBuffer(this._bufferSize);
- this._stashByteStart = 0;
- this._enableStash = true;
- if (config.enableStashBuffer === false) {
- this._enableStash = false;
- }
- this._loader = null;
- this._loaderClass = null;
- this._seekHandler = null;
- this._dataSource = dataSource;
- this._isWebSocketURL = /wss?:\/\/(.+?)/.test(dataSource.url);
- this._refTotalLength = dataSource.filesize ? dataSource.filesize : null;
- this._totalLength = this._refTotalLength;
- this._fullRequestFlag = false;
- this._currentRange = null;
- this._redirectedURL = null;
- this._speedNormalized = 0;
- this._speedSampler = new _speedSampler2.default();
- this._speedNormalizeList = [64, 128, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096];
- this._isEarlyEofReconnecting = false;
- this._paused = false;
- this._resumeFrom = 0;
- this._onDataArrival = null;
- this._onSeeked = null;
- this._onError = null;
- this._onComplete = null;
- this._onRedirect = null;
- this._onRecoveredEarlyEof = null;
- this._selectSeekHandler();
- this._selectLoader();
- this._createLoader();
- }
- _createClass(IOController, [{
- key: 'destroy',
- value: function destroy() {
- if (this._loader.isWorking()) {
- this._loader.abort();
- }
- this._loader.destroy();
- this._loader = null;
- this._loaderClass = null;
- this._dataSource = null;
- this._stashBuffer = null;
- this._stashUsed = this._stashSize = this._bufferSize = this._stashByteStart = 0;
- this._currentRange = null;
- this._speedSampler = null;
- this._isEarlyEofReconnecting = false;
- this._onDataArrival = null;
- this._onSeeked = null;
- this._onError = null;
- this._onComplete = null;
- this._onRedirect = null;
- this._onRecoveredEarlyEof = null;
- this._extraData = null;
- }
- }, {
- key: 'isWorking',
- value: function isWorking() {
- return this._loader && this._loader.isWorking() && !this._paused;
- }
- }, {
- key: 'isPaused',
- value: function isPaused() {
- return this._paused;
- }
- }, {
- key: '_selectSeekHandler',
- value: function _selectSeekHandler() {
- var config = this._config;
- if (config.seekType === 'range') {
- this._seekHandler = new _rangeSeekHandler2.default(this._config.rangeLoadZeroStart);
- } else if (config.seekType === 'param') {
- var paramStart = config.seekParamStart || 'bstart';
- var paramEnd = config.seekParamEnd || 'bend';
- this._seekHandler = new _paramSeekHandler2.default(paramStart, paramEnd);
- } else if (config.seekType === 'custom') {
- if (typeof config.customSeekHandler !== 'function') {
- throw new _exception.InvalidArgumentException('Custom seekType specified in config but invalid customSeekHandler!');
- }
- this._seekHandler = new config.customSeekHandler();
- } else {
- throw new _exception.InvalidArgumentException('Invalid seekType in config: ' + config.seekType);
- }
- }
- }, {
- key: '_selectLoader',
- value: function _selectLoader() {
- if (this._isWebSocketURL) {
- this._loaderClass = _websocketLoader2.default;
- } else if (_fetchStreamLoader2.default.isSupported()) {
- this._loaderClass = _fetchStreamLoader2.default;
- } else if (_xhrMozChunkedLoader2.default.isSupported()) {
- this._loaderClass = _xhrMozChunkedLoader2.default;
- } else if (_xhrRangeLoader2.default.isSupported()) {
- this._loaderClass = _xhrRangeLoader2.default;
- } else {
- throw new _exception.RuntimeException('Your browser doesn\'t support xhr with arraybuffer responseType!');
- }
- }
- }, {
- key: '_createLoader',
- value: function _createLoader() {
- this._loader = new this._loaderClass(this._seekHandler, this._config);
- if (this._loader.needStashBuffer === false) {
- this._enableStash = false;
- }
- this._loader.onContentLengthKnown = this._onContentLengthKnown.bind(this);
- this._loader.onURLRedirect = this._onURLRedirect.bind(this);
- this._loader.onDataArrival = this._onLoaderChunkArrival.bind(this);
- this._loader.onComplete = this._onLoaderComplete.bind(this);
- this._loader.onError = this._onLoaderError.bind(this);
- }
- }, {
- key: 'open',
- value: function open(optionalFrom) {
- this._currentRange = { from: 0, to: -1 };
- if (optionalFrom) {
- this._currentRange.from = optionalFrom;
- }
- this._speedSampler.reset();
- if (!optionalFrom) {
- this._fullRequestFlag = true;
- }
- this._loader.open(this._dataSource, Object.assign({}, this._currentRange));
- }
- }, {
- key: 'abort',
- value: function abort() {
- this._loader.abort();
- if (this._paused) {
- this._paused = false;
- this._resumeFrom = 0;
- }
- }
- }, {
- key: 'pause',
- value: function pause() {
- if (this.isWorking()) {
- this._loader.abort();
- if (this._stashUsed !== 0) {
- this._resumeFrom = this._stashByteStart;
- this._currentRange.to = this._stashByteStart - 1;
- } else {
- this._resumeFrom = this._currentRange.to + 1;
- }
- this._stashUsed = 0;
- this._stashByteStart = 0;
- this._paused = true;
- }
- }
- }, {
- key: 'resume',
- value: function resume() {
- if (this._paused) {
- this._paused = false;
- var bytes = this._resumeFrom;
- this._resumeFrom = 0;
- this._internalSeek(bytes, true);
- }
- }
- }, {
- key: 'seek',
- value: function seek(bytes) {
- this._paused = false;
- this._stashUsed = 0;
- this._stashByteStart = 0;
- this._internalSeek(bytes, true);
- }
- /**
- * When seeking request is from media seeking, unconsumed stash data should be dropped
- * However, stash data shouldn't be dropped if seeking requested from http reconnection
- *
- * @dropUnconsumed: Ignore and discard all unconsumed data in stash buffer
- */
- }, {
- key: '_internalSeek',
- value: function _internalSeek(bytes, dropUnconsumed) {
- if (this._loader.isWorking()) {
- this._loader.abort();
- }
- // dispatch & flush stash buffer before seek
- this._flushStashBuffer(dropUnconsumed);
- this._loader.destroy();
- this._loader = null;
- var requestRange = { from: bytes, to: -1 };
- this._currentRange = { from: requestRange.from, to: -1 };
- this._speedSampler.reset();
- this._stashSize = this._stashInitialSize;
- this._createLoader();
- this._loader.open(this._dataSource, requestRange);
- if (this._onSeeked) {
- this._onSeeked();
- }
- }
- }, {
- key: 'updateUrl',
- value: function updateUrl(url) {
- if (!url || typeof url !== 'string' || url.length === 0) {
- throw new _exception.InvalidArgumentException('Url must be a non-empty string!');
- }
- this._dataSource.url = url;
- // TODO: replace with new url
- }
- }, {
- key: '_expandBuffer',
- value: function _expandBuffer(expectedBytes) {
- var bufferNewSize = this._stashSize;
- while (bufferNewSize + 1024 * 1024 * 1 < expectedBytes) {
- bufferNewSize *= 2;
- }
- bufferNewSize += 1024 * 1024 * 1; // bufferSize = stashSize + 1MB
- if (bufferNewSize === this._bufferSize) {
- return;
- }
- var newBuffer = new ArrayBuffer(bufferNewSize);
- if (this._stashUsed > 0) {
- // copy existing data into new buffer
- var stashOldArray = new Uint8Array(this._stashBuffer, 0, this._stashUsed);
- var stashNewArray = new Uint8Array(newBuffer, 0, bufferNewSize);
- stashNewArray.set(stashOldArray, 0);
- }
- this._stashBuffer = newBuffer;
- this._bufferSize = bufferNewSize;
- }
- }, {
- key: '_normalizeSpeed',
- value: function _normalizeSpeed(input) {
- var list = this._speedNormalizeList;
- var last = list.length - 1;
- var mid = 0;
- var lbound = 0;
- var ubound = last;
- if (input < list[0]) {
- return list[0];
- }
- // binary search
- while (lbound <= ubound) {
- mid = lbound + Math.floor((ubound - lbound) / 2);
- if (mid === last || input >= list[mid] && input < list[mid + 1]) {
- return list[mid];
- } else if (list[mid] < input) {
- lbound = mid + 1;
- } else {
- ubound = mid - 1;
- }
- }
- }
- }, {
- key: '_adjustStashSize',
- value: function _adjustStashSize(normalized) {
- var stashSizeKB = 0;
- if (this._config.isLive) {
- // live stream: always use single normalized speed for size of stashSizeKB
- stashSizeKB = normalized;
- } else {
- if (normalized < 512) {
- stashSizeKB = normalized;
- } else if (normalized >= 512 && normalized <= 1024) {
- stashSizeKB = Math.floor(normalized * 1.5);
- } else {
- stashSizeKB = normalized * 2;
- }
- }
- if (stashSizeKB > 8192) {
- stashSizeKB = 8192;
- }
- var bufferSize = stashSizeKB * 1024 + 1024 * 1024 * 1; // stashSize + 1MB
- if (this._bufferSize < bufferSize) {
- this._expandBuffer(bufferSize);
- }
- this._stashSize = stashSizeKB * 1024;
- }
- }, {
- key: '_dispatchChunks',
- value: function _dispatchChunks(chunks, byteStart) {
- this._currentRange.to = byteStart + chunks.byteLength - 1;
- return this._onDataArrival(chunks, byteStart);
- }
- }, {
- key: '_onURLRedirect',
- value: function _onURLRedirect(redirectedURL) {
- this._redirectedURL = redirectedURL;
- if (this._onRedirect) {
- this._onRedirect(redirectedURL);
- }
- }
- }, {
- key: '_onContentLengthKnown',
- value: function _onContentLengthKnown(contentLength) {
- if (contentLength && this._fullRequestFlag) {
- this._totalLength = contentLength;
- this._fullRequestFlag = false;
- }
- }
- }, {
- key: '_onLoaderChunkArrival',
- value: function _onLoaderChunkArrival(chunk, byteStart, receivedLength) {
- if (!this._onDataArrival) {
- throw new _exception.IllegalStateException('IOController: No existing consumer (onDataArrival) callback!');
- }
- if (this._paused) {
- return;
- }
- if (this._isEarlyEofReconnecting) {
- // Auto-reconnect for EarlyEof succeed, notify to upper-layer by callback
- this._isEarlyEofReconnecting = false;
- if (this._onRecoveredEarlyEof) {
- this._onRecoveredEarlyEof();
- }
- }
- this._speedSampler.addBytes(chunk.byteLength);
- // adjust stash buffer size according to network speed dynamically
- var KBps = this._speedSampler.lastSecondKBps;
- if (KBps !== 0) {
- var normalized = this._normalizeSpeed(KBps);
- if (this._speedNormalized !== normalized) {
- this._speedNormalized = normalized;
- this._adjustStashSize(normalized);
- }
- }
- if (!this._enableStash) {
- // disable stash
- if (this._stashUsed === 0) {
- // dispatch chunk directly to consumer;
- // check ret value (consumed bytes) and stash unconsumed to stashBuffer
- var consumed = this._dispatchChunks(chunk, byteStart);
- if (consumed < chunk.byteLength) {
- // unconsumed data remain.
- var remain = chunk.byteLength - consumed;
- if (remain > this._bufferSize) {
- this._expandBuffer(remain);
- }
- var stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
- stashArray.set(new Uint8Array(chunk, consumed), 0);
- this._stashUsed += remain;
- this._stashByteStart = byteStart + consumed;
- }
- } else {
- // else: Merge chunk into stashBuffer, and dispatch stashBuffer to consumer.
- if (this._stashUsed + chunk.byteLength > this._bufferSize) {
- this._expandBuffer(this._stashUsed + chunk.byteLength);
- }
- var _stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
- _stashArray.set(new Uint8Array(chunk), this._stashUsed);
- this._stashUsed += chunk.byteLength;
- var _consumed = this._dispatchChunks(this._stashBuffer.slice(0, this._stashUsed), this._stashByteStart);
- if (_consumed < this._stashUsed && _consumed > 0) {
- // unconsumed data remain
- var remainArray = new Uint8Array(this._stashBuffer, _consumed);
- _stashArray.set(remainArray, 0);
- }
- this._stashUsed -= _consumed;
- this._stashByteStart += _consumed;
- }
- } else {
- // enable stash
- if (this._stashUsed === 0 && this._stashByteStart === 0) {
- // seeked? or init chunk?
- // This is the first chunk after seek action
- this._stashByteStart = byteStart;
- }
- if (this._stashUsed + chunk.byteLength <= this._stashSize) {
- // just stash
- var _stashArray2 = new Uint8Array(this._stashBuffer, 0, this._stashSize);
- _stashArray2.set(new Uint8Array(chunk), this._stashUsed);
- this._stashUsed += chunk.byteLength;
- } else {
- // stashUsed + chunkSize > stashSize, size limit exceeded
- var _stashArray3 = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
- if (this._stashUsed > 0) {
- // There're stash datas in buffer
- // dispatch the whole stashBuffer, and stash remain data
- // then append chunk to stashBuffer (stash)
- var buffer = this._stashBuffer.slice(0, this._stashUsed);
- var _consumed2 = this._dispatchChunks(buffer, this._stashByteStart);
- if (_consumed2 < buffer.byteLength) {
- if (_consumed2 > 0) {
- var _remainArray = new Uint8Array(buffer, _consumed2);
- _stashArray3.set(_remainArray, 0);
- this._stashUsed = _remainArray.byteLength;
- this._stashByteStart += _consumed2;
- }
- } else {
- this._stashUsed = 0;
- this._stashByteStart += _consumed2;
- }
- if (this._stashUsed + chunk.byteLength > this._bufferSize) {
- this._expandBuffer(this._stashUsed + chunk.byteLength);
- _stashArray3 = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
- }
- _stashArray3.set(new Uint8Array(chunk), this._stashUsed);
- this._stashUsed += chunk.byteLength;
- } else {
- // stash buffer empty, but chunkSize > stashSize (oh, holy shit)
- // dispatch chunk directly and stash remain data
- var _consumed3 = this._dispatchChunks(chunk, byteStart);
- if (_consumed3 < chunk.byteLength) {
- var _remain = chunk.byteLength - _consumed3;
- if (_remain > this._bufferSize) {
- this._expandBuffer(_remain);
- _stashArray3 = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
- }
- _stashArray3.set(new Uint8Array(chunk, _consumed3), 0);
- this._stashUsed += _remain;
- this._stashByteStart = byteStart + _consumed3;
- }
- }
- }
- }
- }
- }, {
- key: '_flushStashBuffer',
- value: function _flushStashBuffer(dropUnconsumed) {
- if (this._stashUsed > 0) {
- var buffer = this._stashBuffer.slice(0, this._stashUsed);
- var consumed = this._dispatchChunks(buffer, this._stashByteStart);
- var remain = buffer.byteLength - consumed;
- if (consumed < buffer.byteLength) {
- if (dropUnconsumed) {
- _logger2.default.w(this.TAG, remain + ' bytes unconsumed data remain when flush buffer, dropped');
- } else {
- if (consumed > 0) {
- var stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
- var remainArray = new Uint8Array(buffer, consumed);
- stashArray.set(remainArray, 0);
- this._stashUsed = remainArray.byteLength;
- this._stashByteStart += consumed;
- }
- return 0;
- }
- }
- this._stashUsed = 0;
- this._stashByteStart = 0;
- return remain;
- }
- return 0;
- }
- }, {
- key: '_onLoaderComplete',
- value: function _onLoaderComplete(from, to) {
- // Force-flush stash buffer, and drop unconsumed data
- this._flushStashBuffer(true);
- if (this._onComplete) {
- this._onComplete(this._extraData);
- }
- }
- }, {
- key: '_onLoaderError',
- value: function _onLoaderError(type, data) {
- _logger2.default.e(this.TAG, 'Loader error, code = ' + data.code + ', msg = ' + data.msg);
- this._flushStashBuffer(false);
- if (this._isEarlyEofReconnecting) {
- // Auto-reconnect for EarlyEof failed, throw UnrecoverableEarlyEof error to upper-layer
- this._isEarlyEofReconnecting = false;
- type = _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF;
- }
- switch (type) {
- case _loader.LoaderErrors.EARLY_EOF:
- {
- if (!this._config.isLive) {
- // Do internal http reconnect if not live stream
- if (this._totalLength) {
- var nextFrom = this._currentRange.to + 1;
- if (nextFrom < this._totalLength) {
- _logger2.default.w(this.TAG, 'Connection lost, trying reconnect...');
- this._isEarlyEofReconnecting = true;
- this._internalSeek(nextFrom, false);
- }
- return;
- }
- // else: We don't know totalLength, throw UnrecoverableEarlyEof
- }
- // live stream: throw UnrecoverableEarlyEof error to upper-layer
- type = _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF;
- break;
- }
- case _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF:
- case _loader.LoaderErrors.CONNECTING_TIMEOUT:
- case _loader.LoaderErrors.HTTP_STATUS_CODE_INVALID:
- case _loader.LoaderErrors.EXCEPTION:
- break;
- }
- if (this._onError) {
- this._onError(type, data);
- } else {
- throw new _exception.RuntimeException('IOException: ' + data.msg);
- }
- }
- }, {
- key: 'status',
- get: function get() {
- return this._loader.status;
- }
- }, {
- key: 'extraData',
- get: function get() {
- return this._extraData;
- },
- set: function set(data) {
- this._extraData = data;
- }
- // prototype: function onDataArrival(chunks: ArrayBuffer, byteStart: number): number
- }, {
- key: 'onDataArrival',
- get: function get() {
- return this._onDataArrival;
- },
- set: function set(callback) {
- this._onDataArrival = callback;
- }
- }, {
- key: 'onSeeked',
- get: function get() {
- return this._onSeeked;
- },
- set: function set(callback) {
- this._onSeeked = callback;
- }
- // prototype: function onError(type: number, info: {code: number, msg: string}): void
- }, {
- key: 'onError',
- get: function get() {
- return this._onError;
- },
- set: function set(callback) {
- this._onError = callback;
- }
- }, {
- key: 'onComplete',
- get: function get() {
- return this._onComplete;
- },
- set: function set(callback) {
- this._onComplete = callback;
- }
- }, {
- key: 'onRedirect',
- get: function get() {
- return this._onRedirect;
- },
- set: function set(callback) {
- this._onRedirect = callback;
- }
- }, {
- key: 'onRecoveredEarlyEof',
- get: function get() {
- return this._onRecoveredEarlyEof;
- },
- set: function set(callback) {
- this._onRecoveredEarlyEof = callback;
- }
- }, {
- key: 'currentURL',
- get: function get() {
- return this._dataSource.url;
- }
- }, {
- key: 'hasRedirect',
- get: function get() {
- return this._redirectedURL != null || this._dataSource.redirectedURL != undefined;
- }
- }, {
- key: 'currentRedirectedURL',
- get: function get() {
- return this._redirectedURL || this._dataSource.redirectedURL;
- }
- // in KB/s
- }, {
- key: 'currentSpeed',
- get: function get() {
- if (this._loaderClass === _xhrRangeLoader2.default) {
- // SpeedSampler is inaccuracy if loader is RangeLoader
- return this._loader.currentSpeed;
- }
- return this._speedSampler.lastSecondKBps;
- }
- }, {
- key: 'loaderType',
- get: function get() {
- return this._loader.type;
- }
- }]);
- return IOController;
- }();
- exports.default = IOController;
- module.exports = exports['default'];
- /***/ }),
- /* 13 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- // Utility class to calculate realtime network I/O speed
- var SpeedSampler = function () {
- function SpeedSampler() {
- _classCallCheck(this, SpeedSampler);
- // milliseconds
- this._firstCheckpoint = 0;
- this._lastCheckpoint = 0;
- this._intervalBytes = 0;
- this._totalBytes = 0;
- this._lastSecondBytes = 0;
- // compatibility detection
- if (self.performance && self.performance.now) {
- this._now = self.performance.now.bind(self.performance);
- } else {
- this._now = Date.now;
- }
- }
- _createClass(SpeedSampler, [{
- key: "reset",
- value: function reset() {
- this._firstCheckpoint = this._lastCheckpoint = 0;
- this._totalBytes = this._intervalBytes = 0;
- this._lastSecondBytes = 0;
- }
- }, {
- key: "addBytes",
- value: function addBytes(bytes) {
- if (this._firstCheckpoint === 0) {
- this._firstCheckpoint = this._now();
- this._lastCheckpoint = this._firstCheckpoint;
- this._intervalBytes += bytes;
- this._totalBytes += bytes;
- } else if (this._now() - this._lastCheckpoint < 1000) {
- this._intervalBytes += bytes;
- this._totalBytes += bytes;
- } else {
- // duration >= 1000
- this._lastSecondBytes = this._intervalBytes;
- this._intervalBytes = bytes;
- this._totalBytes += bytes;
- this._lastCheckpoint = this._now();
- }
- }
- }, {
- key: "currentKBps",
- get: function get() {
- this.addBytes(0);
- var durationSeconds = (this._now() - this._lastCheckpoint) / 1000;
- if (durationSeconds == 0) durationSeconds = 1;
- return this._intervalBytes / durationSeconds / 1024;
- }
- }, {
- key: "lastSecondKBps",
- get: function get() {
- this.addBytes(0);
- if (this._lastSecondBytes !== 0) {
- return this._lastSecondBytes / 1024;
- } else {
- // lastSecondBytes === 0
- if (this._now() - this._lastCheckpoint >= 500) {
- // if time interval since last checkpoint has exceeded 500ms
- // the speed is nearly accurate
- return this.currentKBps;
- } else {
- // We don't know
- return 0;
- }
- }
- }
- }, {
- key: "averageKBps",
- get: function get() {
- var durationSeconds = (this._now() - this._firstCheckpoint) / 1000;
- return this._totalBytes / durationSeconds / 1024;
- }
- }]);
- return SpeedSampler;
- }();
- exports.default = SpeedSampler;
- module.exports = exports["default"];
- /***/ }),
- /* 14 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var _events = __webpack_require__(2);
- var _events2 = _interopRequireDefault(_events);
- var _logger = __webpack_require__(0);
- var _logger2 = _interopRequireDefault(_logger);
- var _browser = __webpack_require__(4);
- var _browser2 = _interopRequireDefault(_browser);
- var _mediaInfo = __webpack_require__(9);
- var _mediaInfo2 = _interopRequireDefault(_mediaInfo);
- var _flvDemuxer = __webpack_require__(35);
- var _flvDemuxer2 = _interopRequireDefault(_flvDemuxer);
- var _mp4Remuxer = __webpack_require__(40);
- var _mp4Remuxer2 = _interopRequireDefault(_mp4Remuxer);
- var _demuxErrors = __webpack_require__(10);
- var _demuxErrors2 = _interopRequireDefault(_demuxErrors);
- var _ioController = __webpack_require__(12);
- var _ioController2 = _interopRequireDefault(_ioController);
- var _transmuxingEvents = __webpack_require__(5);
- var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
- var _loader = __webpack_require__(3);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- // Transmuxing (IO, Demuxing, Remuxing) controller, with multipart support
- var TransmuxingController = function () {
- function TransmuxingController(mediaDataSource, config) {
- _classCallCheck(this, TransmuxingController);
- this.TAG = 'TransmuxingController';
- this._emitter = new _events2.default();
- this._config = config;
- // treat single part media as multipart media, which has only one segment
- if (!mediaDataSource.segments) {
- mediaDataSource.segments = [{
- duration: mediaDataSource.duration,
- filesize: mediaDataSource.filesize,
- url: mediaDataSource.url
- }];
- }
- // fill in default IO params if not exists
- if (typeof mediaDataSource.cors !== 'boolean') {
- mediaDataSource.cors = true;
- }
- if (typeof mediaDataSource.withCredentials !== 'boolean') {
- mediaDataSource.withCredentials = false;
- }
- this._mediaDataSource = mediaDataSource;
- this._currentSegmentIndex = 0;
- var totalDuration = 0;
- this._mediaDataSource.segments.forEach(function (segment) {
- // timestampBase for each segment, and calculate total duration
- segment.timestampBase = totalDuration;
- totalDuration += segment.duration;
- // params needed by IOController
- segment.cors = mediaDataSource.cors;
- segment.withCredentials = mediaDataSource.withCredentials;
- // referrer policy control, if exist
- if (config.referrerPolicy) {
- segment.referrerPolicy = config.referrerPolicy;
- }
- });
- if (!isNaN(totalDuration) && this._mediaDataSource.duration !== totalDuration) {
- this._mediaDataSource.duration = totalDuration;
- }
- this._mediaInfo = null;
- this._demuxer = null;
- this._remuxer = null;
- this._ioctl = null;
- this._pendingSeekTime = null;
- this._pendingResolveSeekPoint = null;
- this._statisticsReporter = null;
- }
- _createClass(TransmuxingController, [{
- key: 'destroy',
- value: function destroy() {
- this._mediaInfo = null;
- this._mediaDataSource = null;
- if (this._statisticsReporter) {
- this._disableStatisticsReporter();
- }
- if (this._ioctl) {
- this._ioctl.destroy();
- this._ioctl = null;
- }
- if (this._demuxer) {
- this._demuxer.destroy();
- this._demuxer = null;
- }
- if (this._remuxer) {
- this._remuxer.destroy();
- this._remuxer = null;
- }
- this._emitter.removeAllListeners();
- this._emitter = null;
- }
- }, {
- key: 'on',
- value: function on(event, listener) {
- this._emitter.addListener(event, listener);
- }
- }, {
- key: 'off',
- value: function off(event, listener) {
- this._emitter.removeListener(event, listener);
- }
- }, {
- key: 'start',
- value: function start() {
- this._loadSegment(0);
- this._enableStatisticsReporter();
- }
- }, {
- key: '_loadSegment',
- value: function _loadSegment(segmentIndex, optionalFrom) {
- this._currentSegmentIndex = segmentIndex;
- var dataSource = this._mediaDataSource.segments[segmentIndex];
- var ioctl = this._ioctl = new _ioController2.default(dataSource, this._config, segmentIndex);
- ioctl.onError = this._onIOException.bind(this);
- ioctl.onSeeked = this._onIOSeeked.bind(this);
- ioctl.onComplete = this._onIOComplete.bind(this);
- ioctl.onRedirect = this._onIORedirect.bind(this);
- ioctl.onRecoveredEarlyEof = this._onIORecoveredEarlyEof.bind(this);
- if (optionalFrom) {
- this._demuxer.bindDataSource(this._ioctl);
- } else {
- ioctl.onDataArrival = this._onInitChunkArrival.bind(this);
- }
- ioctl.open(optionalFrom);
- }
- }, {
- key: 'stop',
- value: function stop() {
- this._internalAbort();
- this._disableStatisticsReporter();
- }
- }, {
- key: '_internalAbort',
- value: function _internalAbort() {
- if (this._ioctl) {
- this._ioctl.destroy();
- this._ioctl = null;
- }
- }
- }, {
- key: 'pause',
- value: function pause() {
- // take a rest
- if (this._ioctl && this._ioctl.isWorking()) {
- this._ioctl.pause();
- this._disableStatisticsReporter();
- }
- }
- }, {
- key: 'resume',
- value: function resume() {
- if (this._ioctl && this._ioctl.isPaused()) {
- this._ioctl.resume();
- this._enableStatisticsReporter();
- }
- }
- }, {
- key: 'seek',
- value: function seek(milliseconds) {
- if (this._mediaInfo == null || !this._mediaInfo.isSeekable()) {
- return;
- }
- var targetSegmentIndex = this._searchSegmentIndexContains(milliseconds);
- if (targetSegmentIndex === this._currentSegmentIndex) {
- // intra-segment seeking
- var segmentInfo = this._mediaInfo.segments[targetSegmentIndex];
- if (segmentInfo == undefined) {
- // current segment loading started, but mediainfo hasn't received yet
- // wait for the metadata loaded, then seek to expected position
- this._pendingSeekTime = milliseconds;
- } else {
- var keyframe = segmentInfo.getNearestKeyframe(milliseconds);
- this._remuxer.seek(keyframe.milliseconds);
- this._ioctl.seek(keyframe.fileposition);
- // Will be resolved in _onRemuxerMediaSegmentArrival()
- this._pendingResolveSeekPoint = keyframe.milliseconds;
- }
- } else {
- // cross-segment seeking
- var targetSegmentInfo = this._mediaInfo.segments[targetSegmentIndex];
- if (targetSegmentInfo == undefined) {
- // target segment hasn't been loaded. We need metadata then seek to expected time
- this._pendingSeekTime = milliseconds;
- this._internalAbort();
- this._remuxer.seek();
- this._remuxer.insertDiscontinuity();
- this._loadSegment(targetSegmentIndex);
- // Here we wait for the metadata loaded, then seek to expected position
- } else {
- // We have target segment's metadata, direct seek to target position
- var _keyframe = targetSegmentInfo.getNearestKeyframe(milliseconds);
- this._internalAbort();
- this._remuxer.seek(milliseconds);
- this._remuxer.insertDiscontinuity();
- this._demuxer.resetMediaInfo();
- this._demuxer.timestampBase = this._mediaDataSource.segments[targetSegmentIndex].timestampBase;
- this._loadSegment(targetSegmentIndex, _keyframe.fileposition);
- this._pendingResolveSeekPoint = _keyframe.milliseconds;
- this._reportSegmentMediaInfo(targetSegmentIndex);
- }
- }
- this._enableStatisticsReporter();
- }
- }, {
- key: '_searchSegmentIndexContains',
- value: function _searchSegmentIndexContains(milliseconds) {
- var segments = this._mediaDataSource.segments;
- var idx = segments.length - 1;
- for (var i = 0; i < segments.length; i++) {
- if (milliseconds < segments[i].timestampBase) {
- idx = i - 1;
- break;
- }
- }
- return idx;
- }
- }, {
- key: '_onInitChunkArrival',
- value: function _onInitChunkArrival(data, byteStart) {
- var _this = this;
- var probeData = null;
- var consumed = 0;
- if (byteStart > 0) {
- // IOController seeked immediately after opened, byteStart > 0 callback may received
- this._demuxer.bindDataSource(this._ioctl);
- this._demuxer.timestampBase = this._mediaDataSource.segments[this._currentSegmentIndex].timestampBase;
- consumed = this._demuxer.parseChunks(data, byteStart);
- } else if ((probeData = _flvDemuxer2.default.probe(data)).match) {
- // Always create new FLVDemuxer
- this._demuxer = new _flvDemuxer2.default(probeData, this._config);
- if (!this._remuxer) {
- this._remuxer = new _mp4Remuxer2.default(this._config);
- }
- var mds = this._mediaDataSource;
- if (mds.duration != undefined && !isNaN(mds.duration)) {
- this._demuxer.overridedDuration = mds.duration;
- }
- if (typeof mds.hasAudio === 'boolean') {
- this._demuxer.overridedHasAudio = mds.hasAudio;
- }
- if (typeof mds.hasVideo === 'boolean') {
- this._demuxer.overridedHasVideo = mds.hasVideo;
- }
- this._demuxer.timestampBase = mds.segments[this._currentSegmentIndex].timestampBase;
- this._demuxer.onError = this._onDemuxException.bind(this);
- this._demuxer.onMediaInfo = this._onMediaInfo.bind(this);
- this._demuxer.onLoadedSei = this._onLoadedSei.bind(this);
- this._remuxer.bindDataSource(this._demuxer.bindDataSource(this._ioctl));
- this._remuxer.onInitSegment = this._onRemuxerInitSegmentArrival.bind(this);
- this._remuxer.onMediaSegment = this._onRemuxerMediaSegmentArrival.bind(this);
- consumed = this._demuxer.parseChunks(data, byteStart);
- } else {
- probeData = null;
- _logger2.default.e(this.TAG, 'Non-FLV, Unsupported media type!');
- Promise.resolve().then(function () {
- _this._internalAbort();
- });
- this._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR, _demuxErrors2.default.FORMAT_UNSUPPORTED, 'Non-FLV, Unsupported media type');
- consumed = 0;
- }
- return consumed;
- }
- }, {
- key: '_onMediaInfo',
- value: function _onMediaInfo(mediaInfo) {
- var _this2 = this;
- if (this._mediaInfo == null) {
- // Store first segment's mediainfo as global mediaInfo
- this._mediaInfo = Object.assign({}, mediaInfo);
- this._mediaInfo.keyframesIndex = null;
- this._mediaInfo.segments = [];
- this._mediaInfo.segmentCount = this._mediaDataSource.segments.length;
- Object.setPrototypeOf(this._mediaInfo, _mediaInfo2.default.prototype);
- }
- var segmentInfo = Object.assign({}, mediaInfo);
- Object.setPrototypeOf(segmentInfo, _mediaInfo2.default.prototype);
- this._mediaInfo.segments[this._currentSegmentIndex] = segmentInfo;
- // notify mediaInfo update
- this._reportSegmentMediaInfo(this._currentSegmentIndex);
- if (this._pendingSeekTime != null) {
- Promise.resolve().then(function () {
- var target = _this2._pendingSeekTime;
- _this2._pendingSeekTime = null;
- _this2.seek(target);
- });
- }
- }
- }, {
- key: '_onLoadedSei',
- value: function _onLoadedSei(timestamp, data) {
- this._emitter.emit(_transmuxingEvents2.default.LOADED_SEI, timestamp, data);
- }
- }, {
- key: '_onIOSeeked',
- value: function _onIOSeeked() {
- this._remuxer.insertDiscontinuity();
- }
- }, {
- key: '_onIOComplete',
- value: function _onIOComplete(extraData) {
- var segmentIndex = extraData;
- var nextSegmentIndex = segmentIndex + 1;
- if (nextSegmentIndex < this._mediaDataSource.segments.length) {
- this._internalAbort();
- this._remuxer.flushStashedSamples();
- this._loadSegment(nextSegmentIndex);
- } else {
- this._remuxer.flushStashedSamples();
- this._emitter.emit(_transmuxingEvents2.default.LOADING_COMPLETE);
- this._disableStatisticsReporter();
- }
- }
- }, {
- key: '_onIORedirect',
- value: function _onIORedirect(redirectedURL) {
- var segmentIndex = this._ioctl.extraData;
- this._mediaDataSource.segments[segmentIndex].redirectedURL = redirectedURL;
- }
- }, {
- key: '_onIORecoveredEarlyEof',
- value: function _onIORecoveredEarlyEof() {
- this._emitter.emit(_transmuxingEvents2.default.RECOVERED_EARLY_EOF);
- }
- }, {
- key: '_onIOException',
- value: function _onIOException(type, info) {
- _logger2.default.e(this.TAG, 'IOException: type = ' + type + ', code = ' + info.code + ', msg = ' + info.msg);
- this._emitter.emit(_transmuxingEvents2.default.IO_ERROR, type, info);
- this._disableStatisticsReporter();
- }
- }, {
- key: '_onDemuxException',
- value: function _onDemuxException(type, info) {
- _logger2.default.e(this.TAG, 'DemuxException: type = ' + type + ', info = ' + info);
- this._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR, type, info);
- }
- }, {
- key: '_onRemuxerInitSegmentArrival',
- value: function _onRemuxerInitSegmentArrival(type, initSegment) {
- this._emitter.emit(_transmuxingEvents2.default.INIT_SEGMENT, type, initSegment);
- }
- }, {
- key: '_onRemuxerMediaSegmentArrival',
- value: function _onRemuxerMediaSegmentArrival(type, mediaSegment) {
- if (this._pendingSeekTime != null) {
- // Media segments after new-segment cross-seeking should be dropped.
- return;
- }
- this._emitter.emit(_transmuxingEvents2.default.MEDIA_SEGMENT, type, mediaSegment);
- // Resolve pending seekPoint
- if (this._pendingResolveSeekPoint != null && type === 'video') {
- var syncPoints = mediaSegment.info.syncPoints;
- var seekpoint = this._pendingResolveSeekPoint;
- this._pendingResolveSeekPoint = null;
- // Safari: Pass PTS for recommend_seekpoint
- if (_browser2.default.safari && syncPoints.length > 0 && syncPoints[0].originalDts === seekpoint) {
- seekpoint = syncPoints[0].pts;
- }
- // else: use original DTS (keyframe.milliseconds)
- this._emitter.emit(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, seekpoint);
- }
- }
- }, {
- key: '_enableStatisticsReporter',
- value: function _enableStatisticsReporter() {
- if (this._statisticsReporter == null) {
- this._statisticsReporter = self.setInterval(this._reportStatisticsInfo.bind(this), this._config.statisticsInfoReportInterval);
- }
- }
- }, {
- key: '_disableStatisticsReporter',
- value: function _disableStatisticsReporter() {
- if (this._statisticsReporter) {
- self.clearInterval(this._statisticsReporter);
- this._statisticsReporter = null;
- }
- }
- }, {
- key: '_reportSegmentMediaInfo',
- value: function _reportSegmentMediaInfo(segmentIndex) {
- var segmentInfo = this._mediaInfo.segments[segmentIndex];
- var exportInfo = Object.assign({}, segmentInfo);
- exportInfo.duration = this._mediaInfo.duration;
- exportInfo.segmentCount = this._mediaInfo.segmentCount;
- delete exportInfo.segments;
- delete exportInfo.keyframesIndex;
- this._emitter.emit(_transmuxingEvents2.default.MEDIA_INFO, exportInfo);
- }
- }, {
- key: '_reportStatisticsInfo',
- value: function _reportStatisticsInfo() {
- var info = {};
- info.url = this._ioctl.currentURL;
- info.hasRedirect = this._ioctl.hasRedirect;
- if (info.hasRedirect) {
- info.redirectedURL = this._ioctl.currentRedirectedURL;
- }
- info.speed = this._ioctl.currentSpeed;
- info.loaderType = this._ioctl.loaderType;
- info.currentSegmentIndex = this._currentSegmentIndex;
- info.totalSegmentCount = this._mediaDataSource.segments.length;
- this._emitter.emit(_transmuxingEvents2.default.STATISTICS_INFO, info);
- }
- }]);
- return TransmuxingController;
- }();
- exports.default = TransmuxingController;
- module.exports = exports['default'];
- /***/ }),
- /* 15 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- // Represents an media sample (audio / video)
- var SampleInfo = exports.SampleInfo = function SampleInfo(dts, pts, duration, originalDts, isSync) {
- _classCallCheck(this, SampleInfo);
- this.dts = dts;
- this.pts = pts;
- this.duration = duration;
- this.originalDts = originalDts;
- this.isSyncPoint = isSync;
- this.fileposition = null;
- };
- // Media Segment concept is defined in Media Source Extensions spec.
- // Particularly in ISO BMFF format, an Media Segment contains a moof box followed by a mdat box.
- var MediaSegmentInfo = exports.MediaSegmentInfo = function () {
- function MediaSegmentInfo() {
- _classCallCheck(this, MediaSegmentInfo);
- this.beginDts = 0;
- this.endDts = 0;
- this.beginPts = 0;
- this.endPts = 0;
- this.originalBeginDts = 0;
- this.originalEndDts = 0;
- this.syncPoints = []; // SampleInfo[n], for video IDR frames only
- this.firstSample = null; // SampleInfo
- this.lastSample = null; // SampleInfo
- }
- _createClass(MediaSegmentInfo, [{
- key: "appendSyncPoint",
- value: function appendSyncPoint(sampleInfo) {
- // also called Random Access Point
- sampleInfo.isSyncPoint = true;
- this.syncPoints.push(sampleInfo);
- }
- }]);
- return MediaSegmentInfo;
- }();
- // Ordered list for recording video IDR frames, sorted by originalDts
- var IDRSampleList = exports.IDRSampleList = function () {
- function IDRSampleList() {
- _classCallCheck(this, IDRSampleList);
- this._list = [];
- }
- _createClass(IDRSampleList, [{
- key: "clear",
- value: function clear() {
- this._list = [];
- }
- }, {
- key: "appendArray",
- value: function appendArray(syncPoints) {
- var list = this._list;
- if (syncPoints.length === 0) {
- return;
- }
- if (list.length > 0 && syncPoints[0].originalDts < list[list.length - 1].originalDts) {
- this.clear();
- }
- Array.prototype.push.apply(list, syncPoints);
- }
- }, {
- key: "getLastSyncPointBeforeDts",
- value: function getLastSyncPointBeforeDts(dts) {
- if (this._list.length == 0) {
- return null;
- }
- var list = this._list;
- var idx = 0;
- var last = list.length - 1;
- var mid = 0;
- var lbound = 0;
- var ubound = last;
- if (dts < list[0].dts) {
- idx = 0;
- lbound = ubound + 1;
- }
- while (lbound <= ubound) {
- mid = lbound + Math.floor((ubound - lbound) / 2);
- if (mid === last || dts >= list[mid].dts && dts < list[mid + 1].dts) {
- idx = mid;
- break;
- } else if (list[mid].dts < dts) {
- lbound = mid + 1;
- } else {
- ubound = mid - 1;
- }
- }
- return this._list[idx];
- }
- }]);
- return IDRSampleList;
- }();
- // Data structure for recording information of media segments in single track.
- var MediaSegmentInfoList = exports.MediaSegmentInfoList = function () {
- function MediaSegmentInfoList(type) {
- _classCallCheck(this, MediaSegmentInfoList);
- this._type = type;
- this._list = [];
- this._lastAppendLocation = -1; // cached last insert location
- }
- _createClass(MediaSegmentInfoList, [{
- key: "isEmpty",
- value: function isEmpty() {
- return this._list.length === 0;
- }
- }, {
- key: "clear",
- value: function clear() {
- this._list = [];
- this._lastAppendLocation = -1;
- }
- }, {
- key: "_searchNearestSegmentBefore",
- value: function _searchNearestSegmentBefore(originalBeginDts) {
- var list = this._list;
- if (list.length === 0) {
- return -2;
- }
- var last = list.length - 1;
- var mid = 0;
- var lbound = 0;
- var ubound = last;
- var idx = 0;
- if (originalBeginDts < list[0].originalBeginDts) {
- idx = -1;
- return idx;
- }
- while (lbound <= ubound) {
- mid = lbound + Math.floor((ubound - lbound) / 2);
- if (mid === last || originalBeginDts > list[mid].lastSample.originalDts && originalBeginDts < list[mid + 1].originalBeginDts) {
- idx = mid;
- break;
- } else if (list[mid].originalBeginDts < originalBeginDts) {
- lbound = mid + 1;
- } else {
- ubound = mid - 1;
- }
- }
- return idx;
- }
- }, {
- key: "_searchNearestSegmentAfter",
- value: function _searchNearestSegmentAfter(originalBeginDts) {
- return this._searchNearestSegmentBefore(originalBeginDts) + 1;
- }
- }, {
- key: "append",
- value: function append(mediaSegmentInfo) {
- var list = this._list;
- var msi = mediaSegmentInfo;
- var lastAppendIdx = this._lastAppendLocation;
- var insertIdx = 0;
- 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)) {
- insertIdx = lastAppendIdx + 1; // use cached location idx
- } else {
- if (list.length > 0) {
- insertIdx = this._searchNearestSegmentBefore(msi.originalBeginDts) + 1;
- }
- }
- this._lastAppendLocation = insertIdx;
- this._list.splice(insertIdx, 0, msi);
- }
- }, {
- key: "getLastSegmentBefore",
- value: function getLastSegmentBefore(originalBeginDts) {
- var idx = this._searchNearestSegmentBefore(originalBeginDts);
- if (idx >= 0) {
- return this._list[idx];
- } else {
- // -1
- return null;
- }
- }
- }, {
- key: "getLastSampleBefore",
- value: function getLastSampleBefore(originalBeginDts) {
- var segment = this.getLastSegmentBefore(originalBeginDts);
- if (segment != null) {
- return segment.lastSample;
- } else {
- return null;
- }
- }
- }, {
- key: "getLastSyncPointBefore",
- value: function getLastSyncPointBefore(originalBeginDts) {
- var segmentIdx = this._searchNearestSegmentBefore(originalBeginDts);
- var syncPoints = this._list[segmentIdx].syncPoints;
- while (syncPoints.length === 0 && segmentIdx > 0) {
- segmentIdx--;
- syncPoints = this._list[segmentIdx].syncPoints;
- }
- if (syncPoints.length > 0) {
- return syncPoints[syncPoints.length - 1];
- } else {
- return null;
- }
- }
- }, {
- key: "type",
- get: function get() {
- return this._type;
- }
- }, {
- key: "length",
- get: function get() {
- return this._list.length;
- }
- }]);
- return MediaSegmentInfoList;
- }();
- /***/ }),
- /* 16 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var MSEEvents = {
- ERROR: 'error',
- SOURCE_OPEN: 'source_open',
- UPDATE_END: 'update_end',
- BUFFER_FULL: 'buffer_full'
- };
- exports.default = MSEEvents;
- module.exports = exports['default'];
- /***/ }),
- /* 17 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.ErrorDetails = exports.ErrorTypes = undefined;
- var _loader = __webpack_require__(3);
- var _demuxErrors = __webpack_require__(10);
- var _demuxErrors2 = _interopRequireDefault(_demuxErrors);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var ErrorTypes = exports.ErrorTypes = {
- NETWORK_ERROR: 'NetworkError',
- MEDIA_ERROR: 'MediaError',
- OTHER_ERROR: 'OtherError'
- };
- var ErrorDetails = exports.ErrorDetails = {
- NETWORK_EXCEPTION: _loader.LoaderErrors.EXCEPTION,
- NETWORK_STATUS_CODE_INVALID: _loader.LoaderErrors.HTTP_STATUS_CODE_INVALID,
- NETWORK_TIMEOUT: _loader.LoaderErrors.CONNECTING_TIMEOUT,
- NETWORK_UNRECOVERABLE_EARLY_EOF: _loader.LoaderErrors.UNRECOVERABLE_EARLY_EOF,
- MEDIA_MSE_ERROR: 'MediaMSEError',
- MEDIA_FORMAT_ERROR: _demuxErrors2.default.FORMAT_ERROR,
- MEDIA_FORMAT_UNSUPPORTED: _demuxErrors2.default.FORMAT_UNSUPPORTED,
- MEDIA_CODEC_UNSUPPORTED: _demuxErrors2.default.CODEC_UNSUPPORTED
- };
- /***/ }),
- /* 18 */
- /***/ (function(module, exports, __webpack_require__) {
- module.exports = __webpack_require__(19);
- /***/ }),
- /* 19 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- var _xgplayer = __webpack_require__(20);
- var _xgplayer2 = _interopRequireDefault(_xgplayer);
- var _flv = __webpack_require__(21);
- var _flv2 = _interopRequireDefault(_flv);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; }
- var FlvJsPlayer = function (_Player) {
- _inherits(FlvJsPlayer, _Player);
- function FlvJsPlayer(options) {
- _classCallCheck(this, FlvJsPlayer);
- var _this = _possibleConstructorReturn(this, (FlvJsPlayer.__proto__ || Object.getPrototypeOf(FlvJsPlayer)).call(this, options));
- _this.flvOpts = { type: 'flv' };
- _this.optionalConfig = {};
- _xgplayer2.default.util.deepCopy(_this.flvOpts, options);
- _xgplayer2.default.util.deepCopy(_this.optionalConfig, options.flvOptionalConfig);
- var player = _this;
- Object.defineProperty(player, 'src', {
- get: function get() {
- return player.currentSrc;
- },
- set: function set(url) {
- player.flv_load(url);
- var oldVol = player.volume;
- player.video.muted = true;
- _xgplayer2.default.util.addClass(player.root, 'xgplayer-is-enter');
- player.once('playing', function () {
- _xgplayer2.default.util.removeClass(player.root, 'xgplayer-is-enter');
- player.video.muted = false;
- });
- player.once('canplay', function () {
- player.play();
- });
- },
- configurable: true
- });
- player.once('complete', function () {
- player.__flv__ = _flv2.default.createPlayer(_this.flvOpts, _this.optionalConfig);
- player.createInstance(player.__flv__);
- if (player.config.isLive) {
- _xgplayer2.default.util.addClass(player.root, 'xgplayer-is-live');
- var live = _xgplayer2.default.util.createDom('xg-live', '正在直播', {}, 'xgplayer-live');
- player.controls.appendChild(live);
- }
- });
- return _this;
- }
- _createClass(FlvJsPlayer, [{
- key: 'createInstance',
- value: function createInstance(flv) {
- var player = this;
- player.video.addEventListener('contextmenu', function (e) {
- e.preventDefault();
- });
- flv.attachMediaElement(player.video);
- flv.load();
- flv.play();
- flv.on(_flv2.default.Events.ERROR, function (e) {
- player.emit('error', new _xgplayer2.default.Errors('other', player.config.url));
- });
- flv.on(_flv2.default.Events.LOADED_SEI, function (timestamp, data) {
- player.emit('loaded_sei', timestamp, data);
- });
- flv.on(_flv2.default.Events.STATISTICS_INFO, function (data) {
- player.emit("statistics_info", data);
- });
- flv.on(_flv2.default.Events.MEDIA_INFO, function (data) {
- player.mediainfo = data;
- player.emit("MEDIA_INFO", data);
- });
- player.once('destroy', function () {
- flv.destroy();
- player.__flv__ = null;
- });
- }
- }, {
- key: 'flv_load',
- value: function flv_load(newUrl) {
- var mediaDataSource = this.flvOpts;
- mediaDataSource.segments = [{
- cors: true,
- duration: undefined,
- filesize: undefined,
- timestampBase: 0,
- url: newUrl,
- withCredentials: false
- }];
- // mediaDataSource.cors = true
- // mediaDataSource.hasAudio = true
- // mediaDataSource.hasVideo = true
- // mediaDataSource.isLive = true
- mediaDataSource.url = newUrl;
- // mediaDataSource.withCredentials = false
- this.flv_load_mds(mediaDataSource);
- }
- }, {
- key: 'flv_load_mds',
- value: function flv_load_mds(mediaDataSource) {
- var player = this;
- if (typeof player.__flv__ !== 'undefined') {
- if (player.__flv__ != null) {
- player.__flv__.unload();
- player.__flv__.detachMediaElement();
- player.__flv__.destroy();
- player.__flv__ = null;
- }
- }
- player.__flv__ = _flv2.default.createPlayer(mediaDataSource, this.optionalConfig);
- player.__flv__.attachMediaElement(player.video);
- player.__flv__.load();
- }
- }, {
- key: 'switchURL',
- value: function switchURL(url) {
- var player = this;
- var curTime = 0;
- if (!player.config.isLive) {
- curTime = player.currentTime;
- }
- player.flv_load(url);
- var oldVol = player.volume;
- player.video.muted = true;
- _xgplayer2.default.util.addClass(player.root, 'xgplayer-is-enter');
- player.once('playing', function () {
- _xgplayer2.default.util.removeClass(player.root, 'xgplayer-is-enter');
- player.video.muted = false;
- });
- player.once('canplay', function () {
- if (!player.config.isLive) {
- player.currentTime = curTime;
- }
- player.play();
- });
- }
- }]);
- return FlvJsPlayer;
- }(_xgplayer2.default);
- FlvJsPlayer.isSupported = _flv2.default.isSupported;
- exports.default = FlvJsPlayer;
- module.exports = exports['default'];
- /***/ }),
- /* 20 */
- /***/ (function(module, exports) {
- module.exports = __WEBPACK_EXTERNAL_MODULE__20__;
- /***/ }),
- /* 21 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var _polyfill = __webpack_require__(11);
- var _polyfill2 = _interopRequireDefault(_polyfill);
- var _features = __webpack_require__(25);
- var _features2 = _interopRequireDefault(_features);
- var _flvPlayer = __webpack_require__(33);
- var _flvPlayer2 = _interopRequireDefault(_flvPlayer);
- var _nativePlayer = __webpack_require__(46);
- var _nativePlayer2 = _interopRequireDefault(_nativePlayer);
- var _playerEvents = __webpack_require__(7);
- var _playerEvents2 = _interopRequireDefault(_playerEvents);
- var _playerErrors = __webpack_require__(17);
- var _loggingControl = __webpack_require__(8);
- var _loggingControl2 = _interopRequireDefault(_loggingControl);
- var _exception = __webpack_require__(1);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- // here are all the interfaces
- // install polyfills
- _polyfill2.default.install();
- // factory method
- function createPlayer(mediaDataSource, optionalConfig) {
- var mds = mediaDataSource;
- if (mds == null || (typeof mds === 'undefined' ? 'undefined' : _typeof(mds)) !== 'object') {
- throw new _exception.InvalidArgumentException('MediaDataSource must be an javascript object!');
- }
- if (!mds.hasOwnProperty('type')) {
- throw new _exception.InvalidArgumentException('MediaDataSource must has type field to indicate video file type!');
- }
- switch (mds.type) {
- case 'flv':
- return new _flvPlayer2.default(mds, optionalConfig);
- default:
- return new _nativePlayer2.default(mds, optionalConfig);
- }
- }
- // feature detection
- function isSupported() {
- return _features2.default.supportMSEH264Playback();
- }
- function getFeatureList() {
- return _features2.default.getFeatureList();
- }
- // interfaces
- var flvjs = {};
- flvjs.createPlayer = createPlayer;
- flvjs.isSupported = isSupported;
- flvjs.getFeatureList = getFeatureList;
- flvjs.Events = _playerEvents2.default;
- flvjs.ErrorTypes = _playerErrors.ErrorTypes;
- flvjs.ErrorDetails = _playerErrors.ErrorDetails;
- flvjs.FlvPlayer = _flvPlayer2.default;
- flvjs.NativePlayer = _nativePlayer2.default;
- flvjs.LoggingControl = _loggingControl2.default;
- Object.defineProperty(flvjs, 'version', {
- enumerable: true,
- get: function get() {
- // replaced by browserify-versionify transform
- return '__VERSION__';
- }
- });
- exports.default = flvjs;
- module.exports = exports['default'];
- /***/ }),
- /* 22 */
- /***/ (function(module, exports, __webpack_require__) {
- /* WEBPACK VAR INJECTION */(function(process, global) {/*!
- * @overview es6-promise - a tiny implementation of Promises/A+.
- * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
- * @license Licensed under MIT license
- * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
- * @version v4.2.8+1e68dce6
- */
- (function (global, factory) {
- true ? module.exports = factory() :
- undefined;
- }(this, (function () { 'use strict';
- function objectOrFunction(x) {
- var type = typeof x;
- return x !== null && (type === 'object' || type === 'function');
- }
- function isFunction(x) {
- return typeof x === 'function';
- }
- var _isArray = void 0;
- if (Array.isArray) {
- _isArray = Array.isArray;
- } else {
- _isArray = function (x) {
- return Object.prototype.toString.call(x) === '[object Array]';
- };
- }
- var isArray = _isArray;
- var len = 0;
- var vertxNext = void 0;
- var customSchedulerFn = void 0;
- var asap = function asap(callback, arg) {
- queue[len] = callback;
- queue[len + 1] = arg;
- len += 2;
- if (len === 2) {
- // If len is 2, that means that we need to schedule an async flush.
- // If additional callbacks are queued before the queue is flushed, they
- // will be processed by this flush that we are scheduling.
- if (customSchedulerFn) {
- customSchedulerFn(flush);
- } else {
- scheduleFlush();
- }
- }
- };
- function setScheduler(scheduleFn) {
- customSchedulerFn = scheduleFn;
- }
- function setAsap(asapFn) {
- asap = asapFn;
- }
- var browserWindow = typeof window !== 'undefined' ? window : undefined;
- var browserGlobal = browserWindow || {};
- var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
- var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
- // test for web worker but not in IE10
- var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
- // node
- function useNextTick() {
- // node version 0.10.x displays a deprecation warning when nextTick is used recursively
- // see https://github.com/cujojs/when/issues/410 for details
- return function () {
- return process.nextTick(flush);
- };
- }
- // vertx
- function useVertxTimer() {
- if (typeof vertxNext !== 'undefined') {
- return function () {
- vertxNext(flush);
- };
- }
- return useSetTimeout();
- }
- function useMutationObserver() {
- var iterations = 0;
- var observer = new BrowserMutationObserver(flush);
- var node = document.createTextNode('');
- observer.observe(node, { characterData: true });
- return function () {
- node.data = iterations = ++iterations % 2;
- };
- }
- // web worker
- function useMessageChannel() {
- var channel = new MessageChannel();
- channel.port1.onmessage = flush;
- return function () {
- return channel.port2.postMessage(0);
- };
- }
- function useSetTimeout() {
- // Store setTimeout reference so es6-promise will be unaffected by
- // other code modifying setTimeout (like sinon.useFakeTimers())
- var globalSetTimeout = setTimeout;
- return function () {
- return globalSetTimeout(flush, 1);
- };
- }
- var queue = new Array(1000);
- function flush() {
- for (var i = 0; i < len; i += 2) {
- var callback = queue[i];
- var arg = queue[i + 1];
- callback(arg);
- queue[i] = undefined;
- queue[i + 1] = undefined;
- }
- len = 0;
- }
- function attemptVertx() {
- try {
- var vertx = Function('return this')().require('vertx');
- vertxNext = vertx.runOnLoop || vertx.runOnContext;
- return useVertxTimer();
- } catch (e) {
- return useSetTimeout();
- }
- }
- var scheduleFlush = void 0;
- // Decide what async method to use to triggering processing of queued callbacks:
- if (isNode) {
- scheduleFlush = useNextTick();
- } else if (BrowserMutationObserver) {
- scheduleFlush = useMutationObserver();
- } else if (isWorker) {
- scheduleFlush = useMessageChannel();
- } else if (browserWindow === undefined && "function" === 'function') {
- scheduleFlush = attemptVertx();
- } else {
- scheduleFlush = useSetTimeout();
- }
- function then(onFulfillment, onRejection) {
- var parent = this;
- var child = new this.constructor(noop);
- if (child[PROMISE_ID] === undefined) {
- makePromise(child);
- }
- var _state = parent._state;
- if (_state) {
- var callback = arguments[_state - 1];
- asap(function () {
- return invokeCallback(_state, child, callback, parent._result);
- });
- } else {
- subscribe(parent, child, onFulfillment, onRejection);
- }
- return child;
- }
- /**
- `Promise.resolve` returns a promise that will become resolved with the
- passed `value`. It is shorthand for the following:
- ```javascript
- let promise = new Promise(function(resolve, reject){
- resolve(1);
- });
- promise.then(function(value){
- // value === 1
- });
- ```
- Instead of writing the above, your code now simply becomes the following:
- ```javascript
- let promise = Promise.resolve(1);
- promise.then(function(value){
- // value === 1
- });
- ```
- @method resolve
- @static
- @param {Any} value value that the returned promise will be resolved with
- Useful for tooling.
- @return {Promise} a promise that will become fulfilled with the given
- `value`
- */
- function resolve$1(object) {
- /*jshint validthis:true */
- var Constructor = this;
- if (object && typeof object === 'object' && object.constructor === Constructor) {
- return object;
- }
- var promise = new Constructor(noop);
- resolve(promise, object);
- return promise;
- }
- var PROMISE_ID = Math.random().toString(36).substring(2);
- function noop() {}
- var PENDING = void 0;
- var FULFILLED = 1;
- var REJECTED = 2;
- function selfFulfillment() {
- return new TypeError("You cannot resolve a promise with itself");
- }
- function cannotReturnOwn() {
- return new TypeError('A promises callback cannot return that same promise.');
- }
- function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
- try {
- then$$1.call(value, fulfillmentHandler, rejectionHandler);
- } catch (e) {
- return e;
- }
- }
- function handleForeignThenable(promise, thenable, then$$1) {
- asap(function (promise) {
- var sealed = false;
- var error = tryThen(then$$1, thenable, function (value) {
- if (sealed) {
- return;
- }
- sealed = true;
- if (thenable !== value) {
- resolve(promise, value);
- } else {
- fulfill(promise, value);
- }
- }, function (reason) {
- if (sealed) {
- return;
- }
- sealed = true;
- reject(promise, reason);
- }, 'Settle: ' + (promise._label || ' unknown promise'));
- if (!sealed && error) {
- sealed = true;
- reject(promise, error);
- }
- }, promise);
- }
- function handleOwnThenable(promise, thenable) {
- if (thenable._state === FULFILLED) {
- fulfill(promise, thenable._result);
- } else if (thenable._state === REJECTED) {
- reject(promise, thenable._result);
- } else {
- subscribe(thenable, undefined, function (value) {
- return resolve(promise, value);
- }, function (reason) {
- return reject(promise, reason);
- });
- }
- }
- function handleMaybeThenable(promise, maybeThenable, then$$1) {
- if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
- handleOwnThenable(promise, maybeThenable);
- } else {
- if (then$$1 === undefined) {
- fulfill(promise, maybeThenable);
- } else if (isFunction(then$$1)) {
- handleForeignThenable(promise, maybeThenable, then$$1);
- } else {
- fulfill(promise, maybeThenable);
- }
- }
- }
- function resolve(promise, value) {
- if (promise === value) {
- reject(promise, selfFulfillment());
- } else if (objectOrFunction(value)) {
- var then$$1 = void 0;
- try {
- then$$1 = value.then;
- } catch (error) {
- reject(promise, error);
- return;
- }
- handleMaybeThenable(promise, value, then$$1);
- } else {
- fulfill(promise, value);
- }
- }
- function publishRejection(promise) {
- if (promise._onerror) {
- promise._onerror(promise._result);
- }
- publish(promise);
- }
- function fulfill(promise, value) {
- if (promise._state !== PENDING) {
- return;
- }
- promise._result = value;
- promise._state = FULFILLED;
- if (promise._subscribers.length !== 0) {
- asap(publish, promise);
- }
- }
- function reject(promise, reason) {
- if (promise._state !== PENDING) {
- return;
- }
- promise._state = REJECTED;
- promise._result = reason;
- asap(publishRejection, promise);
- }
- function subscribe(parent, child, onFulfillment, onRejection) {
- var _subscribers = parent._subscribers;
- var length = _subscribers.length;
- parent._onerror = null;
- _subscribers[length] = child;
- _subscribers[length + FULFILLED] = onFulfillment;
- _subscribers[length + REJECTED] = onRejection;
- if (length === 0 && parent._state) {
- asap(publish, parent);
- }
- }
- function publish(promise) {
- var subscribers = promise._subscribers;
- var settled = promise._state;
- if (subscribers.length === 0) {
- return;
- }
- var child = void 0,
- callback = void 0,
- detail = promise._result;
- for (var i = 0; i < subscribers.length; i += 3) {
- child = subscribers[i];
- callback = subscribers[i + settled];
- if (child) {
- invokeCallback(settled, child, callback, detail);
- } else {
- callback(detail);
- }
- }
- promise._subscribers.length = 0;
- }
- function invokeCallback(settled, promise, callback, detail) {
- var hasCallback = isFunction(callback),
- value = void 0,
- error = void 0,
- succeeded = true;
- if (hasCallback) {
- try {
- value = callback(detail);
- } catch (e) {
- succeeded = false;
- error = e;
- }
- if (promise === value) {
- reject(promise, cannotReturnOwn());
- return;
- }
- } else {
- value = detail;
- }
- if (promise._state !== PENDING) {
- // noop
- } else if (hasCallback && succeeded) {
- resolve(promise, value);
- } else if (succeeded === false) {
- reject(promise, error);
- } else if (settled === FULFILLED) {
- fulfill(promise, value);
- } else if (settled === REJECTED) {
- reject(promise, value);
- }
- }
- function initializePromise(promise, resolver) {
- try {
- resolver(function resolvePromise(value) {
- resolve(promise, value);
- }, function rejectPromise(reason) {
- reject(promise, reason);
- });
- } catch (e) {
- reject(promise, e);
- }
- }
- var id = 0;
- function nextId() {
- return id++;
- }
- function makePromise(promise) {
- promise[PROMISE_ID] = id++;
- promise._state = undefined;
- promise._result = undefined;
- promise._subscribers = [];
- }
- function validationError() {
- return new Error('Array Methods must be provided an Array');
- }
- var Enumerator = function () {
- function Enumerator(Constructor, input) {
- this._instanceConstructor = Constructor;
- this.promise = new Constructor(noop);
- if (!this.promise[PROMISE_ID]) {
- makePromise(this.promise);
- }
- if (isArray(input)) {
- this.length = input.length;
- this._remaining = input.length;
- this._result = new Array(this.length);
- if (this.length === 0) {
- fulfill(this.promise, this._result);
- } else {
- this.length = this.length || 0;
- this._enumerate(input);
- if (this._remaining === 0) {
- fulfill(this.promise, this._result);
- }
- }
- } else {
- reject(this.promise, validationError());
- }
- }
- Enumerator.prototype._enumerate = function _enumerate(input) {
- for (var i = 0; this._state === PENDING && i < input.length; i++) {
- this._eachEntry(input[i], i);
- }
- };
- Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
- var c = this._instanceConstructor;
- var resolve$$1 = c.resolve;
- if (resolve$$1 === resolve$1) {
- var _then = void 0;
- var error = void 0;
- var didError = false;
- try {
- _then = entry.then;
- } catch (e) {
- didError = true;
- error = e;
- }
- if (_then === then && entry._state !== PENDING) {
- this._settledAt(entry._state, i, entry._result);
- } else if (typeof _then !== 'function') {
- this._remaining--;
- this._result[i] = entry;
- } else if (c === Promise$1) {
- var promise = new c(noop);
- if (didError) {
- reject(promise, error);
- } else {
- handleMaybeThenable(promise, entry, _then);
- }
- this._willSettleAt(promise, i);
- } else {
- this._willSettleAt(new c(function (resolve$$1) {
- return resolve$$1(entry);
- }), i);
- }
- } else {
- this._willSettleAt(resolve$$1(entry), i);
- }
- };
- Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
- var promise = this.promise;
- if (promise._state === PENDING) {
- this._remaining--;
- if (state === REJECTED) {
- reject(promise, value);
- } else {
- this._result[i] = value;
- }
- }
- if (this._remaining === 0) {
- fulfill(promise, this._result);
- }
- };
- Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
- var enumerator = this;
- subscribe(promise, undefined, function (value) {
- return enumerator._settledAt(FULFILLED, i, value);
- }, function (reason) {
- return enumerator._settledAt(REJECTED, i, reason);
- });
- };
- return Enumerator;
- }();
- /**
- `Promise.all` accepts an array of promises, and returns a new promise which
- is fulfilled with an array of fulfillment values for the passed promises, or
- rejected with the reason of the first passed promise to be rejected. It casts all
- elements of the passed iterable to promises as it runs this algorithm.
- Example:
- ```javascript
- let promise1 = resolve(1);
- let promise2 = resolve(2);
- let promise3 = resolve(3);
- let promises = [ promise1, promise2, promise3 ];
- Promise.all(promises).then(function(array){
- // The array here would be [ 1, 2, 3 ];
- });
- ```
- If any of the `promises` given to `all` are rejected, the first promise
- that is rejected will be given as an argument to the returned promises's
- rejection handler. For example:
- Example:
- ```javascript
- let promise1 = resolve(1);
- let promise2 = reject(new Error("2"));
- let promise3 = reject(new Error("3"));
- let promises = [ promise1, promise2, promise3 ];
- Promise.all(promises).then(function(array){
- // Code here never runs because there are rejected promises!
- }, function(error) {
- // error.message === "2"
- });
- ```
- @method all
- @static
- @param {Array} entries array of promises
- @param {String} label optional string for labeling the promise.
- Useful for tooling.
- @return {Promise} promise that is fulfilled when all `promises` have been
- fulfilled, or rejected if any of them become rejected.
- @static
- */
- function all(entries) {
- return new Enumerator(this, entries).promise;
- }
- /**
- `Promise.race` returns a new promise which is settled in the same way as the
- first passed promise to settle.
- Example:
- ```javascript
- let promise1 = new Promise(function(resolve, reject){
- setTimeout(function(){
- resolve('promise 1');
- }, 200);
- });
- let promise2 = new Promise(function(resolve, reject){
- setTimeout(function(){
- resolve('promise 2');
- }, 100);
- });
- Promise.race([promise1, promise2]).then(function(result){
- // result === 'promise 2' because it was resolved before promise1
- // was resolved.
- });
- ```
- `Promise.race` is deterministic in that only the state of the first
- settled promise matters. For example, even if other promises given to the
- `promises` array argument are resolved, but the first settled promise has
- become rejected before the other promises became fulfilled, the returned
- promise will become rejected:
- ```javascript
- let promise1 = new Promise(function(resolve, reject){
- setTimeout(function(){
- resolve('promise 1');
- }, 200);
- });
- let promise2 = new Promise(function(resolve, reject){
- setTimeout(function(){
- reject(new Error('promise 2'));
- }, 100);
- });
- Promise.race([promise1, promise2]).then(function(result){
- // Code here never runs
- }, function(reason){
- // reason.message === 'promise 2' because promise 2 became rejected before
- // promise 1 became fulfilled
- });
- ```
- An example real-world use case is implementing timeouts:
- ```javascript
- Promise.race([ajax('foo.json'), timeout(5000)])
- ```
- @method race
- @static
- @param {Array} promises array of promises to observe
- Useful for tooling.
- @return {Promise} a promise which settles in the same way as the first passed
- promise to settle.
- */
- function race(entries) {
- /*jshint validthis:true */
- var Constructor = this;
- if (!isArray(entries)) {
- return new Constructor(function (_, reject) {
- return reject(new TypeError('You must pass an array to race.'));
- });
- } else {
- return new Constructor(function (resolve, reject) {
- var length = entries.length;
- for (var i = 0; i < length; i++) {
- Constructor.resolve(entries[i]).then(resolve, reject);
- }
- });
- }
- }
- /**
- `Promise.reject` returns a promise rejected with the passed `reason`.
- It is shorthand for the following:
- ```javascript
- let promise = new Promise(function(resolve, reject){
- reject(new Error('WHOOPS'));
- });
- promise.then(function(value){
- // Code here doesn't run because the promise is rejected!
- }, function(reason){
- // reason.message === 'WHOOPS'
- });
- ```
- Instead of writing the above, your code now simply becomes the following:
- ```javascript
- let promise = Promise.reject(new Error('WHOOPS'));
- promise.then(function(value){
- // Code here doesn't run because the promise is rejected!
- }, function(reason){
- // reason.message === 'WHOOPS'
- });
- ```
- @method reject
- @static
- @param {Any} reason value that the returned promise will be rejected with.
- Useful for tooling.
- @return {Promise} a promise rejected with the given `reason`.
- */
- function reject$1(reason) {
- /*jshint validthis:true */
- var Constructor = this;
- var promise = new Constructor(noop);
- reject(promise, reason);
- return promise;
- }
- function needsResolver() {
- throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
- }
- function needsNew() {
- throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
- }
- /**
- Promise objects represent the eventual result of an asynchronous operation. The
- primary way of interacting with a promise is through its `then` method, which
- registers callbacks to receive either a promise's eventual value or the reason
- why the promise cannot be fulfilled.
- Terminology
- -----------
- - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- - `thenable` is an object or function that defines a `then` method.
- - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- - `exception` is a value that is thrown using the throw statement.
- - `reason` is a value that indicates why a promise was rejected.
- - `settled` the final resting state of a promise, fulfilled or rejected.
- A promise can be in one of three states: pending, fulfilled, or rejected.
- Promises that are fulfilled have a fulfillment value and are in the fulfilled
- state. Promises that are rejected have a rejection reason and are in the
- rejected state. A fulfillment value is never a thenable.
- Promises can also be said to *resolve* a value. If this value is also a
- promise, then the original promise's settled state will match the value's
- settled state. So a promise that *resolves* a promise that rejects will
- itself reject, and a promise that *resolves* a promise that fulfills will
- itself fulfill.
- Basic Usage:
- ------------
- ```js
- let promise = new Promise(function(resolve, reject) {
- // on success
- resolve(value);
- // on failure
- reject(reason);
- });
- promise.then(function(value) {
- // on fulfillment
- }, function(reason) {
- // on rejection
- });
- ```
- Advanced Usage:
- ---------------
- Promises shine when abstracting away asynchronous interactions such as
- `XMLHttpRequest`s.
- ```js
- function getJSON(url) {
- return new Promise(function(resolve, reject){
- let xhr = new XMLHttpRequest();
- xhr.open('GET', url);
- xhr.onreadystatechange = handler;
- xhr.responseType = 'json';
- xhr.setRequestHeader('Accept', 'application/json');
- xhr.send();
- function handler() {
- if (this.readyState === this.DONE) {
- if (this.status === 200) {
- resolve(this.response);
- } else {
- reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
- }
- }
- };
- });
- }
- getJSON('/posts.json').then(function(json) {
- // on fulfillment
- }, function(reason) {
- // on rejection
- });
- ```
- Unlike callbacks, promises are great composable primitives.
- ```js
- Promise.all([
- getJSON('/posts'),
- getJSON('/comments')
- ]).then(function(values){
- values[0] // => postsJSON
- values[1] // => commentsJSON
- return values;
- });
- ```
- @class Promise
- @param {Function} resolver
- Useful for tooling.
- @constructor
- */
- var Promise$1 = function () {
- function Promise(resolver) {
- this[PROMISE_ID] = nextId();
- this._result = this._state = undefined;
- this._subscribers = [];
- if (noop !== resolver) {
- typeof resolver !== 'function' && needsResolver();
- this instanceof Promise ? initializePromise(this, resolver) : needsNew();
- }
- }
- /**
- The primary way of interacting with a promise is through its `then` method,
- which registers callbacks to receive either a promise's eventual value or the
- reason why the promise cannot be fulfilled.
- ```js
- findUser().then(function(user){
- // user is available
- }, function(reason){
- // user is unavailable, and you are given the reason why
- });
- ```
- Chaining
- --------
- The return value of `then` is itself a promise. This second, 'downstream'
- promise is resolved with the return value of the first promise's fulfillment
- or rejection handler, or rejected if the handler throws an exception.
- ```js
- findUser().then(function (user) {
- return user.name;
- }, function (reason) {
- return 'default name';
- }).then(function (userName) {
- // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
- // will be `'default name'`
- });
- findUser().then(function (user) {
- throw new Error('Found user, but still unhappy');
- }, function (reason) {
- throw new Error('`findUser` rejected and we're unhappy');
- }).then(function (value) {
- // never reached
- }, function (reason) {
- // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
- // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
- });
- ```
- If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
- ```js
- findUser().then(function (user) {
- throw new PedagogicalException('Upstream error');
- }).then(function (value) {
- // never reached
- }).then(function (value) {
- // never reached
- }, function (reason) {
- // The `PedgagocialException` is propagated all the way down to here
- });
- ```
- Assimilation
- ------------
- Sometimes the value you want to propagate to a downstream promise can only be
- retrieved asynchronously. This can be achieved by returning a promise in the
- fulfillment or rejection handler. The downstream promise will then be pending
- until the returned promise is settled. This is called *assimilation*.
- ```js
- findUser().then(function (user) {
- return findCommentsByAuthor(user);
- }).then(function (comments) {
- // The user's comments are now available
- });
- ```
- If the assimliated promise rejects, then the downstream promise will also reject.
- ```js
- findUser().then(function (user) {
- return findCommentsByAuthor(user);
- }).then(function (comments) {
- // If `findCommentsByAuthor` fulfills, we'll have the value here
- }, function (reason) {
- // If `findCommentsByAuthor` rejects, we'll have the reason here
- });
- ```
- Simple Example
- --------------
- Synchronous Example
- ```javascript
- let result;
- try {
- result = findResult();
- // success
- } catch(reason) {
- // failure
- }
- ```
- Errback Example
- ```js
- findResult(function(result, err){
- if (err) {
- // failure
- } else {
- // success
- }
- });
- ```
- Promise Example;
- ```javascript
- findResult().then(function(result){
- // success
- }, function(reason){
- // failure
- });
- ```
- Advanced Example
- --------------
- Synchronous Example
- ```javascript
- let author, books;
- try {
- author = findAuthor();
- books = findBooksByAuthor(author);
- // success
- } catch(reason) {
- // failure
- }
- ```
- Errback Example
- ```js
- function foundBooks(books) {
- }
- function failure(reason) {
- }
- findAuthor(function(author, err){
- if (err) {
- failure(err);
- // failure
- } else {
- try {
- findBoooksByAuthor(author, function(books, err) {
- if (err) {
- failure(err);
- } else {
- try {
- foundBooks(books);
- } catch(reason) {
- failure(reason);
- }
- }
- });
- } catch(error) {
- failure(err);
- }
- // success
- }
- });
- ```
- Promise Example;
- ```javascript
- findAuthor().
- then(findBooksByAuthor).
- then(function(books){
- // found books
- }).catch(function(reason){
- // something went wrong
- });
- ```
- @method then
- @param {Function} onFulfilled
- @param {Function} onRejected
- Useful for tooling.
- @return {Promise}
- */
- /**
- `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
- as the catch block of a try/catch statement.
- ```js
- function findAuthor(){
- throw new Error('couldn't find that author');
- }
- // synchronous
- try {
- findAuthor();
- } catch(reason) {
- // something went wrong
- }
- // async with promises
- findAuthor().catch(function(reason){
- // something went wrong
- });
- ```
- @method catch
- @param {Function} onRejection
- Useful for tooling.
- @return {Promise}
- */
- Promise.prototype.catch = function _catch(onRejection) {
- return this.then(null, onRejection);
- };
- /**
- `finally` will be invoked regardless of the promise's fate just as native
- try/catch/finally behaves
-
- Synchronous example:
-
- ```js
- findAuthor() {
- if (Math.random() > 0.5) {
- throw new Error();
- }
- return new Author();
- }
-
- try {
- return findAuthor(); // succeed or fail
- } catch(error) {
- return findOtherAuther();
- } finally {
- // always runs
- // doesn't affect the return value
- }
- ```
-
- Asynchronous example:
-
- ```js
- findAuthor().catch(function(reason){
- return findOtherAuther();
- }).finally(function(){
- // author was either found, or not
- });
- ```
-
- @method finally
- @param {Function} callback
- @return {Promise}
- */
- Promise.prototype.finally = function _finally(callback) {
- var promise = this;
- var constructor = promise.constructor;
- if (isFunction(callback)) {
- return promise.then(function (value) {
- return constructor.resolve(callback()).then(function () {
- return value;
- });
- }, function (reason) {
- return constructor.resolve(callback()).then(function () {
- throw reason;
- });
- });
- }
- return promise.then(callback, callback);
- };
- return Promise;
- }();
- Promise$1.prototype.then = then;
- Promise$1.all = all;
- Promise$1.race = race;
- Promise$1.resolve = resolve$1;
- Promise$1.reject = reject$1;
- Promise$1._setScheduler = setScheduler;
- Promise$1._setAsap = setAsap;
- Promise$1._asap = asap;
- /*global self*/
- function polyfill() {
- var local = void 0;
- if (typeof global !== 'undefined') {
- local = global;
- } else if (typeof self !== 'undefined') {
- local = self;
- } else {
- try {
- local = Function('return this')();
- } catch (e) {
- throw new Error('polyfill failed because global object is unavailable in this environment');
- }
- }
- var P = local.Promise;
- if (P) {
- var promiseToString = null;
- try {
- promiseToString = Object.prototype.toString.call(P.resolve());
- } catch (e) {
- // silently ignored
- }
- if (promiseToString === '[object Promise]' && !P.cast) {
- return;
- }
- }
- local.Promise = Promise$1;
- }
- // Strange compat..
- Promise$1.polyfill = polyfill;
- Promise$1.Promise = Promise$1;
- return Promise$1;
- })));
- //# sourceMappingURL=es6-promise.map
- /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(23), __webpack_require__(24)))
- /***/ }),
- /* 23 */
- /***/ (function(module, exports) {
- // shim for using process in browser
- var process = module.exports = {};
- // cached from whatever global is present so that test runners that stub it
- // don't break things. But we need to wrap it in a try catch in case it is
- // wrapped in strict mode code which doesn't define any globals. It's inside a
- // function because try/catches deoptimize in certain engines.
- var cachedSetTimeout;
- var cachedClearTimeout;
- function defaultSetTimout() {
- throw new Error('setTimeout has not been defined');
- }
- function defaultClearTimeout () {
- throw new Error('clearTimeout has not been defined');
- }
- (function () {
- try {
- if (typeof setTimeout === 'function') {
- cachedSetTimeout = setTimeout;
- } else {
- cachedSetTimeout = defaultSetTimout;
- }
- } catch (e) {
- cachedSetTimeout = defaultSetTimout;
- }
- try {
- if (typeof clearTimeout === 'function') {
- cachedClearTimeout = clearTimeout;
- } else {
- cachedClearTimeout = defaultClearTimeout;
- }
- } catch (e) {
- cachedClearTimeout = defaultClearTimeout;
- }
- } ())
- function runTimeout(fun) {
- if (cachedSetTimeout === setTimeout) {
- //normal enviroments in sane situations
- return setTimeout(fun, 0);
- }
- // if setTimeout wasn't available but was latter defined
- if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
- cachedSetTimeout = setTimeout;
- return setTimeout(fun, 0);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedSetTimeout(fun, 0);
- } catch(e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedSetTimeout.call(null, fun, 0);
- } catch(e){
- // 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
- return cachedSetTimeout.call(this, fun, 0);
- }
- }
- }
- function runClearTimeout(marker) {
- if (cachedClearTimeout === clearTimeout) {
- //normal enviroments in sane situations
- return clearTimeout(marker);
- }
- // if clearTimeout wasn't available but was latter defined
- if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
- cachedClearTimeout = clearTimeout;
- return clearTimeout(marker);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedClearTimeout(marker);
- } catch (e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedClearTimeout.call(null, marker);
- } catch (e){
- // 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.
- // Some versions of I.E. have different rules for clearTimeout vs setTimeout
- return cachedClearTimeout.call(this, marker);
- }
- }
- }
- var queue = [];
- var draining = false;
- var currentQueue;
- var queueIndex = -1;
- function cleanUpNextTick() {
- if (!draining || !currentQueue) {
- return;
- }
- draining = false;
- if (currentQueue.length) {
- queue = currentQueue.concat(queue);
- } else {
- queueIndex = -1;
- }
- if (queue.length) {
- drainQueue();
- }
- }
- function drainQueue() {
- if (draining) {
- return;
- }
- var timeout = runTimeout(cleanUpNextTick);
- draining = true;
- var len = queue.length;
- while(len) {
- currentQueue = queue;
- queue = [];
- while (++queueIndex < len) {
- if (currentQueue) {
- currentQueue[queueIndex].run();
- }
- }
- queueIndex = -1;
- len = queue.length;
- }
- currentQueue = null;
- draining = false;
- runClearTimeout(timeout);
- }
- process.nextTick = function (fun) {
- var args = new Array(arguments.length - 1);
- if (arguments.length > 1) {
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
- }
- queue.push(new Item(fun, args));
- if (queue.length === 1 && !draining) {
- runTimeout(drainQueue);
- }
- };
- // v8 likes predictible objects
- function Item(fun, array) {
- this.fun = fun;
- this.array = array;
- }
- Item.prototype.run = function () {
- this.fun.apply(null, this.array);
- };
- process.title = 'browser';
- process.browser = true;
- process.env = {};
- process.argv = [];
- process.version = ''; // empty string to avoid regexp issues
- process.versions = {};
- function noop() {}
- process.on = noop;
- process.addListener = noop;
- process.once = noop;
- process.off = noop;
- process.removeListener = noop;
- process.removeAllListeners = noop;
- process.emit = noop;
- process.prependListener = noop;
- process.prependOnceListener = noop;
- process.listeners = function (name) { return [] }
- process.binding = function (name) {
- throw new Error('process.binding is not supported');
- };
- process.cwd = function () { return '/' };
- process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
- };
- process.umask = function() { return 0; };
- /***/ }),
- /* 24 */
- /***/ (function(module, exports) {
- var g;
- // This works in non-strict mode
- g = (function() {
- return this;
- })();
- try {
- // This works if eval is allowed (see CSP)
- g = g || new Function("return this")();
- } catch (e) {
- // This works if the window reference is available
- if (typeof window === "object") g = window;
- }
- // g can still be undefined, but nothing to do about it...
- // We return undefined, instead of nothing here, so it's
- // easier to handle this case. if(!global) { ...}
- module.exports = g;
- /***/ }),
- /* 25 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var _ioController = __webpack_require__(12);
- var _ioController2 = _interopRequireDefault(_ioController);
- var _config = __webpack_require__(6);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var Features = function () {
- function Features() {
- _classCallCheck(this, Features);
- }
- _createClass(Features, null, [{
- key: 'supportMSEH264Playback',
- value: function supportMSEH264Playback() {
- return window.MediaSource && window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
- }
- }, {
- key: 'supportNetworkStreamIO',
- value: function supportNetworkStreamIO() {
- var ioctl = new _ioController2.default({}, (0, _config.createDefaultConfig)());
- var loaderType = ioctl.loaderType;
- ioctl.destroy();
- return loaderType == 'fetch-stream-loader' || loaderType == 'xhr-moz-chunked-loader';
- }
- }, {
- key: 'getNetworkLoaderTypeName',
- value: function getNetworkLoaderTypeName() {
- var ioctl = new _ioController2.default({}, (0, _config.createDefaultConfig)());
- var loaderType = ioctl.loaderType;
- ioctl.destroy();
- return loaderType;
- }
- }, {
- key: 'supportNativeMediaPlayback',
- value: function supportNativeMediaPlayback(mimeType) {
- if (Features.videoElement == undefined) {
- Features.videoElement = window.document.createElement('video');
- }
- var canPlay = Features.videoElement.canPlayType(mimeType);
- return canPlay === 'probably' || canPlay == 'maybe';
- }
- }, {
- key: 'getFeatureList',
- value: function getFeatureList() {
- var features = {
- mseFlvPlayback: false,
- mseLiveFlvPlayback: false,
- networkStreamIO: false,
- networkLoaderName: '',
- nativeMP4H264Playback: false,
- nativeWebmVP8Playback: false,
- nativeWebmVP9Playback: false
- };
- features.mseFlvPlayback = Features.supportMSEH264Playback();
- features.networkStreamIO = Features.supportNetworkStreamIO();
- features.networkLoaderName = Features.getNetworkLoaderTypeName();
- features.mseLiveFlvPlayback = features.mseFlvPlayback && features.networkStreamIO;
- features.nativeMP4H264Playback = Features.supportNativeMediaPlayback('video/mp4; codecs="avc1.42001E, mp4a.40.2"');
- features.nativeWebmVP8Playback = Features.supportNativeMediaPlayback('video/webm; codecs="vp8.0, vorbis"');
- features.nativeWebmVP9Playback = Features.supportNativeMediaPlayback('video/webm; codecs="vp9"');
- return features;
- }
- }]);
- return Features;
- }();
- exports.default = Features;
- module.exports = exports['default'];
- /***/ }),
- /* 26 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; };
- 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); } };
- 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; }; }();
- var _logger = __webpack_require__(0);
- var _logger2 = _interopRequireDefault(_logger);
- var _browser = __webpack_require__(4);
- var _browser2 = _interopRequireDefault(_browser);
- var _loader = __webpack_require__(3);
- var _exception = __webpack_require__(1);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- /* fetch + stream IO loader. Currently working on chrome 43+.
- * fetch provides a better alternative http API to XMLHttpRequest
- *
- * fetch spec https://fetch.spec.whatwg.org/
- * stream spec https://streams.spec.whatwg.org/
- */
- var FetchStreamLoader = function (_BaseLoader) {
- _inherits(FetchStreamLoader, _BaseLoader);
- _createClass(FetchStreamLoader, null, [{
- key: 'isSupported',
- value: function isSupported() {
- try {
- // fetch + stream is broken on Microsoft Edge. Disable before build 15048.
- // see https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8196907/
- // Fixed in Jan 10, 2017. Build 15048+ removed from blacklist.
- var isWorkWellEdge = _browser2.default.msedge && _browser2.default.version.minor >= 15048;
- var browserNotBlacklisted = _browser2.default.msedge ? isWorkWellEdge : true;
- return self.fetch && self.ReadableStream && browserNotBlacklisted;
- } catch (e) {
- return false;
- }
- }
- }]);
- function FetchStreamLoader(seekHandler, config) {
- _classCallCheck(this, FetchStreamLoader);
- var _this = _possibleConstructorReturn(this, (FetchStreamLoader.__proto__ || Object.getPrototypeOf(FetchStreamLoader)).call(this, 'fetch-stream-loader'));
- _this.TAG = 'FetchStreamLoader';
- _this._seekHandler = seekHandler;
- _this._config = config;
- _this._needStash = true;
- _this._requestAbort = false;
- _this._contentLength = null;
- _this._receivedLength = 0;
- return _this;
- }
- _createClass(FetchStreamLoader, [{
- key: 'destroy',
- value: function destroy() {
- if (this.isWorking()) {
- this.abort();
- }
- _get(FetchStreamLoader.prototype.__proto__ || Object.getPrototypeOf(FetchStreamLoader.prototype), 'destroy', this).call(this);
- }
- }, {
- key: 'open',
- value: function open(dataSource, range) {
- var _this2 = this;
- this._dataSource = dataSource;
- this._range = range;
- var sourceURL = dataSource.url;
- if (this._config.reuseRedirectedURL && dataSource.redirectedURL != undefined) {
- sourceURL = dataSource.redirectedURL;
- }
- var seekConfig = this._seekHandler.getConfig(sourceURL, range);
- var headers = new self.Headers();
- if (_typeof(seekConfig.headers) === 'object') {
- var configHeaders = seekConfig.headers;
- for (var key in configHeaders) {
- if (configHeaders.hasOwnProperty(key)) {
- headers.append(key, configHeaders[key]);
- }
- }
- }
- var params = {
- method: 'GET',
- headers: headers,
- mode: 'cors',
- cache: 'default',
- // The default policy of Fetch API in the whatwg standard
- // Safari incorrectly indicates 'no-referrer' as default policy, fuck it
- referrerPolicy: 'no-referrer-when-downgrade'
- };
- // cors is enabled by default
- if (dataSource.cors === false) {
- // no-cors means 'disregard cors policy', which can only be used in ServiceWorker
- params.mode = 'same-origin';
- }
- // withCredentials is disabled by default
- if (dataSource.withCredentials) {
- params.credentials = 'include';
- }
- // referrerPolicy from config
- if (dataSource.referrerPolicy) {
- params.referrerPolicy = dataSource.referrerPolicy;
- }
- this._status = _loader.LoaderStatus.kConnecting;
- self.fetch(seekConfig.url, params).then(function (res) {
- if (_this2._requestAbort) {
- _this2._requestAbort = false;
- _this2._status = _loader.LoaderStatus.kIdle;
- return;
- }
- if (res.ok && res.status >= 200 && res.status <= 299) {
- if (res.url !== seekConfig.url) {
- if (_this2._onURLRedirect) {
- var redirectedURL = _this2._seekHandler.removeURLParameters(res.url);
- _this2._onURLRedirect(redirectedURL);
- }
- }
- var lengthHeader = res.headers.get('Content-Length');
- if (lengthHeader != null) {
- _this2._contentLength = parseInt(lengthHeader);
- if (_this2._contentLength !== 0) {
- if (_this2._onContentLengthKnown) {
- _this2._onContentLengthKnown(_this2._contentLength);
- }
- }
- }
- return _this2._pump.call(_this2, res.body.getReader());
- } else {
- _this2._status = _loader.LoaderStatus.kError;
- if (_this2._onError) {
- _this2._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: res.status, msg: res.statusText });
- } else {
- throw new _exception.RuntimeException('FetchStreamLoader: Http code invalid, ' + res.status + ' ' + res.statusText);
- }
- }
- }).catch(function (e) {
- _this2._status = _loader.LoaderStatus.kError;
- if (_this2._onError) {
- _this2._onError(_loader.LoaderErrors.EXCEPTION, { code: -1, msg: e.message });
- } else {
- throw e;
- }
- });
- }
- }, {
- key: 'abort',
- value: function abort() {
- this._requestAbort = true;
- }
- }, {
- key: '_pump',
- value: function _pump(reader) {
- var _this3 = this;
- // ReadableStreamReader
- return reader.read().then(function (result) {
- if (result.done) {
- // First check received length
- if (_this3._contentLength !== null && _this3._receivedLength < _this3._contentLength) {
- // Report Early-EOF
- _this3._status = _loader.LoaderStatus.kError;
- var type = _loader.LoaderErrors.EARLY_EOF;
- var info = { code: -1, msg: 'Fetch stream meet Early-EOF' };
- if (_this3._onError) {
- _this3._onError(type, info);
- } else {
- throw new _exception.RuntimeException(info.msg);
- }
- } else {
- // OK. Download complete
- _this3._status = _loader.LoaderStatus.kComplete;
- if (_this3._onComplete) {
- _this3._onComplete(_this3._range.from, _this3._range.from + _this3._receivedLength - 1);
- }
- }
- } else {
- if (_this3._requestAbort === true) {
- _this3._requestAbort = false;
- _this3._status = _loader.LoaderStatus.kComplete;
- return reader.cancel();
- }
- _this3._status = _loader.LoaderStatus.kBuffering;
- var chunk = result.value.buffer;
- var byteStart = _this3._range.from + _this3._receivedLength;
- _this3._receivedLength += chunk.byteLength;
- if (_this3._onDataArrival) {
- _this3._onDataArrival(chunk, byteStart, _this3._receivedLength);
- }
- _this3._pump(reader);
- }
- }).catch(function (e) {
- if (e.code === 11 && _browser2.default.msedge) {
- // InvalidStateError on Microsoft Edge
- // Workaround: Edge may throw InvalidStateError after ReadableStreamReader.cancel() call
- // Ignore the unknown exception.
- // Related issue: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/11265202/
- return;
- }
- _this3._status = _loader.LoaderStatus.kError;
- var type = 0;
- var info = null;
- if ((e.code === 19 || e.message === 'network error') && ( // NETWORK_ERR
- _this3._contentLength === null || _this3._contentLength !== null && _this3._receivedLength < _this3._contentLength)) {
- type = _loader.LoaderErrors.EARLY_EOF;
- info = { code: e.code, msg: 'Fetch stream meet Early-EOF' };
- } else {
- type = _loader.LoaderErrors.EXCEPTION;
- info = { code: e.code, msg: e.message };
- }
- if (_this3._onError) {
- _this3._onError(type, info);
- } else {
- throw new _exception.RuntimeException(info.msg);
- }
- });
- }
- }]);
- return FetchStreamLoader;
- }(_loader.BaseLoader);
- exports.default = FetchStreamLoader;
- module.exports = exports['default'];
- /***/ }),
- /* 27 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; };
- 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); } };
- 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; }; }();
- var _logger = __webpack_require__(0);
- var _logger2 = _interopRequireDefault(_logger);
- var _loader = __webpack_require__(3);
- var _exception = __webpack_require__(1);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- // For FireFox browser which supports `xhr.responseType = 'moz-chunked-arraybuffer'`
- var MozChunkedLoader = function (_BaseLoader) {
- _inherits(MozChunkedLoader, _BaseLoader);
- _createClass(MozChunkedLoader, null, [{
- key: 'isSupported',
- value: function isSupported() {
- try {
- var xhr = new XMLHttpRequest();
- // Firefox 37- requires .open() to be called before setting responseType
- xhr.open('GET', 'https://example.com', true);
- xhr.responseType = 'moz-chunked-arraybuffer';
- return xhr.responseType === 'moz-chunked-arraybuffer';
- } catch (e) {
- _logger2.default.w('MozChunkedLoader', e.message);
- return false;
- }
- }
- }]);
- function MozChunkedLoader(seekHandler, config) {
- _classCallCheck(this, MozChunkedLoader);
- var _this = _possibleConstructorReturn(this, (MozChunkedLoader.__proto__ || Object.getPrototypeOf(MozChunkedLoader)).call(this, 'xhr-moz-chunked-loader'));
- _this.TAG = 'MozChunkedLoader';
- _this._seekHandler = seekHandler;
- _this._config = config;
- _this._needStash = true;
- _this._xhr = null;
- _this._requestAbort = false;
- _this._contentLength = null;
- _this._receivedLength = 0;
- return _this;
- }
- _createClass(MozChunkedLoader, [{
- key: 'destroy',
- value: function destroy() {
- if (this.isWorking()) {
- this.abort();
- }
- if (this._xhr) {
- this._xhr.onreadystatechange = null;
- this._xhr.onprogress = null;
- this._xhr.onloadend = null;
- this._xhr.onerror = null;
- this._xhr = null;
- }
- _get(MozChunkedLoader.prototype.__proto__ || Object.getPrototypeOf(MozChunkedLoader.prototype), 'destroy', this).call(this);
- }
- }, {
- key: 'open',
- value: function open(dataSource, range) {
- this._dataSource = dataSource;
- this._range = range;
- var sourceURL = dataSource.url;
- if (this._config.reuseRedirectedURL && dataSource.redirectedURL != undefined) {
- sourceURL = dataSource.redirectedURL;
- }
- var seekConfig = this._seekHandler.getConfig(sourceURL, range);
- this._requestURL = seekConfig.url;
- var xhr = this._xhr = new XMLHttpRequest();
- xhr.open('GET', seekConfig.url, true);
- xhr.responseType = 'moz-chunked-arraybuffer';
- xhr.onreadystatechange = this._onReadyStateChange.bind(this);
- xhr.onprogress = this._onProgress.bind(this);
- xhr.onloadend = this._onLoadEnd.bind(this);
- xhr.onerror = this._onXhrError.bind(this);
- // cors is auto detected and enabled by xhr
- // withCredentials is disabled by default
- if (dataSource.withCredentials) {
- xhr.withCredentials = true;
- }
- if (_typeof(seekConfig.headers) === 'object') {
- var headers = seekConfig.headers;
- for (var key in headers) {
- if (headers.hasOwnProperty(key)) {
- xhr.setRequestHeader(key, headers[key]);
- }
- }
- }
- this._status = _loader.LoaderStatus.kConnecting;
- xhr.send();
- }
- }, {
- key: 'abort',
- value: function abort() {
- this._requestAbort = true;
- if (this._xhr) {
- this._xhr.abort();
- }
- this._status = _loader.LoaderStatus.kComplete;
- }
- }, {
- key: '_onReadyStateChange',
- value: function _onReadyStateChange(e) {
- var xhr = e.target;
- if (xhr.readyState === 2) {
- // HEADERS_RECEIVED
- if (xhr.responseURL != undefined && xhr.responseURL !== this._requestURL) {
- if (this._onURLRedirect) {
- var redirectedURL = this._seekHandler.removeURLParameters(xhr.responseURL);
- this._onURLRedirect(redirectedURL);
- }
- }
- if (xhr.status !== 0 && (xhr.status < 200 || xhr.status > 299)) {
- this._status = _loader.LoaderStatus.kError;
- if (this._onError) {
- this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: xhr.status, msg: xhr.statusText });
- } else {
- throw new _exception.RuntimeException('MozChunkedLoader: Http code invalid, ' + xhr.status + ' ' + xhr.statusText);
- }
- } else {
- this._status = _loader.LoaderStatus.kBuffering;
- }
- }
- }
- }, {
- key: '_onProgress',
- value: function _onProgress(e) {
- if (this._status === _loader.LoaderStatus.kError) {
- // Ignore error response
- return;
- }
- if (this._contentLength === null) {
- if (e.total !== null && e.total !== 0) {
- this._contentLength = e.total;
- if (this._onContentLengthKnown) {
- this._onContentLengthKnown(this._contentLength);
- }
- }
- }
- var chunk = e.target.response;
- var byteStart = this._range.from + this._receivedLength;
- this._receivedLength += chunk.byteLength;
- if (this._onDataArrival) {
- this._onDataArrival(chunk, byteStart, this._receivedLength);
- }
- }
- }, {
- key: '_onLoadEnd',
- value: function _onLoadEnd(e) {
- if (this._requestAbort === true) {
- this._requestAbort = false;
- return;
- } else if (this._status === _loader.LoaderStatus.kError) {
- return;
- }
- this._status = _loader.LoaderStatus.kComplete;
- if (this._onComplete) {
- this._onComplete(this._range.from, this._range.from + this._receivedLength - 1);
- }
- }
- }, {
- key: '_onXhrError',
- value: function _onXhrError(e) {
- this._status = _loader.LoaderStatus.kError;
- var type = 0;
- var info = null;
- if (this._contentLength && e.loaded < this._contentLength) {
- type = _loader.LoaderErrors.EARLY_EOF;
- info = { code: -1, msg: 'Moz-Chunked stream meet Early-Eof' };
- } else {
- type = _loader.LoaderErrors.EXCEPTION;
- info = { code: -1, msg: e.constructor.name + ' ' + e.type };
- }
- if (this._onError) {
- this._onError(type, info);
- } else {
- throw new _exception.RuntimeException(info.msg);
- }
- }
- }]);
- return MozChunkedLoader;
- }(_loader.BaseLoader);
- exports.default = MozChunkedLoader;
- module.exports = exports['default'];
- /***/ }),
- /* 28 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; };
- 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); } };
- 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; }; }();
- var _logger = __webpack_require__(0);
- var _logger2 = _interopRequireDefault(_logger);
- var _loader = __webpack_require__(3);
- var _exception = __webpack_require__(1);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- /* Notice: ms-stream may cause IE/Edge browser crash if seek too frequently!!!
- * The browser may crash in wininet.dll. Disable for now.
- *
- * For IE11/Edge browser by microsoft which supports `xhr.responseType = 'ms-stream'`
- * Notice that ms-stream API sucks. The buffer is always expanding along with downloading.
- *
- * We need to abort the xhr if buffer size exceeded limit size (e.g. 16 MiB), then do reconnect.
- * in order to release previous ArrayBuffer to avoid memory leak
- *
- * Otherwise, the ArrayBuffer will increase to a terrible size that equals final file size.
- */
- var MSStreamLoader = function (_BaseLoader) {
- _inherits(MSStreamLoader, _BaseLoader);
- _createClass(MSStreamLoader, null, [{
- key: 'isSupported',
- value: function isSupported() {
- try {
- if (typeof self.MSStream === 'undefined' || typeof self.MSStreamReader === 'undefined') {
- return false;
- }
- var xhr = new XMLHttpRequest();
- xhr.open('GET', 'https://example.com', true);
- xhr.responseType = 'ms-stream';
- return xhr.responseType === 'ms-stream';
- } catch (e) {
- _logger2.default.w('MSStreamLoader', e.message);
- return false;
- }
- }
- }]);
- function MSStreamLoader(seekHandler, config) {
- _classCallCheck(this, MSStreamLoader);
- var _this = _possibleConstructorReturn(this, (MSStreamLoader.__proto__ || Object.getPrototypeOf(MSStreamLoader)).call(this, 'xhr-msstream-loader'));
- _this.TAG = 'MSStreamLoader';
- _this._seekHandler = seekHandler;
- _this._config = config;
- _this._needStash = true;
- _this._xhr = null;
- _this._reader = null; // MSStreamReader
- _this._totalRange = null;
- _this._currentRange = null;
- _this._currentRequestURL = null;
- _this._currentRedirectedURL = null;
- _this._contentLength = null;
- _this._receivedLength = 0;
- _this._bufferLimit = 16 * 1024 * 1024; // 16MB
- _this._lastTimeBufferSize = 0;
- _this._isReconnecting = false;
- return _this;
- }
- _createClass(MSStreamLoader, [{
- key: 'destroy',
- value: function destroy() {
- if (this.isWorking()) {
- this.abort();
- }
- if (this._reader) {
- this._reader.onprogress = null;
- this._reader.onload = null;
- this._reader.onerror = null;
- this._reader = null;
- }
- if (this._xhr) {
- this._xhr.onreadystatechange = null;
- this._xhr = null;
- }
- _get(MSStreamLoader.prototype.__proto__ || Object.getPrototypeOf(MSStreamLoader.prototype), 'destroy', this).call(this);
- }
- }, {
- key: 'open',
- value: function open(dataSource, range) {
- this._internalOpen(dataSource, range, false);
- }
- }, {
- key: '_internalOpen',
- value: function _internalOpen(dataSource, range, isSubrange) {
- this._dataSource = dataSource;
- if (!isSubrange) {
- this._totalRange = range;
- } else {
- this._currentRange = range;
- }
- var sourceURL = dataSource.url;
- if (this._config.reuseRedirectedURL) {
- if (this._currentRedirectedURL != undefined) {
- sourceURL = this._currentRedirectedURL;
- } else if (dataSource.redirectedURL != undefined) {
- sourceURL = dataSource.redirectedURL;
- }
- }
- var seekConfig = this._seekHandler.getConfig(sourceURL, range);
- this._currentRequestURL = seekConfig.url;
- var reader = this._reader = new self.MSStreamReader();
- reader.onprogress = this._msrOnProgress.bind(this);
- reader.onload = this._msrOnLoad.bind(this);
- reader.onerror = this._msrOnError.bind(this);
- var xhr = this._xhr = new XMLHttpRequest();
- xhr.open('GET', seekConfig.url, true);
- xhr.responseType = 'ms-stream';
- xhr.onreadystatechange = this._xhrOnReadyStateChange.bind(this);
- xhr.onerror = this._xhrOnError.bind(this);
- if (dataSource.withCredentials) {
- xhr.withCredentials = true;
- }
- if (_typeof(seekConfig.headers) === 'object') {
- var headers = seekConfig.headers;
- for (var key in headers) {
- if (headers.hasOwnProperty(key)) {
- xhr.setRequestHeader(key, headers[key]);
- }
- }
- }
- if (this._isReconnecting) {
- this._isReconnecting = false;
- } else {
- this._status = _loader.LoaderStatus.kConnecting;
- }
- xhr.send();
- }
- }, {
- key: 'abort',
- value: function abort() {
- this._internalAbort();
- this._status = _loader.LoaderStatus.kComplete;
- }
- }, {
- key: '_internalAbort',
- value: function _internalAbort() {
- if (this._reader) {
- if (this._reader.readyState === 1) {
- // LOADING
- this._reader.abort();
- }
- this._reader.onprogress = null;
- this._reader.onload = null;
- this._reader.onerror = null;
- this._reader = null;
- }
- if (this._xhr) {
- this._xhr.abort();
- this._xhr.onreadystatechange = null;
- this._xhr = null;
- }
- }
- }, {
- key: '_xhrOnReadyStateChange',
- value: function _xhrOnReadyStateChange(e) {
- var xhr = e.target;
- if (xhr.readyState === 2) {
- // HEADERS_RECEIVED
- if (xhr.status >= 200 && xhr.status <= 299) {
- this._status = _loader.LoaderStatus.kBuffering;
- if (xhr.responseURL != undefined) {
- var redirectedURL = this._seekHandler.removeURLParameters(xhr.responseURL);
- if (xhr.responseURL !== this._currentRequestURL && redirectedURL !== this._currentRedirectedURL) {
- this._currentRedirectedURL = redirectedURL;
- if (this._onURLRedirect) {
- this._onURLRedirect(redirectedURL);
- }
- }
- }
- var lengthHeader = xhr.getResponseHeader('Content-Length');
- if (lengthHeader != null && this._contentLength == null) {
- var length = parseInt(lengthHeader);
- if (length > 0) {
- this._contentLength = length;
- if (this._onContentLengthKnown) {
- this._onContentLengthKnown(this._contentLength);
- }
- }
- }
- } else {
- this._status = _loader.LoaderStatus.kError;
- if (this._onError) {
- this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: xhr.status, msg: xhr.statusText });
- } else {
- throw new _exception.RuntimeException('MSStreamLoader: Http code invalid, ' + xhr.status + ' ' + xhr.statusText);
- }
- }
- } else if (xhr.readyState === 3) {
- // LOADING
- if (xhr.status >= 200 && xhr.status <= 299) {
- this._status = _loader.LoaderStatus.kBuffering;
- var msstream = xhr.response;
- this._reader.readAsArrayBuffer(msstream);
- }
- }
- }
- }, {
- key: '_xhrOnError',
- value: function _xhrOnError(e) {
- this._status = _loader.LoaderStatus.kError;
- var type = _loader.LoaderErrors.EXCEPTION;
- var info = { code: -1, msg: e.constructor.name + ' ' + e.type };
- if (this._onError) {
- this._onError(type, info);
- } else {
- throw new _exception.RuntimeException(info.msg);
- }
- }
- }, {
- key: '_msrOnProgress',
- value: function _msrOnProgress(e) {
- var reader = e.target;
- var bigbuffer = reader.result;
- if (bigbuffer == null) {
- // result may be null, workaround for buggy M$
- this._doReconnectIfNeeded();
- return;
- }
- var slice = bigbuffer.slice(this._lastTimeBufferSize);
- this._lastTimeBufferSize = bigbuffer.byteLength;
- var byteStart = this._totalRange.from + this._receivedLength;
- this._receivedLength += slice.byteLength;
- if (this._onDataArrival) {
- this._onDataArrival(slice, byteStart, this._receivedLength);
- }
- if (bigbuffer.byteLength >= this._bufferLimit) {
- _logger2.default.v(this.TAG, 'MSStream buffer exceeded max size near ' + (byteStart + slice.byteLength) + ', reconnecting...');
- this._doReconnectIfNeeded();
- }
- }
- }, {
- key: '_doReconnectIfNeeded',
- value: function _doReconnectIfNeeded() {
- if (this._contentLength == null || this._receivedLength < this._contentLength) {
- this._isReconnecting = true;
- this._lastTimeBufferSize = 0;
- this._internalAbort();
- var range = {
- from: this._totalRange.from + this._receivedLength,
- to: -1
- };
- this._internalOpen(this._dataSource, range, true);
- }
- }
- }, {
- key: '_msrOnLoad',
- value: function _msrOnLoad(e) {
- // actually it is onComplete event
- this._status = _loader.LoaderStatus.kComplete;
- if (this._onComplete) {
- this._onComplete(this._totalRange.from, this._totalRange.from + this._receivedLength - 1);
- }
- }
- }, {
- key: '_msrOnError',
- value: function _msrOnError(e) {
- this._status = _loader.LoaderStatus.kError;
- var type = 0;
- var info = null;
- if (this._contentLength && this._receivedLength < this._contentLength) {
- type = _loader.LoaderErrors.EARLY_EOF;
- info = { code: -1, msg: 'MSStream meet Early-Eof' };
- } else {
- type = _loader.LoaderErrors.EARLY_EOF;
- info = { code: -1, msg: e.constructor.name + ' ' + e.type };
- }
- if (this._onError) {
- this._onError(type, info);
- } else {
- throw new _exception.RuntimeException(info.msg);
- }
- }
- }]);
- return MSStreamLoader;
- }(_loader.BaseLoader);
- exports.default = MSStreamLoader;
- module.exports = exports['default'];
- /***/ }),
- /* 29 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; };
- 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); } };
- 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; }; }();
- var _logger = __webpack_require__(0);
- var _logger2 = _interopRequireDefault(_logger);
- var _speedSampler = __webpack_require__(13);
- var _speedSampler2 = _interopRequireDefault(_speedSampler);
- var _loader = __webpack_require__(3);
- var _exception = __webpack_require__(1);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- // Universal IO Loader, implemented by adding Range header in xhr's request header
- var RangeLoader = function (_BaseLoader) {
- _inherits(RangeLoader, _BaseLoader);
- _createClass(RangeLoader, null, [{
- key: 'isSupported',
- value: function isSupported() {
- try {
- var xhr = new XMLHttpRequest();
- xhr.open('GET', 'https://example.com', true);
- xhr.responseType = 'arraybuffer';
- return xhr.responseType === 'arraybuffer';
- } catch (e) {
- _logger2.default.w('RangeLoader', e.message);
- return false;
- }
- }
- }]);
- function RangeLoader(seekHandler, config) {
- _classCallCheck(this, RangeLoader);
- var _this = _possibleConstructorReturn(this, (RangeLoader.__proto__ || Object.getPrototypeOf(RangeLoader)).call(this, 'xhr-range-loader'));
- _this.TAG = 'RangeLoader';
- _this._seekHandler = seekHandler;
- _this._config = config;
- _this._needStash = false;
- _this._chunkSizeKBList = [128, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 5120, 6144, 7168, 8192];
- _this._currentChunkSizeKB = 384;
- _this._currentSpeedNormalized = 0;
- _this._zeroSpeedChunkCount = 0;
- _this._xhr = null;
- _this._speedSampler = new _speedSampler2.default();
- _this._requestAbort = false;
- _this._waitForTotalLength = false;
- _this._totalLengthReceived = false;
- _this._currentRequestURL = null;
- _this._currentRedirectedURL = null;
- _this._currentRequestRange = null;
- _this._totalLength = null; // size of the entire file
- _this._contentLength = null; // Content-Length of entire request range
- _this._receivedLength = 0; // total received bytes
- _this._lastTimeLoaded = 0; // received bytes of current request sub-range
- return _this;
- }
- _createClass(RangeLoader, [{
- key: 'destroy',
- value: function destroy() {
- if (this.isWorking()) {
- this.abort();
- }
- if (this._xhr) {
- this._xhr.onreadystatechange = null;
- this._xhr.onprogress = null;
- this._xhr.onload = null;
- this._xhr.onerror = null;
- this._xhr = null;
- }
- _get(RangeLoader.prototype.__proto__ || Object.getPrototypeOf(RangeLoader.prototype), 'destroy', this).call(this);
- }
- }, {
- key: 'open',
- value: function open(dataSource, range) {
- this._dataSource = dataSource;
- this._range = range;
- this._status = _loader.LoaderStatus.kConnecting;
- var useRefTotalLength = false;
- if (this._dataSource.filesize != undefined && this._dataSource.filesize !== 0) {
- useRefTotalLength = true;
- this._totalLength = this._dataSource.filesize;
- }
- if (!this._totalLengthReceived && !useRefTotalLength) {
- // We need total filesize
- this._waitForTotalLength = true;
- this._internalOpen(this._dataSource, { from: 0, to: -1 });
- } else {
- // We have filesize, start loading
- this._openSubRange();
- }
- }
- }, {
- key: '_openSubRange',
- value: function _openSubRange() {
- var chunkSize = this._currentChunkSizeKB * 1024;
- var from = this._range.from + this._receivedLength;
- var to = from + chunkSize;
- if (this._contentLength != null) {
- if (to - this._range.from >= this._contentLength) {
- to = this._range.from + this._contentLength - 1;
- }
- }
- this._currentRequestRange = { from: from, to: to };
- this._internalOpen(this._dataSource, this._currentRequestRange);
- }
- }, {
- key: '_internalOpen',
- value: function _internalOpen(dataSource, range) {
- this._lastTimeLoaded = 0;
- var sourceURL = dataSource.url;
- if (this._config.reuseRedirectedURL) {
- if (this._currentRedirectedURL != undefined) {
- sourceURL = this._currentRedirectedURL;
- } else if (dataSource.redirectedURL != undefined) {
- sourceURL = dataSource.redirectedURL;
- }
- }
- var seekConfig = this._seekHandler.getConfig(sourceURL, range);
- this._currentRequestURL = seekConfig.url;
- var xhr = this._xhr = new XMLHttpRequest();
- xhr.open('GET', seekConfig.url, true);
- xhr.responseType = 'arraybuffer';
- xhr.onreadystatechange = this._onReadyStateChange.bind(this);
- xhr.onprogress = this._onProgress.bind(this);
- xhr.onload = this._onLoad.bind(this);
- xhr.onerror = this._onXhrError.bind(this);
- if (dataSource.withCredentials) {
- xhr.withCredentials = true;
- }
- if (_typeof(seekConfig.headers) === 'object') {
- var headers = seekConfig.headers;
- for (var key in headers) {
- if (headers.hasOwnProperty(key)) {
- xhr.setRequestHeader(key, headers[key]);
- }
- }
- }
- xhr.send();
- }
- }, {
- key: 'abort',
- value: function abort() {
- this._requestAbort = true;
- this._internalAbort();
- this._status = _loader.LoaderStatus.kComplete;
- }
- }, {
- key: '_internalAbort',
- value: function _internalAbort() {
- if (this._xhr) {
- this._xhr.onreadystatechange = null;
- this._xhr.onprogress = null;
- this._xhr.onload = null;
- this._xhr.onerror = null;
- this._xhr.abort();
- this._xhr = null;
- }
- }
- }, {
- key: '_onReadyStateChange',
- value: function _onReadyStateChange(e) {
- var xhr = e.target;
- if (xhr.readyState === 2) {
- // HEADERS_RECEIVED
- if (xhr.responseURL != undefined) {
- // if the browser support this property
- var redirectedURL = this._seekHandler.removeURLParameters(xhr.responseURL);
- if (xhr.responseURL !== this._currentRequestURL && redirectedURL !== this._currentRedirectedURL) {
- this._currentRedirectedURL = redirectedURL;
- if (this._onURLRedirect) {
- this._onURLRedirect(redirectedURL);
- }
- }
- }
- if (xhr.status >= 200 && xhr.status <= 299) {
- if (this._waitForTotalLength) {
- return;
- }
- this._status = _loader.LoaderStatus.kBuffering;
- } else {
- this._status = _loader.LoaderStatus.kError;
- if (this._onError) {
- this._onError(_loader.LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: xhr.status, msg: xhr.statusText });
- } else {
- throw new _exception.RuntimeException('RangeLoader: Http code invalid, ' + xhr.status + ' ' + xhr.statusText);
- }
- }
- }
- }
- }, {
- key: '_onProgress',
- value: function _onProgress(e) {
- if (this._status === _loader.LoaderStatus.kError) {
- // Ignore error response
- return;
- }
- if (this._contentLength === null) {
- var openNextRange = false;
- if (this._waitForTotalLength) {
- this._waitForTotalLength = false;
- this._totalLengthReceived = true;
- openNextRange = true;
- var total = e.total;
- this._internalAbort();
- if (total != null & total !== 0) {
- this._totalLength = total;
- }
- }
- // calculate currrent request range's contentLength
- if (this._range.to === -1) {
- this._contentLength = this._totalLength - this._range.from;
- } else {
- // to !== -1
- this._contentLength = this._range.to - this._range.from + 1;
- }
- if (openNextRange) {
- this._openSubRange();
- return;
- }
- if (this._onContentLengthKnown) {
- this._onContentLengthKnown(this._contentLength);
- }
- }
- var delta = e.loaded - this._lastTimeLoaded;
- this._lastTimeLoaded = e.loaded;
- this._speedSampler.addBytes(delta);
- }
- }, {
- key: '_normalizeSpeed',
- value: function _normalizeSpeed(input) {
- var list = this._chunkSizeKBList;
- var last = list.length - 1;
- var mid = 0;
- var lbound = 0;
- var ubound = last;
- if (input < list[0]) {
- return list[0];
- }
- while (lbound <= ubound) {
- mid = lbound + Math.floor((ubound - lbound) / 2);
- if (mid === last || input >= list[mid] && input < list[mid + 1]) {
- return list[mid];
- } else if (list[mid] < input) {
- lbound = mid + 1;
- } else {
- ubound = mid - 1;
- }
- }
- }
- }, {
- key: '_onLoad',
- value: function _onLoad(e) {
- if (this._status === _loader.LoaderStatus.kError) {
- // Ignore error response
- return;
- }
- if (this._waitForTotalLength) {
- this._waitForTotalLength = false;
- return;
- }
- this._lastTimeLoaded = 0;
- var KBps = this._speedSampler.lastSecondKBps;
- if (KBps === 0) {
- this._zeroSpeedChunkCount++;
- if (this._zeroSpeedChunkCount >= 3) {
- // Try get currentKBps after 3 chunks
- KBps = this._speedSampler.currentKBps;
- }
- }
- if (KBps !== 0) {
- var normalized = this._normalizeSpeed(KBps);
- if (this._currentSpeedNormalized !== normalized) {
- this._currentSpeedNormalized = normalized;
- this._currentChunkSizeKB = normalized;
- }
- }
- var chunk = e.target.response;
- var byteStart = this._range.from + this._receivedLength;
- this._receivedLength += chunk.byteLength;
- var reportComplete = false;
- if (this._contentLength != null && this._receivedLength < this._contentLength) {
- // continue load next chunk
- this._openSubRange();
- } else {
- reportComplete = true;
- }
- // dispatch received chunk
- if (this._onDataArrival) {
- this._onDataArrival(chunk, byteStart, this._receivedLength);
- }
- if (reportComplete) {
- this._status = _loader.LoaderStatus.kComplete;
- if (this._onComplete) {
- this._onComplete(this._range.from, this._range.from + this._receivedLength - 1);
- }
- }
- }
- }, {
- key: '_onXhrError',
- value: function _onXhrError(e) {
- this._status = _loader.LoaderStatus.kError;
- var type = 0;
- var info = null;
- if (this._contentLength && this._receivedLength > 0 && this._receivedLength < this._contentLength) {
- type = _loader.LoaderErrors.EARLY_EOF;
- info = { code: -1, msg: 'RangeLoader meet Early-Eof' };
- } else {
- type = _loader.LoaderErrors.EXCEPTION;
- info = { code: -1, msg: e.constructor.name + ' ' + e.type };
- }
- if (this._onError) {
- this._onError(type, info);
- } else {
- throw new _exception.RuntimeException(info.msg);
- }
- }
- }, {
- key: 'currentSpeed',
- get: function get() {
- return this._speedSampler.lastSecondKBps;
- }
- }]);
- return RangeLoader;
- }(_loader.BaseLoader);
- exports.default = RangeLoader;
- module.exports = exports['default'];
- /***/ }),
- /* 30 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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); } };
- 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; }; }();
- var _logger = __webpack_require__(0);
- var _logger2 = _interopRequireDefault(_logger);
- var _loader = __webpack_require__(3);
- var _exception = __webpack_require__(1);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- 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; }
- 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; } /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- // For FLV over WebSocket live stream
- var WebSocketLoader = function (_BaseLoader) {
- _inherits(WebSocketLoader, _BaseLoader);
- _createClass(WebSocketLoader, null, [{
- key: 'isSupported',
- value: function isSupported() {
- try {
- return typeof self.WebSocket !== 'undefined';
- } catch (e) {
- return false;
- }
- }
- }]);
- function WebSocketLoader() {
- _classCallCheck(this, WebSocketLoader);
- var _this = _possibleConstructorReturn(this, (WebSocketLoader.__proto__ || Object.getPrototypeOf(WebSocketLoader)).call(this, 'websocket-loader'));
- _this.TAG = 'WebSocketLoader';
- _this._needStash = true;
- _this._ws = null;
- _this._requestAbort = false;
- _this._receivedLength = 0;
- return _this;
- }
- _createClass(WebSocketLoader, [{
- key: 'destroy',
- value: function destroy() {
- if (this._ws) {
- this.abort();
- }
- _get(WebSocketLoader.prototype.__proto__ || Object.getPrototypeOf(WebSocketLoader.prototype), 'destroy', this).call(this);
- }
- }, {
- key: 'open',
- value: function open(dataSource) {
- try {
- var ws = this._ws = new self.WebSocket(dataSource.url);
- ws.binaryType = 'arraybuffer';
- ws.onopen = this._onWebSocketOpen.bind(this);
- ws.onclose = this._onWebSocketClose.bind(this);
- ws.onmessage = this._onWebSocketMessage.bind(this);
- ws.onerror = this._onWebSocketError.bind(this);
- this._status = _loader.LoaderStatus.kConnecting;
- } catch (e) {
- this._status = _loader.LoaderStatus.kError;
- var info = { code: e.code, msg: e.message };
- if (this._onError) {
- this._onError(_loader.LoaderErrors.EXCEPTION, info);
- } else {
- throw new _exception.RuntimeException(info.msg);
- }
- }
- }
- }, {
- key: 'abort',
- value: function abort() {
- var ws = this._ws;
- if (ws && (ws.readyState === 0 || ws.readyState === 1)) {
- // CONNECTING || OPEN
- this._requestAbort = true;
- ws.close();
- }
- this._ws = null;
- this._status = _loader.LoaderStatus.kComplete;
- }
- }, {
- key: '_onWebSocketOpen',
- value: function _onWebSocketOpen(e) {
- this._status = _loader.LoaderStatus.kBuffering;
- }
- }, {
- key: '_onWebSocketClose',
- value: function _onWebSocketClose(e) {
- if (this._requestAbort === true) {
- this._requestAbort = false;
- return;
- }
- this._status = _loader.LoaderStatus.kComplete;
- if (this._onComplete) {
- this._onComplete(0, this._receivedLength - 1);
- }
- }
- }, {
- key: '_onWebSocketMessage',
- value: function _onWebSocketMessage(e) {
- var _this2 = this;
- if (e.data instanceof ArrayBuffer) {
- this._dispatchArrayBuffer(e.data);
- } else if (e.data instanceof Blob) {
- var reader = new FileReader();
- reader.onload = function () {
- _this2._dispatchArrayBuffer(reader.result);
- };
- reader.readAsArrayBuffer(e.data);
- } else {
- this._status = _loader.LoaderStatus.kError;
- var info = { code: -1, msg: 'Unsupported WebSocket message type: ' + e.data.constructor.name };
- if (this._onError) {
- this._onError(_loader.LoaderErrors.EXCEPTION, info);
- } else {
- throw new _exception.RuntimeException(info.msg);
- }
- }
- }
- }, {
- key: '_dispatchArrayBuffer',
- value: function _dispatchArrayBuffer(arraybuffer) {
- var chunk = arraybuffer;
- var byteStart = this._receivedLength;
- this._receivedLength += chunk.byteLength;
- if (this._onDataArrival) {
- this._onDataArrival(chunk, byteStart, this._receivedLength);
- }
- }
- }, {
- key: '_onWebSocketError',
- value: function _onWebSocketError(e) {
- this._status = _loader.LoaderStatus.kError;
- var info = {
- code: e.code,
- msg: e.message
- };
- if (this._onError) {
- this._onError(_loader.LoaderErrors.EXCEPTION, info);
- } else {
- throw new _exception.RuntimeException(info.msg);
- }
- }
- }]);
- return WebSocketLoader;
- }(_loader.BaseLoader);
- exports.default = WebSocketLoader;
- module.exports = exports['default'];
- /***/ }),
- /* 31 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var RangeSeekHandler = function () {
- function RangeSeekHandler(zeroStart) {
- _classCallCheck(this, RangeSeekHandler);
- this._zeroStart = zeroStart || false;
- }
- _createClass(RangeSeekHandler, [{
- key: 'getConfig',
- value: function getConfig(url, range) {
- var headers = {};
- if (range.from !== 0 || range.to !== -1) {
- var param = void 0;
- if (range.to !== -1) {
- param = 'bytes=' + range.from.toString() + '-' + range.to.toString();
- } else {
- param = 'bytes=' + range.from.toString() + '-';
- }
- headers['Range'] = param;
- } else if (this._zeroStart) {
- headers['Range'] = 'bytes=0-';
- }
- return {
- url: url,
- headers: headers
- };
- }
- }, {
- key: 'removeURLParameters',
- value: function removeURLParameters(seekedURL) {
- return seekedURL;
- }
- }]);
- return RangeSeekHandler;
- }();
- exports.default = RangeSeekHandler;
- module.exports = exports['default'];
- /***/ }),
- /* 32 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var ParamSeekHandler = function () {
- function ParamSeekHandler(paramStart, paramEnd) {
- _classCallCheck(this, ParamSeekHandler);
- this._startName = paramStart;
- this._endName = paramEnd;
- }
- _createClass(ParamSeekHandler, [{
- key: 'getConfig',
- value: function getConfig(baseUrl, range) {
- var url = baseUrl;
- if (range.from !== 0 || range.to !== -1) {
- var needAnd = true;
- if (url.indexOf('?') === -1) {
- url += '?';
- needAnd = false;
- }
- if (needAnd) {
- url += '&';
- }
- url += this._startName + '=' + range.from.toString();
- if (range.to !== -1) {
- url += '&' + this._endName + '=' + range.to.toString();
- }
- }
- return {
- url: url,
- headers: {}
- };
- }
- }, {
- key: 'removeURLParameters',
- value: function removeURLParameters(seekedURL) {
- var baseURL = seekedURL.split('?')[0];
- var params = undefined;
- var queryIndex = seekedURL.indexOf('?');
- if (queryIndex !== -1) {
- params = seekedURL.substring(queryIndex + 1);
- }
- var resultParams = '';
- if (params != undefined && params.length > 0) {
- var pairs = params.split('&');
- for (var i = 0; i < pairs.length; i++) {
- var pair = pairs[i].split('=');
- var requireAnd = i > 0;
- if (pair[0] !== this._startName && pair[0] !== this._endName) {
- if (requireAnd) {
- resultParams += '&';
- }
- resultParams += pairs[i];
- }
- }
- }
- return resultParams.length === 0 ? baseURL : baseURL + '?' + resultParams;
- }
- }]);
- return ParamSeekHandler;
- }();
- exports.default = ParamSeekHandler;
- module.exports = exports['default'];
- /***/ }),
- /* 33 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; };
- 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; }; }(); /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var _events = __webpack_require__(2);
- var _events2 = _interopRequireDefault(_events);
- var _logger = __webpack_require__(0);
- var _logger2 = _interopRequireDefault(_logger);
- var _browser = __webpack_require__(4);
- var _browser2 = _interopRequireDefault(_browser);
- var _playerEvents = __webpack_require__(7);
- var _playerEvents2 = _interopRequireDefault(_playerEvents);
- var _transmuxer = __webpack_require__(34);
- var _transmuxer2 = _interopRequireDefault(_transmuxer);
- var _transmuxingEvents = __webpack_require__(5);
- var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
- var _mseController = __webpack_require__(45);
- var _mseController2 = _interopRequireDefault(_mseController);
- var _mseEvents = __webpack_require__(16);
- var _mseEvents2 = _interopRequireDefault(_mseEvents);
- var _playerErrors = __webpack_require__(17);
- var _config = __webpack_require__(6);
- var _exception = __webpack_require__(1);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var FlvPlayer = function () {
- function FlvPlayer(mediaDataSource, config) {
- _classCallCheck(this, FlvPlayer);
- this.TAG = 'FlvPlayer';
- this._type = 'FlvPlayer';
- this._emitter = new _events2.default();
- this._config = (0, _config.createDefaultConfig)();
- if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object') {
- Object.assign(this._config, config);
- }
- if (mediaDataSource.type.toLowerCase() !== 'flv') {
- throw new _exception.InvalidArgumentException('FlvPlayer requires an flv MediaDataSource input!');
- }
- if (mediaDataSource.isLive === true) {
- this._config.isLive = true;
- }
- this.e = {
- onvLoadedMetadata: this._onvLoadedMetadata.bind(this),
- onvSeeking: this._onvSeeking.bind(this),
- onvCanPlay: this._onvCanPlay.bind(this),
- onvStalled: this._onvStalled.bind(this),
- onvProgress: this._onvProgress.bind(this)
- };
- if (self.performance && self.performance.now) {
- this._now = self.performance.now.bind(self.performance);
- } else {
- this._now = Date.now;
- }
- this._pendingSeekTime = null; // in seconds
- this._requestSetTime = false;
- this._seekpointRecord = null;
- this._progressChecker = null;
- this._mediaDataSource = mediaDataSource;
- this._mediaElement = null;
- this._msectl = null;
- this._transmuxer = null;
- this._mseSourceOpened = false;
- this._hasPendingLoad = false;
- this._receivedCanPlay = false;
- this._mediaInfo = null;
- this._statisticsInfo = null;
- var chromeNeedIDRFix = _browser2.default.chrome && (_browser2.default.version.major < 50 || _browser2.default.version.major === 50 && _browser2.default.version.build < 2661);
- this._alwaysSeekKeyframe = chromeNeedIDRFix || _browser2.default.msedge || _browser2.default.msie ? true : false;
- if (this._alwaysSeekKeyframe) {
- this._config.accurateSeek = false;
- }
- }
- _createClass(FlvPlayer, [{
- key: 'destroy',
- value: function destroy() {
- if (this._progressChecker != null) {
- window.clearInterval(this._progressChecker);
- this._progressChecker = null;
- }
- if (this._transmuxer) {
- this.unload();
- }
- if (this._mediaElement) {
- this.detachMediaElement();
- }
- this.e = null;
- this._mediaDataSource = null;
- this._emitter.removeAllListeners();
- this._emitter = null;
- }
- }, {
- key: 'on',
- value: function on(event, listener) {
- var _this = this;
- if (event === _playerEvents2.default.MEDIA_INFO) {
- if (this._mediaInfo != null) {
- Promise.resolve().then(function () {
- _this._emitter.emit(_playerEvents2.default.MEDIA_INFO, _this.mediaInfo);
- });
- }
- } else if (event === _playerEvents2.default.STATISTICS_INFO) {
- if (this._statisticsInfo != null) {
- Promise.resolve().then(function () {
- _this._emitter.emit(_playerEvents2.default.STATISTICS_INFO, _this.statisticsInfo);
- });
- }
- }
- this._emitter.addListener(event, listener);
- }
- }, {
- key: 'off',
- value: function off(event, listener) {
- this._emitter.removeListener(event, listener);
- }
- }, {
- key: 'attachMediaElement',
- value: function attachMediaElement(mediaElement) {
- var _this2 = this;
- this._mediaElement = mediaElement;
- mediaElement.addEventListener('loadedmetadata', this.e.onvLoadedMetadata);
- mediaElement.addEventListener('seeking', this.e.onvSeeking);
- mediaElement.addEventListener('canplay', this.e.onvCanPlay);
- mediaElement.addEventListener('stalled', this.e.onvStalled);
- mediaElement.addEventListener('progress', this.e.onvProgress);
- this._msectl = new _mseController2.default(this._config);
- this._msectl.on(_mseEvents2.default.UPDATE_END, this._onmseUpdateEnd.bind(this));
- this._msectl.on(_mseEvents2.default.BUFFER_FULL, this._onmseBufferFull.bind(this));
- this._msectl.on(_mseEvents2.default.SOURCE_OPEN, function () {
- _this2._mseSourceOpened = true;
- if (_this2._hasPendingLoad) {
- _this2._hasPendingLoad = false;
- _this2.load();
- }
- });
- this._msectl.on(_mseEvents2.default.ERROR, function (info) {
- _this2._emitter.emit(_playerEvents2.default.ERROR, _playerErrors.ErrorTypes.MEDIA_ERROR, _playerErrors.ErrorDetails.MEDIA_MSE_ERROR, info);
- });
- this._msectl.attachMediaElement(mediaElement);
- if (this._pendingSeekTime != null) {
- try {
- mediaElement.currentTime = this._pendingSeekTime;
- this._pendingSeekTime = null;
- } catch (e) {
- // IE11 may throw InvalidStateError if readyState === 0
- // We can defer set currentTime operation after loadedmetadata
- }
- }
- }
- }, {
- key: 'detachMediaElement',
- value: function detachMediaElement() {
- if (this._mediaElement) {
- this._msectl.detachMediaElement();
- this._mediaElement.removeEventListener('loadedmetadata', this.e.onvLoadedMetadata);
- this._mediaElement.removeEventListener('seeking', this.e.onvSeeking);
- this._mediaElement.removeEventListener('canplay', this.e.onvCanPlay);
- this._mediaElement.removeEventListener('stalled', this.e.onvStalled);
- this._mediaElement.removeEventListener('progress', this.e.onvProgress);
- this._mediaElement = null;
- }
- if (this._msectl) {
- this._msectl.destroy();
- this._msectl = null;
- }
- }
- }, {
- key: 'load',
- value: function load() {
- var _this3 = this;
- if (!this._mediaElement) {
- throw new _exception.IllegalStateException('HTMLMediaElement must be attached before load()!');
- }
- if (this._transmuxer) {
- throw new _exception.IllegalStateException('FlvPlayer.load() has been called, please call unload() first!');
- }
- if (this._hasPendingLoad) {
- return;
- }
- if (this._config.deferLoadAfterSourceOpen && this._mseSourceOpened === false) {
- this._hasPendingLoad = true;
- return;
- }
- if (this._mediaElement.readyState > 0) {
- this._requestSetTime = true;
- // IE11 may throw InvalidStateError if readyState === 0
- this._mediaElement.currentTime = 0;
- }
- this._transmuxer = new _transmuxer2.default(this._mediaDataSource, this._config);
- this._transmuxer.on(_transmuxingEvents2.default.INIT_SEGMENT, function (type, is) {
- _this3._msectl.appendInitSegment(is);
- });
- this._transmuxer.on(_transmuxingEvents2.default.MEDIA_SEGMENT, function (type, ms) {
- _this3._msectl.appendMediaSegment(ms);
- // lazyLoad check
- if (_this3._config.lazyLoad && !_this3._config.isLive) {
- var currentTime = _this3._mediaElement.currentTime;
- if (ms.info.endDts >= (currentTime + _this3._config.lazyLoadMaxDuration) * 1000) {
- if (_this3._progressChecker == null) {
- _logger2.default.v(_this3.TAG, 'Maximum buffering duration exceeded, suspend transmuxing task');
- _this3._suspendTransmuxer();
- }
- }
- }
- });
- this._transmuxer.on(_transmuxingEvents2.default.LOADING_COMPLETE, function () {
- _this3._msectl.endOfStream();
- _this3._emitter.emit(_playerEvents2.default.LOADING_COMPLETE);
- });
- this._transmuxer.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF, function () {
- _this3._emitter.emit(_playerEvents2.default.RECOVERED_EARLY_EOF);
- });
- this._transmuxer.on(_transmuxingEvents2.default.IO_ERROR, function (detail, info) {
- _this3._emitter.emit(_playerEvents2.default.ERROR, _playerErrors.ErrorTypes.NETWORK_ERROR, detail, info);
- });
- this._transmuxer.on(_transmuxingEvents2.default.DEMUX_ERROR, function (detail, info) {
- _this3._emitter.emit(_playerEvents2.default.ERROR, _playerErrors.ErrorTypes.MEDIA_ERROR, detail, { code: -1, msg: info });
- });
- this._transmuxer.on(_transmuxingEvents2.default.MEDIA_INFO, function (mediaInfo) {
- _this3._mediaInfo = mediaInfo;
- _this3._emitter.emit(_playerEvents2.default.MEDIA_INFO, Object.assign({}, mediaInfo));
- });
- this._transmuxer.on(_transmuxingEvents2.default.STATISTICS_INFO, function (statInfo) {
- _this3._statisticsInfo = _this3._fillStatisticsInfo(statInfo);
- _this3._emitter.emit(_playerEvents2.default.STATISTICS_INFO, Object.assign({}, _this3._statisticsInfo));
- });
- this._transmuxer.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, function (milliseconds) {
- if (_this3._mediaElement && !_this3._config.accurateSeek) {
- _this3._requestSetTime = true;
- _this3._mediaElement.currentTime = milliseconds / 1000;
- }
- });
- this._transmuxer.on(_transmuxingEvents2.default.LOADED_SEI, function (timestamp, data) {
- _this3._emitter.emit(_playerEvents2.default.LOADED_SEI, timestamp, data);
- });
- this._transmuxer.open();
- }
- }, {
- key: 'unload',
- value: function unload() {
- if (this._mediaElement) {
- this._mediaElement.pause();
- }
- if (this._msectl) {
- this._msectl.seek(0);
- }
- if (this._transmuxer) {
- this._transmuxer.close();
- this._transmuxer.destroy();
- this._transmuxer = null;
- }
- }
- }, {
- key: 'play',
- value: function play() {
- var playPromise = this._mediaElement.play();
- if (playPromise !== undefined && playPromise) {
- return playPromise.catch(function () {});
- } else return undefined;
- }
- }, {
- key: 'pause',
- value: function pause() {
- this._mediaElement.pause();
- }
- }, {
- key: '_fillStatisticsInfo',
- value: function _fillStatisticsInfo(statInfo) {
- statInfo.playerType = this._type;
- if (!(this._mediaElement instanceof HTMLVideoElement)) {
- return statInfo;
- }
- var hasQualityInfo = true;
- var decoded = 0;
- var dropped = 0;
- if (this._mediaElement.getVideoPlaybackQuality) {
- var quality = this._mediaElement.getVideoPlaybackQuality();
- decoded = quality.totalVideoFrames;
- dropped = quality.droppedVideoFrames;
- } else if (this._mediaElement.webkitDecodedFrameCount != undefined) {
- decoded = this._mediaElement.webkitDecodedFrameCount;
- dropped = this._mediaElement.webkitDroppedFrameCount;
- } else {
- hasQualityInfo = false;
- }
- if (hasQualityInfo) {
- statInfo.decodedFrames = decoded;
- statInfo.droppedFrames = dropped;
- }
- return statInfo;
- }
- }, {
- key: '_onmseUpdateEnd',
- value: function _onmseUpdateEnd() {
- if (!this._config.lazyLoad || this._config.isLive) {
- return;
- }
- var buffered = this._mediaElement.buffered;
- var currentTime = this._mediaElement.currentTime;
- var currentRangeStart = 0;
- var currentRangeEnd = 0;
- for (var i = 0; i < buffered.length; i++) {
- var start = buffered.start(i);
- var end = buffered.end(i);
- if (start <= currentTime && currentTime < end) {
- currentRangeStart = start;
- currentRangeEnd = end;
- break;
- }
- }
- if (currentRangeEnd >= currentTime + this._config.lazyLoadMaxDuration && this._progressChecker == null) {
- _logger2.default.v(this.TAG, 'Maximum buffering duration exceeded, suspend transmuxing task');
- this._suspendTransmuxer();
- }
- }
- }, {
- key: '_onmseBufferFull',
- value: function _onmseBufferFull() {
- _logger2.default.v(this.TAG, 'MSE SourceBuffer is full, suspend transmuxing task');
- if (this._progressChecker == null) {
- this._suspendTransmuxer();
- }
- }
- }, {
- key: '_suspendTransmuxer',
- value: function _suspendTransmuxer() {
- if (this._transmuxer) {
- this._transmuxer.pause();
- if (this._progressChecker == null) {
- this._progressChecker = window.setInterval(this._checkProgressAndResume.bind(this), 1000);
- }
- }
- }
- }, {
- key: '_checkProgressAndResume',
- value: function _checkProgressAndResume() {
- var currentTime = this._mediaElement.currentTime;
- var buffered = this._mediaElement.buffered;
- var needResume = false;
- for (var i = 0; i < buffered.length; i++) {
- var from = buffered.start(i);
- var to = buffered.end(i);
- if (currentTime >= from && currentTime < to) {
- if (currentTime >= to - this._config.lazyLoadRecoverDuration) {
- needResume = true;
- }
- break;
- }
- }
- if (needResume) {
- window.clearInterval(this._progressChecker);
- this._progressChecker = null;
- if (needResume) {
- _logger2.default.v(this.TAG, 'Continue loading from paused position');
- this._transmuxer.resume();
- }
- }
- }
- }, {
- key: '_isTimepointBuffered',
- value: function _isTimepointBuffered(seconds) {
- var buffered = this._mediaElement.buffered;
- for (var i = 0; i < buffered.length; i++) {
- var from = buffered.start(i);
- var to = buffered.end(i);
- if (seconds >= from && seconds < to) {
- return true;
- }
- }
- return false;
- }
- }, {
- key: '_internalSeek',
- value: function _internalSeek(seconds) {
- var directSeek = this._isTimepointBuffered(seconds);
- var directSeekBegin = false;
- var directSeekBeginTime = 0;
- if (seconds < 1.0 && this._mediaElement.buffered.length > 0) {
- var videoBeginTime = this._mediaElement.buffered.start(0);
- if (videoBeginTime < 1.0 && seconds < videoBeginTime || _browser2.default.safari) {
- directSeekBegin = true;
- // also workaround for Safari: Seek to 0 may cause video stuck, use 0.1 to avoid
- directSeekBeginTime = _browser2.default.safari ? 0.1 : videoBeginTime;
- }
- }
- if (directSeekBegin) {
- // seek to video begin, set currentTime directly if beginPTS buffered
- this._requestSetTime = true;
- this._mediaElement.currentTime = directSeekBeginTime;
- } else if (directSeek) {
- // buffered position
- if (!this._alwaysSeekKeyframe) {
- this._requestSetTime = true;
- this._mediaElement.currentTime = seconds;
- } else {
- var idr = this._msectl.getNearestKeyframe(Math.floor(seconds * 1000));
- this._requestSetTime = true;
- if (idr != null) {
- this._mediaElement.currentTime = idr.dts / 1000;
- } else {
- this._mediaElement.currentTime = seconds;
- }
- }
- if (this._progressChecker != null) {
- this._checkProgressAndResume();
- }
- } else {
- if (this._progressChecker != null) {
- window.clearInterval(this._progressChecker);
- this._progressChecker = null;
- }
- this._msectl.seek(seconds);
- this._transmuxer.seek(Math.floor(seconds * 1000)); // in milliseconds
- // no need to set mediaElement.currentTime if non-accurateSeek,
- // just wait for the recommend_seekpoint callback
- if (this._config.accurateSeek) {
- this._requestSetTime = true;
- this._mediaElement.currentTime = seconds;
- }
- }
- }
- }, {
- key: '_checkAndApplyUnbufferedSeekpoint',
- value: function _checkAndApplyUnbufferedSeekpoint() {
- if (this._seekpointRecord) {
- if (this._seekpointRecord.recordTime <= this._now() - 100) {
- var target = this._mediaElement.currentTime;
- this._seekpointRecord = null;
- if (!this._isTimepointBuffered(target)) {
- if (this._progressChecker != null) {
- window.clearTimeout(this._progressChecker);
- this._progressChecker = null;
- }
- // .currentTime is consists with .buffered timestamp
- // Chrome/Edge use DTS, while FireFox/Safari use PTS
- this._msectl.seek(target);
- this._transmuxer.seek(Math.floor(target * 1000));
- // set currentTime if accurateSeek, or wait for recommend_seekpoint callback
- if (this._config.accurateSeek) {
- this._requestSetTime = true;
- this._mediaElement.currentTime = target;
- }
- }
- } else {
- window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this), 50);
- }
- }
- }
- }, {
- key: '_checkAndResumeStuckPlayback',
- value: function _checkAndResumeStuckPlayback(stalled) {
- var media = this._mediaElement;
- if (stalled || !this._receivedCanPlay || media.readyState < 2) {
- // HAVE_CURRENT_DATA
- var buffered = media.buffered;
- if (buffered.length > 0 && media.currentTime < buffered.start(0)) {
- _logger2.default.w(this.TAG, 'Playback seems stuck at ' + media.currentTime + ', seek to ' + buffered.start(0));
- this._requestSetTime = true;
- this._mediaElement.currentTime = buffered.start(0);
- this._mediaElement.removeEventListener('progress', this.e.onvProgress);
- }
- } else {
- // Playback didn't stuck, remove progress event listener
- this._mediaElement.removeEventListener('progress', this.e.onvProgress);
- }
- }
- }, {
- key: '_onvLoadedMetadata',
- value: function _onvLoadedMetadata(e) {
- if (this._pendingSeekTime != null) {
- this._mediaElement.currentTime = this._pendingSeekTime;
- this._pendingSeekTime = null;
- }
- }
- }, {
- key: '_onvSeeking',
- value: function _onvSeeking(e) {
- // handle seeking request from browser's progress bar
- var target = this._mediaElement.currentTime;
- var buffered = this._mediaElement.buffered;
- if (this._requestSetTime) {
- this._requestSetTime = false;
- return;
- }
- if (target < 1.0 && buffered.length > 0) {
- // seek to video begin, set currentTime directly if beginPTS buffered
- var videoBeginTime = buffered.start(0);
- if (videoBeginTime < 1.0 && target < videoBeginTime || _browser2.default.safari) {
- this._requestSetTime = true;
- // also workaround for Safari: Seek to 0 may cause video stuck, use 0.1 to avoid
- this._mediaElement.currentTime = _browser2.default.safari ? 0.1 : videoBeginTime;
- return;
- }
- }
- if (this._isTimepointBuffered(target)) {
- if (this._alwaysSeekKeyframe) {
- var idr = this._msectl.getNearestKeyframe(Math.floor(target * 1000));
- if (idr != null) {
- this._requestSetTime = true;
- this._mediaElement.currentTime = idr.dts / 1000;
- }
- }
- if (this._progressChecker != null) {
- this._checkProgressAndResume();
- }
- return;
- }
- this._seekpointRecord = {
- seekPoint: target,
- recordTime: this._now()
- };
- window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this), 50);
- }
- }, {
- key: '_onvCanPlay',
- value: function _onvCanPlay(e) {
- this._receivedCanPlay = true;
- this._mediaElement.removeEventListener('canplay', this.e.onvCanPlay);
- }
- }, {
- key: '_onvStalled',
- value: function _onvStalled(e) {
- this._checkAndResumeStuckPlayback(true);
- }
- }, {
- key: '_onvProgress',
- value: function _onvProgress(e) {
- this._checkAndResumeStuckPlayback();
- }
- }, {
- key: 'type',
- get: function get() {
- return this._type;
- }
- }, {
- key: 'buffered',
- get: function get() {
- return this._mediaElement.buffered;
- }
- }, {
- key: 'duration',
- get: function get() {
- return this._mediaElement.duration;
- }
- }, {
- key: 'volume',
- get: function get() {
- return this._mediaElement.volume;
- },
- set: function set(value) {
- this._mediaElement.volume = value;
- }
- }, {
- key: 'muted',
- get: function get() {
- return this._mediaElement.muted;
- },
- set: function set(muted) {
- this._mediaElement.muted = muted;
- }
- }, {
- key: 'currentTime',
- get: function get() {
- if (this._mediaElement) {
- return this._mediaElement.currentTime;
- }
- return 0;
- },
- set: function set(seconds) {
- if (this._mediaElement) {
- this._internalSeek(seconds);
- } else {
- this._pendingSeekTime = seconds;
- }
- }
- }, {
- key: 'mediaInfo',
- get: function get() {
- return Object.assign({}, this._mediaInfo);
- }
- }, {
- key: 'statisticsInfo',
- get: function get() {
- if (this._statisticsInfo == null) {
- this._statisticsInfo = {};
- }
- this._statisticsInfo = this._fillStatisticsInfo(this._statisticsInfo);
- return Object.assign({}, this._statisticsInfo);
- }
- }]);
- return FlvPlayer;
- }();
- exports.default = FlvPlayer;
- module.exports = exports['default'];
- /***/ }),
- /* 34 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var _events = __webpack_require__(2);
- var _events2 = _interopRequireDefault(_events);
- var _logger = __webpack_require__(0);
- var _logger2 = _interopRequireDefault(_logger);
- var _loggingControl = __webpack_require__(8);
- var _loggingControl2 = _interopRequireDefault(_loggingControl);
- var _transmuxingController = __webpack_require__(14);
- var _transmuxingController2 = _interopRequireDefault(_transmuxingController);
- var _transmuxingEvents = __webpack_require__(5);
- var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
- var _transmuxingWorker = __webpack_require__(43);
- var _transmuxingWorker2 = _interopRequireDefault(_transmuxingWorker);
- var _mediaInfo = __webpack_require__(9);
- var _mediaInfo2 = _interopRequireDefault(_mediaInfo);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var Transmuxer = function () {
- function Transmuxer(mediaDataSource, config) {
- _classCallCheck(this, Transmuxer);
- this.TAG = 'Transmuxer';
- this._emitter = new _events2.default();
- if (config.enableWorker && typeof Worker !== 'undefined') {
- try {
- var work = __webpack_require__(44);
- this._worker = work(_transmuxingWorker2.default);
- this._workerDestroying = false;
- this._worker.addEventListener('message', this._onWorkerMessage.bind(this));
- this._worker.postMessage({ cmd: 'init', param: [mediaDataSource, config] });
- this.e = {
- onLoggingConfigChanged: this._onLoggingConfigChanged.bind(this)
- };
- _loggingControl2.default.registerListener(this.e.onLoggingConfigChanged);
- this._worker.postMessage({ cmd: 'logging_config', param: _loggingControl2.default.getConfig() });
- } catch (error) {
- _logger2.default.e(this.TAG, 'Error while initialize transmuxing worker, fallback to inline transmuxing');
- this._worker = null;
- this._controller = new _transmuxingController2.default(mediaDataSource, config);
- }
- } else {
- this._controller = new _transmuxingController2.default(mediaDataSource, config);
- }
- if (this._controller) {
- var ctl = this._controller;
- ctl.on(_transmuxingEvents2.default.IO_ERROR, this._onIOError.bind(this));
- ctl.on(_transmuxingEvents2.default.DEMUX_ERROR, this._onDemuxError.bind(this));
- ctl.on(_transmuxingEvents2.default.INIT_SEGMENT, this._onInitSegment.bind(this));
- ctl.on(_transmuxingEvents2.default.MEDIA_SEGMENT, this._onMediaSegment.bind(this));
- ctl.on(_transmuxingEvents2.default.LOADING_COMPLETE, this._onLoadingComplete.bind(this));
- ctl.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF, this._onRecoveredEarlyEof.bind(this));
- ctl.on(_transmuxingEvents2.default.MEDIA_INFO, this._onMediaInfo.bind(this));
- ctl.on(_transmuxingEvents2.default.STATISTICS_INFO, this._onStatisticsInfo.bind(this));
- ctl.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, this._onRecommendSeekpoint.bind(this));
- ctl.on(_transmuxingEvents2.default.LOADED_SEI, this._onLoadedSei.bind(this));
- }
- }
- _createClass(Transmuxer, [{
- key: 'destroy',
- value: function destroy() {
- if (this._worker) {
- if (!this._workerDestroying) {
- this._workerDestroying = true;
- this._worker.postMessage({ cmd: 'destroy' });
- _loggingControl2.default.removeListener(this.e.onLoggingConfigChanged);
- this.e = null;
- }
- } else {
- this._controller.destroy();
- this._controller = null;
- }
- this._emitter.removeAllListeners();
- this._emitter = null;
- }
- }, {
- key: 'on',
- value: function on(event, listener) {
- this._emitter.addListener(event, listener);
- }
- }, {
- key: 'off',
- value: function off(event, listener) {
- this._emitter.removeListener(event, listener);
- }
- }, {
- key: 'hasWorker',
- value: function hasWorker() {
- return this._worker != null;
- }
- }, {
- key: 'open',
- value: function open() {
- if (this._worker) {
- this._worker.postMessage({ cmd: 'start' });
- } else {
- this._controller.start();
- }
- }
- }, {
- key: 'close',
- value: function close() {
- if (this._worker) {
- this._worker.postMessage({ cmd: 'stop' });
- } else {
- this._controller.stop();
- }
- }
- }, {
- key: 'seek',
- value: function seek(milliseconds) {
- if (this._worker) {
- this._worker.postMessage({ cmd: 'seek', param: milliseconds });
- } else {
- this._controller.seek(milliseconds);
- }
- }
- }, {
- key: 'pause',
- value: function pause() {
- if (this._worker) {
- this._worker.postMessage({ cmd: 'pause' });
- } else {
- this._controller.pause();
- }
- }
- }, {
- key: 'resume',
- value: function resume() {
- if (this._worker) {
- this._worker.postMessage({ cmd: 'resume' });
- } else {
- this._controller.resume();
- }
- }
- }, {
- key: '_onInitSegment',
- value: function _onInitSegment(type, initSegment) {
- var _this = this;
- // do async invoke
- Promise.resolve().then(function () {
- _this._emitter.emit(_transmuxingEvents2.default.INIT_SEGMENT, type, initSegment);
- });
- }
- }, {
- key: '_onMediaSegment',
- value: function _onMediaSegment(type, mediaSegment) {
- var _this2 = this;
- Promise.resolve().then(function () {
- _this2._emitter.emit(_transmuxingEvents2.default.MEDIA_SEGMENT, type, mediaSegment);
- });
- }
- }, {
- key: '_onLoadingComplete',
- value: function _onLoadingComplete() {
- var _this3 = this;
- Promise.resolve().then(function () {
- _this3._emitter.emit(_transmuxingEvents2.default.LOADING_COMPLETE);
- });
- }
- }, {
- key: '_onRecoveredEarlyEof',
- value: function _onRecoveredEarlyEof() {
- var _this4 = this;
- Promise.resolve().then(function () {
- _this4._emitter.emit(_transmuxingEvents2.default.RECOVERED_EARLY_EOF);
- });
- }
- }, {
- key: '_onMediaInfo',
- value: function _onMediaInfo(mediaInfo) {
- var _this5 = this;
- Promise.resolve().then(function () {
- _this5._emitter.emit(_transmuxingEvents2.default.MEDIA_INFO, mediaInfo);
- });
- }
- }, {
- key: '_onStatisticsInfo',
- value: function _onStatisticsInfo(statisticsInfo) {
- var _this6 = this;
- Promise.resolve().then(function () {
- _this6._emitter.emit(_transmuxingEvents2.default.STATISTICS_INFO, statisticsInfo);
- });
- }
- }, {
- key: '_onIOError',
- value: function _onIOError(type, info) {
- var _this7 = this;
- Promise.resolve().then(function () {
- _this7._emitter.emit(_transmuxingEvents2.default.IO_ERROR, type, info);
- });
- }
- }, {
- key: '_onDemuxError',
- value: function _onDemuxError(type, info) {
- var _this8 = this;
- Promise.resolve().then(function () {
- _this8._emitter.emit(_transmuxingEvents2.default.DEMUX_ERROR, type, info);
- });
- }
- }, {
- key: '_onRecommendSeekpoint',
- value: function _onRecommendSeekpoint(milliseconds) {
- var _this9 = this;
- Promise.resolve().then(function () {
- _this9._emitter.emit(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, milliseconds);
- });
- }
- }, {
- key: '_onLoadedSei',
- value: function _onLoadedSei(timestamp, data) {
- var _this10 = this;
- Promise.resolve().then(function () {
- _this10._emitter.emit(_transmuxingEvents2.default.LOADED_SEI, timestamp, data);
- });
- }
- }, {
- key: '_onLoggingConfigChanged',
- value: function _onLoggingConfigChanged(config) {
- if (this._worker) {
- this._worker.postMessage({ cmd: 'logging_config', param: config });
- }
- }
- }, {
- key: '_onWorkerMessage',
- value: function _onWorkerMessage(e) {
- var message = e.data;
- var data = message.data;
- if (message.msg === 'destroyed' || this._workerDestroying) {
- this._workerDestroying = false;
- this._worker.terminate();
- this._worker = null;
- return;
- }
- switch (message.msg) {
- case _transmuxingEvents2.default.INIT_SEGMENT:
- case _transmuxingEvents2.default.MEDIA_SEGMENT:
- this._emitter.emit(message.msg, data.type, data.data);
- break;
- case _transmuxingEvents2.default.LOADING_COMPLETE:
- case _transmuxingEvents2.default.RECOVERED_EARLY_EOF:
- this._emitter.emit(message.msg);
- break;
- case _transmuxingEvents2.default.MEDIA_INFO:
- Object.setPrototypeOf(data, _mediaInfo2.default.prototype);
- this._emitter.emit(message.msg, data);
- break;
- case _transmuxingEvents2.default.STATISTICS_INFO:
- this._emitter.emit(message.msg, data);
- break;
- case _transmuxingEvents2.default.IO_ERROR:
- case _transmuxingEvents2.default.DEMUX_ERROR:
- this._emitter.emit(message.msg, data.type, data.info);
- break;
- case _transmuxingEvents2.default.RECOMMEND_SEEKPOINT:
- this._emitter.emit(message.msg, data);
- break;
- case 'logcat_callback':
- _logger2.default.emitter.emit('log', data.type, data.logcat);
- break;
- default:
- break;
- }
- }
- }]);
- return Transmuxer;
- }();
- exports.default = Transmuxer;
- module.exports = exports['default'];
- /***/ }),
- /* 35 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; };
- 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; }; }(); /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var _logger = __webpack_require__(0);
- var _logger2 = _interopRequireDefault(_logger);
- var _amfParser = __webpack_require__(36);
- var _amfParser2 = _interopRequireDefault(_amfParser);
- var _spsParser = __webpack_require__(38);
- var _spsParser2 = _interopRequireDefault(_spsParser);
- var _demuxErrors = __webpack_require__(10);
- var _demuxErrors2 = _interopRequireDefault(_demuxErrors);
- var _mediaInfo = __webpack_require__(9);
- var _mediaInfo2 = _interopRequireDefault(_mediaInfo);
- var _exception = __webpack_require__(1);
- var _events = __webpack_require__(2);
- var _events2 = _interopRequireDefault(_events);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- function Swap16(src) {
- return src >>> 8 & 0xFF | (src & 0xFF) << 8;
- }
- function Swap32(src) {
- return (src & 0xFF000000) >>> 24 | (src & 0x00FF0000) >>> 8 | (src & 0x0000FF00) << 8 | (src & 0x000000FF) << 24;
- }
- function ReadBig32(array, index) {
- return array[index] << 24 | array[index + 1] << 16 | array[index + 2] << 8 | array[index + 3];
- }
- var FLVDemuxer = function () {
- function FLVDemuxer(probeData, config) {
- _classCallCheck(this, FLVDemuxer);
- this.TAG = 'FLVDemuxer';
- this._emitter = new _events2.default();
- this._config = config;
- this._onError = null;
- this._onMediaInfo = null;
- this._onTrackMetadata = null;
- this._onDataAvailable = null;
- this._dataOffset = probeData.dataOffset;
- this._firstParse = true;
- this._dispatch = false;
- this._hasAudio = probeData.hasAudioTrack;
- this._hasVideo = probeData.hasVideoTrack;
- this._hasAudioFlagOverrided = false;
- this._hasVideoFlagOverrided = false;
- this._audioInitialMetadataDispatched = false;
- this._videoInitialMetadataDispatched = false;
- this._mediaInfo = new _mediaInfo2.default();
- this._mediaInfo.hasAudio = this._hasAudio;
- this._mediaInfo.hasVideo = this._hasVideo;
- this._metadata = null;
- this._audioMetadata = null;
- this._videoMetadata = null;
- this._naluLengthSize = 4;
- this._timestampBase = 0; // int32, in milliseconds
- this._timescale = 1000;
- this._duration = 0; // int32, in milliseconds
- this._durationOverrided = false;
- this._referenceFrameRate = {
- fixed: true,
- fps: 23.976,
- fps_num: 23976,
- fps_den: 1000
- };
- this._flvSoundRateTable = [5500, 11025, 22050, 44100, 48000];
- this._mpegSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
- this._mpegAudioV10SampleRateTable = [44100, 48000, 32000, 0];
- this._mpegAudioV20SampleRateTable = [22050, 24000, 16000, 0];
- this._mpegAudioV25SampleRateTable = [11025, 12000, 8000, 0];
- this._mpegAudioL1BitRateTable = [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, -1];
- this._mpegAudioL2BitRateTable = [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, -1];
- this._mpegAudioL3BitRateTable = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1];
- this._videoTrack = { type: 'video', id: 1, sequenceNumber: 0, samples: [], length: 0 };
- this._audioTrack = { type: 'audio', id: 2, sequenceNumber: 0, samples: [], length: 0 };
- this._littleEndian = function () {
- var buf = new ArrayBuffer(2);
- new DataView(buf).setInt16(0, 256, true); // little-endian write
- return new Int16Array(buf)[0] === 256; // platform-spec read, if equal then LE
- }();
- }
- _createClass(FLVDemuxer, [{
- key: 'destroy',
- value: function destroy() {
- this._mediaInfo = null;
- this._metadata = null;
- this._audioMetadata = null;
- this._videoMetadata = null;
- this._videoTrack = null;
- this._audioTrack = null;
- this._onError = null;
- this._onMediaInfo = null;
- this._onTrackMetadata = null;
- this._onDataAvailable = null;
- this._emitter.removeAllListeners();
- this._emitter = null;
- }
- }, {
- key: 'bindDataSource',
- value: function bindDataSource(loader) {
- loader.onDataArrival = this.parseChunks.bind(this);
- return this;
- }
- // prototype: function(type: string, metadata: any): void
- }, {
- key: 'resetMediaInfo',
- value: function resetMediaInfo() {
- this._mediaInfo = new _mediaInfo2.default();
- }
- }, {
- key: '_isInitialMetadataDispatched',
- value: function _isInitialMetadataDispatched() {
- if (this._hasAudio && this._hasVideo) {
- // both audio & video
- return this._audioInitialMetadataDispatched && this._videoInitialMetadataDispatched;
- }
- if (this._hasAudio && !this._hasVideo) {
- // audio only
- return this._audioInitialMetadataDispatched;
- }
- if (!this._hasAudio && this._hasVideo) {
- // video only
- return this._videoInitialMetadataDispatched;
- }
- return false;
- }
- // function parseChunks(chunk: ArrayBuffer, byteStart: number): number;
- }, {
- key: 'parseChunks',
- value: function parseChunks(chunk, byteStart) {
- if (!this._onError || !this._onMediaInfo || !this._onTrackMetadata || !this._onDataAvailable) {
- throw new _exception.IllegalStateException('Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified');
- }
- var offset = 0;
- var le = this._littleEndian;
- if (byteStart === 0) {
- // buffer with FLV header
- if (chunk.byteLength > 13) {
- var probeData = FLVDemuxer.probe(chunk);
- offset = probeData.dataOffset;
- } else {
- return 0;
- }
- }
- if (this._firstParse) {
- // handle PreviousTagSize0 before Tag1
- this._firstParse = false;
- if (byteStart + offset !== this._dataOffset) {
- _logger2.default.w(this.TAG, 'First time parsing but chunk byteStart invalid!');
- }
- var v = new DataView(chunk, offset);
- var prevTagSize0 = v.getUint32(0, !le);
- if (prevTagSize0 !== 0) {
- _logger2.default.w(this.TAG, 'PrevTagSize0 !== 0 !!!');
- }
- offset += 4;
- }
- while (offset < chunk.byteLength) {
- this._dispatch = true;
- var _v = new DataView(chunk, offset);
- if (offset + 11 + 4 > chunk.byteLength) {
- // data not enough for parsing an flv tag
- break;
- }
- var tagType = _v.getUint8(0);
- var dataSize = _v.getUint32(0, !le) & 0x00FFFFFF;
- if (offset + 11 + dataSize + 4 > chunk.byteLength) {
- // data not enough for parsing actual data body
- break;
- }
- if (tagType !== 8 && tagType !== 9 && tagType !== 18) {
- _logger2.default.w(this.TAG, 'Unsupported tag type ' + tagType + ', skipped');
- // consume the whole tag (skip it)
- offset += 11 + dataSize + 4;
- continue;
- }
- var ts2 = _v.getUint8(4);
- var ts1 = _v.getUint8(5);
- var ts0 = _v.getUint8(6);
- var ts3 = _v.getUint8(7);
- var timestamp = ts0 | ts1 << 8 | ts2 << 16 | ts3 << 24;
- var streamId = _v.getUint32(7, !le) & 0x00FFFFFF;
- if (streamId !== 0) {
- _logger2.default.w(this.TAG, 'Meet tag which has StreamID != 0!');
- }
- var dataOffset = offset + 11;
- switch (tagType) {
- case 8:
- // Audio
- this._parseAudioData(chunk, dataOffset, dataSize, timestamp);
- break;
- case 9:
- // Video
- this._parseVideoData(chunk, dataOffset, dataSize, timestamp, byteStart + offset);
- break;
- case 18:
- // ScriptDataObject
- this._parseScriptData(chunk, dataOffset, dataSize);
- break;
- }
- var prevTagSize = _v.getUint32(11 + dataSize, !le);
- if (prevTagSize !== 11 + dataSize) {
- _logger2.default.w(this.TAG, 'Invalid PrevTagSize ' + prevTagSize);
- }
- offset += 11 + dataSize + 4; // tagBody + dataSize + prevTagSize
- }
- // dispatch parsed frames to consumer (typically, the remuxer)
- if (this._isInitialMetadataDispatched()) {
- if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
- this._onDataAvailable(this._audioTrack, this._videoTrack);
- }
- }
- return offset; // consumed bytes, just equals latest offset index
- }
- }, {
- key: '_parseScriptData',
- value: function _parseScriptData(arrayBuffer, dataOffset, dataSize) {
- var scriptData = _amfParser2.default.parseScriptData(arrayBuffer, dataOffset, dataSize);
- if (scriptData.hasOwnProperty('onMetaData')) {
- if (scriptData.onMetaData == null || _typeof(scriptData.onMetaData) !== 'object') {
- _logger2.default.w(this.TAG, 'Invalid onMetaData structure!');
- return;
- }
- if (this._metadata) {
- _logger2.default.w(this.TAG, 'Found another onMetaData tag!');
- }
- this._metadata = scriptData;
- var onMetaData = this._metadata.onMetaData;
- this._emitter.emit('metadata_arrived', onMetaData);
- if (typeof onMetaData.hasAudio === 'boolean') {
- // hasAudio
- if (this._hasAudioFlagOverrided === false) {
- this._hasAudio = onMetaData.hasAudio;
- this._mediaInfo.hasAudio = this._hasAudio;
- }
- }
- if (typeof onMetaData.hasVideo === 'boolean') {
- // hasVideo
- if (this._hasVideoFlagOverrided === false) {
- this._hasVideo = onMetaData.hasVideo;
- this._mediaInfo.hasVideo = this._hasVideo;
- }
- }
- if (typeof onMetaData.audiodatarate === 'number') {
- // audiodatarate
- this._mediaInfo.audioDataRate = onMetaData.audiodatarate;
- }
- if (typeof onMetaData.videodatarate === 'number') {
- // videodatarate
- this._mediaInfo.videoDataRate = onMetaData.videodatarate;
- }
- if (typeof onMetaData.width === 'number') {
- // width
- this._mediaInfo.width = onMetaData.width;
- }
- if (typeof onMetaData.height === 'number') {
- // height
- this._mediaInfo.height = onMetaData.height;
- }
- if (typeof onMetaData.duration === 'number') {
- // duration
- if (!this._durationOverrided) {
- var duration = Math.floor(onMetaData.duration * this._timescale);
- this._duration = duration;
- this._mediaInfo.duration = duration;
- }
- } else {
- this._mediaInfo.duration = 0;
- }
- if (typeof onMetaData.framerate === 'number') {
- // framerate
- var fps_num = Math.floor(onMetaData.framerate * 1000);
- if (fps_num > 0) {
- var fps = fps_num / 1000;
- this._referenceFrameRate.fixed = true;
- this._referenceFrameRate.fps = fps;
- this._referenceFrameRate.fps_num = fps_num;
- this._referenceFrameRate.fps_den = 1000;
- this._mediaInfo.fps = fps;
- }
- }
- if (_typeof(onMetaData.keyframes) === 'object') {
- // keyframes
- this._mediaInfo.hasKeyframesIndex = true;
- var keyframes = onMetaData.keyframes;
- this._mediaInfo.keyframesIndex = this._parseKeyframesIndex(keyframes);
- onMetaData.keyframes = null; // keyframes has been extracted, remove it
- } else {
- this._mediaInfo.hasKeyframesIndex = false;
- }
- this._dispatch = false;
- this._mediaInfo.metadata = onMetaData;
- _logger2.default.v(this.TAG, 'Parsed onMetaData');
- if (this._mediaInfo.isComplete()) {
- this._onMediaInfo(this._mediaInfo);
- }
- }
- }
- }, {
- key: '_parseKeyframesIndex',
- value: function _parseKeyframesIndex(keyframes) {
- var times = [];
- var filepositions = [];
- // ignore first keyframe which is actually AVC Sequence Header (AVCDecoderConfigurationRecord)
- for (var i = 1; i < keyframes.times.length; i++) {
- var time = this._timestampBase + Math.floor(keyframes.times[i] * 1000);
- times.push(time);
- filepositions.push(keyframes.filepositions[i]);
- }
- return {
- times: times,
- filepositions: filepositions
- };
- }
- }, {
- key: '_parseAudioData',
- value: function _parseAudioData(arrayBuffer, dataOffset, dataSize, tagTimestamp) {
- if (dataSize <= 1) {
- _logger2.default.w(this.TAG, 'Flv: Invalid audio packet, missing SoundData payload!');
- return;
- }
- if (this._hasAudioFlagOverrided === true && this._hasAudio === false) {
- // If hasAudio: false indicated explicitly in MediaDataSource,
- // Ignore all the audio packets
- return;
- }
- var le = this._littleEndian;
- var v = new DataView(arrayBuffer, dataOffset, dataSize);
- var soundSpec = v.getUint8(0);
- var soundFormat = soundSpec >>> 4;
- if (soundFormat !== 2 && soundFormat !== 10) {
- // MP3 or AAC
- this._onError(_demuxErrors2.default.CODEC_UNSUPPORTED, 'Flv: Unsupported audio codec idx: ' + soundFormat);
- return;
- }
- var soundRate = 0;
- var soundRateIndex = (soundSpec & 12) >>> 2;
- if (soundRateIndex >= 0 && soundRateIndex <= 4) {
- soundRate = this._flvSoundRateTable[soundRateIndex];
- } else {
- this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid audio sample rate idx: ' + soundRateIndex);
- return;
- }
- var soundSize = (soundSpec & 2) >>> 1; // unused
- var soundType = soundSpec & 1;
- var meta = this._audioMetadata;
- var track = this._audioTrack;
- if (!meta) {
- if (this._hasAudio === false && this._hasAudioFlagOverrided === false) {
- this._hasAudio = true;
- this._mediaInfo.hasAudio = true;
- }
- // initial metadata
- meta = this._audioMetadata = {};
- meta.type = 'audio';
- meta.id = track.id;
- meta.timescale = this._timescale;
- meta.duration = this._duration;
- meta.audioSampleRate = soundRate;
- meta.channelCount = soundType === 0 ? 1 : 2;
- }
- if (soundFormat === 10) {
- // AAC
- var aacData = this._parseAACAudioData(arrayBuffer, dataOffset + 1, dataSize - 1);
- if (aacData == undefined) {
- return;
- }
- if (aacData.packetType === 0) {
- // AAC sequence header (AudioSpecificConfig)
- if (meta.config) {
- _logger2.default.w(this.TAG, 'Found another AudioSpecificConfig!');
- }
- var misc = aacData.data;
- meta.audioSampleRate = misc.samplingRate;
- meta.channelCount = misc.channelCount;
- meta.codec = misc.codec;
- meta.originalCodec = misc.originalCodec;
- meta.config = misc.config;
- // The decode result of an aac sample is 1024 PCM samples
- meta.refSampleDuration = 1024 / meta.audioSampleRate * meta.timescale;
- _logger2.default.v(this.TAG, 'Parsed AudioSpecificConfig');
- if (this._isInitialMetadataDispatched()) {
- // Non-initial metadata, force dispatch (or flush) parsed frames to remuxer
- if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
- this._onDataAvailable(this._audioTrack, this._videoTrack);
- }
- } else {
- this._audioInitialMetadataDispatched = true;
- }
- // then notify new metadata
- this._dispatch = false;
- this._onTrackMetadata('audio', meta);
- var mi = this._mediaInfo;
- mi.audioCodec = meta.originalCodec;
- mi.audioSampleRate = meta.audioSampleRate;
- mi.audioChannelCount = meta.channelCount;
- if (mi.hasVideo) {
- if (mi.videoCodec != null) {
- mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
- }
- } else {
- mi.mimeType = 'video/x-flv; codecs="' + mi.audioCodec + '"';
- }
- if (mi.isComplete()) {
- this._onMediaInfo(mi);
- }
- } else if (aacData.packetType === 1) {
- // AAC raw frame data
- var dts = this._timestampBase + tagTimestamp;
- var aacSample = { unit: aacData.data, length: aacData.data.byteLength, dts: dts, pts: dts };
- track.samples.push(aacSample);
- track.length += aacData.data.length;
- } else {
- _logger2.default.e(this.TAG, 'Flv: Unsupported AAC data type ' + aacData.packetType);
- }
- } else if (soundFormat === 2) {
- // MP3
- if (!meta.codec) {
- // We need metadata for mp3 audio track, extract info from frame header
- var _misc = this._parseMP3AudioData(arrayBuffer, dataOffset + 1, dataSize - 1, true);
- if (_misc == undefined) {
- return;
- }
- meta.audioSampleRate = _misc.samplingRate;
- meta.channelCount = _misc.channelCount;
- meta.codec = _misc.codec;
- meta.originalCodec = _misc.originalCodec;
- // The decode result of an mp3 sample is 1152 PCM samples
- meta.refSampleDuration = 1152 / meta.audioSampleRate * meta.timescale;
- _logger2.default.v(this.TAG, 'Parsed MPEG Audio Frame Header');
- this._audioInitialMetadataDispatched = true;
- this._onTrackMetadata('audio', meta);
- var _mi = this._mediaInfo;
- _mi.audioCodec = meta.codec;
- _mi.audioSampleRate = meta.audioSampleRate;
- _mi.audioChannelCount = meta.channelCount;
- _mi.audioDataRate = _misc.bitRate;
- if (_mi.hasVideo) {
- if (_mi.videoCodec != null) {
- _mi.mimeType = 'video/x-flv; codecs="' + _mi.videoCodec + ',' + _mi.audioCodec + '"';
- }
- } else {
- _mi.mimeType = 'video/x-flv; codecs="' + _mi.audioCodec + '"';
- }
- if (_mi.isComplete()) {
- this._onMediaInfo(_mi);
- }
- }
- // This packet is always a valid audio packet, extract it
- var data = this._parseMP3AudioData(arrayBuffer, dataOffset + 1, dataSize - 1, false);
- if (data == undefined) {
- return;
- }
- var _dts = this._timestampBase + tagTimestamp;
- var mp3Sample = { unit: data, length: data.byteLength, dts: _dts, pts: _dts };
- track.samples.push(mp3Sample);
- track.length += data.length;
- }
- }
- }, {
- key: '_parseAACAudioData',
- value: function _parseAACAudioData(arrayBuffer, dataOffset, dataSize) {
- if (dataSize <= 1) {
- _logger2.default.w(this.TAG, 'Flv: Invalid AAC packet, missing AACPacketType or/and Data!');
- return;
- }
- var result = {};
- var array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
- result.packetType = array[0];
- if (array[0] === 0) {
- result.data = this._parseAACAudioSpecificConfig(arrayBuffer, dataOffset + 1, dataSize - 1);
- } else {
- result.data = array.subarray(1);
- }
- return result;
- }
- }, {
- key: '_parseAACAudioSpecificConfig',
- value: function _parseAACAudioSpecificConfig(arrayBuffer, dataOffset, dataSize) {
- var array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
- var config = null;
- /* Audio Object Type:
- 0: Null
- 1: AAC Main
- 2: AAC LC
- 3: AAC SSR (Scalable Sample Rate)
- 4: AAC LTP (Long Term Prediction)
- 5: HE-AAC / SBR (Spectral Band Replication)
- 6: AAC Scalable
- */
- var audioObjectType = 0;
- var originalAudioObjectType = 0;
- var audioExtensionObjectType = null;
- var samplingIndex = 0;
- var extensionSamplingIndex = null;
- // 5 bits
- audioObjectType = originalAudioObjectType = array[0] >>> 3;
- // 4 bits
- samplingIndex = (array[0] & 0x07) << 1 | array[1] >>> 7;
- if (samplingIndex < 0 || samplingIndex >= this._mpegSamplingRates.length) {
- this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: AAC invalid sampling frequency index!');
- return;
- }
- var samplingFrequence = this._mpegSamplingRates[samplingIndex];
- // 4 bits
- var channelConfig = (array[1] & 0x78) >>> 3;
- if (channelConfig < 0 || channelConfig >= 8) {
- this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: AAC invalid channel configuration');
- return;
- }
- if (audioObjectType === 5) {
- // HE-AAC?
- // 4 bits
- extensionSamplingIndex = (array[1] & 0x07) << 1 | array[2] >>> 7;
- // 5 bits
- audioExtensionObjectType = (array[2] & 0x7C) >>> 2;
- }
- // workarounds for various browsers
- var userAgent = self.navigator.userAgent.toLowerCase();
- if (userAgent.indexOf('firefox') !== -1) {
- // firefox: use SBR (HE-AAC) if freq less than 24kHz
- if (samplingIndex >= 6) {
- audioObjectType = 5;
- config = new Array(4);
- extensionSamplingIndex = samplingIndex - 3;
- } else {
- // use LC-AAC
- audioObjectType = 2;
- config = new Array(2);
- extensionSamplingIndex = samplingIndex;
- }
- } else if (userAgent.indexOf('android') !== -1) {
- // android: always use LC-AAC
- audioObjectType = 2;
- config = new Array(2);
- extensionSamplingIndex = samplingIndex;
- } else {
- // for other browsers, e.g. chrome...
- // Always use HE-AAC to make it easier to switch aac codec profile
- audioObjectType = 5;
- extensionSamplingIndex = samplingIndex;
- config = new Array(4);
- if (samplingIndex >= 6) {
- extensionSamplingIndex = samplingIndex - 3;
- } else if (channelConfig === 1) {
- // Mono channel
- audioObjectType = 2;
- config = new Array(2);
- extensionSamplingIndex = samplingIndex;
- }
- }
- config[0] = audioObjectType << 3;
- config[0] |= (samplingIndex & 0x0F) >>> 1;
- config[1] = (samplingIndex & 0x0F) << 7;
- config[1] |= (channelConfig & 0x0F) << 3;
- if (audioObjectType === 5) {
- config[1] |= (extensionSamplingIndex & 0x0F) >>> 1;
- config[2] = (extensionSamplingIndex & 0x01) << 7;
- // extended audio object type: force to 2 (LC-AAC)
- config[2] |= 2 << 2;
- config[3] = 0;
- }
- return {
- config: config,
- samplingRate: samplingFrequence,
- channelCount: channelConfig,
- codec: 'mp4a.40.' + audioObjectType,
- originalCodec: 'mp4a.40.' + originalAudioObjectType
- };
- }
- }, {
- key: '_parseMP3AudioData',
- value: function _parseMP3AudioData(arrayBuffer, dataOffset, dataSize, requestHeader) {
- if (dataSize < 4) {
- _logger2.default.w(this.TAG, 'Flv: Invalid MP3 packet, header missing!');
- return;
- }
- var le = this._littleEndian;
- var array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
- var result = null;
- if (requestHeader) {
- if (array[0] !== 0xFF) {
- return;
- }
- var ver = array[1] >>> 3 & 0x03;
- var layer = (array[1] & 0x06) >> 1;
- var bitrate_index = (array[2] & 0xF0) >>> 4;
- var sampling_freq_index = (array[2] & 0x0C) >>> 2;
- var channel_mode = array[3] >>> 6 & 0x03;
- var channel_count = channel_mode !== 3 ? 2 : 1;
- var sample_rate = 0;
- var bit_rate = 0;
- var object_type = 34; // Layer-3, listed in MPEG-4 Audio Object Types
- var codec = 'mp3';
- switch (ver) {
- case 0:
- // MPEG 2.5
- sample_rate = this._mpegAudioV25SampleRateTable[sampling_freq_index];
- break;
- case 2:
- // MPEG 2
- sample_rate = this._mpegAudioV20SampleRateTable[sampling_freq_index];
- break;
- case 3:
- // MPEG 1
- sample_rate = this._mpegAudioV10SampleRateTable[sampling_freq_index];
- break;
- }
- switch (layer) {
- case 1:
- // Layer 3
- object_type = 34;
- if (bitrate_index < this._mpegAudioL3BitRateTable.length) {
- bit_rate = this._mpegAudioL3BitRateTable[bitrate_index];
- }
- break;
- case 2:
- // Layer 2
- object_type = 33;
- if (bitrate_index < this._mpegAudioL2BitRateTable.length) {
- bit_rate = this._mpegAudioL2BitRateTable[bitrate_index];
- }
- break;
- case 3:
- // Layer 1
- object_type = 32;
- if (bitrate_index < this._mpegAudioL1BitRateTable.length) {
- bit_rate = this._mpegAudioL1BitRateTable[bitrate_index];
- }
- break;
- }
- result = {
- bitRate: bit_rate,
- samplingRate: sample_rate,
- channelCount: channel_count,
- codec: codec,
- originalCodec: codec
- };
- } else {
- result = array;
- }
- return result;
- }
- }, {
- key: '_parseVideoData',
- value: function _parseVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition) {
- if (dataSize <= 1) {
- _logger2.default.w(this.TAG, 'Flv: Invalid video packet, missing VideoData payload!');
- return;
- }
- if (this._hasVideoFlagOverrided === true && this._hasVideo === false) {
- // If hasVideo: false indicated explicitly in MediaDataSource,
- // Ignore all the video packets
- return;
- }
- var spec = new Uint8Array(arrayBuffer, dataOffset, dataSize)[0];
- var frameType = (spec & 240) >>> 4;
- var codecId = spec & 15;
- if (codecId !== 7) {
- this._onError(_demuxErrors2.default.CODEC_UNSUPPORTED, 'Flv: Unsupported codec in video frame: ' + codecId);
- return;
- }
- this._parseAVCVideoPacket(arrayBuffer, dataOffset + 1, dataSize - 1, tagTimestamp, tagPosition, frameType);
- }
- }, {
- key: '_parseAVCVideoPacket',
- value: function _parseAVCVideoPacket(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType) {
- if (dataSize < 4) {
- _logger2.default.w(this.TAG, 'Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime');
- return;
- }
- var le = this._littleEndian;
- var v = new DataView(arrayBuffer, dataOffset, dataSize);
- var packetType = v.getUint8(0);
- var cts_unsigned = v.getUint32(0, !le) & 0x00FFFFFF;
- var cts = cts_unsigned << 8 >> 8; // convert to 24-bit signed int
- if (packetType === 0) {
- // AVCDecoderConfigurationRecord
- this._parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset + 4, dataSize - 4);
- } else if (packetType === 1) {
- // One or more Nalus
- this._parseAVCVideoData(arrayBuffer, dataOffset + 4, dataSize - 4, tagTimestamp, tagPosition, frameType, cts);
- } else if (packetType === 2) {
- // empty, AVC end of sequence
- } else {
- this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid video packet type ' + packetType);
- return;
- }
- }
- }, {
- key: '_parseAVCDecoderConfigurationRecord',
- value: function _parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset, dataSize) {
- if (dataSize < 7) {
- _logger2.default.w(this.TAG, 'Flv: Invalid AVCDecoderConfigurationRecord, lack of data!');
- return;
- }
- var meta = this._videoMetadata;
- var track = this._videoTrack;
- var le = this._littleEndian;
- var v = new DataView(arrayBuffer, dataOffset, dataSize);
- if (!meta) {
- if (this._hasVideo === false && this._hasVideoFlagOverrided === false) {
- this._hasVideo = true;
- this._mediaInfo.hasVideo = true;
- }
- meta = this._videoMetadata = {};
- meta.type = 'video';
- meta.id = track.id;
- meta.timescale = this._timescale;
- meta.duration = this._duration;
- } else {
- if (typeof meta.avcc !== 'undefined') {
- _logger2.default.w(this.TAG, 'Found another AVCDecoderConfigurationRecord!');
- }
- }
- var version = v.getUint8(0); // configurationVersion
- var avcProfile = v.getUint8(1); // avcProfileIndication
- var profileCompatibility = v.getUint8(2); // profile_compatibility
- var avcLevel = v.getUint8(3); // AVCLevelIndication
- if (version !== 1 || avcProfile === 0) {
- this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord');
- return;
- }
- this._naluLengthSize = (v.getUint8(4) & 3) + 1; // lengthSizeMinusOne
- if (this._naluLengthSize !== 3 && this._naluLengthSize !== 4) {
- // holy shit!!!
- this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Strange NaluLengthSizeMinusOne: ' + (this._naluLengthSize - 1));
- return;
- }
- var spsCount = v.getUint8(5) & 31; // numOfSequenceParameterSets
- if (spsCount === 0) {
- this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord: No SPS');
- return;
- } else if (spsCount > 1) {
- _logger2.default.w(this.TAG, 'Flv: Strange AVCDecoderConfigurationRecord: SPS Count = ' + spsCount);
- }
- var offset = 6;
- for (var i = 0; i < spsCount; i++) {
- var len = v.getUint16(offset, !le); // sequenceParameterSetLength
- offset += 2;
- if (len === 0) {
- continue;
- }
- // Notice: Nalu without startcode header (00 00 00 01)
- var sps = new Uint8Array(arrayBuffer, dataOffset + offset, len);
- offset += len;
- var config = _spsParser2.default.parseSPS(sps);
- if (i !== 0) {
- // ignore other sps's config
- continue;
- }
- meta.codecWidth = config.codec_size.width;
- meta.codecHeight = config.codec_size.height;
- meta.presentWidth = config.present_size.width;
- meta.presentHeight = config.present_size.height;
- meta.profile = config.profile_string;
- meta.level = config.level_string;
- meta.bitDepth = config.bit_depth;
- meta.chromaFormat = config.chroma_format;
- meta.sarRatio = config.par_ratio;
- meta.frameRate = config.frame_rate;
- if (config.frame_rate.fixed === false || config.frame_rate.fps_num === 0 || config.frame_rate.fps_den === 0) {
- meta.frameRate = this._referenceFrameRate;
- }
- var fps_den = meta.frameRate.fps_den;
- var fps_num = meta.frameRate.fps_num;
- meta.refSampleDuration = meta.timescale * (fps_den / fps_num);
- var codecArray = sps.subarray(1, 4);
- var codecString = 'avc1.';
- for (var j = 0; j < 3; j++) {
- var h = codecArray[j].toString(16);
- if (h.length < 2) {
- h = '0' + h;
- }
- codecString += h;
- }
- meta.codec = codecString;
- var mi = this._mediaInfo;
- mi.width = meta.codecWidth;
- mi.height = meta.codecHeight;
- mi.fps = meta.frameRate.fps;
- mi.profile = meta.profile;
- mi.level = meta.level;
- mi.refFrames = config.ref_frames;
- mi.chromaFormat = config.chroma_format_string;
- mi.sarNum = meta.sarRatio.width;
- mi.sarDen = meta.sarRatio.height;
- mi.videoCodec = codecString;
- if (mi.hasAudio) {
- if (mi.audioCodec != null) {
- mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
- }
- } else {
- mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + '"';
- }
- if (mi.isComplete()) {
- this._onMediaInfo(mi);
- }
- }
- var ppsCount = v.getUint8(offset); // numOfPictureParameterSets
- if (ppsCount === 0) {
- this._onError(_demuxErrors2.default.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord: No PPS');
- return;
- } else if (ppsCount > 1) {
- _logger2.default.w(this.TAG, 'Flv: Strange AVCDecoderConfigurationRecord: PPS Count = ' + ppsCount);
- }
- offset++;
- for (var _i = 0; _i < ppsCount; _i++) {
- var _len = v.getUint16(offset, !le); // pictureParameterSetLength
- offset += 2;
- if (_len === 0) {
- continue;
- }
- // pps is useless for extracting video information
- offset += _len;
- }
- meta.avcc = new Uint8Array(dataSize);
- meta.avcc.set(new Uint8Array(arrayBuffer, dataOffset, dataSize), 0);
- _logger2.default.v(this.TAG, 'Parsed AVCDecoderConfigurationRecord');
- if (this._isInitialMetadataDispatched()) {
- // flush parsed frames
- if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
- this._onDataAvailable(this._audioTrack, this._videoTrack);
- }
- } else {
- this._videoInitialMetadataDispatched = true;
- }
- // notify new metadata
- this._dispatch = false;
- this._onTrackMetadata('video', meta);
- }
- }, {
- key: '_parseAVCVideoData',
- value: function _parseAVCVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType, cts) {
- var le = this._littleEndian;
- var v = new DataView(arrayBuffer, dataOffset, dataSize);
- var units = [],
- length = 0;
- var offset = 0;
- var lengthSize = this._naluLengthSize;
- var dts = this._timestampBase + tagTimestamp;
- var keyframe = frameType === 1; // from FLV Frame Type constants
- while (offset < dataSize) {
- if (offset + 4 >= dataSize) {
- _logger2.default.w(this.TAG, 'Malformed Nalu near timestamp ' + dts + ', offset = ' + offset + ', dataSize = ' + dataSize);
- break; // data not enough for next Nalu
- }
- // Nalu with length-header (AVC1)
- var naluSize = v.getUint32(offset, !le); // Big-Endian read
- if (lengthSize === 3) {
- naluSize >>>= 8;
- }
- if (naluSize > dataSize - lengthSize) {
- _logger2.default.w(this.TAG, 'Malformed Nalus near timestamp ' + dts + ', NaluSize > DataSize!');
- return;
- }
- var unitType = v.getUint8(offset + lengthSize) & 0x1F;
- if (unitType === 5) {
- // IDR
- keyframe = true;
- }
- var data = new Uint8Array(arrayBuffer, dataOffset + offset, lengthSize + naluSize);
- var unit = { type: unitType, data: data };
- units.push(unit);
- length += data.byteLength;
- offset += lengthSize + naluSize;
- }
- if (units.length) {
- var track = this._videoTrack;
- var avcSample = {
- units: units,
- length: length,
- isKeyframe: keyframe,
- dts: dts,
- cts: cts,
- pts: dts + cts
- };
- if (keyframe) {
- avcSample.fileposition = tagPosition;
- }
- track.samples.push(avcSample);
- track.length += length;
- }
- }
- }, {
- key: 'onTrackMetadata',
- get: function get() {
- return this._onTrackMetadata;
- },
- set: function set(callback) {
- this._onTrackMetadata = callback;
- }
- // prototype: function(mediaInfo: MediaInfo): void
- }, {
- key: 'onMediaInfo',
- get: function get() {
- return this._onMediaInfo;
- },
- set: function set(callback) {
- this._onMediaInfo = callback;
- }
- // prototype: function(type: number, info: string): void
- }, {
- key: 'onError',
- get: function get() {
- return this._onError;
- },
- set: function set(callback) {
- this._onError = callback;
- }
- // prototype: function(videoTrack: any, audioTrack: any): void
- }, {
- key: 'onDataAvailable',
- get: function get() {
- return this._onDataAvailable;
- },
- set: function set(callback) {
- this._onDataAvailable = callback;
- }
- // timestamp base for output samples, must be in milliseconds
- }, {
- key: 'timestampBase',
- get: function get() {
- return this._timestampBase;
- },
- set: function set(base) {
- this._timestampBase = base;
- }
- }, {
- key: 'overridedDuration',
- get: function get() {
- return this._duration;
- }
- // Force-override media duration. Must be in milliseconds, int32
- ,
- set: function set(duration) {
- this._durationOverrided = true;
- this._duration = duration;
- this._mediaInfo.duration = duration;
- }
- // Force-override audio track present flag, boolean
- }, {
- key: 'overridedHasAudio',
- set: function set(hasAudio) {
- this._hasAudioFlagOverrided = true;
- this._hasAudio = hasAudio;
- this._mediaInfo.hasAudio = hasAudio;
- }
- // Force-override video track present flag, boolean
- }, {
- key: 'overridedHasVideo',
- set: function set(hasVideo) {
- this._hasVideoFlagOverrided = true;
- this._hasVideo = hasVideo;
- this._mediaInfo.hasVideo = hasVideo;
- }
- }], [{
- key: 'probe',
- value: function probe(buffer) {
- var data = new Uint8Array(buffer);
- var mismatch = { match: false };
- if (data[0] !== 0x46 || data[1] !== 0x4C || data[2] !== 0x56 || data[3] !== 0x01) {
- return mismatch;
- }
- var hasAudio = (data[4] & 4) >>> 2 !== 0;
- var hasVideo = (data[4] & 1) !== 0;
- var offset = ReadBig32(data, 5);
- if (offset < 9) {
- return mismatch;
- }
- return {
- match: true,
- consumed: offset,
- dataOffset: offset,
- hasAudioTrack: hasAudio,
- hasVideoTrack: hasVideo
- };
- }
- }]);
- return FLVDemuxer;
- }();
- exports.default = FLVDemuxer;
- module.exports = exports['default'];
- /***/ }),
- /* 36 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var _logger = __webpack_require__(0);
- var _logger2 = _interopRequireDefault(_logger);
- var _utf8Conv = __webpack_require__(37);
- var _utf8Conv2 = _interopRequireDefault(_utf8Conv);
- var _exception = __webpack_require__(1);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var le = function () {
- var buf = new ArrayBuffer(2);
- new DataView(buf).setInt16(0, 256, true); // little-endian write
- return new Int16Array(buf)[0] === 256; // platform-spec read, if equal then LE
- }();
- var AMF = function () {
- function AMF() {
- _classCallCheck(this, AMF);
- }
- _createClass(AMF, null, [{
- key: 'parseScriptData',
- value: function parseScriptData(arrayBuffer, dataOffset, dataSize) {
- var data = {};
- try {
- var name = AMF.parseValue(arrayBuffer, dataOffset, dataSize);
- var value = AMF.parseValue(arrayBuffer, dataOffset + name.size, dataSize - name.size);
- data[name.data] = value.data;
- } catch (e) {
- _logger2.default.e('AMF', e.toString());
- }
- return data;
- }
- }, {
- key: 'parseObject',
- value: function parseObject(arrayBuffer, dataOffset, dataSize) {
- if (dataSize < 3) {
- throw new _exception.IllegalStateException('Data not enough when parse ScriptDataObject');
- }
- var name = AMF.parseString(arrayBuffer, dataOffset, dataSize);
- var value = AMF.parseValue(arrayBuffer, dataOffset + name.size, dataSize - name.size);
- var isObjectEnd = value.objectEnd;
- return {
- data: {
- name: name.data,
- value: value.data
- },
- size: name.size + value.size,
- objectEnd: isObjectEnd
- };
- }
- }, {
- key: 'parseVariable',
- value: function parseVariable(arrayBuffer, dataOffset, dataSize) {
- return AMF.parseObject(arrayBuffer, dataOffset, dataSize);
- }
- }, {
- key: 'parseString',
- value: function parseString(arrayBuffer, dataOffset, dataSize) {
- if (dataSize < 2) {
- throw new _exception.IllegalStateException('Data not enough when parse String');
- }
- var v = new DataView(arrayBuffer, dataOffset, dataSize);
- var length = v.getUint16(0, !le);
- var str = void 0;
- if (length > 0) {
- str = (0, _utf8Conv2.default)(new Uint8Array(arrayBuffer, dataOffset + 2, length));
- } else {
- str = '';
- }
- return {
- data: str,
- size: 2 + length
- };
- }
- }, {
- key: 'parseLongString',
- value: function parseLongString(arrayBuffer, dataOffset, dataSize) {
- if (dataSize < 4) {
- throw new _exception.IllegalStateException('Data not enough when parse LongString');
- }
- var v = new DataView(arrayBuffer, dataOffset, dataSize);
- var length = v.getUint32(0, !le);
- var str = void 0;
- if (length > 0) {
- str = (0, _utf8Conv2.default)(new Uint8Array(arrayBuffer, dataOffset + 4, length));
- } else {
- str = '';
- }
- return {
- data: str,
- size: 4 + length
- };
- }
- }, {
- key: 'parseDate',
- value: function parseDate(arrayBuffer, dataOffset, dataSize) {
- if (dataSize < 10) {
- throw new _exception.IllegalStateException('Data size invalid when parse Date');
- }
- var v = new DataView(arrayBuffer, dataOffset, dataSize);
- var timestamp = v.getFloat64(0, !le);
- var localTimeOffset = v.getInt16(8, !le);
- timestamp += localTimeOffset * 60 * 1000; // get UTC time
- return {
- data: new Date(timestamp),
- size: 8 + 2
- };
- }
- }, {
- key: 'parseValue',
- value: function parseValue(arrayBuffer, dataOffset, dataSize) {
- if (dataSize < 1) {
- throw new _exception.IllegalStateException('Data not enough when parse Value');
- }
- var v = new DataView(arrayBuffer, dataOffset, dataSize);
- var offset = 1;
- var type = v.getUint8(0);
- var value = void 0;
- var objectEnd = false;
- try {
- switch (type) {
- case 0:
- // Number(Double) type
- value = v.getFloat64(1, !le);
- offset += 8;
- break;
- case 1:
- {
- // Boolean type
- var b = v.getUint8(1);
- value = b ? true : false;
- offset += 1;
- break;
- }
- case 2:
- {
- // String type
- var amfstr = AMF.parseString(arrayBuffer, dataOffset + 1, dataSize - 1);
- value = amfstr.data;
- offset += amfstr.size;
- break;
- }
- case 3:
- {
- // Object(s) type
- value = {};
- var terminal = 0; // workaround for malformed Objects which has missing ScriptDataObjectEnd
- if ((v.getUint32(dataSize - 4, !le) & 0x00FFFFFF) === 9) {
- terminal = 3;
- }
- var maxLoop = 10000;
- while (offset < dataSize - 4 && maxLoop-- > 0) {
- // 4 === type(UI8) + ScriptDataObjectEnd(UI24)
- var amfobj = AMF.parseObject(arrayBuffer, dataOffset + offset, dataSize - offset - terminal);
- if (amfobj.objectEnd) break;
- value[amfobj.data.name] = amfobj.data.value;
- offset += amfobj.size;
- }
- if (offset <= dataSize - 3) {
- var marker = v.getUint32(offset - 1, !le) & 0x00FFFFFF;
- if (marker === 9) {
- offset += 3;
- }
- }
- break;
- }
- case 8:
- {
- // ECMA array type (Mixed array)
- value = {};
- offset += 4; // ECMAArrayLength(UI32)
- var _terminal = 0; // workaround for malformed MixedArrays which has missing ScriptDataObjectEnd
- if ((v.getUint32(dataSize - 4, !le) & 0x00FFFFFF) === 9) {
- _terminal = 3;
- }
- var _maxLoop = 10000;
- while (offset < dataSize - 8 && _maxLoop-- > 0) {
- // 8 === type(UI8) + ECMAArrayLength(UI32) + ScriptDataVariableEnd(UI24)
- var amfvar = AMF.parseVariable(arrayBuffer, dataOffset + offset, dataSize - offset - _terminal);
- if (amfvar.objectEnd) break;
- value[amfvar.data.name] = amfvar.data.value;
- offset += amfvar.size;
- }
- if (offset <= dataSize - 3) {
- var _marker = v.getUint32(offset - 1, !le) & 0x00FFFFFF;
- if (_marker === 9) {
- offset += 3;
- }
- }
- break;
- }
- case 9:
- // ScriptDataObjectEnd
- value = undefined;
- offset = 1;
- objectEnd = true;
- break;
- case 10:
- {
- // Strict array type
- // ScriptDataValue[n]. NOTE: according to video_file_format_spec_v10_1.pdf
- value = [];
- var strictArrayLength = v.getUint32(1, !le);
- offset += 4;
- for (var i = 0; i < strictArrayLength; i++) {
- var val = AMF.parseValue(arrayBuffer, dataOffset + offset, dataSize - offset);
- value.push(val.data);
- offset += val.size;
- }
- break;
- }
- case 11:
- {
- // Date type
- var date = AMF.parseDate(arrayBuffer, dataOffset + 1, dataSize - 1);
- value = date.data;
- offset += date.size;
- break;
- }
- case 12:
- {
- // Long string type
- var amfLongStr = AMF.parseString(arrayBuffer, dataOffset + 1, dataSize - 1);
- value = amfLongStr.data;
- offset += amfLongStr.size;
- break;
- }
- default:
- // ignore and skip
- offset = dataSize;
- _logger2.default.w('AMF', 'Unsupported AMF value type ' + type);
- }
- } catch (e) {
- _logger2.default.e('AMF', e.toString());
- }
- return {
- data: value,
- size: offset,
- objectEnd: objectEnd
- };
- }
- }]);
- return AMF;
- }();
- exports.default = AMF;
- module.exports = exports['default'];
- /***/ }),
- /* 37 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * This file is derived from C++ project libWinTF8 (https://github.com/m13253/libWinTF8)
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- function checkContinuation(uint8array, start, checkLength) {
- var array = uint8array;
- if (start + checkLength < array.length) {
- while (checkLength--) {
- if ((array[++start] & 0xC0) !== 0x80) return false;
- }
- return true;
- } else {
- return false;
- }
- }
- function decodeUTF8(uint8array) {
- var out = [];
- var input = uint8array;
- var i = 0;
- var length = uint8array.length;
- while (i < length) {
- if (input[i] < 0x80) {
- out.push(String.fromCharCode(input[i]));
- ++i;
- continue;
- } else if (input[i] < 0xC0) {
- // fallthrough
- } else if (input[i] < 0xE0) {
- if (checkContinuation(input, i, 1)) {
- var ucs4 = (input[i] & 0x1F) << 6 | input[i + 1] & 0x3F;
- if (ucs4 >= 0x80) {
- out.push(String.fromCharCode(ucs4 & 0xFFFF));
- i += 2;
- continue;
- }
- }
- } else if (input[i] < 0xF0) {
- if (checkContinuation(input, i, 2)) {
- var _ucs = (input[i] & 0xF) << 12 | (input[i + 1] & 0x3F) << 6 | input[i + 2] & 0x3F;
- if (_ucs >= 0x800 && (_ucs & 0xF800) !== 0xD800) {
- out.push(String.fromCharCode(_ucs & 0xFFFF));
- i += 3;
- continue;
- }
- }
- } else if (input[i] < 0xF8) {
- if (checkContinuation(input, i, 3)) {
- var _ucs2 = (input[i] & 0x7) << 18 | (input[i + 1] & 0x3F) << 12 | (input[i + 2] & 0x3F) << 6 | input[i + 3] & 0x3F;
- if (_ucs2 > 0x10000 && _ucs2 < 0x110000) {
- _ucs2 -= 0x10000;
- out.push(String.fromCharCode(_ucs2 >>> 10 | 0xD800));
- out.push(String.fromCharCode(_ucs2 & 0x3FF | 0xDC00));
- i += 4;
- continue;
- }
- }
- }
- out.push(String.fromCharCode(0xFFFD));
- ++i;
- }
- return out.join('');
- }
- exports.default = decodeUTF8;
- module.exports = exports['default'];
- /***/ }),
- /* 38 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var _expGolomb = __webpack_require__(39);
- var _expGolomb2 = _interopRequireDefault(_expGolomb);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var SPSParser = function () {
- function SPSParser() {
- _classCallCheck(this, SPSParser);
- }
- _createClass(SPSParser, null, [{
- key: '_ebsp2rbsp',
- value: function _ebsp2rbsp(uint8array) {
- var src = uint8array;
- var src_length = src.byteLength;
- var dst = new Uint8Array(src_length);
- var dst_idx = 0;
- for (var i = 0; i < src_length; i++) {
- if (i >= 2) {
- // Unescape: Skip 0x03 after 00 00
- if (src[i] === 0x03 && src[i - 1] === 0x00 && src[i - 2] === 0x00) {
- continue;
- }
- }
- dst[dst_idx] = src[i];
- dst_idx++;
- }
- return new Uint8Array(dst.buffer, 0, dst_idx);
- }
- }, {
- key: 'parseSPS',
- value: function parseSPS(uint8array) {
- var rbsp = SPSParser._ebsp2rbsp(uint8array);
- var gb = new _expGolomb2.default(rbsp);
- gb.readByte();
- var profile_idc = gb.readByte(); // profile_idc
- gb.readByte(); // constraint_set_flags[5] + reserved_zero[3]
- var level_idc = gb.readByte(); // level_idc
- gb.readUEG(); // seq_parameter_set_id
- var profile_string = SPSParser.getProfileString(profile_idc);
- var level_string = SPSParser.getLevelString(level_idc);
- var chroma_format_idc = 1;
- var chroma_format = 420;
- var chroma_format_table = [0, 420, 422, 444];
- var bit_depth = 8;
- 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) {
- chroma_format_idc = gb.readUEG();
- if (chroma_format_idc === 3) {
- gb.readBits(1); // separate_colour_plane_flag
- }
- if (chroma_format_idc <= 3) {
- chroma_format = chroma_format_table[chroma_format_idc];
- }
- bit_depth = gb.readUEG() + 8; // bit_depth_luma_minus8
- gb.readUEG(); // bit_depth_chroma_minus8
- gb.readBits(1); // qpprime_y_zero_transform_bypass_flag
- if (gb.readBool()) {
- // seq_scaling_matrix_present_flag
- var scaling_list_count = chroma_format_idc !== 3 ? 8 : 12;
- for (var i = 0; i < scaling_list_count; i++) {
- if (gb.readBool()) {
- // seq_scaling_list_present_flag
- if (i < 6) {
- SPSParser._skipScalingList(gb, 16);
- } else {
- SPSParser._skipScalingList(gb, 64);
- }
- }
- }
- }
- }
- gb.readUEG(); // log2_max_frame_num_minus4
- var pic_order_cnt_type = gb.readUEG();
- if (pic_order_cnt_type === 0) {
- gb.readUEG(); // log2_max_pic_order_cnt_lsb_minus_4
- } else if (pic_order_cnt_type === 1) {
- gb.readBits(1); // delta_pic_order_always_zero_flag
- gb.readSEG(); // offset_for_non_ref_pic
- gb.readSEG(); // offset_for_top_to_bottom_field
- var num_ref_frames_in_pic_order_cnt_cycle = gb.readUEG();
- for (var _i = 0; _i < num_ref_frames_in_pic_order_cnt_cycle; _i++) {
- gb.readSEG(); // offset_for_ref_frame
- }
- }
- var ref_frames = gb.readUEG(); // max_num_ref_frames
- gb.readBits(1); // gaps_in_frame_num_value_allowed_flag
- var pic_width_in_mbs_minus1 = gb.readUEG();
- var pic_height_in_map_units_minus1 = gb.readUEG();
- var frame_mbs_only_flag = gb.readBits(1);
- if (frame_mbs_only_flag === 0) {
- gb.readBits(1); // mb_adaptive_frame_field_flag
- }
- gb.readBits(1); // direct_8x8_inference_flag
- var frame_crop_left_offset = 0;
- var frame_crop_right_offset = 0;
- var frame_crop_top_offset = 0;
- var frame_crop_bottom_offset = 0;
- var frame_cropping_flag = gb.readBool();
- if (frame_cropping_flag) {
- frame_crop_left_offset = gb.readUEG();
- frame_crop_right_offset = gb.readUEG();
- frame_crop_top_offset = gb.readUEG();
- frame_crop_bottom_offset = gb.readUEG();
- }
- var sar_width = 1,
- sar_height = 1;
- var fps = 0,
- fps_fixed = true,
- fps_num = 0,
- fps_den = 0;
- var vui_parameters_present_flag = gb.readBool();
- if (vui_parameters_present_flag) {
- if (gb.readBool()) {
- // aspect_ratio_info_present_flag
- var aspect_ratio_idc = gb.readByte();
- var sar_w_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2];
- var sar_h_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
- if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) {
- sar_width = sar_w_table[aspect_ratio_idc - 1];
- sar_height = sar_h_table[aspect_ratio_idc - 1];
- } else if (aspect_ratio_idc === 255) {
- sar_width = gb.readByte() << 8 | gb.readByte();
- sar_height = gb.readByte() << 8 | gb.readByte();
- }
- }
- if (gb.readBool()) {
- // overscan_info_present_flag
- gb.readBool(); // overscan_appropriate_flag
- }
- if (gb.readBool()) {
- // video_signal_type_present_flag
- gb.readBits(4); // video_format & video_full_range_flag
- if (gb.readBool()) {
- // colour_description_present_flag
- gb.readBits(24); // colour_primaries & transfer_characteristics & matrix_coefficients
- }
- }
- if (gb.readBool()) {
- // chroma_loc_info_present_flag
- gb.readUEG(); // chroma_sample_loc_type_top_field
- gb.readUEG(); // chroma_sample_loc_type_bottom_field
- }
- if (gb.readBool()) {
- // timing_info_present_flag
- var num_units_in_tick = gb.readBits(32);
- var time_scale = gb.readBits(32);
- fps_fixed = gb.readBool(); // fixed_frame_rate_flag
- fps_num = time_scale;
- fps_den = num_units_in_tick * 2;
- fps = fps_num / fps_den;
- }
- }
- var sarScale = 1;
- if (sar_width !== 1 || sar_height !== 1) {
- sarScale = sar_width / sar_height;
- }
- var crop_unit_x = 0,
- crop_unit_y = 0;
- if (chroma_format_idc === 0) {
- crop_unit_x = 1;
- crop_unit_y = 2 - frame_mbs_only_flag;
- } else {
- var sub_wc = chroma_format_idc === 3 ? 1 : 2;
- var sub_hc = chroma_format_idc === 1 ? 2 : 1;
- crop_unit_x = sub_wc;
- crop_unit_y = sub_hc * (2 - frame_mbs_only_flag);
- }
- var codec_width = (pic_width_in_mbs_minus1 + 1) * 16;
- var codec_height = (2 - frame_mbs_only_flag) * ((pic_height_in_map_units_minus1 + 1) * 16);
- codec_width -= (frame_crop_left_offset + frame_crop_right_offset) * crop_unit_x;
- codec_height -= (frame_crop_top_offset + frame_crop_bottom_offset) * crop_unit_y;
- var present_width = Math.ceil(codec_width * sarScale);
- gb.destroy();
- gb = null;
- return {
- profile_string: profile_string, // baseline, high, high10, ...
- level_string: level_string, // 3, 3.1, 4, 4.1, 5, 5.1, ...
- bit_depth: bit_depth, // 8bit, 10bit, ...
- ref_frames: ref_frames,
- chroma_format: chroma_format, // 4:2:0, 4:2:2, ...
- chroma_format_string: SPSParser.getChromaFormatString(chroma_format),
- frame_rate: {
- fixed: fps_fixed,
- fps: fps,
- fps_den: fps_den,
- fps_num: fps_num
- },
- par_ratio: {
- width: sar_width,
- height: sar_height
- },
- codec_size: {
- width: codec_width,
- height: codec_height
- },
- present_size: {
- width: present_width,
- height: codec_height
- }
- };
- }
- }, {
- key: '_skipScalingList',
- value: function _skipScalingList(gb, count) {
- var last_scale = 8,
- next_scale = 8;
- var delta_scale = 0;
- for (var i = 0; i < count; i++) {
- if (next_scale !== 0) {
- delta_scale = gb.readSEG();
- next_scale = (last_scale + delta_scale + 256) % 256;
- }
- last_scale = next_scale === 0 ? last_scale : next_scale;
- }
- }
- }, {
- key: 'getProfileString',
- value: function getProfileString(profile_idc) {
- switch (profile_idc) {
- case 66:
- return 'Baseline';
- case 77:
- return 'Main';
- case 88:
- return 'Extended';
- case 100:
- return 'High';
- case 110:
- return 'High10';
- case 122:
- return 'High422';
- case 244:
- return 'High444';
- default:
- return 'Unknown';
- }
- }
- }, {
- key: 'getLevelString',
- value: function getLevelString(level_idc) {
- return (level_idc / 10).toFixed(1);
- }
- }, {
- key: 'getChromaFormatString',
- value: function getChromaFormatString(chroma) {
- switch (chroma) {
- case 420:
- return '4:2:0';
- case 422:
- return '4:2:2';
- case 444:
- return '4:4:4';
- default:
- return 'Unknown';
- }
- }
- }]);
- return SPSParser;
- }();
- exports.default = SPSParser;
- module.exports = exports['default'];
- /***/ }),
- /* 39 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var _exception = __webpack_require__(1);
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- // Exponential-Golomb buffer decoder
- var ExpGolomb = function () {
- function ExpGolomb(uint8array) {
- _classCallCheck(this, ExpGolomb);
- this.TAG = 'ExpGolomb';
- this._buffer = uint8array;
- this._buffer_index = 0;
- this._total_bytes = uint8array.byteLength;
- this._total_bits = uint8array.byteLength * 8;
- this._current_word = 0;
- this._current_word_bits_left = 0;
- }
- _createClass(ExpGolomb, [{
- key: 'destroy',
- value: function destroy() {
- this._buffer = null;
- }
- }, {
- key: '_fillCurrentWord',
- value: function _fillCurrentWord() {
- var buffer_bytes_left = this._total_bytes - this._buffer_index;
- if (buffer_bytes_left <= 0) throw new _exception.IllegalStateException('ExpGolomb: _fillCurrentWord() but no bytes available');
- var bytes_read = Math.min(4, buffer_bytes_left);
- var word = new Uint8Array(4);
- word.set(this._buffer.subarray(this._buffer_index, this._buffer_index + bytes_read));
- this._current_word = new DataView(word.buffer).getUint32(0, false);
- this._buffer_index += bytes_read;
- this._current_word_bits_left = bytes_read * 8;
- }
- }, {
- key: 'readBits',
- value: function readBits(bits) {
- if (bits > 32) throw new _exception.InvalidArgumentException('ExpGolomb: readBits() bits exceeded max 32bits!');
- if (bits <= this._current_word_bits_left) {
- var _result = this._current_word >>> 32 - bits;
- this._current_word <<= bits;
- this._current_word_bits_left -= bits;
- return _result;
- }
- var result = this._current_word_bits_left ? this._current_word : 0;
- result = result >>> 32 - this._current_word_bits_left;
- var bits_need_left = bits - this._current_word_bits_left;
- this._fillCurrentWord();
- var bits_read_next = Math.min(bits_need_left, this._current_word_bits_left);
- var result2 = this._current_word >>> 32 - bits_read_next;
- this._current_word <<= bits_read_next;
- this._current_word_bits_left -= bits_read_next;
- result = result << bits_read_next | result2;
- return result;
- }
- }, {
- key: 'readBool',
- value: function readBool() {
- return this.readBits(1) === 1;
- }
- }, {
- key: 'readByte',
- value: function readByte() {
- return this.readBits(8);
- }
- }, {
- key: '_skipLeadingZero',
- value: function _skipLeadingZero() {
- var zero_count = void 0;
- for (zero_count = 0; zero_count < this._current_word_bits_left; zero_count++) {
- if (0 !== (this._current_word & 0x80000000 >>> zero_count)) {
- this._current_word <<= zero_count;
- this._current_word_bits_left -= zero_count;
- return zero_count;
- }
- }
- this._fillCurrentWord();
- return zero_count + this._skipLeadingZero();
- }
- }, {
- key: 'readUEG',
- value: function readUEG() {
- // unsigned exponential golomb
- var leading_zeros = this._skipLeadingZero();
- return this.readBits(leading_zeros + 1) - 1;
- }
- }, {
- key: 'readSEG',
- value: function readSEG() {
- // signed exponential golomb
- var value = this.readUEG();
- if (value & 0x01) {
- return value + 1 >>> 1;
- } else {
- return -1 * (value >>> 1);
- }
- }
- }]);
- return ExpGolomb;
- }();
- exports.default = ExpGolomb;
- module.exports = exports['default'];
- /***/ }),
- /* 40 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var _logger = __webpack_require__(0);
- var _logger2 = _interopRequireDefault(_logger);
- var _mp4Generator = __webpack_require__(41);
- var _mp4Generator2 = _interopRequireDefault(_mp4Generator);
- var _aacSilent = __webpack_require__(42);
- var _aacSilent2 = _interopRequireDefault(_aacSilent);
- var _browser = __webpack_require__(4);
- var _browser2 = _interopRequireDefault(_browser);
- var _mediaSegmentInfo = __webpack_require__(15);
- var _exception = __webpack_require__(1);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- // Fragmented mp4 remuxer
- var MP4Remuxer = function () {
- function MP4Remuxer(config) {
- _classCallCheck(this, MP4Remuxer);
- this.TAG = 'MP4Remuxer';
- this._config = config;
- this._isLive = config.isLive === true ? true : false;
- this._dtsBase = -1;
- this._dtsBaseInited = false;
- this._audioDtsBase = Infinity;
- this._videoDtsBase = Infinity;
- this._audioNextDts = undefined;
- this._videoNextDts = undefined;
- this._audioStashedLastSample = null;
- this._videoStashedLastSample = null;
- this._audioMeta = null;
- this._videoMeta = null;
- this._audioSegmentInfoList = new _mediaSegmentInfo.MediaSegmentInfoList('audio');
- this._videoSegmentInfoList = new _mediaSegmentInfo.MediaSegmentInfoList('video');
- this._onInitSegment = null;
- this._onMediaSegment = null;
- // Workaround for chrome < 50: Always force first sample as a Random Access Point in media segment
- // see https://bugs.chromium.org/p/chromium/issues/detail?id=229412
- this._forceFirstIDR = _browser2.default.chrome && (_browser2.default.version.major < 50 || _browser2.default.version.major === 50 && _browser2.default.version.build < 2661) ? true : false;
- // Workaround for IE11/Edge: Fill silent aac frame after keyframe-seeking
- // Make audio beginDts equals with video beginDts, in order to fix seek freeze
- this._fillSilentAfterSeek = _browser2.default.msedge || _browser2.default.msie;
- // While only FireFox supports 'audio/mp4, codecs="mp3"', use 'audio/mpeg' for chrome, safari, ...
- this._mp3UseMpegAudio = !_browser2.default.firefox;
- this._fillAudioTimestampGap = this._config.fixAudioTimestampGap;
- }
- _createClass(MP4Remuxer, [{
- key: 'destroy',
- value: function destroy() {
- this._dtsBase = -1;
- this._dtsBaseInited = false;
- this._audioMeta = null;
- this._videoMeta = null;
- this._audioSegmentInfoList.clear();
- this._audioSegmentInfoList = null;
- this._videoSegmentInfoList.clear();
- this._videoSegmentInfoList = null;
- this._onInitSegment = null;
- this._onMediaSegment = null;
- }
- }, {
- key: 'bindDataSource',
- value: function bindDataSource(producer) {
- producer.onDataAvailable = this.remux.bind(this);
- producer.onTrackMetadata = this._onTrackMetadataReceived.bind(this);
- return this;
- }
- /* prototype: function onInitSegment(type: string, initSegment: ArrayBuffer): void
- InitSegment: {
- type: string,
- data: ArrayBuffer,
- codec: string,
- container: string
- }
- */
- }, {
- key: 'insertDiscontinuity',
- value: function insertDiscontinuity() {
- this._audioNextDts = this._videoNextDts = undefined;
- }
- }, {
- key: 'seek',
- value: function seek(originalDts) {
- this._audioStashedLastSample = null;
- this._videoStashedLastSample = null;
- this._videoSegmentInfoList.clear();
- this._audioSegmentInfoList.clear();
- }
- }, {
- key: 'remux',
- value: function remux(audioTrack, videoTrack) {
- if (!this._onMediaSegment) {
- throw new _exception.IllegalStateException('MP4Remuxer: onMediaSegment callback must be specificed!');
- }
- if (!this._dtsBaseInited) {
- this._calculateDtsBase(audioTrack, videoTrack);
- }
- this._remuxVideo(videoTrack);
- this._remuxAudio(audioTrack);
- }
- }, {
- key: '_onTrackMetadataReceived',
- value: function _onTrackMetadataReceived(type, metadata) {
- var metabox = null;
- var container = 'mp4';
- var codec = metadata.codec;
- if (type === 'audio') {
- this._audioMeta = metadata;
- if (metadata.codec === 'mp3' && this._mp3UseMpegAudio) {
- // 'audio/mpeg' for MP3 audio track
- container = 'mpeg';
- codec = '';
- metabox = new Uint8Array();
- } else {
- // 'audio/mp4, codecs="codec"'
- metabox = _mp4Generator2.default.generateInitSegment(metadata);
- }
- } else if (type === 'video') {
- this._videoMeta = metadata;
- metabox = _mp4Generator2.default.generateInitSegment(metadata);
- } else {
- return;
- }
- // dispatch metabox (Initialization Segment)
- if (!this._onInitSegment) {
- throw new _exception.IllegalStateException('MP4Remuxer: onInitSegment callback must be specified!');
- }
- this._onInitSegment(type, {
- type: type,
- data: metabox.buffer,
- codec: codec,
- container: type + '/' + container,
- mediaDuration: metadata.duration // in timescale 1000 (milliseconds)
- });
- }
- }, {
- key: '_calculateDtsBase',
- value: function _calculateDtsBase(audioTrack, videoTrack) {
- if (this._dtsBaseInited) {
- return;
- }
- if (audioTrack.samples && audioTrack.samples.length) {
- this._audioDtsBase = audioTrack.samples[0].dts;
- }
- if (videoTrack.samples && videoTrack.samples.length) {
- this._videoDtsBase = videoTrack.samples[0].dts;
- }
- this._dtsBase = Math.min(this._audioDtsBase, this._videoDtsBase);
- this._dtsBaseInited = true;
- }
- }, {
- key: 'flushStashedSamples',
- value: function flushStashedSamples() {
- var videoSample = this._videoStashedLastSample;
- var audioSample = this._audioStashedLastSample;
- var videoTrack = {
- type: 'video',
- id: 1,
- sequenceNumber: 0,
- samples: [],
- length: 0
- };
- if (videoSample != null) {
- videoTrack.samples.push(videoSample);
- videoTrack.length = videoSample.length;
- }
- var audioTrack = {
- type: 'audio',
- id: 2,
- sequenceNumber: 0,
- samples: [],
- length: 0
- };
- if (audioSample != null) {
- audioTrack.samples.push(audioSample);
- audioTrack.length = audioSample.length;
- }
- this._videoStashedLastSample = null;
- this._audioStashedLastSample = null;
- this._remuxVideo(videoTrack, true);
- this._remuxAudio(audioTrack, true);
- }
- }, {
- key: '_remuxAudio',
- value: function _remuxAudio(audioTrack, force) {
- if (this._audioMeta == null) {
- return;
- }
- var track = audioTrack;
- var samples = track.samples;
- var dtsCorrection = undefined;
- var firstDts = -1,
- lastDts = -1,
- lastPts = -1;
- var refSampleDuration = this._audioMeta.refSampleDuration;
- var mpegRawTrack = this._audioMeta.codec === 'mp3' && this._mp3UseMpegAudio;
- var firstSegmentAfterSeek = this._dtsBaseInited && this._audioNextDts === undefined;
- var insertPrefixSilentFrame = false;
- if (!samples || samples.length === 0) {
- return;
- }
- if (samples.length === 1 && !force) {
- // If [sample count in current batch] === 1 && (force != true)
- // Ignore and keep in demuxer's queue
- return;
- } // else if (force === true) do remux
- var offset = 0;
- var mdatbox = null;
- var mdatBytes = 0;
- // calculate initial mdat size
- if (mpegRawTrack) {
- // for raw mpeg buffer
- offset = 0;
- mdatBytes = track.length;
- } else {
- // for fmp4 mdat box
- offset = 8; // size + type
- mdatBytes = 8 + track.length;
- }
- var lastSample = null;
- // Pop the lastSample and waiting for stash
- if (samples.length > 1) {
- lastSample = samples.pop();
- mdatBytes -= lastSample.length;
- }
- // Insert [stashed lastSample in the previous batch] to the front
- if (this._audioStashedLastSample != null) {
- var sample = this._audioStashedLastSample;
- this._audioStashedLastSample = null;
- samples.unshift(sample);
- mdatBytes += sample.length;
- }
- // Stash the lastSample of current batch, waiting for next batch
- if (lastSample != null) {
- this._audioStashedLastSample = lastSample;
- }
- var firstSampleOriginalDts = samples[0].dts - this._dtsBase;
- // calculate dtsCorrection
- if (this._audioNextDts) {
- dtsCorrection = firstSampleOriginalDts - this._audioNextDts;
- } else {
- // this._audioNextDts == undefined
- if (this._audioSegmentInfoList.isEmpty()) {
- dtsCorrection = 0;
- if (this._fillSilentAfterSeek && !this._videoSegmentInfoList.isEmpty()) {
- if (this._audioMeta.originalCodec !== 'mp3') {
- insertPrefixSilentFrame = true;
- }
- }
- } else {
- var _lastSample = this._audioSegmentInfoList.getLastSampleBefore(firstSampleOriginalDts);
- if (_lastSample != null) {
- var distance = firstSampleOriginalDts - (_lastSample.originalDts + _lastSample.duration);
- if (distance <= 3) {
- distance = 0;
- }
- var expectedDts = _lastSample.dts + _lastSample.duration + distance;
- dtsCorrection = firstSampleOriginalDts - expectedDts;
- } else {
- // lastSample == null, cannot found
- dtsCorrection = 0;
- }
- }
- }
- if (insertPrefixSilentFrame) {
- // align audio segment beginDts to match with current video segment's beginDts
- var firstSampleDts = firstSampleOriginalDts - dtsCorrection;
- var videoSegment = this._videoSegmentInfoList.getLastSegmentBefore(firstSampleOriginalDts);
- if (videoSegment != null && videoSegment.beginDts < firstSampleDts) {
- var silentUnit = _aacSilent2.default.getSilentFrame(this._audioMeta.originalCodec, this._audioMeta.channelCount);
- if (silentUnit) {
- var dts = videoSegment.beginDts;
- var silentFrameDuration = firstSampleDts - videoSegment.beginDts;
- _logger2.default.v(this.TAG, 'InsertPrefixSilentAudio: dts: ' + dts + ', duration: ' + silentFrameDuration);
- samples.unshift({ unit: silentUnit, dts: dts, pts: dts });
- mdatBytes += silentUnit.byteLength;
- } // silentUnit == null: Cannot generate, skip
- } else {
- insertPrefixSilentFrame = false;
- }
- }
- var mp4Samples = [];
- // Correct dts for each sample, and calculate sample duration. Then output to mp4Samples
- for (var i = 0; i < samples.length; i++) {
- var _sample = samples[i];
- var unit = _sample.unit;
- var originalDts = _sample.dts - this._dtsBase;
- var _dts = originalDts;
- var needFillSilentFrames = false;
- var silentFrames = null;
- var sampleDuration = 0;
- if (originalDts < -0.001) {
- continue; //pass the first sample with the invalid dts
- }
- if (this._audioMeta.codec !== 'mp3') {
- // for AAC codec, we need to keep dts increase based on refSampleDuration
- var curRefDts = originalDts;
- var maxAudioFramesDrift = 3;
- if (this._audioNextDts) {
- curRefDts = this._audioNextDts;
- }
- dtsCorrection = originalDts - curRefDts;
- if (dtsCorrection <= -maxAudioFramesDrift * refSampleDuration) {
- // If we're overlapping by more than maxAudioFramesDrift number of frame, drop this sample
- _logger2.default.w(this.TAG, 'Dropping 1 audio frame (originalDts: ' + originalDts + ' ms ,curRefDts: ' + curRefDts + ' ms) due to dtsCorrection: ' + dtsCorrection + ' ms overlap.');
- continue;
- } else if (dtsCorrection >= maxAudioFramesDrift * refSampleDuration && this._fillAudioTimestampGap && !_browser2.default.safari) {
- // Silent frame generation, if large timestamp gap detected && config.fixAudioTimestampGap
- needFillSilentFrames = true;
- // We need to insert silent frames to fill timestamp gap
- var frameCount = Math.floor(dtsCorrection / refSampleDuration);
- _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'));
- _dts = Math.floor(curRefDts);
- sampleDuration = Math.floor(curRefDts + refSampleDuration) - _dts;
- var _silentUnit = _aacSilent2.default.getSilentFrame(this._audioMeta.originalCodec, this._audioMeta.channelCount);
- if (_silentUnit == null) {
- _logger2.default.w(this.TAG, 'Unable to generate silent frame for ' + (this._audioMeta.originalCodec + ' with ' + this._audioMeta.channelCount + ' channels, repeat last frame'));
- // Repeat last frame
- _silentUnit = unit;
- }
- silentFrames = [];
- for (var j = 0; j < frameCount; j++) {
- curRefDts = curRefDts + refSampleDuration;
- var intDts = Math.floor(curRefDts); // change to integer
- var intDuration = Math.floor(curRefDts + refSampleDuration) - intDts;
- var frame = {
- dts: intDts,
- pts: intDts,
- cts: 0,
- unit: _silentUnit,
- size: _silentUnit.byteLength,
- duration: intDuration, // wait for next sample
- originalDts: originalDts,
- flags: {
- isLeading: 0,
- dependsOn: 1,
- isDependedOn: 0,
- hasRedundancy: 0
- }
- };
- silentFrames.push(frame);
- mdatBytes += unit.byteLength;
- }
- this._audioNextDts = curRefDts + refSampleDuration;
- } else {
- _dts = Math.floor(curRefDts);
- sampleDuration = Math.floor(curRefDts + refSampleDuration) - _dts;
- this._audioNextDts = curRefDts + refSampleDuration;
- }
- } else {
- // keep the original dts calculate algorithm for mp3
- _dts = originalDts - dtsCorrection;
- if (i !== samples.length - 1) {
- var nextDts = samples[i + 1].dts - this._dtsBase - dtsCorrection;
- sampleDuration = nextDts - _dts;
- } else {
- // the last sample
- if (lastSample != null) {
- // use stashed sample's dts to calculate sample duration
- var _nextDts = lastSample.dts - this._dtsBase - dtsCorrection;
- sampleDuration = _nextDts - _dts;
- } else if (mp4Samples.length >= 1) {
- // use second last sample duration
- sampleDuration = mp4Samples[mp4Samples.length - 1].duration;
- } else {
- // the only one sample, use reference sample duration
- sampleDuration = Math.floor(refSampleDuration);
- }
- }
- this._audioNextDts = _dts + sampleDuration;
- }
- if (firstDts === -1) {
- firstDts = _dts;
- }
- mp4Samples.push({
- dts: _dts,
- pts: _dts,
- cts: 0,
- unit: _sample.unit,
- size: _sample.unit.byteLength,
- duration: sampleDuration,
- originalDts: originalDts,
- flags: {
- isLeading: 0,
- dependsOn: 1,
- isDependedOn: 0,
- hasRedundancy: 0
- }
- });
- if (needFillSilentFrames) {
- // Silent frames should be inserted after wrong-duration frame
- mp4Samples.push.apply(mp4Samples, silentFrames);
- }
- }
- if (mp4Samples.length === 0) {
- //no samples need to remux
- track.samples = [];
- track.length = 0;
- return;
- }
- // allocate mdatbox
- if (mpegRawTrack) {
- // allocate for raw mpeg buffer
- mdatbox = new Uint8Array(mdatBytes);
- } else {
- // allocate for fmp4 mdat box
- mdatbox = new Uint8Array(mdatBytes);
- // size field
- mdatbox[0] = mdatBytes >>> 24 & 0xFF;
- mdatbox[1] = mdatBytes >>> 16 & 0xFF;
- mdatbox[2] = mdatBytes >>> 8 & 0xFF;
- mdatbox[3] = mdatBytes & 0xFF;
- // type field (fourCC)
- mdatbox.set(_mp4Generator2.default.types.mdat, 4);
- }
- // Write samples into mdatbox
- for (var _i = 0; _i < mp4Samples.length; _i++) {
- var _unit = mp4Samples[_i].unit;
- mdatbox.set(_unit, offset);
- offset += _unit.byteLength;
- }
- var latest = mp4Samples[mp4Samples.length - 1];
- lastDts = latest.dts + latest.duration;
- //this._audioNextDts = lastDts;
- // fill media segment info & add to info list
- var info = new _mediaSegmentInfo.MediaSegmentInfo();
- info.beginDts = firstDts;
- info.endDts = lastDts;
- info.beginPts = firstDts;
- info.endPts = lastDts;
- info.originalBeginDts = mp4Samples[0].originalDts;
- info.originalEndDts = latest.originalDts + latest.duration;
- info.firstSample = new _mediaSegmentInfo.SampleInfo(mp4Samples[0].dts, mp4Samples[0].pts, mp4Samples[0].duration, mp4Samples[0].originalDts, false);
- info.lastSample = new _mediaSegmentInfo.SampleInfo(latest.dts, latest.pts, latest.duration, latest.originalDts, false);
- if (!this._isLive) {
- this._audioSegmentInfoList.append(info);
- }
- track.samples = mp4Samples;
- track.sequenceNumber++;
- var moofbox = null;
- if (mpegRawTrack) {
- // Generate empty buffer, because useless for raw mpeg
- moofbox = new Uint8Array();
- } else {
- // Generate moof for fmp4 segment
- moofbox = _mp4Generator2.default.moof(track, firstDts);
- }
- track.samples = [];
- track.length = 0;
- var segment = {
- type: 'audio',
- data: this._mergeBoxes(moofbox, mdatbox).buffer,
- sampleCount: mp4Samples.length,
- info: info
- };
- if (mpegRawTrack && firstSegmentAfterSeek) {
- // For MPEG audio stream in MSE, if seeking occurred, before appending new buffer
- // We need explicitly set timestampOffset to the desired point in timeline for mpeg SourceBuffer.
- segment.timestampOffset = firstDts;
- }
- this._onMediaSegment('audio', segment);
- }
- }, {
- key: '_remuxVideo',
- value: function _remuxVideo(videoTrack, force) {
- if (this._videoMeta == null) {
- return;
- }
- var track = videoTrack;
- var samples = track.samples;
- var dtsCorrection = undefined;
- var firstDts = -1,
- lastDts = -1;
- var firstPts = -1,
- lastPts = -1;
- if (!samples || samples.length === 0) {
- return;
- }
- if (samples.length === 1 && !force) {
- // If [sample count in current batch] === 1 && (force != true)
- // Ignore and keep in demuxer's queue
- return;
- } // else if (force === true) do remux
- var offset = 8;
- var mdatbox = null;
- var mdatBytes = 8 + videoTrack.length;
- var lastSample = null;
- // Pop the lastSample and waiting for stash
- if (samples.length > 1) {
- lastSample = samples.pop();
- mdatBytes -= lastSample.length;
- }
- // Insert [stashed lastSample in the previous batch] to the front
- if (this._videoStashedLastSample != null) {
- var sample = this._videoStashedLastSample;
- this._videoStashedLastSample = null;
- samples.unshift(sample);
- mdatBytes += sample.length;
- }
- // Stash the lastSample of current batch, waiting for next batch
- if (lastSample != null) {
- this._videoStashedLastSample = lastSample;
- }
- var firstSampleOriginalDts = samples[0].dts - this._dtsBase;
- // calculate dtsCorrection
- if (this._videoNextDts) {
- dtsCorrection = firstSampleOriginalDts - this._videoNextDts;
- } else {
- // this._videoNextDts == undefined
- if (this._videoSegmentInfoList.isEmpty()) {
- dtsCorrection = 0;
- } else {
- var _lastSample2 = this._videoSegmentInfoList.getLastSampleBefore(firstSampleOriginalDts);
- if (_lastSample2 != null) {
- var distance = firstSampleOriginalDts - (_lastSample2.originalDts + _lastSample2.duration);
- if (distance <= 3) {
- distance = 0;
- }
- var expectedDts = _lastSample2.dts + _lastSample2.duration + distance;
- dtsCorrection = firstSampleOriginalDts - expectedDts;
- } else {
- // lastSample == null, cannot found
- dtsCorrection = 0;
- }
- }
- }
- var info = new _mediaSegmentInfo.MediaSegmentInfo();
- var mp4Samples = [];
- // Correct dts for each sample, and calculate sample duration. Then output to mp4Samples
- for (var i = 0; i < samples.length; i++) {
- var _sample2 = samples[i];
- var originalDts = _sample2.dts - this._dtsBase;
- var isKeyframe = _sample2.isKeyframe;
- var dts = originalDts - dtsCorrection;
- var cts = _sample2.cts;
- var pts = dts + cts;
- if (firstDts === -1) {
- firstDts = dts;
- firstPts = pts;
- }
- var sampleDuration = 0;
- if (i !== samples.length - 1) {
- var nextDts = samples[i + 1].dts - this._dtsBase - dtsCorrection;
- sampleDuration = nextDts - dts;
- } else {
- // the last sample
- if (lastSample != null) {
- // use stashed sample's dts to calculate sample duration
- var _nextDts2 = lastSample.dts - this._dtsBase - dtsCorrection;
- sampleDuration = _nextDts2 - dts;
- } else if (mp4Samples.length >= 1) {
- // use second last sample duration
- sampleDuration = mp4Samples[mp4Samples.length - 1].duration;
- } else {
- // the only one sample, use reference sample duration
- sampleDuration = Math.floor(this._videoMeta.refSampleDuration);
- }
- }
- if (isKeyframe) {
- var syncPoint = new _mediaSegmentInfo.SampleInfo(dts, pts, sampleDuration, _sample2.dts, true);
- syncPoint.fileposition = _sample2.fileposition;
- info.appendSyncPoint(syncPoint);
- }
- mp4Samples.push({
- dts: dts,
- pts: pts,
- cts: cts,
- units: _sample2.units,
- size: _sample2.length,
- isKeyframe: isKeyframe,
- duration: sampleDuration,
- originalDts: originalDts,
- flags: {
- isLeading: 0,
- dependsOn: isKeyframe ? 2 : 1,
- isDependedOn: isKeyframe ? 1 : 0,
- hasRedundancy: 0,
- isNonSync: isKeyframe ? 0 : 1
- }
- });
- }
- // allocate mdatbox
- mdatbox = new Uint8Array(mdatBytes);
- mdatbox[0] = mdatBytes >>> 24 & 0xFF;
- mdatbox[1] = mdatBytes >>> 16 & 0xFF;
- mdatbox[2] = mdatBytes >>> 8 & 0xFF;
- mdatbox[3] = mdatBytes & 0xFF;
- mdatbox.set(_mp4Generator2.default.types.mdat, 4);
- // Write samples into mdatbox
- for (var _i2 = 0; _i2 < mp4Samples.length; _i2++) {
- var units = mp4Samples[_i2].units;
- while (units.length) {
- var unit = units.shift();
- var data = unit.data;
- mdatbox.set(data, offset);
- offset += data.byteLength;
- }
- }
- var latest = mp4Samples[mp4Samples.length - 1];
- lastDts = latest.dts + latest.duration;
- lastPts = latest.pts + latest.duration;
- this._videoNextDts = lastDts;
- // fill media segment info & add to info list
- info.beginDts = firstDts;
- info.endDts = lastDts;
- info.beginPts = firstPts;
- info.endPts = lastPts;
- info.originalBeginDts = mp4Samples[0].originalDts;
- info.originalEndDts = latest.originalDts + latest.duration;
- info.firstSample = new _mediaSegmentInfo.SampleInfo(mp4Samples[0].dts, mp4Samples[0].pts, mp4Samples[0].duration, mp4Samples[0].originalDts, mp4Samples[0].isKeyframe);
- info.lastSample = new _mediaSegmentInfo.SampleInfo(latest.dts, latest.pts, latest.duration, latest.originalDts, latest.isKeyframe);
- if (!this._isLive) {
- this._videoSegmentInfoList.append(info);
- }
- track.samples = mp4Samples;
- track.sequenceNumber++;
- // workaround for chrome < 50: force first sample as a random access point
- // see https://bugs.chromium.org/p/chromium/issues/detail?id=229412
- if (this._forceFirstIDR) {
- var flags = mp4Samples[0].flags;
- flags.dependsOn = 2;
- flags.isNonSync = 0;
- }
- var moofbox = _mp4Generator2.default.moof(track, firstDts);
- track.samples = [];
- track.length = 0;
- this._onMediaSegment('video', {
- type: 'video',
- data: this._mergeBoxes(moofbox, mdatbox).buffer,
- sampleCount: mp4Samples.length,
- info: info
- });
- }
- }, {
- key: '_mergeBoxes',
- value: function _mergeBoxes(moof, mdat) {
- var result = new Uint8Array(moof.byteLength + mdat.byteLength);
- result.set(moof, 0);
- result.set(mdat, moof.byteLength);
- return result;
- }
- }, {
- key: 'onInitSegment',
- get: function get() {
- return this._onInitSegment;
- },
- set: function set(callback) {
- this._onInitSegment = callback;
- }
- /* prototype: function onMediaSegment(type: string, mediaSegment: MediaSegment): void
- MediaSegment: {
- type: string,
- data: ArrayBuffer,
- sampleCount: int32
- info: MediaSegmentInfo
- }
- */
- }, {
- key: 'onMediaSegment',
- get: function get() {
- return this._onMediaSegment;
- },
- set: function set(callback) {
- this._onMediaSegment = callback;
- }
- }]);
- return MP4Remuxer;
- }();
- exports.default = MP4Remuxer;
- module.exports = exports['default'];
- /***/ }),
- /* 41 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * This file is derived from dailymotion's hls.js library (hls.js/src/remux/mp4-generator.js)
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- // MP4 boxes generator for ISO BMFF (ISO Base Media File Format, defined in ISO/IEC 14496-12)
- var MP4 = function () {
- function MP4() {
- _classCallCheck(this, MP4);
- }
- _createClass(MP4, null, [{
- key: 'init',
- value: function init() {
- MP4.types = {
- avc1: [],
- avcC: [],
- btrt: [],
- dinf: [],
- dref: [],
- esds: [],
- ftyp: [],
- hdlr: [],
- mdat: [],
- mdhd: [],
- mdia: [],
- mfhd: [],
- minf: [],
- moof: [],
- moov: [],
- mp4a: [],
- mvex: [],
- mvhd: [],
- sdtp: [],
- stbl: [],
- stco: [],
- stsc: [],
- stsd: [],
- stsz: [],
- stts: [],
- tfdt: [],
- tfhd: [],
- traf: [],
- trak: [],
- trun: [],
- trex: [],
- tkhd: [],
- vmhd: [],
- smhd: [],
- '.mp3': []
- };
- for (var name in MP4.types) {
- if (MP4.types.hasOwnProperty(name)) {
- MP4.types[name] = [name.charCodeAt(0), name.charCodeAt(1), name.charCodeAt(2), name.charCodeAt(3)];
- }
- }
- var constants = MP4.constants = {};
- constants.FTYP = new Uint8Array([0x69, 0x73, 0x6F, 0x6D, // major_brand: isom
- 0x0, 0x0, 0x0, 0x1, // minor_version: 0x01
- 0x69, 0x73, 0x6F, 0x6D, // isom
- 0x61, 0x76, 0x63, 0x31 // avc1
- ]);
- constants.STSD_PREFIX = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
- 0x00, 0x00, 0x00, 0x01 // entry_count
- ]);
- constants.STTS = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
- 0x00, 0x00, 0x00, 0x00 // entry_count
- ]);
- constants.STSC = constants.STCO = constants.STTS;
- constants.STSZ = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
- 0x00, 0x00, 0x00, 0x00, // sample_size
- 0x00, 0x00, 0x00, 0x00 // sample_count
- ]);
- constants.HDLR_VIDEO = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
- 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
- 0x00, 0x00, 0x00, 0x00, // reserved: 3 * 4 bytes
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x69, 0x64, 0x65, 0x6F, 0x48, 0x61, 0x6E, 0x64, 0x6C, 0x65, 0x72, 0x00 // name: VideoHandler
- ]);
- constants.HDLR_AUDIO = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
- 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0x73, 0x6F, 0x75, 0x6E, // handler_type: 'soun'
- 0x00, 0x00, 0x00, 0x00, // reserved: 3 * 4 bytes
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x6F, 0x75, 0x6E, 0x64, 0x48, 0x61, 0x6E, 0x64, 0x6C, 0x65, 0x72, 0x00 // name: SoundHandler
- ]);
- constants.DREF = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
- 0x00, 0x00, 0x00, 0x01, // entry_count
- 0x00, 0x00, 0x00, 0x0C, // entry_size
- 0x75, 0x72, 0x6C, 0x20, // type 'url '
- 0x00, 0x00, 0x00, 0x01 // version(0) + flags
- ]);
- // Sound media header
- constants.SMHD = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
- 0x00, 0x00, 0x00, 0x00 // balance(2) + reserved(2)
- ]);
- // video media header
- constants.VMHD = new Uint8Array([0x00, 0x00, 0x00, 0x01, // version(0) + flags
- 0x00, 0x00, // graphicsmode: 2 bytes
- 0x00, 0x00, 0x00, 0x00, // opcolor: 3 * 2 bytes
- 0x00, 0x00]);
- }
- // Generate a box
- }, {
- key: 'box',
- value: function box(type) {
- var size = 8;
- var result = null;
- var datas = Array.prototype.slice.call(arguments, 1);
- var arrayCount = datas.length;
- for (var i = 0; i < arrayCount; i++) {
- size += datas[i].byteLength;
- }
- result = new Uint8Array(size);
- result[0] = size >>> 24 & 0xFF; // size
- result[1] = size >>> 16 & 0xFF;
- result[2] = size >>> 8 & 0xFF;
- result[3] = size & 0xFF;
- result.set(type, 4); // type
- var offset = 8;
- for (var _i = 0; _i < arrayCount; _i++) {
- // data body
- result.set(datas[_i], offset);
- offset += datas[_i].byteLength;
- }
- return result;
- }
- // emit ftyp & moov
- }, {
- key: 'generateInitSegment',
- value: function generateInitSegment(meta) {
- var ftyp = MP4.box(MP4.types.ftyp, MP4.constants.FTYP);
- var moov = MP4.moov(meta);
- var result = new Uint8Array(ftyp.byteLength + moov.byteLength);
- result.set(ftyp, 0);
- result.set(moov, ftyp.byteLength);
- return result;
- }
- // Movie metadata box
- }, {
- key: 'moov',
- value: function moov(meta) {
- var mvhd = MP4.mvhd(meta.timescale, meta.duration);
- var trak = MP4.trak(meta);
- var mvex = MP4.mvex(meta);
- return MP4.box(MP4.types.moov, mvhd, trak, mvex);
- }
- // Movie header box
- }, {
- key: 'mvhd',
- value: function mvhd(timescale, duration) {
- return MP4.box(MP4.types.mvhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
- 0x00, 0x00, 0x00, 0x00, // creation_time
- 0x00, 0x00, 0x00, 0x00, // modification_time
- timescale >>> 24 & 0xFF, // timescale: 4 bytes
- timescale >>> 16 & 0xFF, timescale >>> 8 & 0xFF, timescale & 0xFF, duration >>> 24 & 0xFF, // duration: 4 bytes
- duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x00, 0x01, 0x00, 0x00, // Preferred rate: 1.0
- 0x01, 0x00, 0x00, 0x00, // PreferredVolume(1.0, 2bytes) + reserved(2bytes)
- 0x00, 0x00, 0x00, 0x00, // reserved: 4 + 4 bytes
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, // ----begin composition matrix----
- 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----
- 0x00, 0x00, 0x00, 0x00, // ----begin pre_defined 6 * 4 bytes----
- 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----
- 0xFF, 0xFF, 0xFF, 0xFF // next_track_ID
- ]));
- }
- // Track box
- }, {
- key: 'trak',
- value: function trak(meta) {
- return MP4.box(MP4.types.trak, MP4.tkhd(meta), MP4.mdia(meta));
- }
- // Track header box
- }, {
- key: 'tkhd',
- value: function tkhd(meta) {
- var trackId = meta.id,
- duration = meta.duration;
- var width = meta.presentWidth,
- height = meta.presentHeight;
- return MP4.box(MP4.types.tkhd, new Uint8Array([0x00, 0x00, 0x00, 0x07, // version(0) + flags
- 0x00, 0x00, 0x00, 0x00, // creation_time
- 0x00, 0x00, 0x00, 0x00, // modification_time
- trackId >>> 24 & 0xFF, // track_ID: 4 bytes
- trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF, 0x00, 0x00, 0x00, 0x00, // reserved: 4 bytes
- duration >>> 24 & 0xFF, // duration: 4 bytes
- duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // layer(2bytes) + alternate_group(2bytes)
- 0x00, 0x00, 0x00, 0x00, // volume(2bytes) + reserved(2bytes)
- 0x00, 0x01, 0x00, 0x00, // ----begin composition matrix----
- 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----
- width >>> 8 & 0xFF, // width and height
- width & 0xFF, 0x00, 0x00, height >>> 8 & 0xFF, height & 0xFF, 0x00, 0x00]));
- }
- // Media Box
- }, {
- key: 'mdia',
- value: function mdia(meta) {
- return MP4.box(MP4.types.mdia, MP4.mdhd(meta), MP4.hdlr(meta), MP4.minf(meta));
- }
- // Media header box
- }, {
- key: 'mdhd',
- value: function mdhd(meta) {
- var timescale = meta.timescale;
- var duration = meta.duration;
- return MP4.box(MP4.types.mdhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
- 0x00, 0x00, 0x00, 0x00, // creation_time
- 0x00, 0x00, 0x00, 0x00, // modification_time
- timescale >>> 24 & 0xFF, // timescale: 4 bytes
- timescale >>> 16 & 0xFF, timescale >>> 8 & 0xFF, timescale & 0xFF, duration >>> 24 & 0xFF, // duration: 4 bytes
- duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, 0x55, 0xC4, // language: und (undetermined)
- 0x00, 0x00 // pre_defined = 0
- ]));
- }
- // Media handler reference box
- }, {
- key: 'hdlr',
- value: function hdlr(meta) {
- var data = null;
- if (meta.type === 'audio') {
- data = MP4.constants.HDLR_AUDIO;
- } else {
- data = MP4.constants.HDLR_VIDEO;
- }
- return MP4.box(MP4.types.hdlr, data);
- }
- // Media infomation box
- }, {
- key: 'minf',
- value: function minf(meta) {
- var xmhd = null;
- if (meta.type === 'audio') {
- xmhd = MP4.box(MP4.types.smhd, MP4.constants.SMHD);
- } else {
- xmhd = MP4.box(MP4.types.vmhd, MP4.constants.VMHD);
- }
- return MP4.box(MP4.types.minf, xmhd, MP4.dinf(), MP4.stbl(meta));
- }
- // Data infomation box
- }, {
- key: 'dinf',
- value: function dinf() {
- var result = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, MP4.constants.DREF));
- return result;
- }
- // Sample table box
- }, {
- key: 'stbl',
- value: function stbl(meta) {
- var result = MP4.box(MP4.types.stbl, // type: stbl
- MP4.stsd(meta), // Sample Description Table
- MP4.box(MP4.types.stts, MP4.constants.STTS), // Time-To-Sample
- MP4.box(MP4.types.stsc, MP4.constants.STSC), // Sample-To-Chunk
- MP4.box(MP4.types.stsz, MP4.constants.STSZ), // Sample size
- MP4.box(MP4.types.stco, MP4.constants.STCO) // Chunk offset
- );
- return result;
- }
- // Sample description box
- }, {
- key: 'stsd',
- value: function stsd(meta) {
- if (meta.type === 'audio') {
- if (meta.codec === 'mp3') {
- return MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.mp3(meta));
- }
- // else: aac -> mp4a
- return MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.mp4a(meta));
- } else {
- return MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.avc1(meta));
- }
- }
- }, {
- key: 'mp3',
- value: function mp3(meta) {
- var channelCount = meta.channelCount;
- var sampleRate = meta.audioSampleRate;
- var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // reserved(4)
- 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2)
- 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes
- 0x00, 0x00, 0x00, 0x00, 0x00, channelCount, // channelCount(2)
- 0x00, 0x10, // sampleSize(2)
- 0x00, 0x00, 0x00, 0x00, // reserved(4)
- sampleRate >>> 8 & 0xFF, // Audio sample rate
- sampleRate & 0xFF, 0x00, 0x00]);
- return MP4.box(MP4.types['.mp3'], data);
- }
- }, {
- key: 'mp4a',
- value: function mp4a(meta) {
- var channelCount = meta.channelCount;
- var sampleRate = meta.audioSampleRate;
- var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // reserved(4)
- 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2)
- 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes
- 0x00, 0x00, 0x00, 0x00, 0x00, channelCount, // channelCount(2)
- 0x00, 0x10, // sampleSize(2)
- 0x00, 0x00, 0x00, 0x00, // reserved(4)
- sampleRate >>> 8 & 0xFF, // Audio sample rate
- sampleRate & 0xFF, 0x00, 0x00]);
- return MP4.box(MP4.types.mp4a, data, MP4.esds(meta));
- }
- }, {
- key: 'esds',
- value: function esds(meta) {
- var config = meta.config || [];
- var configSize = config.length;
- var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version 0 + flags
- 0x03, // descriptor_type
- 0x17 + configSize, // length3
- 0x00, 0x01, // es_id
- 0x00, // stream_priority
- 0x04, // descriptor_type
- 0x0F + configSize, // length
- 0x40, // codec: mpeg4_audio
- 0x15, // stream_type: Audio
- 0x00, 0x00, 0x00, // buffer_size
- 0x00, 0x00, 0x00, 0x00, // maxBitrate
- 0x00, 0x00, 0x00, 0x00, // avgBitrate
- 0x05 // descriptor_type
- ].concat([configSize]).concat(config).concat([0x06, 0x01, 0x02 // GASpecificConfig
- ]));
- return MP4.box(MP4.types.esds, data);
- }
- }, {
- key: 'avc1',
- value: function avc1(meta) {
- var avcc = meta.avcc;
- var width = meta.codecWidth,
- height = meta.codecHeight;
- var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // reserved(4)
- 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2)
- 0x00, 0x00, 0x00, 0x00, // pre_defined(2) + reserved(2)
- 0x00, 0x00, 0x00, 0x00, // pre_defined: 3 * 4 bytes
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, width >>> 8 & 0xFF, // width: 2 bytes
- width & 0xFF, height >>> 8 & 0xFF, // height: 2 bytes
- height & 0xFF, 0x00, 0x48, 0x00, 0x00, // horizresolution: 4 bytes
- 0x00, 0x48, 0x00, 0x00, // vertresolution: 4 bytes
- 0x00, 0x00, 0x00, 0x00, // reserved: 4 bytes
- 0x00, 0x01, // frame_count
- 0x0A, // strlen
- 0x78, 0x71, 0x71, 0x2F, // compressorname: 32 bytes
- 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
- 0xFF, 0xFF // pre_defined = -1
- ]);
- return MP4.box(MP4.types.avc1, data, MP4.box(MP4.types.avcC, avcc));
- }
- // Movie Extends box
- }, {
- key: 'mvex',
- value: function mvex(meta) {
- return MP4.box(MP4.types.mvex, MP4.trex(meta));
- }
- // Track Extends box
- }, {
- key: 'trex',
- value: function trex(meta) {
- var trackId = meta.id;
- var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) + flags
- trackId >>> 24 & 0xFF, // track_ID
- trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF, 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
- 0x00, 0x00, 0x00, 0x00, // default_sample_duration
- 0x00, 0x00, 0x00, 0x00, // default_sample_size
- 0x00, 0x01, 0x00, 0x01 // default_sample_flags
- ]);
- return MP4.box(MP4.types.trex, data);
- }
- // Movie fragment box
- }, {
- key: 'moof',
- value: function moof(track, baseMediaDecodeTime) {
- return MP4.box(MP4.types.moof, MP4.mfhd(track.sequenceNumber), MP4.traf(track, baseMediaDecodeTime));
- }
- }, {
- key: 'mfhd',
- value: function mfhd(sequenceNumber) {
- var data = new Uint8Array([0x00, 0x00, 0x00, 0x00, sequenceNumber >>> 24 & 0xFF, // sequence_number: int32
- sequenceNumber >>> 16 & 0xFF, sequenceNumber >>> 8 & 0xFF, sequenceNumber & 0xFF]);
- return MP4.box(MP4.types.mfhd, data);
- }
- // Track fragment box
- }, {
- key: 'traf',
- value: function traf(track, baseMediaDecodeTime) {
- var trackId = track.id;
- // Track fragment header box
- var tfhd = MP4.box(MP4.types.tfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) & flags
- trackId >>> 24 & 0xFF, // track_ID
- trackId >>> 16 & 0xFF, trackId >>> 8 & 0xFF, trackId & 0xFF]));
- // Track Fragment Decode Time
- var tfdt = MP4.box(MP4.types.tfdt, new Uint8Array([0x00, 0x00, 0x00, 0x00, // version(0) & flags
- baseMediaDecodeTime >>> 24 & 0xFF, // baseMediaDecodeTime: int32
- baseMediaDecodeTime >>> 16 & 0xFF, baseMediaDecodeTime >>> 8 & 0xFF, baseMediaDecodeTime & 0xFF]));
- var sdtp = MP4.sdtp(track);
- var trun = MP4.trun(track, sdtp.byteLength + 16 + 16 + 8 + 16 + 8 + 8);
- if (trackId === 1) {
- // console.log(trun)
- }
- return MP4.box(MP4.types.traf, tfhd, tfdt, trun, sdtp);
- }
- // Sample Dependency Type box
- }, {
- key: 'sdtp',
- value: function sdtp(track) {
- var samples = track.samples || [];
- var sampleCount = samples.length;
- var data = new Uint8Array(4 + sampleCount);
- // 0~4 bytes: version(0) & flags
- for (var i = 0; i < sampleCount; i++) {
- var flags = samples[i].flags;
- data[i + 4] = flags.isLeading << 6 | // is_leading: 2 (bit)
- flags.dependsOn << 4 | // sample_depends_on
- flags.isDependedOn << 2 | // sample_is_depended_on
- flags.hasRedundancy; // sample_has_redundancy
- }
- return MP4.box(MP4.types.sdtp, data);
- }
- // Track fragment run box
- }, {
- key: 'trun',
- value: function trun(track, offset) {
- var samples = track.samples || [];
- var sampleCount = samples.length;
- var dataSize = 12 + 16 * sampleCount;
- var data = new Uint8Array(dataSize);
- offset += 8 + dataSize;
- data.set([0x00, 0x00, 0x0F, 0x01, // version(0) & flags
- sampleCount >>> 24 & 0xFF, // sample_count
- sampleCount >>> 16 & 0xFF, sampleCount >>> 8 & 0xFF, sampleCount & 0xFF, offset >>> 24 & 0xFF, // data_offset
- offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF], 0);
- for (var i = 0; i < sampleCount; i++) {
- // console.log(samples[i].duration)
- var duration = samples[i].duration;
- var size = samples[i].size;
- var flags = samples[i].flags;
- var cts = samples[i].cts;
- data.set([duration >>> 24 & 0xFF, // sample_duration
- duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, size >>> 24 & 0xFF, // sample_size
- size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, flags.isLeading << 2 | flags.dependsOn, // sample_flags
- flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.isNonSync, 0x00, 0x00, // sample_degradation_priority
- cts >>> 24 & 0xFF, // sample_composition_time_offset
- cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF], 12 + 16 * i);
- }
- return MP4.box(MP4.types.trun, data);
- }
- }, {
- key: 'mdat',
- value: function mdat(data) {
- return MP4.box(MP4.types.mdat, data);
- }
- }]);
- return MP4;
- }();
- MP4.init();
- exports.default = MP4;
- module.exports = exports['default'];
- /***/ }),
- /* 42 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }();
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * This file is modified from dailymotion's hls.js library (hls.js/src/helper/aac.js)
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var AAC = function () {
- function AAC() {
- _classCallCheck(this, AAC);
- }
- _createClass(AAC, null, [{
- key: 'getSilentFrame',
- value: function getSilentFrame(codec, channelCount) {
- if (codec === 'mp4a.40.2') {
- // handle LC-AAC
- if (channelCount === 1) {
- return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
- } else if (channelCount === 2) {
- return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
- } else if (channelCount === 3) {
- return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
- } else if (channelCount === 4) {
- return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
- } else if (channelCount === 5) {
- return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
- } else if (channelCount === 6) {
- 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]);
- }
- } else {
- // handle HE-AAC (mp4a.40.5 / mp4a.40.29)
- if (channelCount === 1) {
- // 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
- 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]);
- } else if (channelCount === 2) {
- // 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
- 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]);
- } else if (channelCount === 3) {
- // 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
- 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]);
- }
- }
- return null;
- }
- }]);
- return AAC;
- }();
- exports.default = AAC;
- module.exports = exports['default'];
- /***/ }),
- /* 43 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var _logger = __webpack_require__(0);
- var _logger2 = _interopRequireDefault(_logger);
- var _loggingControl = __webpack_require__(8);
- var _loggingControl2 = _interopRequireDefault(_loggingControl);
- var _polyfill = __webpack_require__(11);
- var _polyfill2 = _interopRequireDefault(_polyfill);
- var _transmuxingController = __webpack_require__(14);
- var _transmuxingController2 = _interopRequireDefault(_transmuxingController);
- var _transmuxingEvents = __webpack_require__(5);
- var _transmuxingEvents2 = _interopRequireDefault(_transmuxingEvents);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /* post message to worker:
- data: {
- cmd: string
- param: any
- }
- receive message from worker:
- data: {
- msg: string,
- data: any
- }
- */
- var TransmuxingWorker = function TransmuxingWorker(self) {
- var TAG = 'TransmuxingWorker';
- var controller = null;
- var logcatListener = onLogcatCallback.bind(this);
- _polyfill2.default.install();
- self.addEventListener('message', function (e) {
- switch (e.data.cmd) {
- case 'init':
- controller = new _transmuxingController2.default(e.data.param[0], e.data.param[1]);
- controller.on(_transmuxingEvents2.default.IO_ERROR, onIOError.bind(this));
- controller.on(_transmuxingEvents2.default.DEMUX_ERROR, onDemuxError.bind(this));
- controller.on(_transmuxingEvents2.default.INIT_SEGMENT, onInitSegment.bind(this));
- controller.on(_transmuxingEvents2.default.MEDIA_SEGMENT, onMediaSegment.bind(this));
- controller.on(_transmuxingEvents2.default.LOADING_COMPLETE, onLoadingComplete.bind(this));
- controller.on(_transmuxingEvents2.default.RECOVERED_EARLY_EOF, onRecoveredEarlyEof.bind(this));
- controller.on(_transmuxingEvents2.default.MEDIA_INFO, onMediaInfo.bind(this));
- controller.on(_transmuxingEvents2.default.STATISTICS_INFO, onStatisticsInfo.bind(this));
- controller.on(_transmuxingEvents2.default.RECOMMEND_SEEKPOINT, onRecommendSeekpoint.bind(this));
- break;
- case 'destroy':
- if (controller) {
- controller.destroy();
- controller = null;
- }
- self.postMessage({ msg: 'destroyed' });
- break;
- case 'start':
- controller.start();
- break;
- case 'stop':
- controller.stop();
- break;
- case 'seek':
- controller.seek(e.data.param);
- break;
- case 'pause':
- controller.pause();
- break;
- case 'resume':
- controller.resume();
- break;
- case 'logging_config':
- {
- var config = e.data.param;
- _loggingControl2.default.applyConfig(config);
- if (config.enableCallback === true) {
- _loggingControl2.default.addLogListener(logcatListener);
- } else {
- _loggingControl2.default.removeLogListener(logcatListener);
- }
- break;
- }
- }
- });
- function onInitSegment(type, initSegment) {
- var obj = {
- msg: _transmuxingEvents2.default.INIT_SEGMENT,
- data: {
- type: type,
- data: initSegment
- }
- };
- self.postMessage(obj, [initSegment.data]); // data: ArrayBuffer
- }
- function onMediaSegment(type, mediaSegment) {
- var obj = {
- msg: _transmuxingEvents2.default.MEDIA_SEGMENT,
- data: {
- type: type,
- data: mediaSegment
- }
- };
- self.postMessage(obj, [mediaSegment.data]); // data: ArrayBuffer
- }
- function onLoadingComplete() {
- var obj = {
- msg: _transmuxingEvents2.default.LOADING_COMPLETE
- };
- self.postMessage(obj);
- }
- function onRecoveredEarlyEof() {
- var obj = {
- msg: _transmuxingEvents2.default.RECOVERED_EARLY_EOF
- };
- self.postMessage(obj);
- }
- function onMediaInfo(mediaInfo) {
- var obj = {
- msg: _transmuxingEvents2.default.MEDIA_INFO,
- data: mediaInfo
- };
- self.postMessage(obj);
- }
- function onStatisticsInfo(statInfo) {
- var obj = {
- msg: _transmuxingEvents2.default.STATISTICS_INFO,
- data: statInfo
- };
- self.postMessage(obj);
- }
- function onIOError(type, info) {
- self.postMessage({
- msg: _transmuxingEvents2.default.IO_ERROR,
- data: {
- type: type,
- info: info
- }
- });
- }
- function onDemuxError(type, info) {
- self.postMessage({
- msg: _transmuxingEvents2.default.DEMUX_ERROR,
- data: {
- type: type,
- info: info
- }
- });
- }
- function onRecommendSeekpoint(milliseconds) {
- self.postMessage({
- msg: _transmuxingEvents2.default.RECOMMEND_SEEKPOINT,
- data: milliseconds
- });
- }
- function onLogcatCallback(type, str) {
- self.postMessage({
- msg: 'logcat_callback',
- data: {
- type: type,
- logcat: str
- }
- });
- }
- }; /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- exports.default = TransmuxingWorker;
- module.exports = exports['default'];
- /***/ }),
- /* 44 */
- /***/ (function(module, exports) {
- var bundleFn = arguments[3];
- var sources = arguments[4];
- var cache = arguments[5];
- var stringify = JSON.stringify;
- module.exports = function (fn, options) {
- var wkey;
- var cacheKeys = Object.keys(cache);
- for (var i = 0, l = cacheKeys.length; i < l; i++) {
- var key = cacheKeys[i];
- var exp = cache[key].exports;
- // Using babel as a transpiler to use esmodule, the export will always
- // be an object with the default export as a property of it. To ensure
- // the existing api and babel esmodule exports are both supported we
- // check for both
- if (exp === fn || exp && exp.default === fn) {
- wkey = key;
- break;
- }
- }
- if (!wkey) {
- wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
- var wcache = {};
- for (var i = 0, l = cacheKeys.length; i < l; i++) {
- var key = cacheKeys[i];
- wcache[key] = key;
- }
- sources[wkey] = [
- 'function(require,module,exports){' + fn + '(self); }',
- wcache
- ];
- }
- var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
- var scache = {}; scache[wkey] = wkey;
- sources[skey] = [
- 'function(require,module,exports){' +
- // try to call default if defined to also support babel esmodule exports
- 'var f = require(' + stringify(wkey) + ');' +
- '(f.default ? f.default : f)(self);' +
- '}',
- scache
- ];
- var workerSources = {};
- resolveSources(skey);
- function resolveSources(key) {
- workerSources[key] = true;
- for (var depPath in sources[key][1]) {
- var depKey = sources[key][1][depPath];
- if (!workerSources[depKey]) {
- resolveSources(depKey);
- }
- }
- }
- var src = '(' + bundleFn + ')({'
- + Object.keys(workerSources).map(function (key) {
- return stringify(key) + ':['
- + sources[key][0]
- + ',' + stringify(sources[key][1]) + ']'
- ;
- }).join(',')
- + '},{},[' + stringify(skey) + '])'
- ;
- var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
- var blob = new Blob([src], { type: 'text/javascript' });
- if (options && options.bare) { return blob; }
- var workerUrl = URL.createObjectURL(blob);
- var worker = new Worker(workerUrl);
- worker.objectURL = workerUrl;
- return worker;
- };
- /***/ }),
- /* 45 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; }; }(); /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var _events = __webpack_require__(2);
- var _events2 = _interopRequireDefault(_events);
- var _logger = __webpack_require__(0);
- var _logger2 = _interopRequireDefault(_logger);
- var _browser = __webpack_require__(4);
- var _browser2 = _interopRequireDefault(_browser);
- var _mseEvents = __webpack_require__(16);
- var _mseEvents2 = _interopRequireDefault(_mseEvents);
- var _mediaSegmentInfo = __webpack_require__(15);
- var _exception = __webpack_require__(1);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- // Media Source Extensions controller
- var MSEController = function () {
- function MSEController(config) {
- _classCallCheck(this, MSEController);
- this.TAG = 'MSEController';
- this._config = config;
- this._emitter = new _events2.default();
- if (this._config.isLive && this._config.autoCleanupSourceBuffer == undefined) {
- // For live stream, do auto cleanup by default
- this._config.autoCleanupSourceBuffer = true;
- }
- this.e = {
- onSourceOpen: this._onSourceOpen.bind(this),
- onSourceEnded: this._onSourceEnded.bind(this),
- onSourceClose: this._onSourceClose.bind(this),
- onSourceBufferError: this._onSourceBufferError.bind(this),
- onSourceBufferUpdateEnd: this._onSourceBufferUpdateEnd.bind(this)
- };
- this._mediaSource = null;
- this._mediaSourceObjectURL = null;
- this._mediaElement = null;
- this._isBufferFull = false;
- this._hasPendingEos = false;
- this._requireSetMediaDuration = false;
- this._pendingMediaDuration = 0;
- this._pendingSourceBufferInit = [];
- this._mimeTypes = {
- video: null,
- audio: null
- };
- this._sourceBuffers = {
- video: null,
- audio: null
- };
- this._lastInitSegments = {
- video: null,
- audio: null
- };
- this._pendingSegments = {
- video: [],
- audio: []
- };
- this._pendingRemoveRanges = {
- video: [],
- audio: []
- };
- this._idrList = new _mediaSegmentInfo.IDRSampleList();
- }
- _createClass(MSEController, [{
- key: 'destroy',
- value: function destroy() {
- if (this._mediaElement || this._mediaSource) {
- this.detachMediaElement();
- }
- this.e = null;
- this._emitter.removeAllListeners();
- this._emitter = null;
- }
- }, {
- key: 'on',
- value: function on(event, listener) {
- this._emitter.addListener(event, listener);
- }
- }, {
- key: 'off',
- value: function off(event, listener) {
- this._emitter.removeListener(event, listener);
- }
- }, {
- key: 'attachMediaElement',
- value: function attachMediaElement(mediaElement) {
- if (this._mediaSource) {
- throw new _exception.IllegalStateException('MediaSource has been attached to an HTMLMediaElement!');
- }
- var ms = this._mediaSource = new window.MediaSource();
- ms.addEventListener('sourceopen', this.e.onSourceOpen);
- ms.addEventListener('sourceended', this.e.onSourceEnded);
- ms.addEventListener('sourceclose', this.e.onSourceClose);
- this._mediaElement = mediaElement;
- this._mediaSourceObjectURL = window.URL.createObjectURL(this._mediaSource);
- mediaElement.src = this._mediaSourceObjectURL;
- }
- }, {
- key: 'detachMediaElement',
- value: function detachMediaElement() {
- if (this._mediaSource) {
- var ms = this._mediaSource;
- for (var type in this._sourceBuffers) {
- // pending segments should be discard
- var ps = this._pendingSegments[type];
- ps.splice(0, ps.length);
- this._pendingSegments[type] = null;
- this._pendingRemoveRanges[type] = null;
- this._lastInitSegments[type] = null;
- // remove all sourcebuffers
- var sb = this._sourceBuffers[type];
- if (sb) {
- if (ms.readyState !== 'closed') {
- ms.removeSourceBuffer(sb);
- sb.removeEventListener('error', this.e.onSourceBufferError);
- sb.removeEventListener('updateend', this.e.onSourceBufferUpdateEnd);
- }
- this._mimeTypes[type] = null;
- this._sourceBuffers[type] = null;
- }
- }
- if (ms.readyState === 'open') {
- try {
- ms.endOfStream();
- } catch (error) {
- _logger2.default.e(this.TAG, error.message);
- }
- }
- ms.removeEventListener('sourceopen', this.e.onSourceOpen);
- ms.removeEventListener('sourceended', this.e.onSourceEnded);
- ms.removeEventListener('sourceclose', this.e.onSourceClose);
- this._pendingSourceBufferInit = [];
- this._isBufferFull = false;
- this._idrList.clear();
- this._mediaSource = null;
- }
- if (this._mediaElement) {
- this._mediaElement.src = '';
- this._mediaElement.removeAttribute('src');
- this._mediaElement = null;
- }
- if (this._mediaSourceObjectURL) {
- window.URL.revokeObjectURL(this._mediaSourceObjectURL);
- this._mediaSourceObjectURL = null;
- }
- }
- }, {
- key: 'appendInitSegment',
- value: function appendInitSegment(initSegment, deferred) {
- if (!this._mediaSource || this._mediaSource.readyState !== 'open') {
- // sourcebuffer creation requires mediaSource.readyState === 'open'
- // so we defer the sourcebuffer creation, until sourceopen event triggered
- this._pendingSourceBufferInit.push(initSegment);
- // make sure that this InitSegment is in the front of pending segments queue
- this._pendingSegments[initSegment.type].push(initSegment);
- // console.log(`${initSegment.type}`, initSegment)
- return;
- }
- var is = initSegment;
- var mimeType = '' + is.container;
- if (is.codec && is.codec.length > 0) {
- mimeType += ';codecs=' + is.codec;
- }
- var firstInitSegment = false;
- _logger2.default.v(this.TAG, 'Received Initialization Segment, mimeType: ' + mimeType);
- this._lastInitSegments[is.type] = is;
- if (mimeType !== this._mimeTypes[is.type]) {
- if (!this._mimeTypes[is.type]) {
- // empty, first chance create sourcebuffer
- firstInitSegment = true;
- try {
- var sb = this._sourceBuffers[is.type] = this._mediaSource.addSourceBuffer(mimeType);
- sb.addEventListener('error', this.e.onSourceBufferError);
- sb.addEventListener('updateend', this.e.onSourceBufferUpdateEnd);
- } catch (error) {
- _logger2.default.e(this.TAG, error.message);
- this._emitter.emit(_mseEvents2.default.ERROR, { code: error.code, msg: error.message });
- return;
- }
- } else {
- _logger2.default.v(this.TAG, 'Notice: ' + is.type + ' mimeType changed, origin: ' + this._mimeTypes[is.type] + ', target: ' + mimeType);
- }
- this._mimeTypes[is.type] = mimeType;
- }
- if (!deferred) {
- // deferred means this InitSegment has been pushed to pendingSegments queue
- this._pendingSegments[is.type].push(is);
- }
- if (!firstInitSegment) {
- // append immediately only if init segment in subsequence
- if (this._sourceBuffers[is.type] && !this._sourceBuffers[is.type].updating) {
- this._doAppendSegments();
- }
- }
- if (_browser2.default.safari && is.container === 'audio/mpeg' && is.mediaDuration > 0) {
- // 'audio/mpeg' track under Safari may cause MediaElement's duration to be NaN
- // Manually correct MediaSource.duration to make progress bar seekable, and report right duration
- this._requireSetMediaDuration = true;
- this._pendingMediaDuration = is.mediaDuration / 1000; // in seconds
- this._updateMediaSourceDuration();
- }
- }
- }, {
- key: 'appendMediaSegment',
- value: function appendMediaSegment(mediaSegment) {
- var ms = mediaSegment;
- this._pendingSegments[ms.type].push(ms);
- if (this._config.autoCleanupSourceBuffer && this._needCleanupSourceBuffer()) {
- this._doCleanupSourceBuffer();
- }
- var sb = this._sourceBuffers[ms.type];
- if (sb && !sb.updating && !this._hasPendingRemoveRanges()) {
- this._doAppendSegments();
- }
- }
- }, {
- key: 'seek',
- value: function seek(seconds) {
- // remove all appended buffers
- for (var type in this._sourceBuffers) {
- if (!this._sourceBuffers[type]) {
- continue;
- }
- // abort current buffer append algorithm
- var sb = this._sourceBuffers[type];
- if (this._mediaSource.readyState === 'open') {
- try {
- // If range removal algorithm is running, InvalidStateError will be throwed
- // Ignore it.
- sb.abort();
- } catch (error) {
- _logger2.default.e(this.TAG, error.message);
- }
- }
- // IDRList should be clear
- this._idrList.clear();
- // pending segments should be discard
- var ps = this._pendingSegments[type];
- ps.splice(0, ps.length);
- if (this._mediaSource.readyState === 'closed') {
- // Parent MediaSource object has been detached from HTMLMediaElement
- continue;
- }
- // record ranges to be remove from SourceBuffer
- for (var i = 0; i < sb.buffered.length; i++) {
- var start = sb.buffered.start(i);
- var end = sb.buffered.end(i);
- this._pendingRemoveRanges[type].push({ start: start, end: end });
- }
- // if sb is not updating, let's remove ranges now!
- if (!sb.updating) {
- this._doRemoveRanges();
- }
- // Safari 10 may get InvalidStateError in the later appendBuffer() after SourceBuffer.remove() call
- // Internal parser's state may be invalid at this time. Re-append last InitSegment to workaround.
- // Related issue: https://bugs.webkit.org/show_bug.cgi?id=159230
- if (_browser2.default.safari) {
- var lastInitSegment = this._lastInitSegments[type];
- if (lastInitSegment) {
- this._pendingSegments[type].push(lastInitSegment);
- if (!sb.updating) {
- this._doAppendSegments();
- }
- }
- }
- }
- }
- }, {
- key: 'endOfStream',
- value: function endOfStream() {
- var ms = this._mediaSource;
- var sb = this._sourceBuffers;
- if (!ms || ms.readyState !== 'open') {
- if (ms && ms.readyState === 'closed' && this._hasPendingSegments()) {
- // If MediaSource hasn't turned into open state, and there're pending segments
- // Mark pending endOfStream, defer call until all pending segments appended complete
- this._hasPendingEos = true;
- }
- return;
- }
- if (sb.video && sb.video.updating || sb.audio && sb.audio.updating) {
- // If any sourcebuffer is updating, defer endOfStream operation
- // See _onSourceBufferUpdateEnd()
- this._hasPendingEos = true;
- } else {
- this._hasPendingEos = false;
- // Notify media data loading complete
- // This is helpful for correcting total duration to match last media segment
- // Otherwise MediaElement's ended event may not be triggered
- ms.endOfStream();
- }
- }
- }, {
- key: 'getNearestKeyframe',
- value: function getNearestKeyframe(dts) {
- return this._idrList.getLastSyncPointBeforeDts(dts);
- }
- }, {
- key: '_needCleanupSourceBuffer',
- value: function _needCleanupSourceBuffer() {
- if (!this._config.autoCleanupSourceBuffer) {
- return false;
- }
- var currentTime = this._mediaElement.currentTime;
- for (var type in this._sourceBuffers) {
- var sb = this._sourceBuffers[type];
- if (sb) {
- var buffered = sb.buffered;
- if (buffered.length >= 1) {
- if (currentTime - buffered.start(0) >= this._config.autoCleanupMaxBackwardDuration) {
- return true;
- }
- }
- }
- }
- return false;
- }
- }, {
- key: '_doCleanupSourceBuffer',
- value: function _doCleanupSourceBuffer() {
- var currentTime = this._mediaElement.currentTime;
- for (var type in this._sourceBuffers) {
- var sb = this._sourceBuffers[type];
- if (sb) {
- var buffered = sb.buffered;
- var doRemove = false;
- for (var i = 0; i < buffered.length; i++) {
- var start = buffered.start(i);
- var end = buffered.end(i);
- if (start <= currentTime && currentTime < end + 3) {
- // padding 3 seconds
- if (currentTime - start >= this._config.autoCleanupMaxBackwardDuration) {
- doRemove = true;
- var removeEnd = currentTime - this._config.autoCleanupMinBackwardDuration;
- this._pendingRemoveRanges[type].push({ start: start, end: removeEnd });
- }
- } else if (end < currentTime) {
- doRemove = true;
- this._pendingRemoveRanges[type].push({ start: start, end: end });
- }
- }
- if (doRemove && !sb.updating) {
- this._doRemoveRanges();
- }
- }
- }
- }
- }, {
- key: '_updateMediaSourceDuration',
- value: function _updateMediaSourceDuration() {
- var sb = this._sourceBuffers;
- if (this._mediaElement.readyState === 0 || this._mediaSource.readyState !== 'open') {
- return;
- }
- if (sb.video && sb.video.updating || sb.audio && sb.audio.updating) {
- return;
- }
- var current = this._mediaSource.duration;
- var target = this._pendingMediaDuration;
- if (target > 0 && (isNaN(current) || target > current)) {
- _logger2.default.v(this.TAG, 'Update MediaSource duration from ' + current + ' to ' + target);
- this._mediaSource.duration = target;
- }
- this._requireSetMediaDuration = false;
- this._pendingMediaDuration = 0;
- }
- }, {
- key: '_doRemoveRanges',
- value: function _doRemoveRanges() {
- for (var type in this._pendingRemoveRanges) {
- if (!this._sourceBuffers[type] || this._sourceBuffers[type].updating) {
- continue;
- }
- var sb = this._sourceBuffers[type];
- var ranges = this._pendingRemoveRanges[type];
- while (ranges.length && !sb.updating) {
- var range = ranges.shift();
- sb.remove(range.start, range.end);
- }
- }
- }
- }, {
- key: '_doAppendSegments',
- value: function _doAppendSegments() {
- var pendingSegments = this._pendingSegments;
- for (var type in pendingSegments) {
- if (!this._sourceBuffers[type] || this._sourceBuffers[type].updating) {
- continue;
- }
- if (pendingSegments[type].length > 0) {
- var segment = pendingSegments[type].shift();
- if (segment.timestampOffset) {
- // For MPEG audio stream in MSE, if unbuffered-seeking occurred
- // We need explicitly set timestampOffset to the desired point in timeline for mpeg SourceBuffer.
- var currentOffset = this._sourceBuffers[type].timestampOffset;
- var targetOffset = segment.timestampOffset / 1000; // in seconds
- var delta = Math.abs(currentOffset - targetOffset);
- if (delta > 0.1) {
- // If time delta > 100ms
- _logger2.default.v(this.TAG, 'Update MPEG audio timestampOffset from ' + currentOffset + ' to ' + targetOffset);
- this._sourceBuffers[type].timestampOffset = targetOffset;
- }
- delete segment.timestampOffset;
- }
- if (!segment.data || segment.data.byteLength === 0) {
- // Ignore empty buffer
- continue;
- }
- try {
- this._sourceBuffers[type].appendBuffer(segment.data);
- this._isBufferFull = false;
- if (type === 'video' && segment.hasOwnProperty('info')) {
- this._idrList.appendArray(segment.info.syncPoints);
- }
- } catch (error) {
- this._pendingSegments[type].unshift(segment);
- if (error.code === 22) {
- // QuotaExceededError
- /* Notice that FireFox may not throw QuotaExceededError if SourceBuffer is full
- * Currently we can only do lazy-load to avoid SourceBuffer become scattered.
- * SourceBuffer eviction policy may be changed in future version of FireFox.
- *
- * Related issues:
- * https://bugzilla.mozilla.org/show_bug.cgi?id=1279885
- * https://bugzilla.mozilla.org/show_bug.cgi?id=1280023
- */
- // report buffer full, abort network IO
- if (!this._isBufferFull) {
- this._emitter.emit(_mseEvents2.default.BUFFER_FULL);
- }
- this._isBufferFull = true;
- } else {
- _logger2.default.e(this.TAG, error.message);
- this._emitter.emit(_mseEvents2.default.ERROR, { code: error.code, msg: error.message });
- }
- }
- }
- }
- }
- }, {
- key: '_onSourceOpen',
- value: function _onSourceOpen() {
- _logger2.default.v(this.TAG, 'MediaSource onSourceOpen');
- this._mediaSource.removeEventListener('sourceopen', this.e.onSourceOpen);
- // deferred sourcebuffer creation / initialization
- if (this._pendingSourceBufferInit.length > 0) {
- var pendings = this._pendingSourceBufferInit;
- while (pendings.length) {
- var segment = pendings.shift();
- this.appendInitSegment(segment, true);
- }
- }
- // there may be some pending media segments, append them
- if (this._hasPendingSegments()) {
- this._doAppendSegments();
- }
- this._emitter.emit(_mseEvents2.default.SOURCE_OPEN);
- }
- }, {
- key: '_onSourceEnded',
- value: function _onSourceEnded() {
- // fired on endOfStream
- _logger2.default.v(this.TAG, 'MediaSource onSourceEnded');
- }
- }, {
- key: '_onSourceClose',
- value: function _onSourceClose() {
- // fired on detaching from media element
- _logger2.default.v(this.TAG, 'MediaSource onSourceClose');
- if (this._mediaSource && this.e != null) {
- this._mediaSource.removeEventListener('sourceopen', this.e.onSourceOpen);
- this._mediaSource.removeEventListener('sourceended', this.e.onSourceEnded);
- this._mediaSource.removeEventListener('sourceclose', this.e.onSourceClose);
- }
- }
- }, {
- key: '_hasPendingSegments',
- value: function _hasPendingSegments() {
- var ps = this._pendingSegments;
- return ps.video.length > 0 || ps.audio.length > 0;
- }
- }, {
- key: '_hasPendingRemoveRanges',
- value: function _hasPendingRemoveRanges() {
- var prr = this._pendingRemoveRanges;
- return prr.video.length > 0 || prr.audio.length > 0;
- }
- }, {
- key: '_onSourceBufferUpdateEnd',
- value: function _onSourceBufferUpdateEnd() {
- if (this._requireSetMediaDuration) {
- this._updateMediaSourceDuration();
- } else if (this._hasPendingRemoveRanges()) {
- this._doRemoveRanges();
- } else if (this._hasPendingSegments()) {
- this._doAppendSegments();
- } else if (this._hasPendingEos) {
- this.endOfStream();
- }
- this._emitter.emit(_mseEvents2.default.UPDATE_END);
- }
- }, {
- key: '_onSourceBufferError',
- value: function _onSourceBufferError(e) {
- _logger2.default.e(this.TAG, 'SourceBuffer Error: ' + e);
- // this error might not always be fatal, just ignore it
- }
- }]);
- return MSEController;
- }();
- exports.default = MSEController;
- module.exports = exports['default'];
- /***/ }),
- /* 46 */
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- 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; };
- 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; }; }(); /*
- * Copyright (C) 2016 Bilibili. All Rights Reserved.
- *
- * @author zheng qian <xqq@xqq.im>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var _events = __webpack_require__(2);
- var _events2 = _interopRequireDefault(_events);
- var _playerEvents = __webpack_require__(7);
- var _playerEvents2 = _interopRequireDefault(_playerEvents);
- var _config = __webpack_require__(6);
- var _exception = __webpack_require__(1);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- // Player wrapper for browser's native player (HTMLVideoElement) without MediaSource src.
- var NativePlayer = function () {
- function NativePlayer(mediaDataSource, config) {
- _classCallCheck(this, NativePlayer);
- this.TAG = 'NativePlayer';
- this._type = 'NativePlayer';
- this._emitter = new _events2.default();
- this._config = (0, _config.createDefaultConfig)();
- if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object') {
- Object.assign(this._config, config);
- }
- if (mediaDataSource.type.toLowerCase() === 'flv') {
- throw new _exception.InvalidArgumentException('NativePlayer does\'t support flv MediaDataSource input!');
- }
- if (mediaDataSource.hasOwnProperty('segments')) {
- throw new _exception.InvalidArgumentException('NativePlayer(' + mediaDataSource.type + ') doesn\'t support multipart playback!');
- }
- this.e = {
- onvLoadedMetadata: this._onvLoadedMetadata.bind(this)
- };
- this._pendingSeekTime = null;
- this._statisticsReporter = null;
- this._mediaDataSource = mediaDataSource;
- this._mediaElement = null;
- }
- _createClass(NativePlayer, [{
- key: 'destroy',
- value: function destroy() {
- if (this._mediaElement) {
- this.unload();
- this.detachMediaElement();
- }
- this.e = null;
- this._mediaDataSource = null;
- this._emitter.removeAllListeners();
- this._emitter = null;
- }
- }, {
- key: 'on',
- value: function on(event, listener) {
- var _this = this;
- if (event === _playerEvents2.default.MEDIA_INFO) {
- if (this._mediaElement != null && this._mediaElement.readyState !== 0) {
- // HAVE_NOTHING
- Promise.resolve().then(function () {
- _this._emitter.emit(_playerEvents2.default.MEDIA_INFO, _this.mediaInfo);
- });
- }
- } else if (event === _playerEvents2.default.STATISTICS_INFO) {
- if (this._mediaElement != null && this._mediaElement.readyState !== 0) {
- Promise.resolve().then(function () {
- _this._emitter.emit(_playerEvents2.default.STATISTICS_INFO, _this.statisticsInfo);
- });
- }
- }
- this._emitter.addListener(event, listener);
- }
- }, {
- key: 'off',
- value: function off(event, listener) {
- this._emitter.removeListener(event, listener);
- }
- }, {
- key: 'attachMediaElement',
- value: function attachMediaElement(mediaElement) {
- this._mediaElement = mediaElement;
- mediaElement.addEventListener('loadedmetadata', this.e.onvLoadedMetadata);
- if (this._pendingSeekTime != null) {
- try {
- mediaElement.currentTime = this._pendingSeekTime;
- this._pendingSeekTime = null;
- } catch (e) {
- // IE11 may throw InvalidStateError if readyState === 0
- // Defer set currentTime operation after loadedmetadata
- }
- }
- }
- }, {
- key: 'detachMediaElement',
- value: function detachMediaElement() {
- if (this._mediaElement) {
- this._mediaElement.src = '';
- this._mediaElement.removeAttribute('src');
- this._mediaElement.removeEventListener('loadedmetadata', this.e.onvLoadedMetadata);
- this._mediaElement = null;
- }
- if (this._statisticsReporter != null) {
- window.clearInterval(this._statisticsReporter);
- this._statisticsReporter = null;
- }
- }
- }, {
- key: 'load',
- value: function load() {
- if (!this._mediaElement) {
- throw new _exception.IllegalStateException('HTMLMediaElement must be attached before load()!');
- }
- this._mediaElement.src = this._mediaDataSource.url;
- if (this._mediaElement.readyState > 0) {
- this._mediaElement.currentTime = 0;
- }
- this._mediaElement.preload = 'auto';
- this._mediaElement.load();
- this._statisticsReporter = window.setInterval(this._reportStatisticsInfo.bind(this), this._config.statisticsInfoReportInterval);
- }
- }, {
- key: 'unload',
- value: function unload() {
- if (this._mediaElement) {
- this._mediaElement.src = '';
- this._mediaElement.removeAttribute('src');
- }
- if (this._statisticsReporter != null) {
- window.clearInterval(this._statisticsReporter);
- this._statisticsReporter = null;
- }
- }
- }, {
- key: 'play',
- value: function play() {
- var playPromise = this._mediaElement.play();
- if (playPromise !== undefined && playPromise) {
- return playPromise.catch(function () {});
- } else return undefined;
- }
- }, {
- key: 'pause',
- value: function pause() {
- this._mediaElement.pause();
- }
- }, {
- key: '_onvLoadedMetadata',
- value: function _onvLoadedMetadata(e) {
- if (this._pendingSeekTime != null) {
- this._mediaElement.currentTime = this._pendingSeekTime;
- this._pendingSeekTime = null;
- }
- this._emitter.emit(_playerEvents2.default.MEDIA_INFO, this.mediaInfo);
- }
- }, {
- key: '_reportStatisticsInfo',
- value: function _reportStatisticsInfo() {
- this._emitter.emit(_playerEvents2.default.STATISTICS_INFO, this.statisticsInfo);
- }
- }, {
- key: 'type',
- get: function get() {
- return this._type;
- }
- }, {
- key: 'buffered',
- get: function get() {
- return this._mediaElement.buffered;
- }
- }, {
- key: 'duration',
- get: function get() {
- return this._mediaElement.duration;
- }
- }, {
- key: 'volume',
- get: function get() {
- return this._mediaElement.volume;
- },
- set: function set(value) {
- this._mediaElement.volume = value;
- }
- }, {
- key: 'muted',
- get: function get() {
- return this._mediaElement.muted;
- },
- set: function set(muted) {
- this._mediaElement.muted = muted;
- }
- }, {
- key: 'currentTime',
- get: function get() {
- if (this._mediaElement) {
- return this._mediaElement.currentTime;
- }
- return 0;
- },
- set: function set(seconds) {
- if (this._mediaElement) {
- this._mediaElement.currentTime = seconds;
- } else {
- this._pendingSeekTime = seconds;
- }
- }
- }, {
- key: 'mediaInfo',
- get: function get() {
- var mediaPrefix = this._mediaElement instanceof HTMLAudioElement ? 'audio/' : 'video/';
- var info = {
- mimeType: mediaPrefix + this._mediaDataSource.type
- };
- if (this._mediaElement) {
- info.duration = Math.floor(this._mediaElement.duration * 1000);
- if (this._mediaElement instanceof HTMLVideoElement) {
- info.width = this._mediaElement.videoWidth;
- info.height = this._mediaElement.videoHeight;
- }
- }
- return info;
- }
- }, {
- key: 'statisticsInfo',
- get: function get() {
- var info = {
- playerType: this._type,
- url: this._mediaDataSource.url
- };
- if (!(this._mediaElement instanceof HTMLVideoElement)) {
- return info;
- }
- var hasQualityInfo = true;
- var decoded = 0;
- var dropped = 0;
- if (this._mediaElement.getVideoPlaybackQuality) {
- var quality = this._mediaElement.getVideoPlaybackQuality();
- decoded = quality.totalVideoFrames;
- dropped = quality.droppedVideoFrames;
- } else if (this._mediaElement.webkitDecodedFrameCount != undefined) {
- decoded = this._mediaElement.webkitDecodedFrameCount;
- dropped = this._mediaElement.webkitDroppedFrameCount;
- } else {
- hasQualityInfo = false;
- }
- if (hasQualityInfo) {
- info.decodedFrames = decoded;
- info.droppedFrames = dropped;
- }
- return info;
- }
- }]);
- return NativePlayer;
- }();
- exports.default = NativePlayer;
- module.exports = exports['default'];
- /***/ })
- /******/ ]);
- });
- /***/ }),
- /***/ "c04e":
- /***/ (function(module, exports, __webpack_require__) {
- var isObject = __webpack_require__("861d");
- // `ToPrimitive` abstract operation
- // https://tc39.github.io/ecma262/#sec-toprimitive
- // instead of the ES6 spec version, we didn't implement @@toPrimitive case
- // and the second argument - flag - preferred type is a string
- module.exports = function (input, PREFERRED_STRING) {
- if (!isObject(input)) return input;
- var fn, val;
- if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
- if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;
- if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
- throw TypeError("Can't convert object to primitive value");
- };
- /***/ }),
- /***/ "c430":
- /***/ (function(module, exports) {
- module.exports = false;
- /***/ }),
- /***/ "c6b6":
- /***/ (function(module, exports) {
- var toString = {}.toString;
- module.exports = function (it) {
- return toString.call(it).slice(8, -1);
- };
- /***/ }),
- /***/ "c6cd":
- /***/ (function(module, exports, __webpack_require__) {
- var global = __webpack_require__("da84");
- var setGlobal = __webpack_require__("ce4e");
- var SHARED = '__core-js_shared__';
- var store = global[SHARED] || setGlobal(SHARED, {});
- module.exports = store;
- /***/ }),
- /***/ "c8ba":
- /***/ (function(module, exports) {
- var g;
- // This works in non-strict mode
- g = (function() {
- return this;
- })();
- try {
- // This works if eval is allowed (see CSP)
- g = g || new Function("return this")();
- } catch (e) {
- // This works if the window reference is available
- if (typeof window === "object") g = window;
- }
- // g can still be undefined, but nothing to do about it...
- // We return undefined, instead of nothing here, so it's
- // easier to handle this case. if(!global) { ...}
- module.exports = g;
- /***/ }),
- /***/ "ca84":
- /***/ (function(module, exports, __webpack_require__) {
- var has = __webpack_require__("5135");
- var toIndexedObject = __webpack_require__("fc6a");
- var indexOf = __webpack_require__("4d64").indexOf;
- var hiddenKeys = __webpack_require__("d012");
- module.exports = function (object, names) {
- var O = toIndexedObject(object);
- var i = 0;
- var result = [];
- var key;
- for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key);
- // Don't enum bug & hidden keys
- while (names.length > i) if (has(O, key = names[i++])) {
- ~indexOf(result, key) || result.push(key);
- }
- return result;
- };
- /***/ }),
- /***/ "cc12":
- /***/ (function(module, exports, __webpack_require__) {
- var global = __webpack_require__("da84");
- var isObject = __webpack_require__("861d");
- var document = global.document;
- // typeof document.createElement is 'object' in old IE
- var EXISTS = isObject(document) && isObject(document.createElement);
- module.exports = function (it) {
- return EXISTS ? document.createElement(it) : {};
- };
- /***/ }),
- /***/ "cca6":
- /***/ (function(module, exports, __webpack_require__) {
- var $ = __webpack_require__("23e7");
- var assign = __webpack_require__("60da");
- // `Object.assign` method
- // https://tc39.github.io/ecma262/#sec-object.assign
- $({ target: 'Object', stat: true, forced: Object.assign !== assign }, {
- assign: assign
- });
- /***/ }),
- /***/ "ce4e":
- /***/ (function(module, exports, __webpack_require__) {
- var global = __webpack_require__("da84");
- var createNonEnumerableProperty = __webpack_require__("9112");
- module.exports = function (key, value) {
- try {
- createNonEnumerableProperty(global, key, value);
- } catch (error) {
- global[key] = value;
- } return value;
- };
- /***/ }),
- /***/ "d012":
- /***/ (function(module, exports) {
- module.exports = {};
- /***/ }),
- /***/ "d039":
- /***/ (function(module, exports) {
- module.exports = function (exec) {
- try {
- return !!exec();
- } catch (error) {
- return true;
- }
- };
- /***/ }),
- /***/ "d066":
- /***/ (function(module, exports, __webpack_require__) {
- var path = __webpack_require__("428f");
- var global = __webpack_require__("da84");
- var aFunction = function (variable) {
- return typeof variable == 'function' ? variable : undefined;
- };
- module.exports = function (namespace, method) {
- return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global[namespace])
- : path[namespace] && path[namespace][method] || global[namespace] && global[namespace][method];
- };
- /***/ }),
- /***/ "d1e7":
- /***/ (function(module, exports, __webpack_require__) {
- "use strict";
- var nativePropertyIsEnumerable = {}.propertyIsEnumerable;
- var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
- // Nashorn ~ JDK8 bug
- var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1);
- // `Object.prototype.propertyIsEnumerable` method implementation
- // https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable
- exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
- var descriptor = getOwnPropertyDescriptor(this, V);
- return !!descriptor && descriptor.enumerable;
- } : nativePropertyIsEnumerable;
- /***/ }),
- /***/ "da84":
- /***/ (function(module, exports, __webpack_require__) {
- /* WEBPACK VAR INJECTION */(function(global) {var check = function (it) {
- return it && it.Math == Math && it;
- };
- // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
- module.exports =
- // eslint-disable-next-line no-undef
- check(typeof globalThis == 'object' && globalThis) ||
- check(typeof window == 'object' && window) ||
- check(typeof self == 'object' && self) ||
- check(typeof global == 'object' && global) ||
- // eslint-disable-next-line no-new-func
- Function('return this')();
- /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__("c8ba")))
- /***/ }),
- /***/ "df75":
- /***/ (function(module, exports, __webpack_require__) {
- var internalObjectKeys = __webpack_require__("ca84");
- var enumBugKeys = __webpack_require__("7839");
- // `Object.keys` method
- // https://tc39.github.io/ecma262/#sec-object.keys
- module.exports = Object.keys || function keys(O) {
- return internalObjectKeys(O, enumBugKeys);
- };
- /***/ }),
- /***/ "e893":
- /***/ (function(module, exports, __webpack_require__) {
- var has = __webpack_require__("5135");
- var ownKeys = __webpack_require__("56ef");
- var getOwnPropertyDescriptorModule = __webpack_require__("06cf");
- var definePropertyModule = __webpack_require__("9bf2");
- module.exports = function (target, source) {
- var keys = ownKeys(source);
- var defineProperty = definePropertyModule.f;
- var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
- for (var i = 0; i < keys.length; i++) {
- var key = keys[i];
- if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
- }
- };
- /***/ }),
- /***/ "f772":
- /***/ (function(module, exports, __webpack_require__) {
- var shared = __webpack_require__("5692");
- var uid = __webpack_require__("90e3");
- var keys = shared('keys');
- module.exports = function (key) {
- return keys[key] || (keys[key] = uid(key));
- };
- /***/ }),
- /***/ "fae3":
- /***/ (function(module, __webpack_exports__, __webpack_require__) {
- "use strict";
- // ESM COMPAT FLAG
- __webpack_require__.r(__webpack_exports__);
- // EXPORTS
- __webpack_require__.d(__webpack_exports__, "Mp4", function() { return /* reexport */ Mp4; });
- __webpack_require__.d(__webpack_exports__, "Hls", function() { return /* reexport */ Hls; });
- __webpack_require__.d(__webpack_exports__, "Flv", function() { return /* reexport */ Flv; });
- // CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/setPublicPath.js
- // This file is imported into lib/wc client bundles.
- if (typeof window !== 'undefined') {
- var currentScript = window.document.currentScript
- if (true) {
- var getCurrentScript = __webpack_require__("8875")
- currentScript = getCurrentScript()
- // for backward compatibility, because previously we directly included the polyfill
- if (!('currentScript' in document)) {
- Object.defineProperty(document, 'currentScript', { get: getCurrentScript })
- }
- }
- var src = currentScript && currentScript.src.match(/(.+\/)[^/]+\.js(\?.*)?$/)
- if (src) {
- __webpack_require__.p = src[1] // eslint-disable-line
- }
- }
- // Indicate to webpack that this file can be concatenated
- /* harmony default export */ var setPublicPath = (null);
- // 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&
- 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}})}
- var staticRenderFns = []
- // CONCATENATED MODULE: ./src/components/Mp4.vue?vue&type=template&id=cedd472c&
- // EXTERNAL MODULE: ./node_modules/core-js/modules/es.object.assign.js
- var es_object_assign = __webpack_require__("cca6");
- // EXTERNAL MODULE: ./node_modules/xgplayer/dist/index.js
- var dist = __webpack_require__("5392");
- var dist_default = /*#__PURE__*/__webpack_require__.n(dist);
- // 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&
- //
- //
- //
- //
- /* harmony default export */ var Mp4vue_type_script_lang_js_ = ({
- name: "Mp4",
- props: {
- config: {
- type: Object,
- default: function _default() {
- return {
- id: "mse",
- url: ""
- };
- }
- },
- rootStyle: {
- type: Object,
- default: function _default() {
- return {};
- }
- }
- },
- data: function data() {
- return {
- player: null,
- finalConfig: {
- volume: 0,
- autoplayMuted: true,
- //解决浏览器非静音阻止自动播放机制
- autoplay: true,
- //自动播放
- loop: true,
- //循环播放
- fluid: true,
- //流式布局
- videoInit: true,
- //加载首屏
- playbackRate: [0.5, 0.75, 1, 1.5, 2],
- //快进设置
- pip: true,
- //画中画
- screenShot: true,
- //开启截屏
- lang: "zh-cn",
- enterLogo: {
- url: "",
- width: 231,
- height: 42
- },
- enterBg: {
- color: "rgba(0,0,0,0.87)"
- },
- enterTips: {
- background: "linear-gradient(to right, rgba(0,0,0,0.87), #3D96FD, rgba(86,195,248), #3D96FD, rgba(0,0,0,0.87))"
- }
- }
- };
- },
- mounted: function mounted() {
- this.init();
- },
- beforeUpdate: function beforeUpdate() {
- this.init();
- },
- beforeDestroy: function beforeDestroy() {
- this.player && typeof this.player.destroy === "function" && this.player.destroy();
- },
- methods: {
- init: function init() {
- this.finalConfig = Object.assign(this.finalConfig, this.config);
- if (this.finalConfig.url && this.finalConfig.url !== "") {
- this.player = new dist_default.a(this.finalConfig);
- this.$emit("player", this.player);
- }
- }
- }
- });
- // CONCATENATED MODULE: ./src/components/Mp4.vue?vue&type=script&lang=js&
- /* harmony default export */ var components_Mp4vue_type_script_lang_js_ = (Mp4vue_type_script_lang_js_);
- // CONCATENATED MODULE: ./node_modules/vue-loader/lib/runtime/componentNormalizer.js
- /* globals __VUE_SSR_CONTEXT__ */
- // IMPORTANT: Do NOT use ES2015 features in this file (except for modules).
- // This module is a runtime utility for cleaner component module output and will
- // be included in the final webpack user bundle.
- function normalizeComponent (
- scriptExports,
- render,
- staticRenderFns,
- functionalTemplate,
- injectStyles,
- scopeId,
- moduleIdentifier, /* server only */
- shadowMode /* vue-cli only */
- ) {
- // Vue.extend constructor export interop
- var options = typeof scriptExports === 'function'
- ? scriptExports.options
- : scriptExports
- // render functions
- if (render) {
- options.render = render
- options.staticRenderFns = staticRenderFns
- options._compiled = true
- }
- // functional template
- if (functionalTemplate) {
- options.functional = true
- }
- // scopedId
- if (scopeId) {
- options._scopeId = 'data-v-' + scopeId
- }
- var hook
- if (moduleIdentifier) { // server build
- hook = function (context) {
- // 2.3 injection
- context =
- context || // cached call
- (this.$vnode && this.$vnode.ssrContext) || // stateful
- (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
- // 2.2 with runInNewContext: true
- if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
- context = __VUE_SSR_CONTEXT__
- }
- // inject component styles
- if (injectStyles) {
- injectStyles.call(this, context)
- }
- // register component module identifier for async chunk inferrence
- if (context && context._registeredComponents) {
- context._registeredComponents.add(moduleIdentifier)
- }
- }
- // used by ssr in case component is cached and beforeCreate
- // never gets called
- options._ssrRegister = hook
- } else if (injectStyles) {
- hook = shadowMode
- ? function () {
- injectStyles.call(
- this,
- (options.functional ? this.parent : this).$root.$options.shadowRoot
- )
- }
- : injectStyles
- }
- if (hook) {
- if (options.functional) {
- // for template-only hot-reload because in that case the render fn doesn't
- // go through the normalizer
- options._injectStyles = hook
- // register for functional component in vue file
- var originalRender = options.render
- options.render = function renderWithStyleInjection (h, context) {
- hook.call(context)
- return originalRender(h, context)
- }
- } else {
- // inject component registration as beforeCreate hook
- var existing = options.beforeCreate
- options.beforeCreate = existing
- ? [].concat(existing, hook)
- : [hook]
- }
- }
- return {
- exports: scriptExports,
- options: options
- }
- }
- // CONCATENATED MODULE: ./src/components/Mp4.vue
- /* normalize component */
- var component = normalizeComponent(
- components_Mp4vue_type_script_lang_js_,
- render,
- staticRenderFns,
- false,
- null,
- null,
- null
-
- )
- /* harmony default export */ var Mp4 = (component.exports);
- // 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&
- 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}})}
- var Hlsvue_type_template_id_5bef744a_staticRenderFns = []
- // CONCATENATED MODULE: ./src/components/Hls.vue?vue&type=template&id=5bef744a&
- // EXTERNAL MODULE: ./node_modules/xgplayer-hls.js/dist/index.js
- var xgplayer_hls_js_dist = __webpack_require__("9000");
- var xgplayer_hls_js_dist_default = /*#__PURE__*/__webpack_require__.n(xgplayer_hls_js_dist);
- // 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&
- //
- //
- //
- //
- /* harmony default export */ var Hlsvue_type_script_lang_js_ = ({
- name: "Hls",
- props: {
- config: {
- type: Object,
- default: function _default() {
- return {
- id: "mse",
- url: ""
- };
- }
- },
- rootStyle: {
- type: Object,
- default: function _default() {
- return {};
- }
- }
- },
- data: function data() {
- return {
- player: null,
- finalConfig: {
- volume: 0,
- autoplayMuted: true,
- //解决浏览器非静音阻止自动播放机制
- autoplay: true,
- //自动播放
- loop: true,
- //循环播放
- fluid: true,
- //流式布局
- videoInit: true,
- //加载首屏
- playbackRate: [0.5, 0.75, 1, 1.5, 2],
- //快进设置
- pip: true,
- //画中画
- screenShot: true,
- //开启截屏
- lang: "zh-cn",
- enterLogo: {
- url: "",
- width: 231,
- height: 42
- },
- enterBg: {
- color: "rgba(0,0,0,0.87)"
- },
- enterTips: {
- background: "linear-gradient(to right, rgba(0,0,0,0.87), #3D96FD, rgba(86,195,248), #3D96FD, rgba(0,0,0,0.87))"
- }
- }
- };
- },
- mounted: function mounted() {
- this.init();
- },
- beforeUpdate: function beforeUpdate() {
- this.init();
- },
- beforeDestroy: function beforeDestroy() {
- this.player && typeof this.player.destroy === "function" && this.player.destroy();
- },
- methods: {
- init: function init() {
- this.finalConfig = Object.assign(this.finalConfig, this.config);
- if (this.finalConfig.url && this.finalConfig.url !== "") {
- this.player = new xgplayer_hls_js_dist_default.a(this.finalConfig);
- this.$emit("player", this.player);
- }
- }
- }
- });
- // CONCATENATED MODULE: ./src/components/Hls.vue?vue&type=script&lang=js&
- /* harmony default export */ var components_Hlsvue_type_script_lang_js_ = (Hlsvue_type_script_lang_js_);
- // CONCATENATED MODULE: ./src/components/Hls.vue
- /* normalize component */
- var Hls_component = normalizeComponent(
- components_Hlsvue_type_script_lang_js_,
- Hlsvue_type_template_id_5bef744a_render,
- Hlsvue_type_template_id_5bef744a_staticRenderFns,
- false,
- null,
- null,
- null
-
- )
- /* harmony default export */ var Hls = (Hls_component.exports);
- // 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&
- 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}})}
- var Flvvue_type_template_id_e5412e0a_staticRenderFns = []
- // CONCATENATED MODULE: ./src/components/Flv.vue?vue&type=template&id=e5412e0a&
- // EXTERNAL MODULE: ./node_modules/xgplayer-flv.js/dist/index.js
- var xgplayer_flv_js_dist = __webpack_require__("b402");
- var xgplayer_flv_js_dist_default = /*#__PURE__*/__webpack_require__.n(xgplayer_flv_js_dist);
- // 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&
- //
- //
- //
- //
- /* harmony default export */ var Flvvue_type_script_lang_js_ = ({
- name: "Flv",
- props: {
- config: {
- type: Object,
- default: function _default() {
- return {
- id: "mse",
- url: ""
- };
- }
- },
- rootStyle: {
- type: Object,
- default: function _default() {
- return {};
- }
- }
- },
- data: function data() {
- return {
- player: null,
- finalConfig: {
- volume: 0,
- autoplayMuted: true,
- //解决浏览器非静音阻止自动播放机制
- autoplay: true,
- //自动播放
- loop: true,
- //循环播放
- fluid: true,
- //流式布局
- videoInit: true,
- //加载首屏
- playbackRate: [0.5, 0.75, 1, 1.5, 2],
- //快进设置
- pip: true,
- //画中画
- screenShot: true,
- //开启截屏
- lang: "zh-cn",
- hasVideo: true,
- hasAudio: true,
- flvOptionalConfig: {
- enableWorker: true
- },
- enterLogo: {
- url: "",
- width: 231,
- height: 42
- },
- enterBg: {
- color: "rgba(0,0,0,0.87)"
- },
- enterTips: {
- background: "linear-gradient(to right, rgba(0,0,0,0.87), #3D96FD, rgba(86,195,248), #3D96FD, rgba(0,0,0,0.87))"
- }
- }
- };
- },
- mounted: function mounted() {
- this.init();
- },
- beforeUpdate: function beforeUpdate() {
- this.init();
- },
- beforeDestroy: function beforeDestroy() {
- this.player && typeof this.player.destroy === "function" && this.player.destroy();
- },
- methods: {
- init: function init() {
- this.finalConfig = Object.assign(this.finalConfig, this.config);
- if (this.finalConfig.url && this.finalConfig.url !== "") {
- this.player = new xgplayer_flv_js_dist_default.a(this.finalConfig);
- this.$emit("player", this.player);
- }
- }
- }
- });
- // CONCATENATED MODULE: ./src/components/Flv.vue?vue&type=script&lang=js&
- /* harmony default export */ var components_Flvvue_type_script_lang_js_ = (Flvvue_type_script_lang_js_);
- // CONCATENATED MODULE: ./src/components/Flv.vue
- /* normalize component */
- var Flv_component = normalizeComponent(
- components_Flvvue_type_script_lang_js_,
- Flvvue_type_template_id_e5412e0a_render,
- Flvvue_type_template_id_e5412e0a_staticRenderFns,
- false,
- null,
- null,
- null
-
- )
- /* harmony default export */ var Flv = (Flv_component.exports);
- // CONCATENATED MODULE: ./src/components/export.js
- if (typeof window !== "undefined" && window.Vue) {
- window.Vue.component("zx-player-mp4", Mp4);
- window.Vue.component("zx-player-hls", Hls);
- window.Vue.component("zx-player-flv", Flv);
- }
- // CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/entry-lib-no-default.js
- /***/ }),
- /***/ "fc6a":
- /***/ (function(module, exports, __webpack_require__) {
- // toObject with fallback for non-array-like ES3 strings
- var IndexedObject = __webpack_require__("44ad");
- var requireObjectCoercible = __webpack_require__("1d80");
- module.exports = function (it) {
- return IndexedObject(requireObjectCoercible(it));
- };
- /***/ })
- /******/ });
- //# sourceMappingURL=zx-player.common.js.map
|