hls.js 619 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Hls = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  2. // Copyright Joyent, Inc. and other Node contributors.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a
  5. // copy of this software and associated documentation files (the
  6. // "Software"), to deal in the Software without restriction, including
  7. // without limitation the rights to use, copy, modify, merge, publish,
  8. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9. // persons to whom the Software is furnished to do so, subject to the
  10. // following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included
  13. // in all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  18. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  21. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. function EventEmitter() {
  23. this._events = this._events || {};
  24. this._maxListeners = this._maxListeners || undefined;
  25. }
  26. module.exports = EventEmitter;
  27. // Backwards-compat with node 0.10.x
  28. EventEmitter.EventEmitter = EventEmitter;
  29. EventEmitter.prototype._events = undefined;
  30. EventEmitter.prototype._maxListeners = undefined;
  31. // By default EventEmitters will print a warning if more than 10 listeners are
  32. // added to it. This is a useful default which helps finding memory leaks.
  33. EventEmitter.defaultMaxListeners = 10;
  34. // Obviously not all Emitters should be limited to 10. This function allows
  35. // that to be increased. Set to zero for unlimited.
  36. EventEmitter.prototype.setMaxListeners = function(n) {
  37. if (!isNumber(n) || n < 0 || isNaN(n))
  38. throw TypeError('n must be a positive number');
  39. this._maxListeners = n;
  40. return this;
  41. };
  42. EventEmitter.prototype.emit = function(type) {
  43. var er, handler, len, args, i, listeners;
  44. if (!this._events)
  45. this._events = {};
  46. // If there is no 'error' event listener then throw.
  47. if (type === 'error') {
  48. if (!this._events.error ||
  49. (isObject(this._events.error) && !this._events.error.length)) {
  50. er = arguments[1];
  51. if (er instanceof Error) {
  52. throw er; // Unhandled 'error' event
  53. } else {
  54. // At least give some kind of context to the user
  55. var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
  56. err.context = er;
  57. throw err;
  58. }
  59. }
  60. }
  61. handler = this._events[type];
  62. if (isUndefined(handler))
  63. return false;
  64. if (isFunction(handler)) {
  65. switch (arguments.length) {
  66. // fast cases
  67. case 1:
  68. handler.call(this);
  69. break;
  70. case 2:
  71. handler.call(this, arguments[1]);
  72. break;
  73. case 3:
  74. handler.call(this, arguments[1], arguments[2]);
  75. break;
  76. // slower
  77. default:
  78. args = Array.prototype.slice.call(arguments, 1);
  79. handler.apply(this, args);
  80. }
  81. } else if (isObject(handler)) {
  82. args = Array.prototype.slice.call(arguments, 1);
  83. listeners = handler.slice();
  84. len = listeners.length;
  85. for (i = 0; i < len; i++)
  86. listeners[i].apply(this, args);
  87. }
  88. return true;
  89. };
  90. EventEmitter.prototype.addListener = function(type, listener) {
  91. var m;
  92. if (!isFunction(listener))
  93. throw TypeError('listener must be a function');
  94. if (!this._events)
  95. this._events = {};
  96. // To avoid recursion in the case that type === "newListener"! Before
  97. // adding it to the listeners, first emit "newListener".
  98. if (this._events.newListener)
  99. this.emit('newListener', type,
  100. isFunction(listener.listener) ?
  101. listener.listener : listener);
  102. if (!this._events[type])
  103. // Optimize the case of one listener. Don't need the extra array object.
  104. this._events[type] = listener;
  105. else if (isObject(this._events[type]))
  106. // If we've already got an array, just append.
  107. this._events[type].push(listener);
  108. else
  109. // Adding the second element, need to change to array.
  110. this._events[type] = [this._events[type], listener];
  111. // Check for listener leak
  112. if (isObject(this._events[type]) && !this._events[type].warned) {
  113. if (!isUndefined(this._maxListeners)) {
  114. m = this._maxListeners;
  115. } else {
  116. m = EventEmitter.defaultMaxListeners;
  117. }
  118. if (m && m > 0 && this._events[type].length > m) {
  119. this._events[type].warned = true;
  120. console.error('(node) warning: possible EventEmitter memory ' +
  121. 'leak detected. %d listeners added. ' +
  122. 'Use emitter.setMaxListeners() to increase limit.',
  123. this._events[type].length);
  124. if (typeof console.trace === 'function') {
  125. // not supported in IE 10
  126. console.trace();
  127. }
  128. }
  129. }
  130. return this;
  131. };
  132. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  133. EventEmitter.prototype.once = function(type, listener) {
  134. if (!isFunction(listener))
  135. throw TypeError('listener must be a function');
  136. var fired = false;
  137. function g() {
  138. this.removeListener(type, g);
  139. if (!fired) {
  140. fired = true;
  141. listener.apply(this, arguments);
  142. }
  143. }
  144. g.listener = listener;
  145. this.on(type, g);
  146. return this;
  147. };
  148. // emits a 'removeListener' event iff the listener was removed
  149. EventEmitter.prototype.removeListener = function(type, listener) {
  150. var list, position, length, i;
  151. if (!isFunction(listener))
  152. throw TypeError('listener must be a function');
  153. if (!this._events || !this._events[type])
  154. return this;
  155. list = this._events[type];
  156. length = list.length;
  157. position = -1;
  158. if (list === listener ||
  159. (isFunction(list.listener) && list.listener === listener)) {
  160. delete this._events[type];
  161. if (this._events.removeListener)
  162. this.emit('removeListener', type, listener);
  163. } else if (isObject(list)) {
  164. for (i = length; i-- > 0;) {
  165. if (list[i] === listener ||
  166. (list[i].listener && list[i].listener === listener)) {
  167. position = i;
  168. break;
  169. }
  170. }
  171. if (position < 0)
  172. return this;
  173. if (list.length === 1) {
  174. list.length = 0;
  175. delete this._events[type];
  176. } else {
  177. list.splice(position, 1);
  178. }
  179. if (this._events.removeListener)
  180. this.emit('removeListener', type, listener);
  181. }
  182. return this;
  183. };
  184. EventEmitter.prototype.removeAllListeners = function(type) {
  185. var key, listeners;
  186. if (!this._events)
  187. return this;
  188. // not listening for removeListener, no need to emit
  189. if (!this._events.removeListener) {
  190. if (arguments.length === 0)
  191. this._events = {};
  192. else if (this._events[type])
  193. delete this._events[type];
  194. return this;
  195. }
  196. // emit removeListener for all listeners on all events
  197. if (arguments.length === 0) {
  198. for (key in this._events) {
  199. if (key === 'removeListener') continue;
  200. this.removeAllListeners(key);
  201. }
  202. this.removeAllListeners('removeListener');
  203. this._events = {};
  204. return this;
  205. }
  206. listeners = this._events[type];
  207. if (isFunction(listeners)) {
  208. this.removeListener(type, listeners);
  209. } else if (listeners) {
  210. // LIFO order
  211. while (listeners.length)
  212. this.removeListener(type, listeners[listeners.length - 1]);
  213. }
  214. delete this._events[type];
  215. return this;
  216. };
  217. EventEmitter.prototype.listeners = function(type) {
  218. var ret;
  219. if (!this._events || !this._events[type])
  220. ret = [];
  221. else if (isFunction(this._events[type]))
  222. ret = [this._events[type]];
  223. else
  224. ret = this._events[type].slice();
  225. return ret;
  226. };
  227. EventEmitter.prototype.listenerCount = function(type) {
  228. if (this._events) {
  229. var evlistener = this._events[type];
  230. if (isFunction(evlistener))
  231. return 1;
  232. else if (evlistener)
  233. return evlistener.length;
  234. }
  235. return 0;
  236. };
  237. EventEmitter.listenerCount = function(emitter, type) {
  238. return emitter.listenerCount(type);
  239. };
  240. function isFunction(arg) {
  241. return typeof arg === 'function';
  242. }
  243. function isNumber(arg) {
  244. return typeof arg === 'number';
  245. }
  246. function isObject(arg) {
  247. return typeof arg === 'object' && arg !== null;
  248. }
  249. function isUndefined(arg) {
  250. return arg === void 0;
  251. }
  252. },{}],2:[function(_dereq_,module,exports){
  253. // see https://tools.ietf.org/html/rfc1808
  254. /* jshint ignore:start */
  255. (function(root) {
  256. /* jshint ignore:end */
  257. var URL_REGEX = /^((?:[^\/;?#]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/;
  258. var FIRST_SEGMENT_REGEX = /^([^\/;?#]*)(.*)$/;
  259. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  260. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/g;
  261. var URLToolkit = { // jshint ignore:line
  262. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  263. // E.g
  264. // With opts.alwaysNormalize = false (default, spec compliant)
  265. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  266. // With opts.alwaysNormalize = true (default, not spec compliant)
  267. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  268. buildAbsoluteURL: function(baseURL, relativeURL, opts) {
  269. opts = opts || {};
  270. // remove any remaining space and CRLF
  271. baseURL = baseURL.trim();
  272. relativeURL = relativeURL.trim();
  273. if (!relativeURL) {
  274. // 2a) If the embedded URL is entirely empty, it inherits the
  275. // entire base URL (i.e., is set equal to the base URL)
  276. // and we are done.
  277. if (!opts.alwaysNormalize) {
  278. return baseURL;
  279. }
  280. var basePartsForNormalise = this.parseURL(baseURL);
  281. if (!baseParts) {
  282. throw new Error('Error trying to parse base URL.');
  283. }
  284. basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
  285. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  286. }
  287. var relativeParts = this.parseURL(relativeURL);
  288. if (!relativeParts) {
  289. throw new Error('Error trying to parse relative URL.');
  290. }
  291. if (relativeParts.scheme) {
  292. // 2b) If the embedded URL starts with a scheme name, it is
  293. // interpreted as an absolute URL and we are done.
  294. if (!opts.alwaysNormalize) {
  295. return relativeURL;
  296. }
  297. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  298. return URLToolkit.buildURLFromParts(relativeParts);
  299. }
  300. var baseParts = this.parseURL(baseURL);
  301. if (!baseParts) {
  302. throw new Error('Error trying to parse base URL.');
  303. }
  304. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  305. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  306. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  307. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  308. baseParts.netLoc = pathParts[1];
  309. baseParts.path = pathParts[2];
  310. }
  311. if (baseParts.netLoc && !baseParts.path) {
  312. baseParts.path = '/';
  313. }
  314. var builtParts = {
  315. // 2c) Otherwise, the embedded URL inherits the scheme of
  316. // the base URL.
  317. scheme: baseParts.scheme,
  318. netLoc: relativeParts.netLoc,
  319. path: null,
  320. params: relativeParts.params,
  321. query: relativeParts.query,
  322. fragment: relativeParts.fragment
  323. };
  324. if (!relativeParts.netLoc) {
  325. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  326. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  327. // (if any) of the base URL.
  328. builtParts.netLoc = baseParts.netLoc;
  329. // 4) If the embedded URL path is preceded by a slash "/", the
  330. // path is not relative and we skip to Step 7.
  331. if (relativeParts.path[0] !== '/') {
  332. if (!relativeParts.path) {
  333. // 5) If the embedded URL path is empty (and not preceded by a
  334. // slash), then the embedded URL inherits the base URL path
  335. builtParts.path = baseParts.path;
  336. // 5a) if the embedded URL's <params> is non-empty, we skip to
  337. // step 7; otherwise, it inherits the <params> of the base
  338. // URL (if any) and
  339. if (!relativeParts.params) {
  340. builtParts.params = baseParts.params;
  341. // 5b) if the embedded URL's <query> is non-empty, we skip to
  342. // step 7; otherwise, it inherits the <query> of the base
  343. // URL (if any) and we skip to step 7.
  344. if (!relativeParts.query) {
  345. builtParts.query = baseParts.query;
  346. }
  347. }
  348. } else {
  349. // 6) The last segment of the base URL's path (anything
  350. // following the rightmost slash "/", or the entire path if no
  351. // slash is present) is removed and the embedded URL's path is
  352. // appended in its place.
  353. var baseURLPath = baseParts.path;
  354. var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;
  355. builtParts.path = URLToolkit.normalizePath(newPath);
  356. }
  357. }
  358. }
  359. if (builtParts.path === null) {
  360. builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
  361. }
  362. return URLToolkit.buildURLFromParts(builtParts);
  363. },
  364. parseURL: function(url) {
  365. var parts = URL_REGEX.exec(url);
  366. if (!parts) {
  367. return null;
  368. }
  369. return {
  370. scheme: parts[1] || '',
  371. netLoc: parts[2] || '',
  372. path: parts[3] || '',
  373. params: parts[4] || '',
  374. query: parts[5] || '',
  375. fragment: parts[6] || ''
  376. };
  377. },
  378. normalizePath: function(path) {
  379. // The following operations are
  380. // then applied, in order, to the new path:
  381. // 6a) All occurrences of "./", where "." is a complete path
  382. // segment, are removed.
  383. // 6b) If the path ends with "." as a complete path segment,
  384. // that "." is removed.
  385. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
  386. // 6c) All occurrences of "<segment>/../", where <segment> is a
  387. // complete path segment not equal to "..", are removed.
  388. // Removal of these path segments is performed iteratively,
  389. // removing the leftmost matching pattern on each iteration,
  390. // until no matching pattern remains.
  391. // 6d) If the path ends with "<segment>/..", where <segment> is a
  392. // complete path segment not equal to "..", that
  393. // "<segment>/.." is removed.
  394. while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {} // jshint ignore:line
  395. return path.split('').reverse().join('');
  396. },
  397. buildURLFromParts: function(parts) {
  398. return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
  399. }
  400. };
  401. /* jshint ignore:start */
  402. if(typeof exports === 'object' && typeof module === 'object')
  403. module.exports = URLToolkit;
  404. else if(typeof define === 'function' && define.amd)
  405. define([], function() { return URLToolkit; });
  406. else if(typeof exports === 'object')
  407. exports["URLToolkit"] = URLToolkit;
  408. else
  409. root["URLToolkit"] = URLToolkit;
  410. })(this);
  411. /* jshint ignore:end */
  412. },{}],3:[function(_dereq_,module,exports){
  413. var bundleFn = arguments[3];
  414. var sources = arguments[4];
  415. var cache = arguments[5];
  416. var stringify = JSON.stringify;
  417. module.exports = function (fn, options) {
  418. var wkey;
  419. var cacheKeys = Object.keys(cache);
  420. for (var i = 0, l = cacheKeys.length; i < l; i++) {
  421. var key = cacheKeys[i];
  422. var exp = cache[key].exports;
  423. // Using babel as a transpiler to use esmodule, the export will always
  424. // be an object with the default export as a property of it. To ensure
  425. // the existing api and babel esmodule exports are both supported we
  426. // check for both
  427. if (exp === fn || exp && exp.default === fn) {
  428. wkey = key;
  429. break;
  430. }
  431. }
  432. if (!wkey) {
  433. wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
  434. var wcache = {};
  435. for (var i = 0, l = cacheKeys.length; i < l; i++) {
  436. var key = cacheKeys[i];
  437. wcache[key] = key;
  438. }
  439. sources[wkey] = [
  440. Function(['require','module','exports'], '(' + fn + ')(self)'),
  441. wcache
  442. ];
  443. }
  444. var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
  445. var scache = {}; scache[wkey] = wkey;
  446. sources[skey] = [
  447. Function(['require'], (
  448. // try to call default if defined to also support babel esmodule
  449. // exports
  450. 'var f = require(' + stringify(wkey) + ');' +
  451. '(f.default ? f.default : f)(self);'
  452. )),
  453. scache
  454. ];
  455. var workerSources = {};
  456. resolveSources(skey);
  457. function resolveSources(key) {
  458. workerSources[key] = true;
  459. for (var depPath in sources[key][1]) {
  460. var depKey = sources[key][1][depPath];
  461. if (!workerSources[depKey]) {
  462. resolveSources(depKey);
  463. }
  464. }
  465. }
  466. var src = '(' + bundleFn + ')({'
  467. + Object.keys(workerSources).map(function (key) {
  468. return stringify(key) + ':['
  469. + sources[key][0]
  470. + ',' + stringify(sources[key][1]) + ']'
  471. ;
  472. }).join(',')
  473. + '},{},[' + stringify(skey) + '])'
  474. ;
  475. var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  476. var blob = new Blob([src], { type: 'text/javascript' });
  477. if (options && options.bare) { return blob; }
  478. var workerUrl = URL.createObjectURL(blob);
  479. var worker = new Worker(workerUrl);
  480. worker.objectURL = workerUrl;
  481. return worker;
  482. };
  483. },{}],4:[function(_dereq_,module,exports){
  484. /**
  485. * HLS config
  486. */
  487. 'use strict';
  488. Object.defineProperty(exports, "__esModule", {
  489. value: true
  490. });
  491. exports.hlsDefaultConfig = undefined;
  492. var _abrController = _dereq_(5);
  493. var _abrController2 = _interopRequireDefault(_abrController);
  494. var _bufferController = _dereq_(8);
  495. var _bufferController2 = _interopRequireDefault(_bufferController);
  496. var _capLevelController = _dereq_(9);
  497. var _capLevelController2 = _interopRequireDefault(_capLevelController);
  498. var _fpsController = _dereq_(10);
  499. var _fpsController2 = _interopRequireDefault(_fpsController);
  500. var _xhrLoader = _dereq_(55);
  501. var _xhrLoader2 = _interopRequireDefault(_xhrLoader);
  502. var _audioTrackController = _dereq_(7);
  503. var _audioTrackController2 = _interopRequireDefault(_audioTrackController);
  504. var _audioStreamController = _dereq_(6);
  505. var _audioStreamController2 = _interopRequireDefault(_audioStreamController);
  506. var _cues = _dereq_(47);
  507. var _cues2 = _interopRequireDefault(_cues);
  508. var _timelineController = _dereq_(15);
  509. var _timelineController2 = _interopRequireDefault(_timelineController);
  510. var _subtitleTrackController = _dereq_(14);
  511. var _subtitleTrackController2 = _interopRequireDefault(_subtitleTrackController);
  512. var _subtitleStreamController = _dereq_(13);
  513. var _subtitleStreamController2 = _interopRequireDefault(_subtitleStreamController);
  514. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  515. //#endif
  516. //#endif
  517. //#if subtitle
  518. //import FetchLoader from './utils/fetch-loader';
  519. //#if altaudio
  520. var hlsDefaultConfig = exports.hlsDefaultConfig = {
  521. autoStartLoad: true, // used by stream-controller
  522. startPosition: -1, // used by stream-controller
  523. defaultAudioCodec: undefined, // used by stream-controller
  524. debug: false, // used by logger
  525. capLevelOnFPSDrop: false, // used by fps-controller
  526. capLevelToPlayerSize: false, // used by cap-level-controller
  527. initialLiveManifestSize: 1, // used by stream-controller
  528. maxBufferLength: 30, // used by stream-controller
  529. maxBufferSize: 60 * 1000 * 1000, // used by stream-controller
  530. maxBufferHole: 0.5, // used by stream-controller
  531. maxSeekHole: 2, // used by stream-controller
  532. lowBufferWatchdogPeriod: 0.5, // used by stream-controller
  533. highBufferWatchdogPeriod: 3, // used by stream-controller
  534. nudgeOffset: 0.1, // used by stream-controller
  535. nudgeMaxRetry: 3, // used by stream-controller
  536. maxFragLookUpTolerance: 0.2, // used by stream-controller
  537. liveSyncDurationCount: 3, // used by stream-controller
  538. liveMaxLatencyDurationCount: Infinity, // used by stream-controller
  539. liveSyncDuration: undefined, // used by stream-controller
  540. liveMaxLatencyDuration: undefined, // used by stream-controller
  541. maxMaxBufferLength: 600, // used by stream-controller
  542. enableWorker: true, // used by demuxer
  543. enableSoftwareAES: true, // used by decrypter
  544. manifestLoadingTimeOut: 10000, // used by playlist-loader
  545. manifestLoadingMaxRetry: 1, // used by playlist-loader
  546. manifestLoadingRetryDelay: 1000, // used by playlist-loader
  547. manifestLoadingMaxRetryTimeout: 64000, // used by playlist-loader
  548. startLevel: undefined, // used by level-controller
  549. levelLoadingTimeOut: 10000, // used by playlist-loader
  550. levelLoadingMaxRetry: 4, // used by playlist-loader
  551. levelLoadingRetryDelay: 1000, // used by playlist-loader
  552. levelLoadingMaxRetryTimeout: 64000, // used by playlist-loader
  553. fragLoadingTimeOut: 20000, // used by fragment-loader
  554. fragLoadingMaxRetry: 6, // used by fragment-loader
  555. fragLoadingRetryDelay: 1000, // used by fragment-loader
  556. fragLoadingMaxRetryTimeout: 64000, // used by fragment-loader
  557. fragLoadingLoopThreshold: 3, // used by stream-controller
  558. startFragPrefetch: false, // used by stream-controller
  559. fpsDroppedMonitoringPeriod: 5000, // used by fps-controller
  560. fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller
  561. appendErrorMaxRetry: 3, // used by buffer-controller
  562. loader: _xhrLoader2.default,
  563. //loader: FetchLoader,
  564. fLoader: undefined,
  565. pLoader: undefined,
  566. xhrSetup: undefined,
  567. fetchSetup: undefined,
  568. abrController: _abrController2.default,
  569. bufferController: _bufferController2.default,
  570. capLevelController: _capLevelController2.default,
  571. fpsController: _fpsController2.default,
  572. //#if altaudio
  573. audioStreamController: _audioStreamController2.default,
  574. audioTrackController: _audioTrackController2.default,
  575. //#endif
  576. //#if subtitle
  577. subtitleStreamController: _subtitleStreamController2.default,
  578. subtitleTrackController: _subtitleTrackController2.default,
  579. timelineController: _timelineController2.default,
  580. cueHandler: _cues2.default,
  581. enableCEA708Captions: true, // used by timeline-controller
  582. enableWebVTT: true, // used by timeline-controller
  583. captionsTextTrack1Label: 'English', // used by timeline-controller
  584. captionsTextTrack1LanguageCode: 'en', // used by timeline-controller
  585. captionsTextTrack2Label: 'Spanish', // used by timeline-controller
  586. captionsTextTrack2LanguageCode: 'es', // used by timeline-controller
  587. //#endif
  588. stretchShortVideoTrack: false, // used by mp4-remuxer
  589. forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer
  590. abrEwmaFastLive: 3, // used by abr-controller
  591. abrEwmaSlowLive: 9, // used by abr-controller
  592. abrEwmaFastVoD: 3, // used by abr-controller
  593. abrEwmaSlowVoD: 9, // used by abr-controller
  594. abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller
  595. abrBandWidthFactor: 0.95, // used by abr-controller
  596. abrBandWidthUpFactor: 0.7, // used by abr-controller
  597. abrMaxWithRealBitrate: false, // used by abr-controller
  598. maxStarvationDelay: 4, // used by abr-controller
  599. maxLoadingDelay: 4, // used by abr-controller
  600. minAutoBitrate: 0 // used by hls
  601. };
  602. },{"10":10,"13":13,"14":14,"15":15,"47":47,"5":5,"55":55,"6":6,"7":7,"8":8,"9":9}],5:[function(_dereq_,module,exports){
  603. 'use strict';
  604. Object.defineProperty(exports, "__esModule", {
  605. value: true
  606. });
  607. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  608. var _events = _dereq_(32);
  609. var _events2 = _interopRequireDefault(_events);
  610. var _eventHandler = _dereq_(31);
  611. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  612. var _bufferHelper = _dereq_(34);
  613. var _bufferHelper2 = _interopRequireDefault(_bufferHelper);
  614. var _errors = _dereq_(30);
  615. var _logger = _dereq_(50);
  616. var _ewmaBandwidthEstimator = _dereq_(48);
  617. var _ewmaBandwidthEstimator2 = _interopRequireDefault(_ewmaBandwidthEstimator);
  618. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  619. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  620. 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; }
  621. 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; } /*
  622. * simple ABR Controller
  623. * - compute next level based on last fragment bw heuristics
  624. * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling
  625. */
  626. var AbrController = function (_EventHandler) {
  627. _inherits(AbrController, _EventHandler);
  628. function AbrController(hls) {
  629. _classCallCheck(this, AbrController);
  630. 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));
  631. _this.lastLoadedFragLevel = 0;
  632. _this._nextAutoLevel = -1;
  633. _this.hls = hls;
  634. _this.onCheck = _this._abandonRulesCheck.bind(_this);
  635. return _this;
  636. }
  637. _createClass(AbrController, [{
  638. key: 'destroy',
  639. value: function destroy() {
  640. this.clearTimer();
  641. _eventHandler2.default.prototype.destroy.call(this);
  642. }
  643. }, {
  644. key: 'onFragLoading',
  645. value: function onFragLoading(data) {
  646. var frag = data.frag;
  647. if (frag.type === 'main') {
  648. if (!this.timer) {
  649. this.timer = setInterval(this.onCheck, 100);
  650. }
  651. // lazy init of bw Estimator, rationale is that we use different params for Live/VoD
  652. // so we need to wait for stream manifest / playlist type to instantiate it.
  653. if (!this._bwEstimator) {
  654. var hls = this.hls,
  655. level = data.frag.level,
  656. isLive = hls.levels[level].details.live,
  657. config = hls.config,
  658. ewmaFast = void 0,
  659. ewmaSlow = void 0;
  660. if (isLive) {
  661. ewmaFast = config.abrEwmaFastLive;
  662. ewmaSlow = config.abrEwmaSlowLive;
  663. } else {
  664. ewmaFast = config.abrEwmaFastVoD;
  665. ewmaSlow = config.abrEwmaSlowVoD;
  666. }
  667. this._bwEstimator = new _ewmaBandwidthEstimator2.default(hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate);
  668. }
  669. this.fragCurrent = frag;
  670. }
  671. }
  672. }, {
  673. key: '_abandonRulesCheck',
  674. value: function _abandonRulesCheck() {
  675. /*
  676. monitor fragment retrieval time...
  677. we compute expected time of arrival of the complete fragment.
  678. we compare it to expected time of buffer starvation
  679. */
  680. var hls = this.hls,
  681. v = hls.media,
  682. frag = this.fragCurrent,
  683. loader = frag.loader,
  684. minAutoLevel = hls.minAutoLevel;
  685. // if loader has been destroyed or loading has been aborted, stop timer and return
  686. if (!loader || loader.stats && loader.stats.aborted) {
  687. _logger.logger.warn('frag loader destroy or aborted, disarm abandonRules');
  688. this.clearTimer();
  689. return;
  690. }
  691. var stats = loader.stats;
  692. /* only monitor frag retrieval time if
  693. (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) */
  694. if (v && (!v.paused && v.playbackRate !== 0 || !v.readyState) && frag.autoLevel && frag.level) {
  695. var requestDelay = performance.now() - stats.trequest,
  696. playbackRate = Math.abs(v.playbackRate);
  697. // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate
  698. if (requestDelay > 500 * frag.duration / playbackRate) {
  699. var levels = hls.levels,
  700. loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay),
  701. // byte/s; at least 1 byte/s to avoid division by zero
  702. // compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size
  703. level = levels[frag.level],
  704. levelBitrate = level.realBitrate ? Math.max(level.realBitrate, level.bitrate) : level.bitrate,
  705. expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8)),
  706. pos = v.currentTime,
  707. fragLoadedDelay = (expectedLen - stats.loaded) / loadRate,
  708. bufferStarvationDelay = (_bufferHelper2.default.bufferInfo(v, pos, hls.config.maxBufferHole).end - pos) / playbackRate;
  709. // consider emergency switch down only if we have less than 2 frag buffered AND
  710. // time to finish loading current fragment is bigger than buffer starvation delay
  711. // ie if we risk buffer starvation if bw does not increase quickly
  712. if (bufferStarvationDelay < 2 * frag.duration / playbackRate && fragLoadedDelay > bufferStarvationDelay) {
  713. var fragLevelNextLoadedDelay = void 0,
  714. nextLoadLevel = void 0;
  715. // lets iterate through lower level and try to find the biggest one that could avoid rebuffering
  716. // we start from current level - 1 and we step down , until we find a matching level
  717. for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  718. // compute time to load next fragment at lower level
  719. // 0.8 : consider only 80% of current bw to be conservative
  720. // 8 = bits per byte (bps/Bps)
  721. var levelNextBitrate = levels[nextLoadLevel].realBitrate ? Math.max(levels[nextLoadLevel].realBitrate, levels[nextLoadLevel].bitrate) : levels[nextLoadLevel].bitrate;
  722. fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate);
  723. if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
  724. // we found a lower level that be rebuffering free with current estimated bw !
  725. break;
  726. }
  727. }
  728. // only emergency switch down if it takes less time to load new fragment at lowest level instead
  729. // of finishing loading current one ...
  730. if (fragLevelNextLoadedDelay < fragLoadedDelay) {
  731. _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));
  732. // force next load level in auto mode
  733. hls.nextLoadLevel = nextLoadLevel;
  734. // update bw estimate for this fragment before cancelling load (this will help reducing the bw)
  735. this._bwEstimator.sample(requestDelay, stats.loaded);
  736. //abort fragment loading
  737. loader.abort();
  738. // stop abandon rules timer
  739. this.clearTimer();
  740. hls.trigger(_events2.default.FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag, stats: stats });
  741. }
  742. }
  743. }
  744. }
  745. }
  746. }, {
  747. key: 'onFragLoaded',
  748. value: function onFragLoaded(data) {
  749. var frag = data.frag;
  750. if (frag.type === 'main' && !isNaN(frag.sn)) {
  751. // stop monitoring bw once frag loaded
  752. this.clearTimer();
  753. // store level id after successful fragment load
  754. this.lastLoadedFragLevel = frag.level;
  755. // reset forced auto level value so that next level will be selected
  756. this._nextAutoLevel = -1;
  757. // compute level average bitrate
  758. if (this.hls.config.abrMaxWithRealBitrate) {
  759. var level = this.hls.levels[frag.level];
  760. var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;
  761. var loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration;
  762. level.loaded = { bytes: loadedBytes, duration: loadedDuration };
  763. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  764. }
  765. // if fragment has been loaded to perform a bitrate test,
  766. if (data.frag.bitrateTest) {
  767. var stats = data.stats;
  768. stats.tparsed = stats.tbuffered = stats.tload;
  769. this.onFragBuffered(data);
  770. }
  771. }
  772. }
  773. }, {
  774. key: 'onFragBuffered',
  775. value: function onFragBuffered(data) {
  776. var stats = data.stats,
  777. frag = data.frag;
  778. // only update stats on first frag buffering
  779. // if same frag is loaded multiple times, it might be in browser cache, and loaded quickly
  780. // and leading to wrong bw estimation
  781. // on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED)
  782. if (stats.aborted !== true && frag.loadCounter === 1 && frag.type === 'main' && !isNaN(frag.sn) && (!frag.bitrateTest || stats.tload === stats.tbuffered)) {
  783. // use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached
  784. // 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
  785. // as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation
  786. var fragLoadingProcessingMs = stats.tparsed - stats.trequest;
  787. _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)));
  788. this._bwEstimator.sample(fragLoadingProcessingMs, stats.loaded);
  789. // if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration
  790. if (frag.bitrateTest) {
  791. this.bitrateTestDelay = fragLoadingProcessingMs / 1000;
  792. } else {
  793. this.bitrateTestDelay = 0;
  794. }
  795. }
  796. }
  797. }, {
  798. key: 'onError',
  799. value: function onError(data) {
  800. // stop timer in case of frag loading error
  801. switch (data.details) {
  802. case _errors.ErrorDetails.FRAG_LOAD_ERROR:
  803. case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
  804. this.clearTimer();
  805. break;
  806. default:
  807. break;
  808. }
  809. }
  810. }, {
  811. key: 'clearTimer',
  812. value: function clearTimer() {
  813. if (this.timer) {
  814. clearInterval(this.timer);
  815. this.timer = null;
  816. }
  817. }
  818. // return next auto level
  819. }, {
  820. key: '_findBestLevel',
  821. value: function _findBestLevel(currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) {
  822. for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
  823. var levelInfo = levels[i],
  824. levelDetails = levelInfo.details,
  825. avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration,
  826. live = levelDetails ? levelDetails.live : false,
  827. adjustedbw = void 0;
  828. // follow algorithm captured from stagefright :
  829. // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
  830. // Pick the highest bandwidth stream below or equal to estimated bandwidth.
  831. // consider only 80% of the available bandwidth, but if we are switching up,
  832. // be even more conservative (70%) to avoid overestimating and immediately
  833. // switching back.
  834. if (i <= currentLevel) {
  835. adjustedbw = bwFactor * currentBw;
  836. } else {
  837. adjustedbw = bwUpFactor * currentBw;
  838. }
  839. var bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate,
  840. fetchDuration = bitrate * avgDuration / adjustedbw;
  841. _logger.logger.trace('level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: ' + i + '/' + Math.round(adjustedbw) + '/' + bitrate + '/' + avgDuration + '/' + maxFetchDuration + '/' + fetchDuration);
  842. // if adjusted bw is greater than level bitrate AND
  843. if (adjustedbw > bitrate && (
  844. // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  845. // 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 ...
  846. !fetchDuration || live || fetchDuration < maxFetchDuration)) {
  847. // as we are looping from highest to lowest, this will return the best achievable quality level
  848. return i;
  849. }
  850. }
  851. // not enough time budget even with quality level 0 ... rebuffering might happen
  852. return -1;
  853. }
  854. }, {
  855. key: 'nextAutoLevel',
  856. get: function get() {
  857. var forcedAutoLevel = this._nextAutoLevel;
  858. var bwEstimator = this._bwEstimator;
  859. // in case next auto level has been forced, and bw not available or not reliable, return forced value
  860. if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {
  861. return forcedAutoLevel;
  862. }
  863. // compute next level using ABR logic
  864. var nextABRAutoLevel = this._nextABRAutoLevel;
  865. // if forced auto level has been defined, use it to cap ABR computed quality level
  866. if (forcedAutoLevel !== -1) {
  867. nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);
  868. }
  869. return nextABRAutoLevel;
  870. },
  871. set: function set(nextLevel) {
  872. this._nextAutoLevel = nextLevel;
  873. }
  874. }, {
  875. key: '_nextABRAutoLevel',
  876. get: function get() {
  877. var hls = this.hls,
  878. maxAutoLevel = hls.maxAutoLevel,
  879. levels = hls.levels,
  880. config = hls.config,
  881. minAutoLevel = hls.minAutoLevel;
  882. var v = hls.media,
  883. currentLevel = this.lastLoadedFragLevel,
  884. currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0,
  885. pos = v ? v.currentTime : 0,
  886. // playbackRate is the absolute value of the playback rate; if v.playbackRate is 0, we use 1 to load as
  887. // if we're playing back at the normal rate.
  888. playbackRate = v && v.playbackRate !== 0 ? Math.abs(v.playbackRate) : 1.0,
  889. avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate,
  890. // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
  891. bufferStarvationDelay = (_bufferHelper2.default.bufferInfo(v, pos, config.maxBufferHole).end - pos) / playbackRate;
  892. // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
  893. var bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor, levels);
  894. if (bestLevel >= 0) {
  895. return bestLevel;
  896. } else {
  897. _logger.logger.trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering');
  898. // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering
  899. // if no matching level found, logic will return 0
  900. var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay,
  901. bwFactor = config.abrBandWidthFactor,
  902. bwUpFactor = config.abrBandWidthUpFactor;
  903. if (bufferStarvationDelay === 0) {
  904. // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
  905. var bitrateTestDelay = this.bitrateTestDelay;
  906. if (bitrateTestDelay) {
  907. // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
  908. // max video loading delay used in automatic start level selection :
  909. // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
  910. // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
  911. // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
  912. var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  913. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  914. _logger.logger.trace('bitrate test took ' + Math.round(1000 * bitrateTestDelay) + 'ms, set first fragment max fetchDuration to ' + Math.round(1000 * maxStarvationDelay) + ' ms');
  915. // don't use conservative factor on bitrate test
  916. bwFactor = bwUpFactor = 1;
  917. }
  918. }
  919. bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor, levels);
  920. return Math.max(bestLevel, 0);
  921. }
  922. }
  923. }]);
  924. return AbrController;
  925. }(_eventHandler2.default);
  926. exports.default = AbrController;
  927. },{"30":30,"31":31,"32":32,"34":34,"48":48,"50":50}],6:[function(_dereq_,module,exports){
  928. 'use strict';
  929. Object.defineProperty(exports, "__esModule", {
  930. value: true
  931. });
  932. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  933. var _binarySearch = _dereq_(45);
  934. var _binarySearch2 = _interopRequireDefault(_binarySearch);
  935. var _bufferHelper = _dereq_(34);
  936. var _bufferHelper2 = _interopRequireDefault(_bufferHelper);
  937. var _demuxer = _dereq_(24);
  938. var _demuxer2 = _interopRequireDefault(_demuxer);
  939. var _events = _dereq_(32);
  940. var _events2 = _interopRequireDefault(_events);
  941. var _eventHandler = _dereq_(31);
  942. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  943. var _levelHelper = _dereq_(35);
  944. var _levelHelper2 = _interopRequireDefault(_levelHelper);
  945. var _timeRanges = _dereq_(51);
  946. var _timeRanges2 = _interopRequireDefault(_timeRanges);
  947. var _errors = _dereq_(30);
  948. var _logger = _dereq_(50);
  949. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  950. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  951. 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; }
  952. 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; } /*
  953. * Audio Stream Controller
  954. */
  955. var State = {
  956. STOPPED: 'STOPPED',
  957. STARTING: 'STARTING',
  958. IDLE: 'IDLE',
  959. PAUSED: 'PAUSED',
  960. KEY_LOADING: 'KEY_LOADING',
  961. FRAG_LOADING: 'FRAG_LOADING',
  962. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  963. WAITING_TRACK: 'WAITING_TRACK',
  964. PARSING: 'PARSING',
  965. PARSED: 'PARSED',
  966. BUFFER_FLUSHING: 'BUFFER_FLUSHING',
  967. ENDED: 'ENDED',
  968. ERROR: 'ERROR',
  969. WAITING_INIT_PTS: 'WAITING_INIT_PTS'
  970. };
  971. var AudioStreamController = function (_EventHandler) {
  972. _inherits(AudioStreamController, _EventHandler);
  973. function AudioStreamController(hls) {
  974. _classCallCheck(this, AudioStreamController);
  975. 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_CREATED, _events2.default.BUFFER_APPENDED, _events2.default.BUFFER_FLUSHED, _events2.default.INIT_PTS_FOUND));
  976. _this.config = hls.config;
  977. _this.audioCodecSwap = false;
  978. _this.ticks = 0;
  979. _this._state = State.STOPPED;
  980. _this.ontick = _this.tick.bind(_this);
  981. _this.initPTS = [];
  982. _this.waitingFragment = null;
  983. return _this;
  984. }
  985. _createClass(AudioStreamController, [{
  986. key: 'destroy',
  987. value: function destroy() {
  988. this.stopLoad();
  989. if (this.timer) {
  990. clearInterval(this.timer);
  991. this.timer = null;
  992. }
  993. _eventHandler2.default.prototype.destroy.call(this);
  994. this.state = State.STOPPED;
  995. }
  996. //Signal that video PTS was found
  997. }, {
  998. key: 'onInitPtsFound',
  999. value: function onInitPtsFound(data) {
  1000. var demuxerId = data.id,
  1001. cc = data.frag.cc,
  1002. initPTS = data.initPTS;
  1003. if (demuxerId === 'main') {
  1004. //Always update the new INIT PTS
  1005. //Can change due level switch
  1006. this.initPTS[cc] = initPTS;
  1007. _logger.logger.log('InitPTS for cc:' + cc + ' found from video track:' + initPTS);
  1008. //If we are waiting we need to demux/remux the waiting frag
  1009. //With the new initPTS
  1010. if (this.state === State.WAITING_INIT_PTS) {
  1011. _logger.logger.log('sending pending audio frag to demuxer');
  1012. this.state = State.FRAG_LOADING;
  1013. //We have audio frag waiting or video pts
  1014. //Let process it
  1015. this.onFragLoaded(this.waitingFragment);
  1016. //Lets clean the waiting frag
  1017. this.waitingFragment = null;
  1018. }
  1019. }
  1020. }
  1021. }, {
  1022. key: 'startLoad',
  1023. value: function startLoad(startPosition) {
  1024. if (this.tracks) {
  1025. var lastCurrentTime = this.lastCurrentTime;
  1026. this.stopLoad();
  1027. if (!this.timer) {
  1028. this.timer = setInterval(this.ontick, 100);
  1029. }
  1030. this.fragLoadError = 0;
  1031. if (lastCurrentTime > 0 && startPosition === -1) {
  1032. _logger.logger.log('audio:override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3));
  1033. this.state = State.IDLE;
  1034. } else {
  1035. this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition;
  1036. this.state = State.STARTING;
  1037. }
  1038. this.nextLoadPosition = this.startPosition = this.lastCurrentTime;
  1039. this.tick();
  1040. } else {
  1041. this.startPosition = startPosition;
  1042. this.state = State.STOPPED;
  1043. }
  1044. }
  1045. }, {
  1046. key: 'stopLoad',
  1047. value: function stopLoad() {
  1048. var frag = this.fragCurrent;
  1049. if (frag) {
  1050. if (frag.loader) {
  1051. frag.loader.abort();
  1052. }
  1053. this.fragCurrent = null;
  1054. }
  1055. this.fragPrevious = null;
  1056. if (this.demuxer) {
  1057. this.demuxer.destroy();
  1058. this.demuxer = null;
  1059. }
  1060. this.state = State.STOPPED;
  1061. }
  1062. }, {
  1063. key: 'tick',
  1064. value: function tick() {
  1065. this.ticks++;
  1066. if (this.ticks === 1) {
  1067. this.doTick();
  1068. if (this.ticks > 1) {
  1069. setTimeout(this.tick, 1);
  1070. }
  1071. this.ticks = 0;
  1072. }
  1073. }
  1074. }, {
  1075. key: 'doTick',
  1076. value: function doTick() {
  1077. var pos,
  1078. track,
  1079. trackDetails,
  1080. hls = this.hls,
  1081. config = hls.config;
  1082. //logger.log('audioStream:' + this.state);
  1083. switch (this.state) {
  1084. case State.ERROR:
  1085. //don't do anything in error state to avoid breaking further ...
  1086. case State.PAUSED:
  1087. //don't do anything in paused state either ...
  1088. case State.BUFFER_FLUSHING:
  1089. break;
  1090. case State.STARTING:
  1091. this.state = State.WAITING_TRACK;
  1092. this.loadedmetadata = false;
  1093. break;
  1094. case State.IDLE:
  1095. var tracks = this.tracks;
  1096. // audio tracks not received => exit loop
  1097. if (!tracks) {
  1098. break;
  1099. }
  1100. // if video not attached AND
  1101. // start fragment already requested OR start frag prefetch disable
  1102. // exit loop
  1103. // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
  1104. if (!this.media && (this.startFragRequested || !config.startFragPrefetch)) {
  1105. break;
  1106. }
  1107. // determine next candidate fragment to be loaded, based on current position and
  1108. // end of buffer position
  1109. // if we have not yet loaded any fragment, start loading from start position
  1110. if (this.loadedmetadata) {
  1111. pos = this.media.currentTime;
  1112. } else {
  1113. pos = this.nextLoadPosition;
  1114. }
  1115. var media = this.mediaBuffer ? this.mediaBuffer : this.media,
  1116. bufferInfo = _bufferHelper2.default.bufferInfo(media, pos, config.maxBufferHole),
  1117. bufferLen = bufferInfo.len,
  1118. bufferEnd = bufferInfo.end,
  1119. fragPrevious = this.fragPrevious,
  1120. maxBufLen = config.maxMaxBufferLength,
  1121. audioSwitch = this.audioSwitch,
  1122. trackId = this.trackId;
  1123. // if buffer length is less than maxBufLen try to load a new fragment
  1124. if ((bufferLen < maxBufLen || audioSwitch) && trackId < tracks.length) {
  1125. trackDetails = tracks[trackId].details;
  1126. // if track info not retrieved yet, switch state and wait for track retrieval
  1127. if (typeof trackDetails === 'undefined') {
  1128. this.state = State.WAITING_TRACK;
  1129. break;
  1130. }
  1131. // we just got done loading the final fragment, check if we need to finalize media stream
  1132. if (!audioSwitch && !trackDetails.live && fragPrevious && fragPrevious.sn === trackDetails.endSN) {
  1133. // if we are not seeking or if we are seeking but everything (almost) til the end is buffered, let's signal eos
  1134. // we don't compare exactly media.duration === bufferInfo.end as there could be some subtle media duration difference when switching
  1135. // between different renditions. using half frag duration should help cope with these cases.
  1136. if (!this.media.seeking || this.media.duration - bufferEnd < fragPrevious.duration / 2) {
  1137. // Finalize the media stream
  1138. this.hls.trigger(_events2.default.BUFFER_EOS, { type: 'audio' });
  1139. this.state = State.ENDED;
  1140. break;
  1141. }
  1142. }
  1143. // find fragment index, contiguous with end of buffer position
  1144. var fragments = trackDetails.fragments,
  1145. fragLen = fragments.length,
  1146. start = fragments[0].start,
  1147. end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
  1148. frag = void 0;
  1149. // When switching audio track, reload audio as close as possible to currentTime
  1150. if (audioSwitch) {
  1151. if (trackDetails.live && !trackDetails.PTSKnown) {
  1152. _logger.logger.log('switching audiotrack, live stream, unknown PTS,load first fragment');
  1153. bufferEnd = 0;
  1154. } else {
  1155. bufferEnd = pos;
  1156. // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime
  1157. if (trackDetails.PTSKnown && pos < start) {
  1158. // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start
  1159. if (bufferInfo.end > start || bufferInfo.nextStart) {
  1160. _logger.logger.log('alt audio track ahead of main track, seek to start of alt audio track');
  1161. this.media.currentTime = start + 0.05;
  1162. } else {
  1163. return;
  1164. }
  1165. }
  1166. }
  1167. }
  1168. if (trackDetails.initSegment && !trackDetails.initSegment.data) {
  1169. frag = trackDetails.initSegment;
  1170. }
  1171. // if bufferEnd before start of playlist, load first fragment
  1172. else if (bufferEnd <= start) {
  1173. frag = fragments[0];
  1174. if (trackDetails.live && frag.loadIdx && frag.loadIdx === this.fragLoadIdx) {
  1175. // we just loaded this first fragment, and we are still lagging behind the start of the live playlist
  1176. // let's force seek to start
  1177. var nextBuffered = bufferInfo.nextStart ? bufferInfo.nextStart : start;
  1178. _logger.logger.log('no alt audio available @currentTime:' + this.media.currentTime + ', seeking @' + (nextBuffered + 0.05));
  1179. this.media.currentTime = nextBuffered + 0.05;
  1180. return;
  1181. }
  1182. } else {
  1183. var foundFrag = void 0;
  1184. var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
  1185. var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;
  1186. var fragmentWithinToleranceTest = function fragmentWithinToleranceTest(candidate) {
  1187. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  1188. // this is to cope with situations like
  1189. // bufferEnd = 9.991
  1190. // frag[Ø] : [0,10]
  1191. // frag[1] : [10,20]
  1192. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  1193. // frag start frag start+duration
  1194. // |-----------------------------|
  1195. // <---> <--->
  1196. // ...--------><-----------------------------><---------....
  1197. // previous frag matching fragment next frag
  1198. // return -1 return 0 return 1
  1199. //logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  1200. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  1201. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration);
  1202. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  1203. return 1;
  1204. } // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  1205. else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  1206. return -1;
  1207. }
  1208. return 0;
  1209. };
  1210. if (bufferEnd < end) {
  1211. if (bufferEnd > end - maxFragLookUpTolerance) {
  1212. maxFragLookUpTolerance = 0;
  1213. }
  1214. // Prefer the next fragment if it's within tolerance
  1215. if (fragNext && !fragmentWithinToleranceTest(fragNext)) {
  1216. foundFrag = fragNext;
  1217. } else {
  1218. foundFrag = _binarySearch2.default.search(fragments, fragmentWithinToleranceTest);
  1219. }
  1220. } else {
  1221. // reach end of playlist
  1222. foundFrag = fragments[fragLen - 1];
  1223. }
  1224. if (foundFrag) {
  1225. frag = foundFrag;
  1226. start = foundFrag.start;
  1227. //logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
  1228. if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) {
  1229. if (frag.sn < trackDetails.endSN) {
  1230. frag = fragments[frag.sn + 1 - trackDetails.startSN];
  1231. _logger.logger.log('SN just loaded, load next one: ' + frag.sn);
  1232. } else {
  1233. frag = null;
  1234. }
  1235. }
  1236. }
  1237. }
  1238. if (frag) {
  1239. //logger.log(' loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));
  1240. if (frag.decryptdata && frag.decryptdata.uri != null && frag.decryptdata.key == null) {
  1241. _logger.logger.log('Loading key for ' + frag.sn + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId);
  1242. this.state = State.KEY_LOADING;
  1243. hls.trigger(_events2.default.KEY_LOADING, { frag: frag });
  1244. } else {
  1245. _logger.logger.log('Loading ' + frag.sn + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId + ', currentTime:' + pos + ',bufferEnd:' + bufferEnd.toFixed(3));
  1246. // ensure that we are not reloading the same fragments in loop ...
  1247. if (this.fragLoadIdx !== undefined) {
  1248. this.fragLoadIdx++;
  1249. } else {
  1250. this.fragLoadIdx = 0;
  1251. }
  1252. if (frag.loadCounter) {
  1253. frag.loadCounter++;
  1254. var maxThreshold = config.fragLoadingLoopThreshold;
  1255. // if this frag has already been loaded 3 times, and if it has been reloaded recently
  1256. if (frag.loadCounter > maxThreshold && Math.abs(this.fragLoadIdx - frag.loadIdx) < maxThreshold) {
  1257. hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag });
  1258. return;
  1259. }
  1260. } else {
  1261. frag.loadCounter = 1;
  1262. }
  1263. frag.loadIdx = this.fragLoadIdx;
  1264. this.fragCurrent = frag;
  1265. this.startFragRequested = true;
  1266. if (!isNaN(frag.sn)) {
  1267. this.nextLoadPosition = frag.start + frag.duration;
  1268. }
  1269. hls.trigger(_events2.default.FRAG_LOADING, { frag: frag });
  1270. this.state = State.FRAG_LOADING;
  1271. }
  1272. }
  1273. }
  1274. break;
  1275. case State.WAITING_TRACK:
  1276. track = this.tracks[this.trackId];
  1277. // check if playlist is already loaded
  1278. if (track && track.details) {
  1279. this.state = State.IDLE;
  1280. }
  1281. break;
  1282. case State.FRAG_LOADING_WAITING_RETRY:
  1283. var now = performance.now();
  1284. var retryDate = this.retryDate;
  1285. media = this.media;
  1286. var isSeeking = media && media.seeking;
  1287. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  1288. if (!retryDate || now >= retryDate || isSeeking) {
  1289. _logger.logger.log('audioStreamController: retryDate reached, switch back to IDLE state');
  1290. this.state = State.IDLE;
  1291. }
  1292. break;
  1293. case State.WAITING_INIT_PTS:
  1294. case State.STOPPED:
  1295. case State.FRAG_LOADING:
  1296. case State.PARSING:
  1297. case State.PARSED:
  1298. case State.ENDED:
  1299. break;
  1300. default:
  1301. break;
  1302. }
  1303. }
  1304. }, {
  1305. key: 'onMediaAttached',
  1306. value: function onMediaAttached(data) {
  1307. var media = this.media = this.mediaBuffer = data.media;
  1308. this.onvseeking = this.onMediaSeeking.bind(this);
  1309. this.onvended = this.onMediaEnded.bind(this);
  1310. media.addEventListener('seeking', this.onvseeking);
  1311. media.addEventListener('ended', this.onvended);
  1312. var config = this.config;
  1313. if (this.tracks && config.autoStartLoad) {
  1314. this.startLoad(config.startPosition);
  1315. }
  1316. }
  1317. }, {
  1318. key: 'onMediaDetaching',
  1319. value: function onMediaDetaching() {
  1320. var media = this.media;
  1321. if (media && media.ended) {
  1322. _logger.logger.log('MSE detaching and video ended, reset startPosition');
  1323. this.startPosition = this.lastCurrentTime = 0;
  1324. }
  1325. // reset fragment loading counter on MSE detaching to avoid reporting FRAG_LOOP_LOADING_ERROR after error recovery
  1326. var tracks = this.tracks;
  1327. if (tracks) {
  1328. // reset fragment load counter
  1329. tracks.forEach(function (track) {
  1330. if (track.details) {
  1331. track.details.fragments.forEach(function (fragment) {
  1332. fragment.loadCounter = undefined;
  1333. });
  1334. }
  1335. });
  1336. }
  1337. // remove video listeners
  1338. if (media) {
  1339. media.removeEventListener('seeking', this.onvseeking);
  1340. media.removeEventListener('ended', this.onvended);
  1341. this.onvseeking = this.onvseeked = this.onvended = null;
  1342. }
  1343. this.media = this.mediaBuffer = null;
  1344. this.loadedmetadata = false;
  1345. this.stopLoad();
  1346. }
  1347. }, {
  1348. key: 'onMediaSeeking',
  1349. value: function onMediaSeeking() {
  1350. if (this.state === State.ENDED) {
  1351. // switch to IDLE state to check for potential new fragment
  1352. this.state = State.IDLE;
  1353. }
  1354. if (this.media) {
  1355. this.lastCurrentTime = this.media.currentTime;
  1356. }
  1357. // avoid reporting fragment loop loading error in case user is seeking several times on same position
  1358. if (this.fragLoadIdx !== undefined) {
  1359. this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
  1360. }
  1361. // tick to speed up processing
  1362. this.tick();
  1363. }
  1364. }, {
  1365. key: 'onMediaEnded',
  1366. value: function onMediaEnded() {
  1367. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  1368. this.startPosition = this.lastCurrentTime = 0;
  1369. }
  1370. }, {
  1371. key: 'onAudioTracksUpdated',
  1372. value: function onAudioTracksUpdated(data) {
  1373. _logger.logger.log('audio tracks updated');
  1374. this.tracks = data.audioTracks;
  1375. }
  1376. }, {
  1377. key: 'onAudioTrackSwitching',
  1378. value: function onAudioTrackSwitching(data) {
  1379. // if any URL found on new audio track, it is an alternate audio track
  1380. var altAudio = !!data.url;
  1381. this.trackId = data.id;
  1382. this.state = State.IDLE;
  1383. this.fragCurrent = null;
  1384. this.state = State.PAUSED;
  1385. this.waitingFragment = null;
  1386. // destroy useless demuxer when switching audio to main
  1387. if (!altAudio) {
  1388. if (this.demuxer) {
  1389. this.demuxer.destroy();
  1390. this.demuxer = null;
  1391. }
  1392. } else {
  1393. // switching to audio track, start timer if not already started
  1394. if (!this.timer) {
  1395. this.timer = setInterval(this.ontick, 100);
  1396. }
  1397. }
  1398. //should we switch tracks ?
  1399. if (altAudio) {
  1400. this.audioSwitch = true;
  1401. //main audio track are handled by stream-controller, just do something if switching to alt audio track
  1402. this.state = State.IDLE;
  1403. // increase fragment load Index to avoid frag loop loading error after buffer flush
  1404. if (this.fragLoadIdx !== undefined) {
  1405. this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
  1406. }
  1407. }
  1408. this.tick();
  1409. }
  1410. }, {
  1411. key: 'onAudioTrackLoaded',
  1412. value: function onAudioTrackLoaded(data) {
  1413. var newDetails = data.details,
  1414. trackId = data.id,
  1415. track = this.tracks[trackId],
  1416. duration = newDetails.totalduration,
  1417. sliding = 0;
  1418. _logger.logger.log('track ' + trackId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration);
  1419. if (newDetails.live) {
  1420. var curDetails = track.details;
  1421. if (curDetails && newDetails.fragments.length > 0) {
  1422. // we already have details for that level, merge them
  1423. _levelHelper2.default.mergeDetails(curDetails, newDetails);
  1424. sliding = newDetails.fragments[0].start;
  1425. // TODO
  1426. //this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
  1427. if (newDetails.PTSKnown) {
  1428. _logger.logger.log('live audio playlist sliding:' + sliding.toFixed(3));
  1429. } else {
  1430. _logger.logger.log('live audio playlist - outdated PTS, unknown sliding');
  1431. }
  1432. } else {
  1433. newDetails.PTSKnown = false;
  1434. _logger.logger.log('live audio playlist - first load, unknown sliding');
  1435. }
  1436. } else {
  1437. newDetails.PTSKnown = false;
  1438. }
  1439. track.details = newDetails;
  1440. // compute start position
  1441. if (!this.startFragRequested) {
  1442. // compute start position if set to -1. use it straight away if value is defined
  1443. if (this.startPosition === -1) {
  1444. // first, check if start time offset has been set in playlist, if yes, use this value
  1445. var startTimeOffset = newDetails.startTimeOffset;
  1446. if (!isNaN(startTimeOffset)) {
  1447. _logger.logger.log('start time offset found in playlist, adjust startPosition to ' + startTimeOffset);
  1448. this.startPosition = startTimeOffset;
  1449. } else {
  1450. this.startPosition = 0;
  1451. }
  1452. }
  1453. this.nextLoadPosition = this.startPosition;
  1454. }
  1455. // only switch batck to IDLE state if we were waiting for track to start downloading a new fragment
  1456. if (this.state === State.WAITING_TRACK) {
  1457. this.state = State.IDLE;
  1458. }
  1459. //trigger handler right now
  1460. this.tick();
  1461. }
  1462. }, {
  1463. key: 'onKeyLoaded',
  1464. value: function onKeyLoaded() {
  1465. if (this.state === State.KEY_LOADING) {
  1466. this.state = State.IDLE;
  1467. this.tick();
  1468. }
  1469. }
  1470. }, {
  1471. key: 'onFragLoaded',
  1472. value: function onFragLoaded(data) {
  1473. var fragCurrent = this.fragCurrent,
  1474. fragLoaded = data.frag;
  1475. if (this.state === State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'audio' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
  1476. var track = this.tracks[this.trackId],
  1477. details = track.details,
  1478. duration = details.totalduration,
  1479. trackId = fragCurrent.level,
  1480. sn = fragCurrent.sn,
  1481. cc = fragCurrent.cc,
  1482. audioCodec = this.config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2',
  1483. stats = this.stats = data.stats;
  1484. if (sn === 'initSegment') {
  1485. this.state = State.IDLE;
  1486. stats.tparsed = stats.tbuffered = performance.now();
  1487. details.initSegment.data = data.payload;
  1488. this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'audio' });
  1489. this.tick();
  1490. } else {
  1491. this.state = State.PARSING;
  1492. // transmux the MPEG-TS data to ISO-BMFF segments
  1493. this.appended = false;
  1494. if (!this.demuxer) {
  1495. this.demuxer = new _demuxer2.default(this.hls, 'audio');
  1496. }
  1497. //Check if we have video initPTS
  1498. // If not we need to wait for it
  1499. var initPTS = this.initPTS[cc];
  1500. var initSegmentData = details.initSegment ? details.initSegment.data : [];
  1501. if (initSegmentData || initPTS !== undefined) {
  1502. this.pendingBuffering = true;
  1503. _logger.logger.log('Demuxing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],track ' + trackId);
  1504. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  1505. var accurateTimeOffset = false; //details.PTSKnown || !details.live;
  1506. this.demuxer.push(data.payload, initSegmentData, audioCodec, null, fragCurrent, duration, accurateTimeOffset, initPTS);
  1507. } else {
  1508. _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);
  1509. this.waitingFragment = data;
  1510. this.state = State.WAITING_INIT_PTS;
  1511. }
  1512. }
  1513. }
  1514. this.fragLoadError = 0;
  1515. }
  1516. }, {
  1517. key: 'onFragParsingInitSegment',
  1518. value: function onFragParsingInitSegment(data) {
  1519. var fragCurrent = this.fragCurrent;
  1520. var fragNew = data.frag;
  1521. if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
  1522. var tracks = data.tracks,
  1523. track = void 0;
  1524. // delete any video track found on audio demuxer
  1525. if (tracks.video) {
  1526. delete tracks.video;
  1527. }
  1528. // include levelCodec in audio and video tracks
  1529. track = tracks.audio;
  1530. if (track) {
  1531. track.levelCodec = 'mp4a.40.2';
  1532. track.id = data.id;
  1533. this.hls.trigger(_events2.default.BUFFER_CODECS, tracks);
  1534. _logger.logger.log('audio track:audio,container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']');
  1535. var initSegment = track.initSegment;
  1536. if (initSegment) {
  1537. var appendObj = { type: 'audio', data: initSegment, parent: 'audio', content: 'initSegment' };
  1538. if (this.audioSwitch) {
  1539. this.pendingData = [appendObj];
  1540. } else {
  1541. this.appended = true;
  1542. // arm pending Buffering flag before appending a segment
  1543. this.pendingBuffering = true;
  1544. this.hls.trigger(_events2.default.BUFFER_APPENDING, appendObj);
  1545. }
  1546. }
  1547. //trigger handler right now
  1548. this.tick();
  1549. }
  1550. }
  1551. }
  1552. }, {
  1553. key: 'onFragParsingData',
  1554. value: function onFragParsingData(data) {
  1555. var _this2 = this;
  1556. var fragCurrent = this.fragCurrent;
  1557. var fragNew = data.frag;
  1558. if (fragCurrent && data.id === 'audio' && data.type === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
  1559. var trackId = this.trackId,
  1560. track = this.tracks[trackId],
  1561. hls = this.hls;
  1562. if (isNaN(data.endPTS)) {
  1563. data.endPTS = data.startPTS + fragCurrent.duration;
  1564. data.endDTS = data.startDTS + fragCurrent.duration;
  1565. }
  1566. _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);
  1567. _levelHelper2.default.updateFragPTSDTS(track.details, fragCurrent.sn, data.startPTS, data.endPTS);
  1568. var audioSwitch = this.audioSwitch,
  1569. media = this.media,
  1570. appendOnBufferFlush = false;
  1571. //Only flush audio from old audio tracks when PTS is known on new audio track
  1572. if (audioSwitch && media) {
  1573. if (media.readyState) {
  1574. var currentTime = media.currentTime;
  1575. _logger.logger.log('switching audio track : currentTime:' + currentTime);
  1576. if (currentTime >= data.startPTS) {
  1577. _logger.logger.log('switching audio track : flushing all audio');
  1578. this.state = State.BUFFER_FLUSHING;
  1579. hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
  1580. appendOnBufferFlush = true;
  1581. //Lets announce that the initial audio track switch flush occur
  1582. this.audioSwitch = false;
  1583. hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: trackId });
  1584. }
  1585. } else {
  1586. //Lets announce that the initial audio track switch flush occur
  1587. this.audioSwitch = false;
  1588. hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: trackId });
  1589. }
  1590. }
  1591. var pendingData = this.pendingData;
  1592. if (!this.audioSwitch) {
  1593. [data.data1, data.data2].forEach(function (buffer) {
  1594. if (buffer && buffer.length) {
  1595. pendingData.push({ type: data.type, data: buffer, parent: 'audio', content: 'data' });
  1596. }
  1597. });
  1598. if (!appendOnBufferFlush && pendingData.length) {
  1599. pendingData.forEach(function (appendObj) {
  1600. // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
  1601. // in that case it is useless to append following segments
  1602. if (_this2.state === State.PARSING) {
  1603. // arm pending Buffering flag before appending a segment
  1604. _this2.pendingBuffering = true;
  1605. _this2.hls.trigger(_events2.default.BUFFER_APPENDING, appendObj);
  1606. }
  1607. });
  1608. this.pendingData = [];
  1609. this.appended = true;
  1610. }
  1611. }
  1612. //trigger handler right now
  1613. this.tick();
  1614. }
  1615. }
  1616. }, {
  1617. key: 'onFragParsed',
  1618. value: function onFragParsed(data) {
  1619. var fragCurrent = this.fragCurrent;
  1620. var fragNew = data.frag;
  1621. if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
  1622. this.stats.tparsed = performance.now();
  1623. this.state = State.PARSED;
  1624. this._checkAppendedParsed();
  1625. }
  1626. }
  1627. }, {
  1628. key: 'onBufferCreated',
  1629. value: function onBufferCreated(data) {
  1630. var audioTrack = data.tracks.audio;
  1631. if (audioTrack) {
  1632. this.mediaBuffer = audioTrack.buffer;
  1633. this.loadedmetadata = true;
  1634. }
  1635. }
  1636. }, {
  1637. key: 'onBufferAppended',
  1638. value: function onBufferAppended(data) {
  1639. if (data.parent === 'audio') {
  1640. var state = this.state;
  1641. if (state === State.PARSING || state === State.PARSED) {
  1642. // check if all buffers have been appended
  1643. this.pendingBuffering = data.pending > 0;
  1644. this._checkAppendedParsed();
  1645. }
  1646. }
  1647. }
  1648. }, {
  1649. key: '_checkAppendedParsed',
  1650. value: function _checkAppendedParsed() {
  1651. //trigger handler right now
  1652. if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {
  1653. var frag = this.fragCurrent,
  1654. stats = this.stats,
  1655. hls = this.hls;
  1656. if (frag) {
  1657. this.fragPrevious = frag;
  1658. stats.tbuffered = performance.now();
  1659. hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'audio' });
  1660. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  1661. _logger.logger.log('audio buffered : ' + _timeRanges2.default.toString(media.buffered));
  1662. if (this.audioSwitch && this.appended) {
  1663. this.audioSwitch = false;
  1664. hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: this.trackId });
  1665. }
  1666. this.state = State.IDLE;
  1667. }
  1668. this.tick();
  1669. }
  1670. }
  1671. }, {
  1672. key: 'onError',
  1673. value: function onError(data) {
  1674. var frag = data.frag;
  1675. // don't handle frag error not related to audio fragment
  1676. if (frag && frag.type !== 'audio') {
  1677. return;
  1678. }
  1679. switch (data.details) {
  1680. case _errors.ErrorDetails.FRAG_LOAD_ERROR:
  1681. case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
  1682. if (!data.fatal) {
  1683. var loadError = this.fragLoadError;
  1684. if (loadError) {
  1685. loadError++;
  1686. } else {
  1687. loadError = 1;
  1688. }
  1689. var config = this.config;
  1690. if (loadError <= config.fragLoadingMaxRetry) {
  1691. this.fragLoadError = loadError;
  1692. // reset load counter to avoid frag loop loading error
  1693. frag.loadCounter = 0;
  1694. // exponential backoff capped to config.fragLoadingMaxRetryTimeout
  1695. var delay = Math.min(Math.pow(2, loadError - 1) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);
  1696. _logger.logger.warn('audioStreamController: frag loading failed, retry in ' + delay + ' ms');
  1697. this.retryDate = performance.now() + delay;
  1698. // retry loading state
  1699. this.state = State.FRAG_LOADING_WAITING_RETRY;
  1700. } else {
  1701. _logger.logger.error('audioStreamController: ' + data.details + ' reaches max retry, redispatch as fatal ...');
  1702. // switch error to fatal
  1703. data.fatal = true;
  1704. this.state = State.ERROR;
  1705. }
  1706. }
  1707. break;
  1708. case _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR:
  1709. case _errors.ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  1710. case _errors.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  1711. case _errors.ErrorDetails.KEY_LOAD_ERROR:
  1712. case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
  1713. // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received
  1714. if (this.state !== State.ERROR) {
  1715. // if fatal error, stop processing, otherwise move to IDLE to retry loading
  1716. this.state = data.fatal ? State.ERROR : State.IDLE;
  1717. _logger.logger.warn('audioStreamController: ' + data.details + ' while loading frag,switch to ' + this.state + ' state ...');
  1718. }
  1719. break;
  1720. case _errors.ErrorDetails.BUFFER_FULL_ERROR:
  1721. // if in appending state
  1722. if (data.parent === 'audio' && (this.state === State.PARSING || this.state === State.PARSED)) {
  1723. var media = this.mediaBuffer,
  1724. currentTime = this.media.currentTime,
  1725. mediaBuffered = media && _bufferHelper2.default.isBuffered(media, currentTime) && _bufferHelper2.default.isBuffered(media, currentTime + 0.5);
  1726. // reduce max buf len if current position is buffered
  1727. if (mediaBuffered) {
  1728. var _config = this.config;
  1729. if (_config.maxMaxBufferLength >= _config.maxBufferLength) {
  1730. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  1731. _config.maxMaxBufferLength /= 2;
  1732. _logger.logger.warn('audio:reduce max buffer length to ' + _config.maxMaxBufferLength + 's');
  1733. // increase fragment load Index to avoid frag loop loading error after buffer flush
  1734. this.fragLoadIdx += 2 * _config.fragLoadingLoopThreshold;
  1735. }
  1736. this.state = State.IDLE;
  1737. } else {
  1738. // current position is not buffered, but browser is still complaining about buffer full error
  1739. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  1740. // in that case flush the whole audio buffer to recover
  1741. _logger.logger.warn('buffer full error also media.currentTime is not buffered, flush audio buffer');
  1742. this.fragCurrent = null;
  1743. // flush everything
  1744. this.state = State.BUFFER_FLUSHING;
  1745. this.hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
  1746. }
  1747. }
  1748. break;
  1749. default:
  1750. break;
  1751. }
  1752. }
  1753. }, {
  1754. key: 'onBufferFlushed',
  1755. value: function onBufferFlushed() {
  1756. var _this3 = this;
  1757. var pendingData = this.pendingData;
  1758. if (pendingData && pendingData.length) {
  1759. _logger.logger.log('appending pending audio data on Buffer Flushed');
  1760. pendingData.forEach(function (appendObj) {
  1761. _this3.hls.trigger(_events2.default.BUFFER_APPENDING, appendObj);
  1762. });
  1763. this.appended = true;
  1764. this.pendingData = [];
  1765. this.state = State.PARSED;
  1766. } else {
  1767. // move to IDLE once flush complete. this should trigger new fragment loading
  1768. this.state = State.IDLE;
  1769. // reset reference to frag
  1770. this.fragPrevious = null;
  1771. this.tick();
  1772. }
  1773. }
  1774. }, {
  1775. key: 'state',
  1776. set: function set(nextState) {
  1777. if (this.state !== nextState) {
  1778. var previousState = this.state;
  1779. this._state = nextState;
  1780. _logger.logger.log('audio stream:' + previousState + '->' + nextState);
  1781. }
  1782. },
  1783. get: function get() {
  1784. return this._state;
  1785. }
  1786. }]);
  1787. return AudioStreamController;
  1788. }(_eventHandler2.default);
  1789. exports.default = AudioStreamController;
  1790. },{"24":24,"30":30,"31":31,"32":32,"34":34,"35":35,"45":45,"50":50,"51":51}],7:[function(_dereq_,module,exports){
  1791. 'use strict';
  1792. Object.defineProperty(exports, "__esModule", {
  1793. value: true
  1794. });
  1795. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  1796. var _events = _dereq_(32);
  1797. var _events2 = _interopRequireDefault(_events);
  1798. var _eventHandler = _dereq_(31);
  1799. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  1800. var _logger = _dereq_(50);
  1801. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1802. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1803. 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; }
  1804. 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; } /*
  1805. * audio track controller
  1806. */
  1807. var AudioTrackController = function (_EventHandler) {
  1808. _inherits(AudioTrackController, _EventHandler);
  1809. function AudioTrackController(hls) {
  1810. _classCallCheck(this, AudioTrackController);
  1811. var _this = _possibleConstructorReturn(this, (AudioTrackController.__proto__ || Object.getPrototypeOf(AudioTrackController)).call(this, hls, _events2.default.MANIFEST_LOADING, _events2.default.MANIFEST_LOADED, _events2.default.AUDIO_TRACK_LOADED));
  1812. _this.ticks = 0;
  1813. _this.ontick = _this.tick.bind(_this);
  1814. return _this;
  1815. }
  1816. _createClass(AudioTrackController, [{
  1817. key: 'destroy',
  1818. value: function destroy() {
  1819. _eventHandler2.default.prototype.destroy.call(this);
  1820. }
  1821. }, {
  1822. key: 'tick',
  1823. value: function tick() {
  1824. this.ticks++;
  1825. if (this.ticks === 1) {
  1826. this.doTick();
  1827. if (this.ticks > 1) {
  1828. setTimeout(this.tick, 1);
  1829. }
  1830. this.ticks = 0;
  1831. }
  1832. }
  1833. }, {
  1834. key: 'doTick',
  1835. value: function doTick() {
  1836. this.updateTrack(this.trackId);
  1837. }
  1838. }, {
  1839. key: 'onManifestLoading',
  1840. value: function onManifestLoading() {
  1841. // reset audio tracks on manifest loading
  1842. this.tracks = [];
  1843. this.trackId = -1;
  1844. }
  1845. }, {
  1846. key: 'onManifestLoaded',
  1847. value: function onManifestLoaded(data) {
  1848. var _this2 = this;
  1849. var tracks = data.audioTracks || [];
  1850. var defaultFound = false;
  1851. this.tracks = tracks;
  1852. this.hls.trigger(_events2.default.AUDIO_TRACKS_UPDATED, { audioTracks: tracks });
  1853. // loop through available audio tracks and autoselect default if needed
  1854. var id = 0;
  1855. tracks.forEach(function (track) {
  1856. if (track.default) {
  1857. _this2.audioTrack = id;
  1858. defaultFound = true;
  1859. return;
  1860. }
  1861. id++;
  1862. });
  1863. if (defaultFound === false && tracks.length) {
  1864. _logger.logger.log('no default audio track defined, use first audio track as default');
  1865. this.audioTrack = 0;
  1866. }
  1867. }
  1868. }, {
  1869. key: 'onAudioTrackLoaded',
  1870. value: function onAudioTrackLoaded(data) {
  1871. if (data.id < this.tracks.length) {
  1872. _logger.logger.log('audioTrack ' + data.id + ' loaded');
  1873. this.tracks[data.id].details = data.details;
  1874. // check if current playlist is a live playlist
  1875. if (data.details.live && !this.timer) {
  1876. // if live playlist we will have to reload it periodically
  1877. // set reload period to playlist target duration
  1878. this.timer = setInterval(this.ontick, 1000 * data.details.targetduration);
  1879. }
  1880. if (!data.details.live && this.timer) {
  1881. // playlist is not live and timer is armed : stopping it
  1882. clearInterval(this.timer);
  1883. this.timer = null;
  1884. }
  1885. }
  1886. }
  1887. /** get alternate audio tracks list from playlist **/
  1888. }, {
  1889. key: 'setAudioTrackInternal',
  1890. value: function setAudioTrackInternal(newId) {
  1891. // check if level idx is valid
  1892. if (newId >= 0 && newId < this.tracks.length) {
  1893. // stopping live reloading timer if any
  1894. if (this.timer) {
  1895. clearInterval(this.timer);
  1896. this.timer = null;
  1897. }
  1898. this.trackId = newId;
  1899. _logger.logger.log('switching to audioTrack ' + newId);
  1900. var audioTrack = this.tracks[newId],
  1901. hls = this.hls,
  1902. type = audioTrack.type,
  1903. url = audioTrack.url,
  1904. eventObj = { id: newId, type: type, url: url };
  1905. // keep AUDIO_TRACK_SWITCH for legacy reason
  1906. hls.trigger(_events2.default.AUDIO_TRACK_SWITCH, eventObj);
  1907. hls.trigger(_events2.default.AUDIO_TRACK_SWITCHING, eventObj);
  1908. // check if we need to load playlist for this audio Track
  1909. var details = audioTrack.details;
  1910. if (url && (details === undefined || details.live === true)) {
  1911. // track not retrieved yet, or live playlist we need to (re)load it
  1912. _logger.logger.log('(re)loading playlist for audioTrack ' + newId);
  1913. hls.trigger(_events2.default.AUDIO_TRACK_LOADING, { url: url, id: newId });
  1914. }
  1915. }
  1916. }
  1917. }, {
  1918. key: 'updateTrack',
  1919. value: function updateTrack(newId) {
  1920. // check if level idx is valid
  1921. if (newId >= 0 && newId < this.tracks.length) {
  1922. // stopping live reloading timer if any
  1923. if (this.timer) {
  1924. clearInterval(this.timer);
  1925. this.timer = null;
  1926. }
  1927. this.trackId = newId;
  1928. _logger.logger.log('updating audioTrack ' + newId);
  1929. var audioTrack = this.tracks[newId],
  1930. url = audioTrack.url;
  1931. // check if we need to load playlist for this audio Track
  1932. var details = audioTrack.details;
  1933. if (url && (details === undefined || details.live === true)) {
  1934. // track not retrieved yet, or live playlist we need to (re)load it
  1935. _logger.logger.log('(re)loading playlist for audioTrack ' + newId);
  1936. this.hls.trigger(_events2.default.AUDIO_TRACK_LOADING, { url: url, id: newId });
  1937. }
  1938. }
  1939. }
  1940. }, {
  1941. key: 'audioTracks',
  1942. get: function get() {
  1943. return this.tracks;
  1944. }
  1945. /** get index of the selected audio track (index in audio track lists) **/
  1946. }, {
  1947. key: 'audioTrack',
  1948. get: function get() {
  1949. return this.trackId;
  1950. }
  1951. /** select an audio track, based on its index in audio track lists**/
  1952. ,
  1953. set: function set(audioTrackId) {
  1954. if (this.trackId !== audioTrackId || this.tracks[audioTrackId].details === undefined) {
  1955. this.setAudioTrackInternal(audioTrackId);
  1956. }
  1957. }
  1958. }]);
  1959. return AudioTrackController;
  1960. }(_eventHandler2.default);
  1961. exports.default = AudioTrackController;
  1962. },{"31":31,"32":32,"50":50}],8:[function(_dereq_,module,exports){
  1963. 'use strict';
  1964. Object.defineProperty(exports, "__esModule", {
  1965. value: true
  1966. });
  1967. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  1968. var _events = _dereq_(32);
  1969. var _events2 = _interopRequireDefault(_events);
  1970. var _eventHandler = _dereq_(31);
  1971. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  1972. var _logger = _dereq_(50);
  1973. var _errors = _dereq_(30);
  1974. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1975. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1976. 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; }
  1977. 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; } /*
  1978. * Buffer Controller
  1979. */
  1980. var BufferController = function (_EventHandler) {
  1981. _inherits(BufferController, _EventHandler);
  1982. function BufferController(hls) {
  1983. _classCallCheck(this, BufferController);
  1984. // the value that we have set mediasource.duration to
  1985. // (the actual duration may be tweaked slighly by the browser)
  1986. 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));
  1987. _this._msDuration = null;
  1988. // the value that we want to set mediaSource.duration to
  1989. _this._levelDuration = null;
  1990. // Source Buffer listeners
  1991. _this.onsbue = _this.onSBUpdateEnd.bind(_this);
  1992. _this.onsbe = _this.onSBUpdateError.bind(_this);
  1993. _this.pendingTracks = {};
  1994. _this.tracks = {};
  1995. return _this;
  1996. }
  1997. _createClass(BufferController, [{
  1998. key: 'destroy',
  1999. value: function destroy() {
  2000. _eventHandler2.default.prototype.destroy.call(this);
  2001. }
  2002. }, {
  2003. key: 'onLevelPtsUpdated',
  2004. value: function onLevelPtsUpdated(data) {
  2005. var type = data.type;
  2006. var audioTrack = this.tracks.audio;
  2007. // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
  2008. // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
  2009. // 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
  2010. // `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend`
  2011. // event if SB is in updating state.
  2012. // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
  2013. if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') {
  2014. // Chrome audio mp3 track
  2015. var audioBuffer = this.sourceBuffer.audio;
  2016. var delta = Math.abs(audioBuffer.timestampOffset - data.start);
  2017. // adjust timestamp offset if time delta is greater than 100ms
  2018. if (delta > 0.1) {
  2019. var updating = audioBuffer.updating;
  2020. try {
  2021. audioBuffer.abort();
  2022. } catch (err) {
  2023. updating = true;
  2024. _logger.logger.warn('can not abort audio buffer: ' + err);
  2025. }
  2026. if (!updating) {
  2027. _logger.logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.start);
  2028. audioBuffer.timestampOffset = data.start;
  2029. } else {
  2030. this.audioTimestampOffset = data.start;
  2031. }
  2032. }
  2033. }
  2034. }
  2035. }, {
  2036. key: 'onManifestParsed',
  2037. value: function onManifestParsed(data) {
  2038. var audioExpected = data.audio,
  2039. videoExpected = data.video,
  2040. sourceBufferNb = 0;
  2041. // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
  2042. // sourcebuffers will be created all at once when the expected nb of tracks will be reached
  2043. // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
  2044. // it will contain the expected nb of source buffers, no need to compute it
  2045. if (data.altAudio && (audioExpected || videoExpected)) {
  2046. sourceBufferNb = (audioExpected ? 1 : 0) + (videoExpected ? 1 : 0);
  2047. _logger.logger.log(sourceBufferNb + ' sourceBuffer(s) expected');
  2048. }
  2049. this.sourceBufferNb = sourceBufferNb;
  2050. }
  2051. }, {
  2052. key: 'onMediaAttaching',
  2053. value: function onMediaAttaching(data) {
  2054. var media = this.media = data.media;
  2055. if (media) {
  2056. // setup the media source
  2057. var ms = this.mediaSource = new MediaSource();
  2058. //Media Source listeners
  2059. this.onmso = this.onMediaSourceOpen.bind(this);
  2060. this.onmse = this.onMediaSourceEnded.bind(this);
  2061. this.onmsc = this.onMediaSourceClose.bind(this);
  2062. ms.addEventListener('sourceopen', this.onmso);
  2063. ms.addEventListener('sourceended', this.onmse);
  2064. ms.addEventListener('sourceclose', this.onmsc);
  2065. // link video and media Source
  2066. media.src = URL.createObjectURL(ms);
  2067. }
  2068. }
  2069. }, {
  2070. key: 'onMediaDetaching',
  2071. value: function onMediaDetaching() {
  2072. _logger.logger.log('media source detaching');
  2073. var ms = this.mediaSource;
  2074. if (ms) {
  2075. if (ms.readyState === 'open') {
  2076. try {
  2077. // endOfStream could trigger exception if any sourcebuffer is in updating state
  2078. // we don't really care about checking sourcebuffer state here,
  2079. // as we are anyway detaching the MediaSource
  2080. // let's just avoid this exception to propagate
  2081. ms.endOfStream();
  2082. } catch (err) {
  2083. _logger.logger.warn('onMediaDetaching:' + err.message + ' while calling endOfStream');
  2084. }
  2085. }
  2086. ms.removeEventListener('sourceopen', this.onmso);
  2087. ms.removeEventListener('sourceended', this.onmse);
  2088. ms.removeEventListener('sourceclose', this.onmsc);
  2089. // Detach properly the MediaSource from the HTMLMediaElement as
  2090. // suggested in https://github.com/w3c/media-source/issues/53.
  2091. if (this.media) {
  2092. URL.revokeObjectURL(this.media.src);
  2093. this.media.removeAttribute('src');
  2094. this.media.load();
  2095. }
  2096. this.mediaSource = null;
  2097. this.media = null;
  2098. this.pendingTracks = {};
  2099. this.tracks = {};
  2100. this.sourceBuffer = {};
  2101. this.flushRange = [];
  2102. this.segments = [];
  2103. this.appended = 0;
  2104. }
  2105. this.onmso = this.onmse = this.onmsc = null;
  2106. this.hls.trigger(_events2.default.MEDIA_DETACHED);
  2107. }
  2108. }, {
  2109. key: 'onMediaSourceOpen',
  2110. value: function onMediaSourceOpen() {
  2111. _logger.logger.log('media source opened');
  2112. this.hls.trigger(_events2.default.MEDIA_ATTACHED, { media: this.media });
  2113. var mediaSource = this.mediaSource;
  2114. if (mediaSource) {
  2115. // once received, don't listen anymore to sourceopen event
  2116. mediaSource.removeEventListener('sourceopen', this.onmso);
  2117. }
  2118. this.checkPendingTracks();
  2119. }
  2120. }, {
  2121. key: 'checkPendingTracks',
  2122. value: function checkPendingTracks() {
  2123. // if any buffer codecs pending, check if we have enough to create sourceBuffers
  2124. var pendingTracks = this.pendingTracks,
  2125. pendingTracksNb = Object.keys(pendingTracks).length;
  2126. // if any pending tracks and (if nb of pending tracks gt or equal than expected nb or if unknown expected nb)
  2127. if (pendingTracksNb && (this.sourceBufferNb <= pendingTracksNb || this.sourceBufferNb === 0)) {
  2128. // ok, let's create them now !
  2129. this.createSourceBuffers(pendingTracks);
  2130. this.pendingTracks = {};
  2131. // append any pending segments now !
  2132. this.doAppending();
  2133. }
  2134. }
  2135. }, {
  2136. key: 'onMediaSourceClose',
  2137. value: function onMediaSourceClose() {
  2138. _logger.logger.log('media source closed');
  2139. }
  2140. }, {
  2141. key: 'onMediaSourceEnded',
  2142. value: function onMediaSourceEnded() {
  2143. _logger.logger.log('media source ended');
  2144. }
  2145. }, {
  2146. key: 'onSBUpdateEnd',
  2147. value: function onSBUpdateEnd() {
  2148. // update timestampOffset
  2149. if (this.audioTimestampOffset) {
  2150. var audioBuffer = this.sourceBuffer.audio;
  2151. _logger.logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + this.audioTimestampOffset);
  2152. audioBuffer.timestampOffset = this.audioTimestampOffset;
  2153. delete this.audioTimestampOffset;
  2154. }
  2155. if (this._needsFlush) {
  2156. this.doFlush();
  2157. }
  2158. if (this._needsEos) {
  2159. this.checkEos();
  2160. }
  2161. this.appending = false;
  2162. var parent = this.parent;
  2163. // count nb of pending segments waiting for appending on this sourcebuffer
  2164. var pending = this.segments.reduce(function (counter, segment) {
  2165. return segment.parent === parent ? counter + 1 : counter;
  2166. }, 0);
  2167. this.hls.trigger(_events2.default.BUFFER_APPENDED, { parent: parent, pending: pending });
  2168. // don't append in flushing mode
  2169. if (!this._needsFlush) {
  2170. this.doAppending();
  2171. }
  2172. this.updateMediaElementDuration();
  2173. }
  2174. }, {
  2175. key: 'onSBUpdateError',
  2176. value: function onSBUpdateError(event) {
  2177. _logger.logger.error('sourceBuffer error:', event);
  2178. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  2179. // this error might not always be fatal (it is fatal if decode error is set, in that case
  2180. // it will be followed by a mediaElement error ...)
  2181. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false });
  2182. // we don't need to do more than that, as accordin to the spec, updateend will be fired just after
  2183. }
  2184. }, {
  2185. key: 'onBufferReset',
  2186. value: function onBufferReset() {
  2187. var sourceBuffer = this.sourceBuffer;
  2188. for (var type in sourceBuffer) {
  2189. var sb = sourceBuffer[type];
  2190. try {
  2191. this.mediaSource.removeSourceBuffer(sb);
  2192. sb.removeEventListener('updateend', this.onsbue);
  2193. sb.removeEventListener('error', this.onsbe);
  2194. } catch (err) {}
  2195. }
  2196. this.sourceBuffer = {};
  2197. this.flushRange = [];
  2198. this.segments = [];
  2199. this.appended = 0;
  2200. }
  2201. }, {
  2202. key: 'onBufferCodecs',
  2203. value: function onBufferCodecs(tracks) {
  2204. // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
  2205. // if sourcebuffers already created, do nothing ...
  2206. if (Object.keys(this.sourceBuffer).length === 0) {
  2207. for (var trackName in tracks) {
  2208. this.pendingTracks[trackName] = tracks[trackName];
  2209. }
  2210. var mediaSource = this.mediaSource;
  2211. if (mediaSource && mediaSource.readyState === 'open') {
  2212. // try to create sourcebuffers if mediasource opened
  2213. this.checkPendingTracks();
  2214. }
  2215. }
  2216. }
  2217. }, {
  2218. key: 'createSourceBuffers',
  2219. value: function createSourceBuffers(tracks) {
  2220. var sourceBuffer = this.sourceBuffer,
  2221. mediaSource = this.mediaSource;
  2222. for (var trackName in tracks) {
  2223. if (!sourceBuffer[trackName]) {
  2224. var track = tracks[trackName];
  2225. // use levelCodec as first priority
  2226. var codec = track.levelCodec || track.codec;
  2227. var mimeType = track.container + ';codecs=' + codec;
  2228. _logger.logger.log('creating sourceBuffer(' + mimeType + ')');
  2229. try {
  2230. var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
  2231. sb.addEventListener('updateend', this.onsbue);
  2232. sb.addEventListener('error', this.onsbe);
  2233. this.tracks[trackName] = { codec: codec, container: track.container };
  2234. track.buffer = sb;
  2235. } catch (err) {
  2236. _logger.logger.error('error while trying to add sourceBuffer:' + err.message);
  2237. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType });
  2238. }
  2239. }
  2240. }
  2241. this.hls.trigger(_events2.default.BUFFER_CREATED, { tracks: tracks });
  2242. }
  2243. }, {
  2244. key: 'onBufferAppending',
  2245. value: function onBufferAppending(data) {
  2246. if (!this._needsFlush) {
  2247. if (!this.segments) {
  2248. this.segments = [data];
  2249. } else {
  2250. this.segments.push(data);
  2251. }
  2252. this.doAppending();
  2253. }
  2254. }
  2255. }, {
  2256. key: 'onBufferAppendFail',
  2257. value: function onBufferAppendFail(data) {
  2258. _logger.logger.error('sourceBuffer error:', data.event);
  2259. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  2260. // this error might not always be fatal (it is fatal if decode error is set, in that case
  2261. // it will be followed by a mediaElement error ...)
  2262. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false });
  2263. }
  2264. // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
  2265. }, {
  2266. key: 'onBufferEos',
  2267. value: function onBufferEos(data) {
  2268. var sb = this.sourceBuffer;
  2269. var dataType = data.type;
  2270. for (var type in sb) {
  2271. if (!dataType || type === dataType) {
  2272. if (!sb[type].ended) {
  2273. sb[type].ended = true;
  2274. _logger.logger.log(type + ' sourceBuffer now EOS');
  2275. }
  2276. }
  2277. }
  2278. this.checkEos();
  2279. }
  2280. // if all source buffers are marked as ended, signal endOfStream() to MediaSource.
  2281. }, {
  2282. key: 'checkEos',
  2283. value: function checkEos() {
  2284. var sb = this.sourceBuffer,
  2285. mediaSource = this.mediaSource;
  2286. if (!mediaSource || mediaSource.readyState !== 'open') {
  2287. this._needsEos = false;
  2288. return;
  2289. }
  2290. for (var type in sb) {
  2291. var sbobj = sb[type];
  2292. if (!sbobj.ended) {
  2293. return;
  2294. }
  2295. if (sbobj.updating) {
  2296. this._needsEos = true;
  2297. return;
  2298. }
  2299. }
  2300. _logger.logger.log('all media data available, signal endOfStream() to MediaSource and stop loading fragment');
  2301. //Notify the media element that it now has all of the media data
  2302. try {
  2303. mediaSource.endOfStream();
  2304. } catch (e) {
  2305. _logger.logger.warn('exception while calling mediaSource.endOfStream()');
  2306. }
  2307. this._needsEos = false;
  2308. }
  2309. }, {
  2310. key: 'onBufferFlushing',
  2311. value: function onBufferFlushing(data) {
  2312. this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });
  2313. // attempt flush immediatly
  2314. this.flushBufferCounter = 0;
  2315. this.doFlush();
  2316. }
  2317. }, {
  2318. key: 'onLevelUpdated',
  2319. value: function onLevelUpdated(event) {
  2320. var details = event.details;
  2321. if (details.fragments.length === 0) {
  2322. return;
  2323. }
  2324. this._levelDuration = details.totalduration + details.fragments[0].start;
  2325. this.updateMediaElementDuration();
  2326. }
  2327. // https://github.com/video-dev/hls.js/issues/355
  2328. }, {
  2329. key: 'updateMediaElementDuration',
  2330. value: function updateMediaElementDuration() {
  2331. var media = this.media,
  2332. mediaSource = this.mediaSource,
  2333. sourceBuffer = this.sourceBuffer,
  2334. levelDuration = this._levelDuration;
  2335. if (levelDuration === null || !media || !mediaSource || !sourceBuffer || media.readyState === 0 || mediaSource.readyState !== 'open') {
  2336. return;
  2337. }
  2338. for (var type in sourceBuffer) {
  2339. if (sourceBuffer[type].updating) {
  2340. // can't set duration whilst a buffer is updating
  2341. return;
  2342. }
  2343. }
  2344. if (this._msDuration === null) {
  2345. // initialise to the value that the media source is reporting
  2346. this._msDuration = mediaSource.duration;
  2347. }
  2348. var duration = media.duration;
  2349. // levelDuration was the last value we set.
  2350. // not using mediaSource.duration as the browser may tweak this value
  2351. // only update mediasource duration if its value increase, this is to avoid
  2352. // flushing already buffered portion when switching between quality level
  2353. if (levelDuration > this._msDuration && levelDuration > duration || duration === Infinity || isNaN(duration)) {
  2354. _logger.logger.log('Updating mediasource duration to ' + levelDuration.toFixed(3));
  2355. this._msDuration = mediaSource.duration = levelDuration;
  2356. }
  2357. }
  2358. }, {
  2359. key: 'doFlush',
  2360. value: function doFlush() {
  2361. // loop through all buffer ranges to flush
  2362. while (this.flushRange.length) {
  2363. var range = this.flushRange[0];
  2364. // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer
  2365. if (this.flushBuffer(range.start, range.end, range.type)) {
  2366. // range flushed, remove from flush array
  2367. this.flushRange.shift();
  2368. this.flushBufferCounter = 0;
  2369. } else {
  2370. this._needsFlush = true;
  2371. // avoid looping, wait for SB update end to retrigger a flush
  2372. return;
  2373. }
  2374. }
  2375. if (this.flushRange.length === 0) {
  2376. // everything flushed
  2377. this._needsFlush = false;
  2378. // let's recompute this.appended, which is used to avoid flush looping
  2379. var appended = 0;
  2380. var sourceBuffer = this.sourceBuffer;
  2381. try {
  2382. for (var type in sourceBuffer) {
  2383. appended += sourceBuffer[type].buffered.length;
  2384. }
  2385. } catch (error) {
  2386. // error could be thrown while accessing buffered, in case sourcebuffer has already been removed from MediaSource
  2387. // this is harmess at this stage, catch this to avoid reporting an internal exception
  2388. _logger.logger.error('error while accessing sourceBuffer.buffered');
  2389. }
  2390. this.appended = appended;
  2391. this.hls.trigger(_events2.default.BUFFER_FLUSHED);
  2392. }
  2393. }
  2394. }, {
  2395. key: 'doAppending',
  2396. value: function doAppending() {
  2397. var hls = this.hls,
  2398. sourceBuffer = this.sourceBuffer,
  2399. segments = this.segments;
  2400. if (Object.keys(sourceBuffer).length) {
  2401. if (this.media.error) {
  2402. this.segments = [];
  2403. _logger.logger.error('trying to append although a media error occured, flush segment and abort');
  2404. return;
  2405. }
  2406. if (this.appending) {
  2407. //logger.log(`sb appending in progress`);
  2408. return;
  2409. }
  2410. if (segments && segments.length) {
  2411. var segment = segments.shift();
  2412. try {
  2413. var type = segment.type,
  2414. sb = sourceBuffer[type];
  2415. if (sb) {
  2416. if (!sb.updating) {
  2417. // reset sourceBuffer ended flag before appending segment
  2418. sb.ended = false;
  2419. //logger.log(`appending ${segment.content} ${type} SB, size:${segment.data.length}, ${segment.parent}`);
  2420. this.parent = segment.parent;
  2421. sb.appendBuffer(segment.data);
  2422. this.appendError = 0;
  2423. this.appended++;
  2424. this.appending = true;
  2425. } else {
  2426. segments.unshift(segment);
  2427. }
  2428. } else {
  2429. // in case we don't have any source buffer matching with this segment type,
  2430. // it means that Mediasource fails to create sourcebuffer
  2431. // discard this segment, and trigger update end
  2432. this.onSBUpdateEnd();
  2433. }
  2434. } catch (err) {
  2435. // in case any error occured while appending, put back segment in segments table
  2436. _logger.logger.error('error while trying to append buffer:' + err.message);
  2437. segments.unshift(segment);
  2438. var event = { type: _errors.ErrorTypes.MEDIA_ERROR, parent: segment.parent };
  2439. if (err.code !== 22) {
  2440. if (this.appendError) {
  2441. this.appendError++;
  2442. } else {
  2443. this.appendError = 1;
  2444. }
  2445. event.details = _errors.ErrorDetails.BUFFER_APPEND_ERROR;
  2446. /* with UHD content, we could get loop of quota exceeded error until
  2447. browser is able to evict some data from sourcebuffer. retrying help recovering this
  2448. */
  2449. if (this.appendError > hls.config.appendErrorMaxRetry) {
  2450. _logger.logger.log('fail ' + hls.config.appendErrorMaxRetry + ' times to append segment in sourceBuffer');
  2451. segments = [];
  2452. event.fatal = true;
  2453. hls.trigger(_events2.default.ERROR, event);
  2454. return;
  2455. } else {
  2456. event.fatal = false;
  2457. hls.trigger(_events2.default.ERROR, event);
  2458. }
  2459. } else {
  2460. // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
  2461. // let's stop appending any segments, and report BUFFER_FULL_ERROR error
  2462. this.segments = [];
  2463. event.details = _errors.ErrorDetails.BUFFER_FULL_ERROR;
  2464. event.fatal = false;
  2465. hls.trigger(_events2.default.ERROR, event);
  2466. return;
  2467. }
  2468. }
  2469. }
  2470. }
  2471. }
  2472. /*
  2473. flush specified buffered range,
  2474. return true once range has been flushed.
  2475. as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end
  2476. */
  2477. }, {
  2478. key: 'flushBuffer',
  2479. value: function flushBuffer(startOffset, endOffset, typeIn) {
  2480. var sb,
  2481. i,
  2482. bufStart,
  2483. bufEnd,
  2484. flushStart,
  2485. flushEnd,
  2486. sourceBuffer = this.sourceBuffer;
  2487. if (Object.keys(sourceBuffer).length) {
  2488. _logger.logger.log('flushBuffer,pos/start/end: ' + this.media.currentTime.toFixed(3) + '/' + startOffset + '/' + endOffset);
  2489. // safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments
  2490. if (this.flushBufferCounter < this.appended) {
  2491. for (var type in sourceBuffer) {
  2492. // check if sourcebuffer type is defined (typeIn): if yes, let's only flush this one
  2493. // if no, let's flush all sourcebuffers
  2494. if (typeIn && type !== typeIn) {
  2495. continue;
  2496. }
  2497. sb = sourceBuffer[type];
  2498. // we are going to flush buffer, mark source buffer as 'not ended'
  2499. sb.ended = false;
  2500. if (!sb.updating) {
  2501. try {
  2502. for (i = 0; i < sb.buffered.length; i++) {
  2503. bufStart = sb.buffered.start(i);
  2504. bufEnd = sb.buffered.end(i);
  2505. // workaround firefox not able to properly flush multiple buffered range.
  2506. if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1 && endOffset === Number.POSITIVE_INFINITY) {
  2507. flushStart = startOffset;
  2508. flushEnd = endOffset;
  2509. } else {
  2510. flushStart = Math.max(bufStart, startOffset);
  2511. flushEnd = Math.min(bufEnd, endOffset);
  2512. }
  2513. /* sometimes sourcebuffer.remove() does not flush
  2514. the exact expected time range.
  2515. to avoid rounding issues/infinite loop,
  2516. only flush buffer range of length greater than 500ms.
  2517. */
  2518. if (Math.min(flushEnd, bufEnd) - flushStart > 0.5) {
  2519. this.flushBufferCounter++;
  2520. _logger.logger.log('flush ' + type + ' [' + flushStart + ',' + flushEnd + '], of [' + bufStart + ',' + bufEnd + '], pos:' + this.media.currentTime);
  2521. sb.remove(flushStart, flushEnd);
  2522. return false;
  2523. }
  2524. }
  2525. } catch (e) {
  2526. _logger.logger.warn('exception while accessing sourcebuffer, it might have been removed from MediaSource');
  2527. }
  2528. } else {
  2529. //logger.log('abort ' + type + ' append in progress');
  2530. // this will abort any appending in progress
  2531. //sb.abort();
  2532. _logger.logger.warn('cannot flush, sb updating in progress');
  2533. return false;
  2534. }
  2535. }
  2536. } else {
  2537. _logger.logger.warn('abort flushing too many retries');
  2538. }
  2539. _logger.logger.log('buffer flushed');
  2540. }
  2541. // everything flushed !
  2542. return true;
  2543. }
  2544. }]);
  2545. return BufferController;
  2546. }(_eventHandler2.default);
  2547. exports.default = BufferController;
  2548. },{"30":30,"31":31,"32":32,"50":50}],9:[function(_dereq_,module,exports){
  2549. 'use strict';
  2550. Object.defineProperty(exports, "__esModule", {
  2551. value: true
  2552. });
  2553. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  2554. var _events = _dereq_(32);
  2555. var _events2 = _interopRequireDefault(_events);
  2556. var _eventHandler = _dereq_(31);
  2557. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  2558. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2559. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2560. 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; }
  2561. 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; } /*
  2562. * cap stream level to media size dimension controller
  2563. */
  2564. var CapLevelController = function (_EventHandler) {
  2565. _inherits(CapLevelController, _EventHandler);
  2566. function CapLevelController(hls) {
  2567. _classCallCheck(this, CapLevelController);
  2568. return _possibleConstructorReturn(this, (CapLevelController.__proto__ || Object.getPrototypeOf(CapLevelController)).call(this, hls, _events2.default.FPS_DROP_LEVEL_CAPPING, _events2.default.MEDIA_ATTACHING, _events2.default.MANIFEST_PARSED));
  2569. }
  2570. _createClass(CapLevelController, [{
  2571. key: 'destroy',
  2572. value: function destroy() {
  2573. if (this.hls.config.capLevelToPlayerSize) {
  2574. this.media = this.restrictedLevels = null;
  2575. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  2576. if (this.timer) {
  2577. this.timer = clearInterval(this.timer);
  2578. }
  2579. }
  2580. }
  2581. }, {
  2582. key: 'onFpsDropLevelCapping',
  2583. value: function onFpsDropLevelCapping(data) {
  2584. if (!this.restrictedLevels) {
  2585. this.restrictedLevels = [];
  2586. }
  2587. if (!this.isLevelRestricted(data.droppedLevel)) {
  2588. this.restrictedLevels.push(data.droppedLevel);
  2589. }
  2590. }
  2591. }, {
  2592. key: 'onMediaAttaching',
  2593. value: function onMediaAttaching(data) {
  2594. this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  2595. }
  2596. }, {
  2597. key: 'onManifestParsed',
  2598. value: function onManifestParsed(data) {
  2599. var hls = this.hls;
  2600. if (hls.config.capLevelToPlayerSize) {
  2601. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  2602. this.levels = data.levels;
  2603. hls.firstLevel = this.getMaxLevel(data.firstLevel);
  2604. clearInterval(this.timer);
  2605. this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);
  2606. this.detectPlayerSize();
  2607. }
  2608. }
  2609. }, {
  2610. key: 'detectPlayerSize',
  2611. value: function detectPlayerSize() {
  2612. if (this.media) {
  2613. var levelsLength = this.levels ? this.levels.length : 0;
  2614. if (levelsLength) {
  2615. var hls = this.hls;
  2616. hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);
  2617. if (hls.autoLevelCapping > this.autoLevelCapping) {
  2618. // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
  2619. // usually happen when the user go to the fullscreen mode.
  2620. hls.streamController.nextLevelSwitch();
  2621. }
  2622. this.autoLevelCapping = hls.autoLevelCapping;
  2623. }
  2624. }
  2625. }
  2626. /*
  2627. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  2628. */
  2629. }, {
  2630. key: 'getMaxLevel',
  2631. value: function getMaxLevel(capLevelIndex) {
  2632. var result = 0,
  2633. i = void 0,
  2634. level = void 0,
  2635. mWidth = this.mediaWidth,
  2636. mHeight = this.mediaHeight,
  2637. lWidth = 0,
  2638. lHeight = 0;
  2639. for (i = 0; i <= capLevelIndex; i++) {
  2640. level = this.levels[i];
  2641. if (this.isLevelRestricted(i)) {
  2642. break;
  2643. }
  2644. result = i;
  2645. lWidth = level.width;
  2646. lHeight = level.height;
  2647. if (mWidth <= lWidth || mHeight <= lHeight) {
  2648. break;
  2649. }
  2650. }
  2651. return result;
  2652. }
  2653. }, {
  2654. key: 'isLevelRestricted',
  2655. value: function isLevelRestricted(level) {
  2656. return this.restrictedLevels && this.restrictedLevels.indexOf(level) !== -1 ? true : false;
  2657. }
  2658. }, {
  2659. key: 'contentScaleFactor',
  2660. get: function get() {
  2661. var pixelRatio = 1;
  2662. try {
  2663. pixelRatio = window.devicePixelRatio;
  2664. } catch (e) {}
  2665. return pixelRatio;
  2666. }
  2667. }, {
  2668. key: 'mediaWidth',
  2669. get: function get() {
  2670. var width = void 0;
  2671. var media = this.media;
  2672. if (media) {
  2673. width = media.width || media.clientWidth || media.offsetWidth;
  2674. width *= this.contentScaleFactor;
  2675. }
  2676. return width;
  2677. }
  2678. }, {
  2679. key: 'mediaHeight',
  2680. get: function get() {
  2681. var height = void 0;
  2682. var media = this.media;
  2683. if (media) {
  2684. height = media.height || media.clientHeight || media.offsetHeight;
  2685. height *= this.contentScaleFactor;
  2686. }
  2687. return height;
  2688. }
  2689. }]);
  2690. return CapLevelController;
  2691. }(_eventHandler2.default);
  2692. exports.default = CapLevelController;
  2693. },{"31":31,"32":32}],10:[function(_dereq_,module,exports){
  2694. 'use strict';
  2695. Object.defineProperty(exports, "__esModule", {
  2696. value: true
  2697. });
  2698. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  2699. var _events = _dereq_(32);
  2700. var _events2 = _interopRequireDefault(_events);
  2701. var _eventHandler = _dereq_(31);
  2702. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  2703. var _logger = _dereq_(50);
  2704. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2705. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2706. 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; }
  2707. 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; } /*
  2708. * FPS Controller
  2709. */
  2710. var FPSController = function (_EventHandler) {
  2711. _inherits(FPSController, _EventHandler);
  2712. function FPSController(hls) {
  2713. _classCallCheck(this, FPSController);
  2714. return _possibleConstructorReturn(this, (FPSController.__proto__ || Object.getPrototypeOf(FPSController)).call(this, hls, _events2.default.MEDIA_ATTACHING));
  2715. }
  2716. _createClass(FPSController, [{
  2717. key: 'destroy',
  2718. value: function destroy() {
  2719. if (this.timer) {
  2720. clearInterval(this.timer);
  2721. }
  2722. this.isVideoPlaybackQualityAvailable = false;
  2723. }
  2724. }, {
  2725. key: 'onMediaAttaching',
  2726. value: function onMediaAttaching(data) {
  2727. var config = this.hls.config;
  2728. if (config.capLevelOnFPSDrop) {
  2729. var video = this.video = data.media instanceof HTMLVideoElement ? data.media : null;
  2730. if (typeof video.getVideoPlaybackQuality === 'function') {
  2731. this.isVideoPlaybackQualityAvailable = true;
  2732. }
  2733. clearInterval(this.timer);
  2734. this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  2735. }
  2736. }
  2737. }, {
  2738. key: 'checkFPS',
  2739. value: function checkFPS(video, decodedFrames, droppedFrames) {
  2740. var currentTime = performance.now();
  2741. if (decodedFrames) {
  2742. if (this.lastTime) {
  2743. var currentPeriod = currentTime - this.lastTime,
  2744. currentDropped = droppedFrames - this.lastDroppedFrames,
  2745. currentDecoded = decodedFrames - this.lastDecodedFrames,
  2746. droppedFPS = 1000 * currentDropped / currentPeriod,
  2747. hls = this.hls;
  2748. hls.trigger(_events2.default.FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames });
  2749. if (droppedFPS > 0) {
  2750. //logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
  2751. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  2752. var currentLevel = hls.currentLevel;
  2753. _logger.logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
  2754. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  2755. currentLevel = currentLevel - 1;
  2756. hls.trigger(_events2.default.FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: hls.currentLevel });
  2757. hls.autoLevelCapping = currentLevel;
  2758. hls.streamController.nextLevelSwitch();
  2759. }
  2760. }
  2761. }
  2762. }
  2763. this.lastTime = currentTime;
  2764. this.lastDroppedFrames = droppedFrames;
  2765. this.lastDecodedFrames = decodedFrames;
  2766. }
  2767. }
  2768. }, {
  2769. key: 'checkFPSInterval',
  2770. value: function checkFPSInterval() {
  2771. var video = this.video;
  2772. if (video) {
  2773. if (this.isVideoPlaybackQualityAvailable) {
  2774. var videoPlaybackQuality = video.getVideoPlaybackQuality();
  2775. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  2776. } else {
  2777. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  2778. }
  2779. }
  2780. }
  2781. }]);
  2782. return FPSController;
  2783. }(_eventHandler2.default);
  2784. exports.default = FPSController;
  2785. },{"31":31,"32":32,"50":50}],11:[function(_dereq_,module,exports){
  2786. 'use strict';
  2787. Object.defineProperty(exports, "__esModule", {
  2788. value: true
  2789. });
  2790. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  2791. var _events = _dereq_(32);
  2792. var _events2 = _interopRequireDefault(_events);
  2793. var _eventHandler = _dereq_(31);
  2794. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  2795. var _logger = _dereq_(50);
  2796. var _errors = _dereq_(30);
  2797. var _bufferHelper = _dereq_(34);
  2798. var _bufferHelper2 = _interopRequireDefault(_bufferHelper);
  2799. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2800. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2801. 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; }
  2802. 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; } /*
  2803. * Level Controller
  2804. */
  2805. var LevelController = function (_EventHandler) {
  2806. _inherits(LevelController, _EventHandler);
  2807. function LevelController(hls) {
  2808. _classCallCheck(this, LevelController);
  2809. var _this = _possibleConstructorReturn(this, (LevelController.__proto__ || Object.getPrototypeOf(LevelController)).call(this, hls, _events2.default.MANIFEST_LOADED, _events2.default.LEVEL_LOADED, _events2.default.FRAG_LOADED, _events2.default.ERROR));
  2810. _this.ontick = _this.tick.bind(_this);
  2811. _this._manualLevel = -1;
  2812. return _this;
  2813. }
  2814. _createClass(LevelController, [{
  2815. key: 'destroy',
  2816. value: function destroy() {
  2817. if (this.timer) {
  2818. clearTimeout(this.timer);
  2819. this.timer = null;
  2820. }
  2821. this._manualLevel = -1;
  2822. }
  2823. }, {
  2824. key: 'startLoad',
  2825. value: function startLoad() {
  2826. this.canload = true;
  2827. var levels = this._levels;
  2828. // clean up live level details to force reload them, and reset load errors
  2829. if (levels) {
  2830. levels.forEach(function (level) {
  2831. level.loadError = 0;
  2832. var levelDetails = level.details;
  2833. if (levelDetails && levelDetails.live) {
  2834. level.details = undefined;
  2835. }
  2836. });
  2837. }
  2838. // speed up live playlist refresh if timer exists
  2839. if (this.timer) {
  2840. this.tick();
  2841. }
  2842. }
  2843. }, {
  2844. key: 'stopLoad',
  2845. value: function stopLoad() {
  2846. this.canload = false;
  2847. }
  2848. }, {
  2849. key: 'onManifestLoaded',
  2850. value: function onManifestLoaded(data) {
  2851. var levels0 = [],
  2852. levels = [],
  2853. bitrateStart,
  2854. bitrateSet = {},
  2855. videoCodecFound = false,
  2856. audioCodecFound = false,
  2857. hls = this.hls,
  2858. brokenmp4inmp3 = /chrome|firefox/.test(navigator.userAgent.toLowerCase()),
  2859. checkSupported = function checkSupported(type, codec) {
  2860. return MediaSource.isTypeSupported(type + '/mp4;codecs=' + codec);
  2861. };
  2862. // regroup redundant level together
  2863. data.levels.forEach(function (level) {
  2864. if (level.videoCodec) {
  2865. videoCodecFound = true;
  2866. }
  2867. // erase audio codec info if browser does not support mp4a.40.34. demuxer will autodetect codec and fallback to mpeg/audio
  2868. if (brokenmp4inmp3 && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {
  2869. level.audioCodec = undefined;
  2870. }
  2871. if (level.audioCodec || level.attrs && level.attrs.AUDIO) {
  2872. audioCodecFound = true;
  2873. }
  2874. var redundantLevelId = bitrateSet[level.bitrate];
  2875. if (redundantLevelId === undefined) {
  2876. bitrateSet[level.bitrate] = levels0.length;
  2877. level.url = [level.url];
  2878. level.urlId = 0;
  2879. levels0.push(level);
  2880. } else {
  2881. levels0[redundantLevelId].url.push(level.url);
  2882. }
  2883. });
  2884. // remove audio-only level if we also have levels with audio+video codecs signalled
  2885. if (videoCodecFound && audioCodecFound) {
  2886. levels0.forEach(function (level) {
  2887. if (level.videoCodec) {
  2888. levels.push(level);
  2889. }
  2890. });
  2891. } else {
  2892. levels = levels0;
  2893. }
  2894. // only keep level with supported audio/video codecs
  2895. levels = levels.filter(function (level) {
  2896. var audioCodec = level.audioCodec,
  2897. videoCodec = level.videoCodec;
  2898. return (!audioCodec || checkSupported('audio', audioCodec)) && (!videoCodec || checkSupported('video', videoCodec));
  2899. });
  2900. if (levels.length) {
  2901. // start bitrate is the first bitrate of the manifest
  2902. bitrateStart = levels[0].bitrate;
  2903. // sort level on bitrate
  2904. levels.sort(function (a, b) {
  2905. return a.bitrate - b.bitrate;
  2906. });
  2907. this._levels = levels;
  2908. // find index of first level in sorted levels
  2909. for (var i = 0; i < levels.length; i++) {
  2910. if (levels[i].bitrate === bitrateStart) {
  2911. this._firstLevel = i;
  2912. _logger.logger.log('manifest loaded,' + levels.length + ' level(s) found, first bitrate:' + bitrateStart);
  2913. break;
  2914. }
  2915. }
  2916. hls.trigger(_events2.default.MANIFEST_PARSED, { levels: levels, firstLevel: this._firstLevel, stats: data.stats, audio: audioCodecFound, video: videoCodecFound, altAudio: data.audioTracks.length > 0 });
  2917. } else {
  2918. hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR, fatal: true, url: hls.url, reason: 'no level with compatible codecs found in manifest' });
  2919. }
  2920. return;
  2921. }
  2922. }, {
  2923. key: 'setLevelInternal',
  2924. value: function setLevelInternal(newLevel) {
  2925. var levels = this._levels;
  2926. var hls = this.hls;
  2927. // check if level idx is valid
  2928. if (newLevel >= 0 && newLevel < levels.length) {
  2929. // stopping live reloading timer if any
  2930. if (this.timer) {
  2931. clearTimeout(this.timer);
  2932. this.timer = null;
  2933. }
  2934. if (this._level !== newLevel) {
  2935. _logger.logger.log('switching to level ' + newLevel);
  2936. this._level = newLevel;
  2937. var levelProperties = levels[newLevel];
  2938. levelProperties.level = newLevel;
  2939. // LEVEL_SWITCH to be deprecated in next major release
  2940. hls.trigger(_events2.default.LEVEL_SWITCH, levelProperties);
  2941. hls.trigger(_events2.default.LEVEL_SWITCHING, levelProperties);
  2942. }
  2943. var level = levels[newLevel],
  2944. levelDetails = level.details;
  2945. // check if we need to load playlist for this level
  2946. if (!levelDetails || levelDetails.live === true) {
  2947. // level not retrieved yet, or live playlist we need to (re)load it
  2948. var urlId = level.urlId;
  2949. hls.trigger(_events2.default.LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId });
  2950. }
  2951. } else {
  2952. // invalid level id given, trigger error
  2953. hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.LEVEL_SWITCH_ERROR, level: newLevel, fatal: false, reason: 'invalid level idx' });
  2954. }
  2955. }
  2956. }, {
  2957. key: 'onError',
  2958. value: function onError(data) {
  2959. if (data.fatal) {
  2960. return;
  2961. }
  2962. var details = data.details,
  2963. hls = this.hls,
  2964. levelId = void 0,
  2965. level = void 0,
  2966. levelError = false;
  2967. // try to recover not fatal errors
  2968. switch (details) {
  2969. case _errors.ErrorDetails.FRAG_LOAD_ERROR:
  2970. case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
  2971. case _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR:
  2972. case _errors.ErrorDetails.KEY_LOAD_ERROR:
  2973. case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
  2974. levelId = data.frag.level;
  2975. break;
  2976. case _errors.ErrorDetails.LEVEL_LOAD_ERROR:
  2977. case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT:
  2978. levelId = data.context.level;
  2979. levelError = true;
  2980. break;
  2981. case _errors.ErrorDetails.REMUX_ALLOC_ERROR:
  2982. levelId = data.level;
  2983. break;
  2984. default:
  2985. break;
  2986. }
  2987. /* try to switch to a redundant stream if any available.
  2988. * if no redundant stream available, emergency switch down (if in auto mode and current level not 0)
  2989. * otherwise, we cannot recover this network error ...
  2990. */
  2991. if (levelId !== undefined) {
  2992. level = this._levels[levelId];
  2993. if (!level.loadError) {
  2994. level.loadError = 1;
  2995. } else {
  2996. level.loadError++;
  2997. }
  2998. // if any redundant streams available and if we haven't try them all (level.loadError is reseted on successful frag/level load.
  2999. // if level.loadError reaches nbRedundantLevel it means that we tried them all, no hope => let's switch down
  3000. var nbRedundantLevel = level.url.length;
  3001. if (nbRedundantLevel > 1 && level.loadError < nbRedundantLevel) {
  3002. level.urlId = (level.urlId + 1) % nbRedundantLevel;
  3003. level.details = undefined;
  3004. _logger.logger.warn('level controller,' + details + ' for level ' + levelId + ': switching to redundant stream id ' + level.urlId);
  3005. } else {
  3006. // we could try to recover if in auto mode and current level not lowest level (0)
  3007. var recoverable = this._manualLevel === -1 && levelId;
  3008. if (recoverable) {
  3009. _logger.logger.warn('level controller,' + details + ': switch-down for next fragment');
  3010. hls.nextAutoLevel = Math.max(0, levelId - 1);
  3011. } else if (level && level.details && level.details.live) {
  3012. _logger.logger.warn('level controller,' + details + ' on live stream, discard');
  3013. if (levelError) {
  3014. // reset this._level so that another call to set level() will retrigger a frag load
  3015. this._level = undefined;
  3016. }
  3017. // other errors are handled by stream controller
  3018. } else if (details === _errors.ErrorDetails.LEVEL_LOAD_ERROR || details === _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT) {
  3019. var media = hls.media,
  3020. // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  3021. mediaBuffered = media && _bufferHelper2.default.isBuffered(media, media.currentTime) && _bufferHelper2.default.isBuffered(media, media.currentTime + 0.5);
  3022. if (mediaBuffered) {
  3023. var retryDelay = hls.config.levelLoadingRetryDelay;
  3024. _logger.logger.warn('level controller,' + details + ', but media buffered, retry in ' + retryDelay + 'ms');
  3025. this.timer = setTimeout(this.ontick, retryDelay);
  3026. } else {
  3027. _logger.logger.error('cannot recover ' + details + ' error');
  3028. this._level = undefined;
  3029. // stopping live reloading timer if any
  3030. if (this.timer) {
  3031. clearTimeout(this.timer);
  3032. this.timer = null;
  3033. }
  3034. // switch error to fatal
  3035. data.fatal = true;
  3036. }
  3037. }
  3038. }
  3039. }
  3040. }
  3041. // reset level load error counter on successful frag loaded
  3042. }, {
  3043. key: 'onFragLoaded',
  3044. value: function onFragLoaded(data) {
  3045. var fragLoaded = data.frag;
  3046. if (fragLoaded && fragLoaded.type === 'main') {
  3047. var level = this._levels[fragLoaded.level];
  3048. if (level) {
  3049. level.loadError = 0;
  3050. }
  3051. }
  3052. }
  3053. }, {
  3054. key: 'onLevelLoaded',
  3055. value: function onLevelLoaded(data) {
  3056. var levelId = data.level;
  3057. // only process level loaded events matching with expected level
  3058. if (levelId === this._level) {
  3059. var curLevel = this._levels[levelId];
  3060. // reset level load error counter on successful level loaded
  3061. curLevel.loadError = 0;
  3062. var newDetails = data.details;
  3063. // if current playlist is a live playlist, arm a timer to reload it
  3064. if (newDetails.live) {
  3065. var reloadInterval = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration),
  3066. curDetails = curLevel.details;
  3067. if (curDetails && newDetails.endSN === curDetails.endSN) {
  3068. // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
  3069. // changed then it MUST wait for a period of one-half the target
  3070. // duration before retrying.
  3071. reloadInterval /= 2;
  3072. _logger.logger.log('same live playlist, reload twice faster');
  3073. }
  3074. // decrement reloadInterval with level loading delay
  3075. reloadInterval -= performance.now() - data.stats.trequest;
  3076. // in any case, don't reload more than every second
  3077. reloadInterval = Math.max(1000, Math.round(reloadInterval));
  3078. _logger.logger.log('live playlist, reload in ' + reloadInterval + ' ms');
  3079. this.timer = setTimeout(this.ontick, reloadInterval);
  3080. } else {
  3081. this.timer = null;
  3082. }
  3083. }
  3084. }
  3085. }, {
  3086. key: 'tick',
  3087. value: function tick() {
  3088. var levelId = this._level;
  3089. if (levelId !== undefined && this.canload) {
  3090. var level = this._levels[levelId];
  3091. if (level && level.url) {
  3092. var urlId = level.urlId;
  3093. this.hls.trigger(_events2.default.LEVEL_LOADING, { url: level.url[urlId], level: levelId, id: urlId });
  3094. }
  3095. }
  3096. }
  3097. }, {
  3098. key: 'levels',
  3099. get: function get() {
  3100. return this._levels;
  3101. }
  3102. }, {
  3103. key: 'level',
  3104. get: function get() {
  3105. return this._level;
  3106. },
  3107. set: function set(newLevel) {
  3108. var levels = this._levels;
  3109. if (levels && levels.length > newLevel) {
  3110. if (this._level !== newLevel || levels[newLevel].details === undefined) {
  3111. this.setLevelInternal(newLevel);
  3112. }
  3113. }
  3114. }
  3115. }, {
  3116. key: 'manualLevel',
  3117. get: function get() {
  3118. return this._manualLevel;
  3119. },
  3120. set: function set(newLevel) {
  3121. this._manualLevel = newLevel;
  3122. if (this._startLevel === undefined) {
  3123. this._startLevel = newLevel;
  3124. }
  3125. if (newLevel !== -1) {
  3126. this.level = newLevel;
  3127. }
  3128. }
  3129. }, {
  3130. key: 'firstLevel',
  3131. get: function get() {
  3132. return this._firstLevel;
  3133. },
  3134. set: function set(newLevel) {
  3135. this._firstLevel = newLevel;
  3136. }
  3137. }, {
  3138. key: 'startLevel',
  3139. get: function get() {
  3140. // hls.startLevel takes precedence over config.startLevel
  3141. // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)
  3142. if (this._startLevel === undefined) {
  3143. var configStartLevel = this.hls.config.startLevel;
  3144. if (configStartLevel !== undefined) {
  3145. return configStartLevel;
  3146. } else {
  3147. return this._firstLevel;
  3148. }
  3149. } else {
  3150. return this._startLevel;
  3151. }
  3152. },
  3153. set: function set(newLevel) {
  3154. this._startLevel = newLevel;
  3155. }
  3156. }, {
  3157. key: 'nextLoadLevel',
  3158. get: function get() {
  3159. if (this._manualLevel !== -1) {
  3160. return this._manualLevel;
  3161. } else {
  3162. return this.hls.nextAutoLevel;
  3163. }
  3164. },
  3165. set: function set(nextLevel) {
  3166. this.level = nextLevel;
  3167. if (this._manualLevel === -1) {
  3168. this.hls.nextAutoLevel = nextLevel;
  3169. }
  3170. }
  3171. }]);
  3172. return LevelController;
  3173. }(_eventHandler2.default);
  3174. exports.default = LevelController;
  3175. },{"30":30,"31":31,"32":32,"34":34,"50":50}],12:[function(_dereq_,module,exports){
  3176. 'use strict';
  3177. Object.defineProperty(exports, "__esModule", {
  3178. value: true
  3179. });
  3180. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  3181. var _binarySearch = _dereq_(45);
  3182. var _binarySearch2 = _interopRequireDefault(_binarySearch);
  3183. var _bufferHelper = _dereq_(34);
  3184. var _bufferHelper2 = _interopRequireDefault(_bufferHelper);
  3185. var _demuxer = _dereq_(24);
  3186. var _demuxer2 = _interopRequireDefault(_demuxer);
  3187. var _events = _dereq_(32);
  3188. var _events2 = _interopRequireDefault(_events);
  3189. var _eventHandler = _dereq_(31);
  3190. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  3191. var _levelHelper = _dereq_(35);
  3192. var _levelHelper2 = _interopRequireDefault(_levelHelper);
  3193. var _timeRanges = _dereq_(51);
  3194. var _timeRanges2 = _interopRequireDefault(_timeRanges);
  3195. var _errors = _dereq_(30);
  3196. var _logger = _dereq_(50);
  3197. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  3198. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3199. 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; }
  3200. 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; } /*
  3201. * Stream Controller
  3202. */
  3203. var State = {
  3204. STOPPED: 'STOPPED',
  3205. IDLE: 'IDLE',
  3206. KEY_LOADING: 'KEY_LOADING',
  3207. FRAG_LOADING: 'FRAG_LOADING',
  3208. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  3209. WAITING_LEVEL: 'WAITING_LEVEL',
  3210. PARSING: 'PARSING',
  3211. PARSED: 'PARSED',
  3212. BUFFER_FLUSHING: 'BUFFER_FLUSHING',
  3213. ENDED: 'ENDED',
  3214. ERROR: 'ERROR'
  3215. };
  3216. var StreamController = function (_EventHandler) {
  3217. _inherits(StreamController, _EventHandler);
  3218. function StreamController(hls) {
  3219. _classCallCheck(this, StreamController);
  3220. 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));
  3221. _this.config = hls.config;
  3222. _this.audioCodecSwap = false;
  3223. _this.ticks = 0;
  3224. _this._state = State.STOPPED;
  3225. _this.ontick = _this.tick.bind(_this);
  3226. return _this;
  3227. }
  3228. _createClass(StreamController, [{
  3229. key: 'destroy',
  3230. value: function destroy() {
  3231. this.stopLoad();
  3232. if (this.timer) {
  3233. clearInterval(this.timer);
  3234. this.timer = null;
  3235. }
  3236. _eventHandler2.default.prototype.destroy.call(this);
  3237. this.state = State.STOPPED;
  3238. }
  3239. }, {
  3240. key: 'startLoad',
  3241. value: function startLoad(startPosition) {
  3242. if (this.levels) {
  3243. var lastCurrentTime = this.lastCurrentTime,
  3244. hls = this.hls;
  3245. this.stopLoad();
  3246. if (!this.timer) {
  3247. this.timer = setInterval(this.ontick, 100);
  3248. }
  3249. this.level = -1;
  3250. this.fragLoadError = 0;
  3251. if (!this.startFragRequested) {
  3252. // determine load level
  3253. var startLevel = hls.startLevel;
  3254. if (startLevel === -1) {
  3255. // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  3256. startLevel = 0;
  3257. this.bitrateTest = true;
  3258. }
  3259. // set new level to playlist loader : this will trigger start level load
  3260. // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  3261. this.level = hls.nextLoadLevel = startLevel;
  3262. this.loadedmetadata = false;
  3263. }
  3264. // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
  3265. if (lastCurrentTime > 0 && startPosition === -1) {
  3266. _logger.logger.log('override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3));
  3267. startPosition = lastCurrentTime;
  3268. }
  3269. this.state = State.IDLE;
  3270. this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
  3271. this.tick();
  3272. } else {
  3273. this.forceStartLoad = true;
  3274. this.state = State.STOPPED;
  3275. }
  3276. }
  3277. }, {
  3278. key: 'stopLoad',
  3279. value: function stopLoad() {
  3280. var frag = this.fragCurrent;
  3281. if (frag) {
  3282. if (frag.loader) {
  3283. frag.loader.abort();
  3284. }
  3285. this.fragCurrent = null;
  3286. }
  3287. this.fragPrevious = null;
  3288. if (this.demuxer) {
  3289. this.demuxer.destroy();
  3290. this.demuxer = null;
  3291. }
  3292. this.state = State.STOPPED;
  3293. this.forceStartLoad = false;
  3294. }
  3295. }, {
  3296. key: 'tick',
  3297. value: function tick() {
  3298. this.ticks++;
  3299. if (this.ticks === 1) {
  3300. this.doTick();
  3301. if (this.ticks > 1) {
  3302. setTimeout(this.tick, 1);
  3303. }
  3304. this.ticks = 0;
  3305. }
  3306. }
  3307. }, {
  3308. key: 'doTick',
  3309. value: function doTick() {
  3310. switch (this.state) {
  3311. case State.ERROR:
  3312. //don't do anything in error state to avoid breaking further ...
  3313. break;
  3314. case State.BUFFER_FLUSHING:
  3315. // in buffer flushing state, reset fragLoadError counter
  3316. this.fragLoadError = 0;
  3317. break;
  3318. case State.IDLE:
  3319. // when this returns false there was an error and we shall return immediatly
  3320. // from current tick
  3321. if (!this._doTickIdle()) {
  3322. return;
  3323. }
  3324. break;
  3325. case State.WAITING_LEVEL:
  3326. var level = this.levels[this.level];
  3327. // check if playlist is already loaded
  3328. if (level && level.details) {
  3329. this.state = State.IDLE;
  3330. }
  3331. break;
  3332. case State.FRAG_LOADING_WAITING_RETRY:
  3333. var now = performance.now();
  3334. var retryDate = this.retryDate;
  3335. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  3336. if (!retryDate || now >= retryDate || this.media && this.media.seeking) {
  3337. _logger.logger.log('mediaController: retryDate reached, switch back to IDLE state');
  3338. this.state = State.IDLE;
  3339. }
  3340. break;
  3341. case State.ERROR:
  3342. case State.STOPPED:
  3343. case State.FRAG_LOADING:
  3344. case State.PARSING:
  3345. case State.PARSED:
  3346. case State.ENDED:
  3347. break;
  3348. default:
  3349. break;
  3350. }
  3351. // check buffer
  3352. this._checkBuffer();
  3353. // check/update current fragment
  3354. this._checkFragmentChanged();
  3355. }
  3356. // Ironically the "idle" state is the on we do the most logic in it seems ....
  3357. // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently
  3358. // played segment, or on pause/play/seek instead of naively checking every 100ms?
  3359. }, {
  3360. key: '_doTickIdle',
  3361. value: function _doTickIdle() {
  3362. var hls = this.hls,
  3363. config = hls.config,
  3364. media = this.media;
  3365. // if video not attached AND
  3366. // start fragment already requested OR start frag prefetch disable
  3367. // exit loop
  3368. // => if start level loaded and media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
  3369. if (this.levelLastLoaded !== undefined && !media && (this.startFragRequested || !config.startFragPrefetch)) {
  3370. return true;
  3371. }
  3372. // if we have not yet loaded any fragment, start loading from start position
  3373. var pos = void 0;
  3374. if (this.loadedmetadata) {
  3375. pos = media.currentTime;
  3376. } else {
  3377. pos = this.nextLoadPosition;
  3378. }
  3379. // determine next load level
  3380. var level = hls.nextLoadLevel,
  3381. levelInfo = this.levels[level],
  3382. levelBitrate = levelInfo.bitrate,
  3383. maxBufLen = void 0;
  3384. // 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
  3385. if (levelBitrate) {
  3386. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  3387. } else {
  3388. maxBufLen = config.maxBufferLength;
  3389. }
  3390. maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);
  3391. // determine next candidate fragment to be loaded, based on current position and end of buffer position
  3392. // ensure up to `config.maxMaxBufferLength` of buffer upfront
  3393. var bufferInfo = _bufferHelper2.default.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, config.maxBufferHole),
  3394. bufferLen = bufferInfo.len;
  3395. // Stay idle if we are still with buffer margins
  3396. if (bufferLen >= maxBufLen) {
  3397. return true;
  3398. }
  3399. // if buffer length is less than maxBufLen try to load a new fragment ...
  3400. _logger.logger.trace('buffer length of ' + bufferLen.toFixed(3) + ' is below max of ' + maxBufLen.toFixed(3) + '. checking for more payload ...');
  3401. // set next load level : this will trigger a playlist load if needed
  3402. this.level = hls.nextLoadLevel = level;
  3403. var levelDetails = levelInfo.details;
  3404. // if level info not retrieved yet, switch state and wait for level retrieval
  3405. // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  3406. // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  3407. if (typeof levelDetails === 'undefined' || levelDetails.live && this.levelLastLoaded !== level) {
  3408. this.state = State.WAITING_LEVEL;
  3409. return true;
  3410. }
  3411. // we just got done loading the final fragment, check if we need to finalize media stream
  3412. var fragPrevious = this.fragPrevious;
  3413. if (!levelDetails.live && fragPrevious && fragPrevious.sn === levelDetails.endSN) {
  3414. // fragPrevious is last fragment. retrieve level duration using last frag start offset + duration
  3415. // real duration might be lower than initial duration if there are drifts between real frag duration and playlist signaling
  3416. var duration = Math.min(media.duration, fragPrevious.start + fragPrevious.duration);
  3417. // if everything (almost) til the end is buffered, let's signal eos
  3418. // we don't compare exactly media.duration === bufferInfo.end as there could be some subtle media duration difference
  3419. // using half frag duration should help cope with these cases.
  3420. // also cope with almost zero last frag duration (max last frag duration with 200ms) refer to https://github.com/video-dev/hls.js/pull/657
  3421. if (duration - Math.max(bufferInfo.end, fragPrevious.start) <= Math.max(0.2, fragPrevious.duration / 2)) {
  3422. // Finalize the media stream
  3423. var data = {};
  3424. if (this.altAudio) {
  3425. data.type = 'video';
  3426. }
  3427. this.hls.trigger(_events2.default.BUFFER_EOS, data);
  3428. this.state = State.ENDED;
  3429. return true;
  3430. }
  3431. }
  3432. // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)
  3433. return this._fetchPayloadOrEos(pos, bufferInfo, levelDetails);
  3434. }
  3435. }, {
  3436. key: '_fetchPayloadOrEos',
  3437. value: function _fetchPayloadOrEos(pos, bufferInfo, levelDetails) {
  3438. var fragPrevious = this.fragPrevious,
  3439. level = this.level,
  3440. fragments = levelDetails.fragments,
  3441. fragLen = fragments.length;
  3442. // empty playlist
  3443. if (fragLen === 0) {
  3444. return false;
  3445. }
  3446. // find fragment index, contiguous with end of buffer position
  3447. var start = fragments[0].start,
  3448. end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
  3449. bufferEnd = bufferInfo.end,
  3450. frag = void 0;
  3451. if (levelDetails.initSegment && !levelDetails.initSegment.data) {
  3452. frag = levelDetails.initSegment;
  3453. } else {
  3454. // in case of live playlist we need to ensure that requested position is not located before playlist start
  3455. if (levelDetails.live) {
  3456. var initialLiveManifestSize = this.config.initialLiveManifestSize;
  3457. if (fragLen < initialLiveManifestSize) {
  3458. _logger.logger.warn('Can not start playback of a level, reason: not enough fragments ' + fragLen + ' < ' + initialLiveManifestSize);
  3459. return false;
  3460. }
  3461. frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen);
  3462. // if it explicitely returns null don't load any fragment and exit function now
  3463. if (frag === null) {
  3464. return false;
  3465. }
  3466. } else {
  3467. // VoD playlist: if bufferEnd before start of playlist, load first fragment
  3468. if (bufferEnd < start) {
  3469. frag = fragments[0];
  3470. }
  3471. }
  3472. }
  3473. if (!frag) {
  3474. frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);
  3475. }
  3476. if (frag) {
  3477. return this._loadFragmentOrKey(frag, level, levelDetails, pos, bufferEnd);
  3478. }
  3479. return true;
  3480. }
  3481. }, {
  3482. key: '_ensureFragmentAtLivePoint',
  3483. value: function _ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen) {
  3484. var config = this.hls.config,
  3485. media = this.media;
  3486. var frag = void 0;
  3487. // check if requested position is within seekable boundaries :
  3488. //logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);
  3489. var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  3490. if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {
  3491. var liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);
  3492. _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));
  3493. bufferEnd = liveSyncPosition;
  3494. if (media && media.readyState && media.duration > liveSyncPosition) {
  3495. media.currentTime = liveSyncPosition;
  3496. }
  3497. }
  3498. // if end of buffer greater than live edge, don't load any fragment
  3499. // this could happen if live playlist intermittently slides in the past.
  3500. // level 1 loaded [182580161,182580167]
  3501. // level 1 loaded [182580162,182580169]
  3502. // Loading 182580168 of [182580162 ,182580169],level 1 ..
  3503. // Loading 182580169 of [182580162 ,182580169],level 1 ..
  3504. // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168
  3505. // level 1 loaded [182580164,182580171]
  3506. //
  3507. // don't return null in case media not loaded yet (readystate === 0)
  3508. if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {
  3509. return null;
  3510. }
  3511. if (this.startFragRequested && !levelDetails.PTSKnown) {
  3512. /* we are switching level on live playlist, but we don't have any PTS info for that quality level ...
  3513. try to load frag matching with next SN.
  3514. even if SN are not synchronized between playlists, loading this frag will help us
  3515. compute playlist sliding and find the right one after in case it was not the right consecutive one */
  3516. if (fragPrevious) {
  3517. var targetSN = fragPrevious.sn + 1;
  3518. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  3519. frag = fragments[targetSN - levelDetails.startSN];
  3520. _logger.logger.log('live playlist, switching playlist, load frag with next SN: ' + frag.sn);
  3521. }
  3522. }
  3523. if (!frag) {
  3524. /* we have no idea about which fragment should be loaded.
  3525. so let's load mid fragment. it will help computing playlist sliding and find the right one
  3526. */
  3527. frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))];
  3528. _logger.logger.log('live playlist, switching playlist, unknown, load middle frag : ' + frag.sn);
  3529. }
  3530. }
  3531. return frag;
  3532. }
  3533. }, {
  3534. key: '_findFragment',
  3535. value: function _findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails) {
  3536. var config = this.hls.config;
  3537. var frag = void 0;
  3538. var foundFrag = void 0;
  3539. var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
  3540. var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;
  3541. var fragmentWithinToleranceTest = function fragmentWithinToleranceTest(candidate) {
  3542. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  3543. // this is to cope with situations like
  3544. // bufferEnd = 9.991
  3545. // frag[Ø] : [0,10]
  3546. // frag[1] : [10,20]
  3547. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  3548. // frag start frag start+duration
  3549. // |-----------------------------|
  3550. // <---> <--->
  3551. // ...--------><-----------------------------><---------....
  3552. // previous frag matching fragment next frag
  3553. // return -1 return 0 return 1
  3554. //logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  3555. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  3556. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration);
  3557. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  3558. return 1;
  3559. } // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  3560. else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  3561. return -1;
  3562. }
  3563. return 0;
  3564. };
  3565. if (bufferEnd < end) {
  3566. if (bufferEnd > end - maxFragLookUpTolerance) {
  3567. maxFragLookUpTolerance = 0;
  3568. }
  3569. // Prefer the next fragment if it's within tolerance
  3570. if (fragNext && !fragmentWithinToleranceTest(fragNext)) {
  3571. foundFrag = fragNext;
  3572. } else {
  3573. foundFrag = _binarySearch2.default.search(fragments, fragmentWithinToleranceTest);
  3574. }
  3575. } else {
  3576. // reach end of playlist
  3577. foundFrag = fragments[fragLen - 1];
  3578. }
  3579. if (foundFrag) {
  3580. frag = foundFrag;
  3581. var curSNIdx = frag.sn - levelDetails.startSN;
  3582. var sameLevel = fragPrevious && frag.level === fragPrevious.level;
  3583. var prevFrag = fragments[curSNIdx - 1];
  3584. var nextFrag = fragments[curSNIdx + 1];
  3585. //logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
  3586. if (sameLevel && frag.sn === fragPrevious.sn) {
  3587. if (frag.sn < levelDetails.endSN) {
  3588. var deltaPTS = fragPrevious.deltaPTS;
  3589. // if there is a significant delta between audio and video, larger than max allowed hole,
  3590. // and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)
  3591. // let's try to load previous fragment again to get last keyframe
  3592. // then we will reload again current fragment (that way we should be able to fill the buffer hole ...)
  3593. if (deltaPTS && deltaPTS > config.maxBufferHole && fragPrevious.dropped && curSNIdx) {
  3594. frag = prevFrag;
  3595. _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');
  3596. // decrement previous frag load counter to avoid frag loop loading error when next fragment will get reloaded
  3597. fragPrevious.loadCounter--;
  3598. } else {
  3599. frag = nextFrag;
  3600. _logger.logger.log('SN just loaded, load next one: ' + frag.sn);
  3601. }
  3602. } else {
  3603. frag = null;
  3604. }
  3605. } else if (frag.dropped && !sameLevel) {
  3606. // Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes
  3607. if (nextFrag && nextFrag.backtracked) {
  3608. _logger.logger.warn('Already backtracked from fragment ' + (curSNIdx + 1) + ', will not backtrack to fragment ' + curSNIdx + '. Loading fragment ' + (curSNIdx + 1));
  3609. frag = nextFrag;
  3610. } else {
  3611. // If a fragment has dropped frames and it's in a different level/sequence, load the previous fragment to try and find the keyframe
  3612. // 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
  3613. _logger.logger.warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');
  3614. frag.dropped = 0;
  3615. if (prevFrag) {
  3616. if (prevFrag.loadCounter) {
  3617. prevFrag.loadCounter--;
  3618. }
  3619. frag = prevFrag;
  3620. } else {
  3621. frag = null;
  3622. }
  3623. }
  3624. }
  3625. }
  3626. return frag;
  3627. }
  3628. }, {
  3629. key: '_loadFragmentOrKey',
  3630. value: function _loadFragmentOrKey(frag, level, levelDetails, pos, bufferEnd) {
  3631. var hls = this.hls,
  3632. config = hls.config;
  3633. //logger.log('loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));
  3634. if (frag.decryptdata && frag.decryptdata.uri != null && frag.decryptdata.key == null) {
  3635. _logger.logger.log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level);
  3636. this.state = State.KEY_LOADING;
  3637. hls.trigger(_events2.default.KEY_LOADING, { frag: frag });
  3638. } else {
  3639. _logger.logger.log('Loading ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level + ', currentTime:' + pos.toFixed(3) + ',bufferEnd:' + bufferEnd.toFixed(3));
  3640. // ensure that we are not reloading the same fragments in loop ...
  3641. if (this.fragLoadIdx !== undefined) {
  3642. this.fragLoadIdx++;
  3643. } else {
  3644. this.fragLoadIdx = 0;
  3645. }
  3646. if (frag.loadCounter) {
  3647. frag.loadCounter++;
  3648. var maxThreshold = config.fragLoadingLoopThreshold;
  3649. // if this frag has already been loaded 3 times, and if it has been reloaded recently
  3650. if (frag.loadCounter > maxThreshold && Math.abs(this.fragLoadIdx - frag.loadIdx) < maxThreshold) {
  3651. hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag });
  3652. return false;
  3653. }
  3654. } else {
  3655. frag.loadCounter = 1;
  3656. }
  3657. frag.loadIdx = this.fragLoadIdx;
  3658. this.fragCurrent = frag;
  3659. this.startFragRequested = true;
  3660. if (!isNaN(frag.sn)) {
  3661. this.nextLoadPosition = frag.start + frag.duration;
  3662. }
  3663. frag.autoLevel = hls.autoLevelEnabled;
  3664. frag.bitrateTest = this.bitrateTest;
  3665. hls.trigger(_events2.default.FRAG_LOADING, { frag: frag });
  3666. // lazy demuxer init, as this could take some time ... do it during frag loading
  3667. if (!this.demuxer) {
  3668. this.demuxer = new _demuxer2.default(hls, 'main');
  3669. }
  3670. this.state = State.FRAG_LOADING;
  3671. return true;
  3672. }
  3673. }
  3674. }, {
  3675. key: 'getBufferedFrag',
  3676. value: function getBufferedFrag(position) {
  3677. return _binarySearch2.default.search(this._bufferedFrags, function (frag) {
  3678. if (position < frag.startPTS) {
  3679. return -1;
  3680. } else if (position > frag.endPTS) {
  3681. return 1;
  3682. }
  3683. return 0;
  3684. });
  3685. }
  3686. }, {
  3687. key: 'followingBufferedFrag',
  3688. value: function followingBufferedFrag(frag) {
  3689. if (frag) {
  3690. // try to get range of next fragment (500ms after this range)
  3691. return this.getBufferedFrag(frag.endPTS + 0.5);
  3692. }
  3693. return null;
  3694. }
  3695. }, {
  3696. key: '_checkFragmentChanged',
  3697. value: function _checkFragmentChanged() {
  3698. var fragPlayingCurrent,
  3699. currentTime,
  3700. video = this.media;
  3701. if (video && video.readyState && video.seeking === false) {
  3702. currentTime = video.currentTime;
  3703. /* if video element is in seeked state, currentTime can only increase.
  3704. (assuming that playback rate is positive ...)
  3705. As sometimes currentTime jumps back to zero after a
  3706. media decode error, check this, to avoid seeking back to
  3707. wrong position after a media decode error
  3708. */
  3709. if (currentTime > video.playbackRate * this.lastCurrentTime) {
  3710. this.lastCurrentTime = currentTime;
  3711. }
  3712. if (_bufferHelper2.default.isBuffered(video, currentTime)) {
  3713. fragPlayingCurrent = this.getBufferedFrag(currentTime);
  3714. } else if (_bufferHelper2.default.isBuffered(video, currentTime + 0.1)) {
  3715. /* ensure that FRAG_CHANGED event is triggered at startup,
  3716. when first video frame is displayed and playback is paused.
  3717. add a tolerance of 100ms, in case current position is not buffered,
  3718. check if current pos+100ms is buffered and use that buffer range
  3719. for FRAG_CHANGED event reporting */
  3720. fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1);
  3721. }
  3722. if (fragPlayingCurrent) {
  3723. var fragPlaying = fragPlayingCurrent;
  3724. if (fragPlaying !== this.fragPlaying) {
  3725. this.hls.trigger(_events2.default.FRAG_CHANGED, { frag: fragPlaying });
  3726. var fragPlayingLevel = fragPlaying.level;
  3727. if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {
  3728. this.hls.trigger(_events2.default.LEVEL_SWITCHED, { level: fragPlayingLevel });
  3729. }
  3730. this.fragPlaying = fragPlaying;
  3731. }
  3732. }
  3733. }
  3734. }
  3735. /*
  3736. on immediate level switch :
  3737. - pause playback if playing
  3738. - cancel any pending load request
  3739. - and trigger a buffer flush
  3740. */
  3741. }, {
  3742. key: 'immediateLevelSwitch',
  3743. value: function immediateLevelSwitch() {
  3744. _logger.logger.log('immediateLevelSwitch');
  3745. if (!this.immediateSwitch) {
  3746. this.immediateSwitch = true;
  3747. var media = this.media,
  3748. previouslyPaused = void 0;
  3749. if (media) {
  3750. previouslyPaused = media.paused;
  3751. media.pause();
  3752. } else {
  3753. // don't restart playback after instant level switch in case media not attached
  3754. previouslyPaused = true;
  3755. }
  3756. this.previouslyPaused = previouslyPaused;
  3757. }
  3758. var fragCurrent = this.fragCurrent;
  3759. if (fragCurrent && fragCurrent.loader) {
  3760. fragCurrent.loader.abort();
  3761. }
  3762. this.fragCurrent = null;
  3763. // increase fragment load Index to avoid frag loop loading error after buffer flush
  3764. this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
  3765. // flush everything
  3766. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  3767. }
  3768. /*
  3769. on immediate level switch end, after new fragment has been buffered :
  3770. - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)
  3771. - resume the playback if needed
  3772. */
  3773. }, {
  3774. key: 'immediateLevelSwitchEnd',
  3775. value: function immediateLevelSwitchEnd() {
  3776. var media = this.media;
  3777. if (media && media.buffered.length) {
  3778. this.immediateSwitch = false;
  3779. if (_bufferHelper2.default.isBuffered(media, media.currentTime)) {
  3780. // only nudge if currentTime is buffered
  3781. media.currentTime -= 0.0001;
  3782. }
  3783. if (!this.previouslyPaused) {
  3784. media.play();
  3785. }
  3786. }
  3787. }
  3788. }, {
  3789. key: 'nextLevelSwitch',
  3790. value: function nextLevelSwitch() {
  3791. /* try to switch ASAP without breaking video playback :
  3792. in order to ensure smooth but quick level switching,
  3793. we need to find the next flushable buffer range
  3794. we should take into account new segment fetch time
  3795. */
  3796. var media = this.media;
  3797. // ensure that media is defined and that metadata are available (to retrieve currentTime)
  3798. if (media && media.readyState) {
  3799. var fetchdelay = void 0,
  3800. fragPlayingCurrent = void 0,
  3801. nextBufferedFrag = void 0;
  3802. // increase fragment load Index to avoid frag loop loading error after buffer flush
  3803. this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
  3804. fragPlayingCurrent = this.getBufferedFrag(media.currentTime);
  3805. if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) {
  3806. // flush buffer preceding current fragment (flush until current fragment start offset)
  3807. // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  3808. this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1);
  3809. }
  3810. if (!media.paused) {
  3811. // add a safety delay of 1s
  3812. var nextLevelId = this.hls.nextLoadLevel,
  3813. nextLevel = this.levels[nextLevelId],
  3814. fragLastKbps = this.fragLastKbps;
  3815. if (fragLastKbps && this.fragCurrent) {
  3816. fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;
  3817. } else {
  3818. fetchdelay = 0;
  3819. }
  3820. } else {
  3821. fetchdelay = 0;
  3822. }
  3823. //logger.log('fetchdelay:'+fetchdelay);
  3824. // find buffer range that will be reached once new fragment will be fetched
  3825. nextBufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  3826. if (nextBufferedFrag) {
  3827. // we can flush buffer range following this one without stalling playback
  3828. nextBufferedFrag = this.followingBufferedFrag(nextBufferedFrag);
  3829. if (nextBufferedFrag) {
  3830. // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  3831. var fragCurrent = this.fragCurrent;
  3832. if (fragCurrent && fragCurrent.loader) {
  3833. fragCurrent.loader.abort();
  3834. }
  3835. this.fragCurrent = null;
  3836. // flush position is the start position of this new buffer
  3837. this.flushMainBuffer(nextBufferedFrag.startPTS, Number.POSITIVE_INFINITY);
  3838. }
  3839. }
  3840. }
  3841. }
  3842. }, {
  3843. key: 'flushMainBuffer',
  3844. value: function flushMainBuffer(startOffset, endOffset) {
  3845. this.state = State.BUFFER_FLUSHING;
  3846. var flushScope = { startOffset: startOffset, endOffset: endOffset };
  3847. // if alternate audio tracks are used, only flush video, otherwise flush everything
  3848. if (this.altAudio) {
  3849. flushScope.type = 'video';
  3850. }
  3851. this.hls.trigger(_events2.default.BUFFER_FLUSHING, flushScope);
  3852. }
  3853. }, {
  3854. key: 'onMediaAttached',
  3855. value: function onMediaAttached(data) {
  3856. var media = this.media = this.mediaBuffer = data.media;
  3857. this.onvseeking = this.onMediaSeeking.bind(this);
  3858. this.onvseeked = this.onMediaSeeked.bind(this);
  3859. this.onvended = this.onMediaEnded.bind(this);
  3860. media.addEventListener('seeking', this.onvseeking);
  3861. media.addEventListener('seeked', this.onvseeked);
  3862. media.addEventListener('ended', this.onvended);
  3863. var config = this.config;
  3864. if (this.levels && config.autoStartLoad) {
  3865. this.hls.startLoad(config.startPosition);
  3866. }
  3867. }
  3868. }, {
  3869. key: 'onMediaDetaching',
  3870. value: function onMediaDetaching() {
  3871. var media = this.media;
  3872. if (media && media.ended) {
  3873. _logger.logger.log('MSE detaching and video ended, reset startPosition');
  3874. this.startPosition = this.lastCurrentTime = 0;
  3875. }
  3876. // reset fragment loading counter on MSE detaching to avoid reporting FRAG_LOOP_LOADING_ERROR after error recovery
  3877. var levels = this.levels;
  3878. if (levels) {
  3879. // reset fragment load counter
  3880. levels.forEach(function (level) {
  3881. if (level.details) {
  3882. level.details.fragments.forEach(function (fragment) {
  3883. fragment.loadCounter = undefined;
  3884. fragment.backtracked = undefined;
  3885. });
  3886. }
  3887. });
  3888. }
  3889. // remove video listeners
  3890. if (media) {
  3891. media.removeEventListener('seeking', this.onvseeking);
  3892. media.removeEventListener('seeked', this.onvseeked);
  3893. media.removeEventListener('ended', this.onvended);
  3894. this.onvseeking = this.onvseeked = this.onvended = null;
  3895. }
  3896. this.media = this.mediaBuffer = null;
  3897. this.loadedmetadata = false;
  3898. this.stopLoad();
  3899. }
  3900. }, {
  3901. key: 'onMediaSeeking',
  3902. value: function onMediaSeeking() {
  3903. var media = this.media,
  3904. currentTime = media ? media.currentTime : undefined,
  3905. config = this.config;
  3906. _logger.logger.log('media seeking to ' + currentTime.toFixed(3));
  3907. if (this.state === State.FRAG_LOADING) {
  3908. var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;
  3909. var bufferInfo = _bufferHelper2.default.bufferInfo(mediaBuffer, currentTime, this.config.maxBufferHole),
  3910. fragCurrent = this.fragCurrent;
  3911. // check if we are seeking to a unbuffered area AND if frag loading is in progress
  3912. if (bufferInfo.len === 0 && fragCurrent) {
  3913. var tolerance = config.maxFragLookUpTolerance,
  3914. fragStartOffset = fragCurrent.start - tolerance,
  3915. fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  3916. // check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything
  3917. if (currentTime < fragStartOffset || currentTime > fragEndOffset) {
  3918. if (fragCurrent.loader) {
  3919. _logger.logger.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
  3920. fragCurrent.loader.abort();
  3921. }
  3922. this.fragCurrent = null;
  3923. this.fragPrevious = null;
  3924. // switch to IDLE state to load new fragment
  3925. this.state = State.IDLE;
  3926. } else {
  3927. _logger.logger.log('seeking outside of buffer but within currently loaded fragment range');
  3928. }
  3929. }
  3930. } else if (this.state === State.ENDED) {
  3931. // switch to IDLE state to check for potential new fragment
  3932. this.state = State.IDLE;
  3933. }
  3934. if (media) {
  3935. this.lastCurrentTime = currentTime;
  3936. }
  3937. // avoid reporting fragment loop loading error in case user is seeking several times on same position
  3938. if (this.state !== State.FRAG_LOADING && this.fragLoadIdx !== undefined) {
  3939. this.fragLoadIdx += 2 * config.fragLoadingLoopThreshold;
  3940. }
  3941. // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
  3942. if (!this.loadedmetadata) {
  3943. this.nextLoadPosition = this.startPosition = currentTime;
  3944. }
  3945. // tick to speed up processing
  3946. this.tick();
  3947. }
  3948. }, {
  3949. key: 'onMediaSeeked',
  3950. value: function onMediaSeeked() {
  3951. _logger.logger.log('media seeked to ' + this.media.currentTime.toFixed(3));
  3952. // tick to speed up FRAGMENT_PLAYING triggering
  3953. this.tick();
  3954. }
  3955. }, {
  3956. key: 'onMediaEnded',
  3957. value: function onMediaEnded() {
  3958. _logger.logger.log('media ended');
  3959. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  3960. this.startPosition = this.lastCurrentTime = 0;
  3961. }
  3962. }, {
  3963. key: 'onManifestLoading',
  3964. value: function onManifestLoading() {
  3965. // reset buffer on manifest loading
  3966. _logger.logger.log('trigger BUFFER_RESET');
  3967. this.hls.trigger(_events2.default.BUFFER_RESET);
  3968. this._bufferedFrags = [];
  3969. this.stalled = false;
  3970. this.startPosition = this.lastCurrentTime = 0;
  3971. }
  3972. }, {
  3973. key: 'onManifestParsed',
  3974. value: function onManifestParsed(data) {
  3975. var aac = false,
  3976. heaac = false,
  3977. codec;
  3978. data.levels.forEach(function (level) {
  3979. // detect if we have different kind of audio codecs used amongst playlists
  3980. codec = level.audioCodec;
  3981. if (codec) {
  3982. if (codec.indexOf('mp4a.40.2') !== -1) {
  3983. aac = true;
  3984. }
  3985. if (codec.indexOf('mp4a.40.5') !== -1) {
  3986. heaac = true;
  3987. }
  3988. }
  3989. });
  3990. this.audioCodecSwitch = aac && heaac;
  3991. if (this.audioCodecSwitch) {
  3992. _logger.logger.log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  3993. }
  3994. this.levels = data.levels;
  3995. this.startLevelLoaded = false;
  3996. this.startFragRequested = false;
  3997. var config = this.config;
  3998. if (config.autoStartLoad || this.forceStartLoad) {
  3999. this.hls.startLoad(config.startPosition);
  4000. }
  4001. }
  4002. }, {
  4003. key: 'onLevelLoaded',
  4004. value: function onLevelLoaded(data) {
  4005. var newDetails = data.details,
  4006. newLevelId = data.level,
  4007. curLevel = this.levels[newLevelId],
  4008. duration = newDetails.totalduration,
  4009. sliding = 0;
  4010. _logger.logger.log('level ' + newLevelId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration);
  4011. this.levelLastLoaded = newLevelId;
  4012. if (newDetails.live) {
  4013. var curDetails = curLevel.details;
  4014. if (curDetails && newDetails.fragments.length > 0) {
  4015. // we already have details for that level, merge them
  4016. _levelHelper2.default.mergeDetails(curDetails, newDetails);
  4017. sliding = newDetails.fragments[0].start;
  4018. this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
  4019. if (newDetails.PTSKnown) {
  4020. _logger.logger.log('live playlist sliding:' + sliding.toFixed(3));
  4021. } else {
  4022. _logger.logger.log('live playlist - outdated PTS, unknown sliding');
  4023. }
  4024. } else {
  4025. newDetails.PTSKnown = false;
  4026. _logger.logger.log('live playlist - first load, unknown sliding');
  4027. }
  4028. } else {
  4029. newDetails.PTSKnown = false;
  4030. }
  4031. // override level info
  4032. curLevel.details = newDetails;
  4033. this.hls.trigger(_events2.default.LEVEL_UPDATED, { details: newDetails, level: newLevelId });
  4034. if (this.startFragRequested === false) {
  4035. // compute start position if set to -1. use it straight away if value is defined
  4036. if (this.startPosition === -1 || this.lastCurrentTime === -1) {
  4037. // first, check if start time offset has been set in playlist, if yes, use this value
  4038. var startTimeOffset = newDetails.startTimeOffset;
  4039. if (!isNaN(startTimeOffset)) {
  4040. if (startTimeOffset < 0) {
  4041. _logger.logger.log('negative start time offset ' + startTimeOffset + ', count from end of last fragment');
  4042. startTimeOffset = sliding + duration + startTimeOffset;
  4043. }
  4044. _logger.logger.log('start time offset found in playlist, adjust startPosition to ' + startTimeOffset);
  4045. this.startPosition = startTimeOffset;
  4046. } else {
  4047. // if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)
  4048. if (newDetails.live) {
  4049. this.startPosition = this.computeLivePosition(sliding, newDetails);
  4050. _logger.logger.log('configure startPosition to ' + this.startPosition);
  4051. } else {
  4052. this.startPosition = 0;
  4053. }
  4054. }
  4055. this.lastCurrentTime = this.startPosition;
  4056. }
  4057. this.nextLoadPosition = this.startPosition;
  4058. }
  4059. // only switch batck to IDLE state if we were waiting for level to start downloading a new fragment
  4060. if (this.state === State.WAITING_LEVEL) {
  4061. this.state = State.IDLE;
  4062. }
  4063. //trigger handler right now
  4064. this.tick();
  4065. }
  4066. }, {
  4067. key: 'onKeyLoaded',
  4068. value: function onKeyLoaded() {
  4069. if (this.state === State.KEY_LOADING) {
  4070. this.state = State.IDLE;
  4071. this.tick();
  4072. }
  4073. }
  4074. }, {
  4075. key: 'onFragLoaded',
  4076. value: function onFragLoaded(data) {
  4077. var fragCurrent = this.fragCurrent,
  4078. fragLoaded = data.frag;
  4079. if (this.state === State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'main' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
  4080. var stats = data.stats,
  4081. currentLevel = this.levels[fragCurrent.level],
  4082. details = currentLevel.details;
  4083. _logger.logger.log('Loaded ' + fragCurrent.sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + fragCurrent.level);
  4084. // reset frag bitrate test in any case after frag loaded event
  4085. this.bitrateTest = false;
  4086. this.stats = stats;
  4087. // if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0
  4088. // then this means that we should be able to load a fragment at a higher quality level
  4089. if (fragLoaded.bitrateTest === true && this.hls.nextLoadLevel) {
  4090. // switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo
  4091. this.state = State.IDLE;
  4092. this.startFragRequested = false;
  4093. stats.tparsed = stats.tbuffered = performance.now();
  4094. this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
  4095. this.tick();
  4096. } else if (fragLoaded.sn === 'initSegment') {
  4097. this.state = State.IDLE;
  4098. stats.tparsed = stats.tbuffered = performance.now();
  4099. details.initSegment.data = data.payload;
  4100. this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
  4101. this.tick();
  4102. } else {
  4103. this.state = State.PARSING;
  4104. // transmux the MPEG-TS data to ISO-BMFF segments
  4105. var duration = details.totalduration,
  4106. level = fragCurrent.level,
  4107. sn = fragCurrent.sn,
  4108. audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  4109. if (this.audioCodecSwap) {
  4110. _logger.logger.log('swapping playlist audio codec');
  4111. if (audioCodec === undefined) {
  4112. audioCodec = this.lastAudioCodec;
  4113. }
  4114. if (audioCodec) {
  4115. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  4116. audioCodec = 'mp4a.40.2';
  4117. } else {
  4118. audioCodec = 'mp4a.40.5';
  4119. }
  4120. }
  4121. }
  4122. this.pendingBuffering = true;
  4123. this.appended = false;
  4124. _logger.logger.log('Parsing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + level + ', cc ' + fragCurrent.cc);
  4125. var demuxer = this.demuxer;
  4126. if (!demuxer) {
  4127. demuxer = this.demuxer = new _demuxer2.default(this.hls, 'main');
  4128. }
  4129. // 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)
  4130. var media = this.media;
  4131. var mediaSeeking = media && media.seeking;
  4132. var accurateTimeOffset = !mediaSeeking && (details.PTSKnown || !details.live);
  4133. var initSegmentData = details.initSegment ? details.initSegment.data : [];
  4134. demuxer.push(data.payload, initSegmentData, audioCodec, currentLevel.videoCodec, fragCurrent, duration, accurateTimeOffset, undefined);
  4135. }
  4136. }
  4137. this.fragLoadError = 0;
  4138. }
  4139. }, {
  4140. key: 'onFragParsingInitSegment',
  4141. value: function onFragParsingInitSegment(data) {
  4142. var fragCurrent = this.fragCurrent;
  4143. var fragNew = data.frag;
  4144. if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
  4145. var tracks = data.tracks,
  4146. trackName,
  4147. track;
  4148. // if audio track is expected to come from audio stream controller, discard any coming from main
  4149. if (tracks.audio && this.altAudio) {
  4150. delete tracks.audio;
  4151. }
  4152. // include levelCodec in audio and video tracks
  4153. track = tracks.audio;
  4154. if (track) {
  4155. var audioCodec = this.levels[this.level].audioCodec,
  4156. ua = navigator.userAgent.toLowerCase();
  4157. if (audioCodec && this.audioCodecSwap) {
  4158. _logger.logger.log('swapping playlist audio codec');
  4159. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  4160. audioCodec = 'mp4a.40.2';
  4161. } else {
  4162. audioCodec = 'mp4a.40.5';
  4163. }
  4164. }
  4165. // in case AAC and HE-AAC audio codecs are signalled in manifest
  4166. // force HE-AAC , as it seems that most browsers prefers that way,
  4167. // except for mono streams OR on FF
  4168. // these conditions might need to be reviewed ...
  4169. if (this.audioCodecSwitch) {
  4170. // don't force HE-AAC if mono stream
  4171. if (track.metadata.channelCount !== 1 &&
  4172. // don't force HE-AAC if firefox
  4173. ua.indexOf('firefox') === -1) {
  4174. audioCodec = 'mp4a.40.5';
  4175. }
  4176. }
  4177. // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  4178. if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') {
  4179. // Exclude mpeg audio
  4180. audioCodec = 'mp4a.40.2';
  4181. _logger.logger.log('Android: force audio codec to ' + audioCodec);
  4182. }
  4183. track.levelCodec = audioCodec;
  4184. track.id = data.id;
  4185. }
  4186. track = tracks.video;
  4187. if (track) {
  4188. track.levelCodec = this.levels[this.level].videoCodec;
  4189. track.id = data.id;
  4190. }
  4191. this.hls.trigger(_events2.default.BUFFER_CODECS, tracks);
  4192. // loop through tracks that are going to be provided to bufferController
  4193. for (trackName in tracks) {
  4194. track = tracks[trackName];
  4195. _logger.logger.log('main track:' + trackName + ',container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']');
  4196. var initSegment = track.initSegment;
  4197. if (initSegment) {
  4198. this.appended = true;
  4199. // arm pending Buffering flag before appending a segment
  4200. this.pendingBuffering = true;
  4201. this.hls.trigger(_events2.default.BUFFER_APPENDING, { type: trackName, data: initSegment, parent: 'main', content: 'initSegment' });
  4202. }
  4203. }
  4204. //trigger handler right now
  4205. this.tick();
  4206. }
  4207. }
  4208. }, {
  4209. key: 'onFragParsingData',
  4210. value: function onFragParsingData(data) {
  4211. var _this2 = this;
  4212. var fragCurrent = this.fragCurrent;
  4213. var fragNew = data.frag;
  4214. 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
  4215. this.state === State.PARSING) {
  4216. var level = this.levels[this.level],
  4217. frag = fragCurrent;
  4218. if (isNaN(data.endPTS)) {
  4219. data.endPTS = data.startPTS + fragCurrent.duration;
  4220. data.endDTS = data.startDTS + fragCurrent.duration;
  4221. }
  4222. _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));
  4223. // Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments)
  4224. if (data.type === 'video') {
  4225. frag.dropped = data.dropped;
  4226. if (frag.dropped) {
  4227. if (!frag.backtracked) {
  4228. // Return back to the IDLE state without appending to buffer
  4229. // Causes findFragments to backtrack a segment and find the keyframe
  4230. // Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment
  4231. frag.backtracked = true;
  4232. this.nextLoadPosition = data.startPTS;
  4233. this.state = State.IDLE;
  4234. this.tick();
  4235. return;
  4236. } else {
  4237. _logger.logger.warn('Already backtracked on this fragment, appending with the gap');
  4238. }
  4239. } else {
  4240. // Only reset the backtracked flag if we've loaded the frag without any dropped frames
  4241. frag.backtracked = false;
  4242. }
  4243. }
  4244. var drift = _levelHelper2.default.updateFragPTSDTS(level.details, frag.sn, data.startPTS, data.endPTS, data.startDTS, data.endDTS),
  4245. hls = this.hls;
  4246. hls.trigger(_events2.default.LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS });
  4247. // has remuxer dropped video frames located before first keyframe ?
  4248. [data.data1, data.data2].forEach(function (buffer) {
  4249. // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
  4250. // in that case it is useless to append following segments
  4251. if (buffer && buffer.length && _this2.state === State.PARSING) {
  4252. _this2.appended = true;
  4253. // arm pending Buffering flag before appending a segment
  4254. _this2.pendingBuffering = true;
  4255. hls.trigger(_events2.default.BUFFER_APPENDING, { type: data.type, data: buffer, parent: 'main', content: 'data' });
  4256. }
  4257. });
  4258. //trigger handler right now
  4259. this.tick();
  4260. }
  4261. }
  4262. }, {
  4263. key: 'onFragParsed',
  4264. value: function onFragParsed(data) {
  4265. var fragCurrent = this.fragCurrent;
  4266. var fragNew = data.frag;
  4267. if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
  4268. this.stats.tparsed = performance.now();
  4269. this.state = State.PARSED;
  4270. this._checkAppendedParsed();
  4271. }
  4272. }
  4273. }, {
  4274. key: 'onAudioTrackSwitching',
  4275. value: function onAudioTrackSwitching(data) {
  4276. // if any URL found on new audio track, it is an alternate audio track
  4277. var altAudio = !!data.url,
  4278. trackId = data.id;
  4279. // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
  4280. // don't do anything if we switch to alt audio: audio stream controller is handling it.
  4281. // we will just have to change buffer scheduling on audioTrackSwitched
  4282. if (!altAudio) {
  4283. if (this.mediaBuffer !== this.media) {
  4284. _logger.logger.log('switching on main audio, use media.buffered to schedule main fragment loading');
  4285. this.mediaBuffer = this.media;
  4286. var fragCurrent = this.fragCurrent;
  4287. // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
  4288. if (fragCurrent.loader) {
  4289. _logger.logger.log('switching to main audio track, cancel main fragment load');
  4290. fragCurrent.loader.abort();
  4291. }
  4292. this.fragCurrent = null;
  4293. this.fragPrevious = null;
  4294. // destroy demuxer to force init segment generation (following audio switch)
  4295. if (this.demuxer) {
  4296. this.demuxer.destroy();
  4297. this.demuxer = null;
  4298. }
  4299. // switch to IDLE state to load new fragment
  4300. this.state = State.IDLE;
  4301. }
  4302. var hls = this.hls;
  4303. // switching to main audio, flush all audio and trigger track switched
  4304. hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
  4305. hls.trigger(_events2.default.AUDIO_TRACK_SWITCHED, { id: trackId });
  4306. this.altAudio = false;
  4307. }
  4308. }
  4309. }, {
  4310. key: 'onAudioTrackSwitched',
  4311. value: function onAudioTrackSwitched(data) {
  4312. var trackId = data.id,
  4313. altAudio = !!this.hls.audioTracks[trackId].url;
  4314. if (altAudio) {
  4315. var videoBuffer = this.videoBuffer;
  4316. // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
  4317. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  4318. _logger.logger.log('switching on alternate audio, use video.buffered to schedule main fragment loading');
  4319. this.mediaBuffer = videoBuffer;
  4320. }
  4321. }
  4322. this.altAudio = altAudio;
  4323. this.tick();
  4324. }
  4325. }, {
  4326. key: 'onBufferCreated',
  4327. value: function onBufferCreated(data) {
  4328. var tracks = data.tracks,
  4329. mediaTrack = void 0,
  4330. name = void 0,
  4331. alternate = false;
  4332. for (var type in tracks) {
  4333. var track = tracks[type];
  4334. if (track.id === 'main') {
  4335. name = type;
  4336. mediaTrack = track;
  4337. // keep video source buffer reference
  4338. if (type === 'video') {
  4339. this.videoBuffer = tracks[type].buffer;
  4340. }
  4341. } else {
  4342. alternate = true;
  4343. }
  4344. }
  4345. if (alternate && mediaTrack) {
  4346. _logger.logger.log('alternate track found, use ' + name + '.buffered to schedule main fragment loading');
  4347. this.mediaBuffer = mediaTrack.buffer;
  4348. } else {
  4349. this.mediaBuffer = this.media;
  4350. }
  4351. }
  4352. }, {
  4353. key: 'onBufferAppended',
  4354. value: function onBufferAppended(data) {
  4355. if (data.parent === 'main') {
  4356. var state = this.state;
  4357. if (state === State.PARSING || state === State.PARSED) {
  4358. // check if all buffers have been appended
  4359. this.pendingBuffering = data.pending > 0;
  4360. this._checkAppendedParsed();
  4361. }
  4362. }
  4363. }
  4364. }, {
  4365. key: '_checkAppendedParsed',
  4366. value: function _checkAppendedParsed() {
  4367. //trigger handler right now
  4368. if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {
  4369. var frag = this.fragCurrent;
  4370. if (frag) {
  4371. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  4372. _logger.logger.log('main buffered : ' + _timeRanges2.default.toString(media.buffered));
  4373. // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams
  4374. var bufferedFrags = this._bufferedFrags.filter(function (frag) {
  4375. return _bufferHelper2.default.isBuffered(media, (frag.startPTS + frag.endPTS) / 2);
  4376. });
  4377. // push new range
  4378. bufferedFrags.push(frag);
  4379. // sort frags, as we use BinarySearch for lookup in getBufferedFrag ...
  4380. this._bufferedFrags = bufferedFrags.sort(function (a, b) {
  4381. return a.startPTS - b.startPTS;
  4382. });
  4383. this.fragPrevious = frag;
  4384. var stats = this.stats;
  4385. stats.tbuffered = performance.now();
  4386. // we should get rid of this.fragLastKbps
  4387. this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));
  4388. this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' });
  4389. this.state = State.IDLE;
  4390. }
  4391. this.tick();
  4392. }
  4393. }
  4394. }, {
  4395. key: 'onError',
  4396. value: function onError(data) {
  4397. var frag = data.frag || this.fragCurrent;
  4398. // don't handle frag error not related to main fragment
  4399. if (frag && frag.type !== 'main') {
  4400. return;
  4401. }
  4402. var media = this.media,
  4403. // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  4404. mediaBuffered = media && _bufferHelper2.default.isBuffered(media, media.currentTime) && _bufferHelper2.default.isBuffered(media, media.currentTime + 0.5);
  4405. switch (data.details) {
  4406. case _errors.ErrorDetails.FRAG_LOAD_ERROR:
  4407. case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
  4408. case _errors.ErrorDetails.KEY_LOAD_ERROR:
  4409. case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
  4410. if (!data.fatal) {
  4411. var loadError = this.fragLoadError;
  4412. if (loadError) {
  4413. loadError++;
  4414. } else {
  4415. loadError = 1;
  4416. }
  4417. var config = this.config;
  4418. // keep retrying / don't raise fatal network error if current position is buffered or if in automode with current level not 0
  4419. if (loadError <= config.fragLoadingMaxRetry || mediaBuffered || frag.autoLevel && frag.level) {
  4420. this.fragLoadError = loadError;
  4421. // reset load counter to avoid frag loop loading error
  4422. frag.loadCounter = 0;
  4423. // exponential backoff capped to config.fragLoadingMaxRetryTimeout
  4424. var delay = Math.min(Math.pow(2, loadError - 1) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);
  4425. _logger.logger.warn('mediaController: frag loading failed, retry in ' + delay + ' ms');
  4426. this.retryDate = performance.now() + delay;
  4427. // retry loading state
  4428. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  4429. // in that case, reset startFragRequested flag
  4430. if (!this.loadedmetadata) {
  4431. this.startFragRequested = false;
  4432. this.nextLoadPosition = this.startPosition;
  4433. }
  4434. this.state = State.FRAG_LOADING_WAITING_RETRY;
  4435. } else {
  4436. _logger.logger.error('mediaController: ' + data.details + ' reaches max retry, redispatch as fatal ...');
  4437. // switch error to fatal
  4438. data.fatal = true;
  4439. this.state = State.ERROR;
  4440. }
  4441. }
  4442. break;
  4443. case _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR:
  4444. if (!data.fatal) {
  4445. // if buffer is not empty
  4446. if (mediaBuffered) {
  4447. // try to reduce max buffer length : rationale is that we could get
  4448. // frag loop loading error because of buffer eviction
  4449. this._reduceMaxBufferLength(frag.duration);
  4450. this.state = State.IDLE;
  4451. } else {
  4452. // buffer empty. report as fatal if in manual mode or if lowest level.
  4453. // level controller takes care of emergency switch down logic
  4454. if (!frag.autoLevel || frag.level === 0) {
  4455. // switch error to fatal
  4456. data.fatal = true;
  4457. this.state = State.ERROR;
  4458. }
  4459. }
  4460. }
  4461. break;
  4462. case _errors.ErrorDetails.LEVEL_LOAD_ERROR:
  4463. case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT:
  4464. if (this.state !== State.ERROR) {
  4465. if (data.fatal) {
  4466. // if fatal error, stop processing
  4467. this.state = State.ERROR;
  4468. _logger.logger.warn('streamController: ' + data.details + ',switch to ' + this.state + ' state ...');
  4469. } else {
  4470. // in cas of non fatal error while waiting level load to be completed, switch back to IDLE
  4471. if (this.state === State.WAITING_LEVEL) {
  4472. this.state = State.IDLE;
  4473. }
  4474. }
  4475. }
  4476. break;
  4477. case _errors.ErrorDetails.BUFFER_FULL_ERROR:
  4478. // if in appending state
  4479. if (data.parent === 'main' && (this.state === State.PARSING || this.state === State.PARSED)) {
  4480. // reduce max buf len if current position is buffered
  4481. if (mediaBuffered) {
  4482. this._reduceMaxBufferLength(this.config.maxBufferLength);
  4483. this.state = State.IDLE;
  4484. } else {
  4485. // current position is not buffered, but browser is still complaining about buffer full error
  4486. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  4487. // in that case flush the whole buffer to recover
  4488. _logger.logger.warn('buffer full error also media.currentTime is not buffered, flush everything');
  4489. this.fragCurrent = null;
  4490. // flush everything
  4491. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  4492. }
  4493. }
  4494. break;
  4495. default:
  4496. break;
  4497. }
  4498. }
  4499. }, {
  4500. key: '_reduceMaxBufferLength',
  4501. value: function _reduceMaxBufferLength(minLength) {
  4502. var config = this.config;
  4503. if (config.maxMaxBufferLength >= minLength) {
  4504. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  4505. config.maxMaxBufferLength /= 2;
  4506. _logger.logger.warn('main:reduce max buffer length to ' + config.maxMaxBufferLength + 's');
  4507. // increase fragment load Index to avoid frag loop loading error after buffer flush
  4508. this.fragLoadIdx += 2 * config.fragLoadingLoopThreshold;
  4509. }
  4510. }
  4511. }, {
  4512. key: '_checkBuffer',
  4513. value: function _checkBuffer() {
  4514. var media = this.media;
  4515. // if ready state different from HAVE_NOTHING (numeric value 0), we are allowed to seek
  4516. if (media && media.readyState) {
  4517. var currentTime = media.currentTime,
  4518. mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media,
  4519. buffered = mediaBuffer.buffered;
  4520. // adjust currentTime to start position on loaded metadata
  4521. if (!this.loadedmetadata && buffered.length) {
  4522. this.loadedmetadata = true;
  4523. // only adjust currentTime if different from startPosition or if startPosition not buffered
  4524. // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
  4525. var startPosition = media.seeking ? currentTime : this.startPosition,
  4526. startPositionBuffered = _bufferHelper2.default.isBuffered(mediaBuffer, startPosition);
  4527. // if currentTime not matching with expected startPosition or startPosition not buffered
  4528. if (currentTime !== startPosition || !startPositionBuffered) {
  4529. _logger.logger.log('target start position:' + startPosition);
  4530. // if startPosition not buffered, let's seek to buffered.start(0)
  4531. if (!startPositionBuffered) {
  4532. startPosition = buffered.start(0);
  4533. _logger.logger.log('target start position not buffered, seek to buffered.start(0) ' + startPosition);
  4534. }
  4535. _logger.logger.log('adjust currentTime from ' + currentTime + ' to ' + startPosition);
  4536. media.currentTime = startPosition;
  4537. }
  4538. } else if (this.immediateSwitch) {
  4539. this.immediateLevelSwitchEnd();
  4540. } else {
  4541. var bufferInfo = _bufferHelper2.default.bufferInfo(media, currentTime, 0),
  4542. expectedPlaying = !(media.paused || // not playing when media is paused
  4543. media.ended || // not playing when media is ended
  4544. media.buffered.length === 0),
  4545. // not playing if nothing buffered
  4546. jumpThreshold = 0.5,
  4547. // tolerance needed as some browsers stalls playback before reaching buffered range end
  4548. playheadMoving = currentTime !== this.lastCurrentTime,
  4549. config = this.config;
  4550. if (playheadMoving) {
  4551. // played moving, but was previously stalled => now not stuck anymore
  4552. if (this.stallReported) {
  4553. _logger.logger.warn('playback not stuck anymore @' + currentTime + ', after ' + Math.round(performance.now() - this.stalled) + 'ms');
  4554. this.stallReported = false;
  4555. }
  4556. this.stalled = undefined;
  4557. this.nudgeRetry = 0;
  4558. } else {
  4559. // playhead not moving
  4560. if (expectedPlaying) {
  4561. // playhead not moving BUT media expected to play
  4562. var tnow = performance.now();
  4563. var hls = this.hls;
  4564. if (!this.stalled) {
  4565. // stall just detected, store current time
  4566. this.stalled = tnow;
  4567. this.stallReported = false;
  4568. } else {
  4569. // playback already stalled, check stalling duration
  4570. // if stalling for more than a given threshold, let's try to recover
  4571. var stalledDuration = tnow - this.stalled;
  4572. var bufferLen = bufferInfo.len;
  4573. var nudgeRetry = this.nudgeRetry || 0;
  4574. // have we reached stall deadline ?
  4575. if (bufferLen <= jumpThreshold && stalledDuration > config.lowBufferWatchdogPeriod * 1000) {
  4576. // report stalled error once
  4577. if (!this.stallReported) {
  4578. this.stallReported = true;
  4579. _logger.logger.warn('playback stalling in low buffer @' + currentTime);
  4580. hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_STALLED_ERROR, fatal: false, buffer: bufferLen });
  4581. }
  4582. // if buffer len is below threshold, try to jump to start of next buffer range if close
  4583. // no buffer available @ currentTime, check if next buffer is close (within a config.maxSeekHole second range)
  4584. var nextBufferStart = bufferInfo.nextStart,
  4585. delta = nextBufferStart - currentTime;
  4586. if (nextBufferStart && delta < config.maxSeekHole && delta > 0) {
  4587. this.nudgeRetry = ++nudgeRetry;
  4588. var nudgeOffset = nudgeRetry * config.nudgeOffset;
  4589. // next buffer is close ! adjust currentTime to nextBufferStart
  4590. // this will ensure effective video decoding
  4591. _logger.logger.log('adjust currentTime from ' + media.currentTime + ' to next buffered @ ' + nextBufferStart + ' + nudge ' + nudgeOffset);
  4592. media.currentTime = nextBufferStart + nudgeOffset;
  4593. // reset stalled so to rearm watchdog timer
  4594. this.stalled = undefined;
  4595. hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_SEEK_OVER_HOLE, fatal: false, hole: nextBufferStart + nudgeOffset - currentTime });
  4596. }
  4597. } else if (bufferLen > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {
  4598. // report stalled error once
  4599. if (!this.stallReported) {
  4600. this.stallReported = true;
  4601. _logger.logger.warn('playback stalling in high buffer @' + currentTime);
  4602. hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_STALLED_ERROR, fatal: false, buffer: bufferLen });
  4603. }
  4604. // reset stalled so to rearm watchdog timer
  4605. this.stalled = undefined;
  4606. this.nudgeRetry = ++nudgeRetry;
  4607. if (nudgeRetry < config.nudgeMaxRetry) {
  4608. var _currentTime = media.currentTime;
  4609. var targetTime = _currentTime + nudgeRetry * config.nudgeOffset;
  4610. _logger.logger.log('adjust currentTime from ' + _currentTime + ' to ' + targetTime);
  4611. // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
  4612. media.currentTime = targetTime;
  4613. hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_NUDGE_ON_STALL, fatal: false });
  4614. } else {
  4615. _logger.logger.error('still stuck in high buffer @' + currentTime + ' after ' + config.nudgeMaxRetry + ', raise fatal error');
  4616. hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_STALLED_ERROR, fatal: true });
  4617. }
  4618. }
  4619. }
  4620. }
  4621. }
  4622. }
  4623. }
  4624. }
  4625. }, {
  4626. key: 'onFragLoadEmergencyAborted',
  4627. value: function onFragLoadEmergencyAborted() {
  4628. this.state = State.IDLE;
  4629. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  4630. // in that case, reset startFragRequested flag
  4631. if (!this.loadedmetadata) {
  4632. this.startFragRequested = false;
  4633. this.nextLoadPosition = this.startPosition;
  4634. }
  4635. this.tick();
  4636. }
  4637. }, {
  4638. key: 'onBufferFlushed',
  4639. value: function onBufferFlushed() {
  4640. /* after successful buffer flushing, filter flushed fragments from bufferedFrags
  4641. use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)
  4642. */
  4643. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  4644. this._bufferedFrags = this._bufferedFrags.filter(function (frag) {
  4645. return _bufferHelper2.default.isBuffered(media, (frag.startPTS + frag.endPTS) / 2);
  4646. });
  4647. // increase fragment load Index to avoid frag loop loading error after buffer flush
  4648. this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
  4649. // move to IDLE once flush complete. this should trigger new fragment loading
  4650. this.state = State.IDLE;
  4651. // reset reference to frag
  4652. this.fragPrevious = null;
  4653. }
  4654. }, {
  4655. key: 'swapAudioCodec',
  4656. value: function swapAudioCodec() {
  4657. this.audioCodecSwap = !this.audioCodecSwap;
  4658. }
  4659. }, {
  4660. key: 'computeLivePosition',
  4661. value: function computeLivePosition(sliding, levelDetails) {
  4662. var targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration;
  4663. return sliding + Math.max(0, levelDetails.totalduration - targetLatency);
  4664. }
  4665. }, {
  4666. key: 'state',
  4667. set: function set(nextState) {
  4668. if (this.state !== nextState) {
  4669. var previousState = this.state;
  4670. this._state = nextState;
  4671. _logger.logger.log('main stream:' + previousState + '->' + nextState);
  4672. this.hls.trigger(_events2.default.STREAM_STATE_TRANSITION, { previousState: previousState, nextState: nextState });
  4673. }
  4674. },
  4675. get: function get() {
  4676. return this._state;
  4677. }
  4678. }, {
  4679. key: 'currentLevel',
  4680. get: function get() {
  4681. var media = this.media;
  4682. if (media) {
  4683. var frag = this.getBufferedFrag(media.currentTime);
  4684. if (frag) {
  4685. return frag.level;
  4686. }
  4687. }
  4688. return -1;
  4689. }
  4690. }, {
  4691. key: 'nextBufferedFrag',
  4692. get: function get() {
  4693. var media = this.media;
  4694. if (media) {
  4695. // first get end range of current fragment
  4696. return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime));
  4697. } else {
  4698. return null;
  4699. }
  4700. }
  4701. }, {
  4702. key: 'nextLevel',
  4703. get: function get() {
  4704. var frag = this.nextBufferedFrag;
  4705. if (frag) {
  4706. return frag.level;
  4707. } else {
  4708. return -1;
  4709. }
  4710. }
  4711. }, {
  4712. key: 'liveSyncPosition',
  4713. get: function get() {
  4714. return this._liveSyncPosition;
  4715. },
  4716. set: function set(value) {
  4717. this._liveSyncPosition = value;
  4718. }
  4719. }]);
  4720. return StreamController;
  4721. }(_eventHandler2.default);
  4722. exports.default = StreamController;
  4723. },{"24":24,"30":30,"31":31,"32":32,"34":34,"35":35,"45":45,"50":50,"51":51}],13:[function(_dereq_,module,exports){
  4724. 'use strict';
  4725. Object.defineProperty(exports, "__esModule", {
  4726. value: true
  4727. });
  4728. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  4729. var _events = _dereq_(32);
  4730. var _events2 = _interopRequireDefault(_events);
  4731. var _eventHandler = _dereq_(31);
  4732. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  4733. var _logger = _dereq_(50);
  4734. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  4735. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4736. 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; }
  4737. 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; } /*
  4738. * Subtitle Stream Controller
  4739. */
  4740. var SubtitleStreamController = function (_EventHandler) {
  4741. _inherits(SubtitleStreamController, _EventHandler);
  4742. function SubtitleStreamController(hls) {
  4743. _classCallCheck(this, SubtitleStreamController);
  4744. var _this = _possibleConstructorReturn(this, (SubtitleStreamController.__proto__ || Object.getPrototypeOf(SubtitleStreamController)).call(this, hls, _events2.default.ERROR, _events2.default.SUBTITLE_TRACKS_UPDATED, _events2.default.SUBTITLE_TRACK_SWITCH, _events2.default.SUBTITLE_TRACK_LOADED, _events2.default.SUBTITLE_FRAG_PROCESSED));
  4745. _this.config = hls.config;
  4746. _this.vttFragSNsProcessed = {};
  4747. _this.vttFragQueues = undefined;
  4748. _this.currentlyProcessing = null;
  4749. _this.currentTrackId = -1;
  4750. return _this;
  4751. }
  4752. _createClass(SubtitleStreamController, [{
  4753. key: 'destroy',
  4754. value: function destroy() {
  4755. _eventHandler2.default.prototype.destroy.call(this);
  4756. }
  4757. // Remove all queued items and create a new, empty queue for each track.
  4758. }, {
  4759. key: 'clearVttFragQueues',
  4760. value: function clearVttFragQueues() {
  4761. var _this2 = this;
  4762. this.vttFragQueues = {};
  4763. this.tracks.forEach(function (track) {
  4764. _this2.vttFragQueues[track.id] = [];
  4765. });
  4766. }
  4767. // If no frag is being processed and queue isn't empty, initiate processing of next frag in line.
  4768. }, {
  4769. key: 'nextFrag',
  4770. value: function nextFrag() {
  4771. if (this.currentlyProcessing === null && this.currentTrackId > -1 && this.vttFragQueues[this.currentTrackId].length) {
  4772. var frag = this.currentlyProcessing = this.vttFragQueues[this.currentTrackId].shift();
  4773. this.hls.trigger(_events2.default.FRAG_LOADING, { frag: frag });
  4774. }
  4775. }
  4776. // When fragment has finished processing, add sn to list of completed if successful.
  4777. }, {
  4778. key: 'onSubtitleFragProcessed',
  4779. value: function onSubtitleFragProcessed(data) {
  4780. if (data.success) {
  4781. this.vttFragSNsProcessed[data.frag.trackId].push(data.frag.sn);
  4782. }
  4783. this.currentlyProcessing = null;
  4784. this.nextFrag();
  4785. }
  4786. // If something goes wrong, procede to next frag, if we were processing one.
  4787. }, {
  4788. key: 'onError',
  4789. value: function onError(data) {
  4790. var frag = data.frag;
  4791. // don't handle frag error not related to subtitle fragment
  4792. if (frag && frag.type !== 'subtitle') {
  4793. return;
  4794. }
  4795. if (this.currentlyProcessing) {
  4796. this.currentlyProcessing = null;
  4797. this.nextFrag();
  4798. }
  4799. }
  4800. // Got all new subtitle tracks.
  4801. }, {
  4802. key: 'onSubtitleTracksUpdated',
  4803. value: function onSubtitleTracksUpdated(data) {
  4804. var _this3 = this;
  4805. _logger.logger.log('subtitle tracks updated');
  4806. this.tracks = data.subtitleTracks;
  4807. this.clearVttFragQueues();
  4808. this.vttFragSNsProcessed = {};
  4809. this.tracks.forEach(function (track) {
  4810. _this3.vttFragSNsProcessed[track.id] = [];
  4811. });
  4812. }
  4813. }, {
  4814. key: 'onSubtitleTrackSwitch',
  4815. value: function onSubtitleTrackSwitch(data) {
  4816. this.currentTrackId = data.id;
  4817. this.clearVttFragQueues();
  4818. }
  4819. // Got a new set of subtitle fragments.
  4820. }, {
  4821. key: 'onSubtitleTrackLoaded',
  4822. value: function onSubtitleTrackLoaded(data) {
  4823. var processedFragSNs = this.vttFragSNsProcessed[data.id],
  4824. fragQueue = this.vttFragQueues[data.id],
  4825. currentFragSN = !!this.currentlyProcessing ? this.currentlyProcessing.sn : -1;
  4826. var alreadyProcessed = function alreadyProcessed(frag) {
  4827. return processedFragSNs.indexOf(frag.sn) > -1;
  4828. };
  4829. var alreadyInQueue = function alreadyInQueue(frag) {
  4830. return fragQueue.some(function (fragInQueue) {
  4831. return fragInQueue.sn === frag.sn;
  4832. });
  4833. };
  4834. // Add all fragments that haven't been, aren't currently being and aren't waiting to be processed, to queue.
  4835. data.details.fragments.forEach(function (frag) {
  4836. if (!(alreadyProcessed(frag) || frag.sn === currentFragSN || alreadyInQueue(frag))) {
  4837. // Frags don't know their subtitle track ID, so let's just add that...
  4838. frag.trackId = data.id;
  4839. fragQueue.push(frag);
  4840. }
  4841. });
  4842. this.nextFrag();
  4843. }
  4844. }]);
  4845. return SubtitleStreamController;
  4846. }(_eventHandler2.default);
  4847. exports.default = SubtitleStreamController;
  4848. },{"31":31,"32":32,"50":50}],14:[function(_dereq_,module,exports){
  4849. 'use strict';
  4850. Object.defineProperty(exports, "__esModule", {
  4851. value: true
  4852. });
  4853. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  4854. var _events = _dereq_(32);
  4855. var _events2 = _interopRequireDefault(_events);
  4856. var _eventHandler = _dereq_(31);
  4857. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  4858. var _logger = _dereq_(50);
  4859. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  4860. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4861. 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; }
  4862. 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; } /*
  4863. * audio track controller
  4864. */
  4865. var SubtitleTrackController = function (_EventHandler) {
  4866. _inherits(SubtitleTrackController, _EventHandler);
  4867. function SubtitleTrackController(hls) {
  4868. _classCallCheck(this, SubtitleTrackController);
  4869. var _this = _possibleConstructorReturn(this, (SubtitleTrackController.__proto__ || Object.getPrototypeOf(SubtitleTrackController)).call(this, hls, _events2.default.MEDIA_ATTACHED, _events2.default.MEDIA_DETACHING, _events2.default.MANIFEST_LOADING, _events2.default.MANIFEST_LOADED, _events2.default.SUBTITLE_TRACK_LOADED));
  4870. _this.tracks = [];
  4871. _this.trackId = -1;
  4872. _this.media = undefined;
  4873. return _this;
  4874. }
  4875. _createClass(SubtitleTrackController, [{
  4876. key: 'destroy',
  4877. value: function destroy() {
  4878. _eventHandler2.default.prototype.destroy.call(this);
  4879. }
  4880. // Listen for subtitle track change, then extract the current track ID.
  4881. }, {
  4882. key: 'onMediaAttached',
  4883. value: function onMediaAttached(data) {
  4884. var _this2 = this;
  4885. this.media = data.media;
  4886. if (!this.media) {
  4887. return;
  4888. }
  4889. this.media.textTracks.addEventListener('change', function () {
  4890. // Media is undefined when switching streams via loadSource()
  4891. if (!_this2.media) {
  4892. return;
  4893. }
  4894. var trackId = -1;
  4895. var tracks = _this2.media.textTracks;
  4896. for (var id = 0; id < tracks.length; id++) {
  4897. if (tracks[id].mode === 'showing') {
  4898. trackId = id;
  4899. }
  4900. }
  4901. // Setting current subtitleTrack will invoke code.
  4902. _this2.subtitleTrack = trackId;
  4903. });
  4904. }
  4905. }, {
  4906. key: 'onMediaDetaching',
  4907. value: function onMediaDetaching() {
  4908. // TODO: Remove event listeners.
  4909. this.media = undefined;
  4910. }
  4911. // Reset subtitle tracks on manifest loading
  4912. }, {
  4913. key: 'onManifestLoading',
  4914. value: function onManifestLoading() {
  4915. this.tracks = [];
  4916. this.trackId = -1;
  4917. }
  4918. // Fired whenever a new manifest is loaded.
  4919. }, {
  4920. key: 'onManifestLoaded',
  4921. value: function onManifestLoaded(data) {
  4922. var _this3 = this;
  4923. var tracks = data.subtitles || [];
  4924. var defaultFound = false;
  4925. this.tracks = tracks;
  4926. this.trackId = -1;
  4927. this.hls.trigger(_events2.default.SUBTITLE_TRACKS_UPDATED, { subtitleTracks: tracks });
  4928. // loop through available subtitle tracks and autoselect default if needed
  4929. // TODO: improve selection logic to handle forced, etc
  4930. tracks.forEach(function (track) {
  4931. if (track.default) {
  4932. _this3.subtitleTrack = track.id;
  4933. defaultFound = true;
  4934. }
  4935. });
  4936. }
  4937. // Trigger subtitle track playlist reload.
  4938. }, {
  4939. key: 'onTick',
  4940. value: function onTick() {
  4941. var trackId = this.trackId;
  4942. var subtitleTrack = this.tracks[trackId];
  4943. if (!subtitleTrack) {
  4944. return;
  4945. }
  4946. var details = subtitleTrack.details;
  4947. // check if we need to load playlist for this subtitle Track
  4948. if (details === undefined || details.live === true) {
  4949. // track not retrieved yet, or live playlist we need to (re)load it
  4950. _logger.logger.log('(re)loading playlist for subtitle track ' + trackId);
  4951. this.hls.trigger(_events2.default.SUBTITLE_TRACK_LOADING, { url: subtitleTrack.url, id: trackId });
  4952. }
  4953. }
  4954. }, {
  4955. key: 'onSubtitleTrackLoaded',
  4956. value: function onSubtitleTrackLoaded(data) {
  4957. var _this4 = this;
  4958. if (data.id < this.tracks.length) {
  4959. _logger.logger.log('subtitle track ' + data.id + ' loaded');
  4960. this.tracks[data.id].details = data.details;
  4961. // check if current playlist is a live playlist
  4962. if (data.details.live && !this.timer) {
  4963. // if live playlist we will have to reload it periodically
  4964. // set reload period to playlist target duration
  4965. this.timer = setInterval(function () {
  4966. _this4.onTick();
  4967. }, 1000 * data.details.targetduration, this);
  4968. }
  4969. if (!data.details.live && this.timer) {
  4970. // playlist is not live and timer is armed : stopping it
  4971. clearInterval(this.timer);
  4972. this.timer = null;
  4973. }
  4974. }
  4975. }
  4976. /** get alternate subtitle tracks list from playlist **/
  4977. }, {
  4978. key: 'setSubtitleTrackInternal',
  4979. value: function setSubtitleTrackInternal(newId) {
  4980. // check if level idx is valid
  4981. if (newId >= 0 && newId < this.tracks.length) {
  4982. // stopping live reloading timer if any
  4983. if (this.timer) {
  4984. clearInterval(this.timer);
  4985. this.timer = null;
  4986. }
  4987. this.trackId = newId;
  4988. _logger.logger.log('switching to subtitle track ' + newId);
  4989. var subtitleTrack = this.tracks[newId];
  4990. this.hls.trigger(_events2.default.SUBTITLE_TRACK_SWITCH, { id: newId });
  4991. // check if we need to load playlist for this subtitle Track
  4992. var details = subtitleTrack.details;
  4993. if (details === undefined || details.live === true) {
  4994. // track not retrieved yet, or live playlist we need to (re)load it
  4995. _logger.logger.log('(re)loading playlist for subtitle track ' + newId);
  4996. this.hls.trigger(_events2.default.SUBTITLE_TRACK_LOADING, { url: subtitleTrack.url, id: newId });
  4997. }
  4998. }
  4999. }
  5000. }, {
  5001. key: 'subtitleTracks',
  5002. get: function get() {
  5003. return this.tracks;
  5004. }
  5005. /** get index of the selected subtitle track (index in subtitle track lists) **/
  5006. }, {
  5007. key: 'subtitleTrack',
  5008. get: function get() {
  5009. return this.trackId;
  5010. }
  5011. /** select a subtitle track, based on its index in subtitle track lists**/
  5012. ,
  5013. set: function set(subtitleTrackId) {
  5014. if (this.trackId !== subtitleTrackId) {
  5015. // || this.tracks[subtitleTrackId].details === undefined) {
  5016. this.setSubtitleTrackInternal(subtitleTrackId);
  5017. }
  5018. }
  5019. }]);
  5020. return SubtitleTrackController;
  5021. }(_eventHandler2.default);
  5022. exports.default = SubtitleTrackController;
  5023. },{"31":31,"32":32,"50":50}],15:[function(_dereq_,module,exports){
  5024. 'use strict';
  5025. Object.defineProperty(exports, "__esModule", {
  5026. value: true
  5027. });
  5028. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  5029. var _events = _dereq_(32);
  5030. var _events2 = _interopRequireDefault(_events);
  5031. var _eventHandler = _dereq_(31);
  5032. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  5033. var _cea608Parser = _dereq_(46);
  5034. var _cea608Parser2 = _interopRequireDefault(_cea608Parser);
  5035. var _webvttParser = _dereq_(54);
  5036. var _webvttParser2 = _interopRequireDefault(_webvttParser);
  5037. var _logger = _dereq_(50);
  5038. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5039. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5040. 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; }
  5041. 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; } /*
  5042. * Timeline Controller
  5043. */
  5044. function clearCurrentCues(track) {
  5045. if (track && track.cues) {
  5046. while (track.cues.length > 0) {
  5047. track.removeCue(track.cues[0]);
  5048. }
  5049. }
  5050. }
  5051. function reuseVttTextTrack(inUseTrack, manifestTrack) {
  5052. return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);
  5053. }
  5054. function intersection(x1, x2, y1, y2) {
  5055. return Math.min(x2, y2) - Math.max(x1, y1);
  5056. }
  5057. var TimelineController = function (_EventHandler) {
  5058. _inherits(TimelineController, _EventHandler);
  5059. function TimelineController(hls) {
  5060. _classCallCheck(this, TimelineController);
  5061. 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.MANIFEST_LOADING, _events2.default.MANIFEST_LOADED, _events2.default.FRAG_LOADED, _events2.default.LEVEL_SWITCHING, _events2.default.INIT_PTS_FOUND));
  5062. _this.hls = hls;
  5063. _this.config = hls.config;
  5064. _this.enabled = true;
  5065. _this.Cues = hls.config.cueHandler;
  5066. _this.textTracks = [];
  5067. _this.tracks = [];
  5068. _this.unparsedVttFrags = [];
  5069. _this.initPTS = undefined;
  5070. _this.cueRanges = [];
  5071. if (_this.config.enableCEA708Captions) {
  5072. var self = _this;
  5073. var sendAddTrackEvent = function sendAddTrackEvent(track, media) {
  5074. var e = null;
  5075. try {
  5076. e = new window.Event('addtrack');
  5077. } catch (err) {
  5078. //for IE11
  5079. e = document.createEvent('Event');
  5080. e.initEvent('addtrack', false, false);
  5081. }
  5082. e.track = track;
  5083. media.dispatchEvent(e);
  5084. };
  5085. var channel1 = {
  5086. 'newCue': function newCue(startTime, endTime, screen) {
  5087. if (!self.textTrack1) {
  5088. //Enable reuse of existing text track.
  5089. var existingTrack1 = self.getExistingTrack('1');
  5090. if (!existingTrack1) {
  5091. var textTrack1 = self.createTextTrack('captions', self.config.captionsTextTrack1Label, self.config.captionsTextTrack1LanguageCode);
  5092. if (textTrack1) {
  5093. textTrack1.textTrack1 = true;
  5094. self.textTrack1 = textTrack1;
  5095. }
  5096. } else {
  5097. self.textTrack1 = existingTrack1;
  5098. clearCurrentCues(self.textTrack1);
  5099. sendAddTrackEvent(self.textTrack1, self.media);
  5100. }
  5101. }
  5102. self.addCues('textTrack1', startTime, endTime, screen);
  5103. }
  5104. };
  5105. var channel2 = {
  5106. 'newCue': function newCue(startTime, endTime, screen) {
  5107. if (!self.textTrack2) {
  5108. //Enable reuse of existing text track.
  5109. var existingTrack2 = self.getExistingTrack('2');
  5110. if (!existingTrack2) {
  5111. var textTrack2 = self.createTextTrack('captions', self.config.captionsTextTrack2Label, self.config.captionsTextTrack1LanguageCode);
  5112. if (textTrack2) {
  5113. textTrack2.textTrack2 = true;
  5114. self.textTrack2 = textTrack2;
  5115. }
  5116. } else {
  5117. self.textTrack2 = existingTrack2;
  5118. clearCurrentCues(self.textTrack2);
  5119. sendAddTrackEvent(self.textTrack2, self.media);
  5120. }
  5121. }
  5122. self.addCues('textTrack2', startTime, endTime, screen);
  5123. }
  5124. };
  5125. _this.cea608Parser = new _cea608Parser2.default(0, channel1, channel2);
  5126. }
  5127. return _this;
  5128. }
  5129. _createClass(TimelineController, [{
  5130. key: 'addCues',
  5131. value: function addCues(channel, startTime, endTime, screen) {
  5132. // skip cues which overlap more than 50% with previously parsed time ranges
  5133. var ranges = this.cueRanges;
  5134. var merged = false;
  5135. for (var i = ranges.length; i--;) {
  5136. var cueRange = ranges[i];
  5137. var overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
  5138. if (overlap >= 0) {
  5139. cueRange[0] = Math.min(cueRange[0], startTime);
  5140. cueRange[1] = Math.max(cueRange[1], endTime);
  5141. merged = true;
  5142. if (overlap / (endTime - startTime) > 0.5) {
  5143. return;
  5144. }
  5145. }
  5146. }
  5147. if (!merged) {
  5148. ranges.push([startTime, endTime]);
  5149. }
  5150. this.Cues.newCue(this[channel], startTime, endTime, screen);
  5151. }
  5152. // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
  5153. }, {
  5154. key: 'onInitPtsFound',
  5155. value: function onInitPtsFound(data) {
  5156. var _this2 = this;
  5157. if (typeof this.initPTS === 'undefined') {
  5158. this.initPTS = data.initPTS;
  5159. }
  5160. // Due to asynchrony, initial PTS may arrive later than the first VTT fragments are loaded.
  5161. // Parse any unparsed fragments upon receiving the initial PTS.
  5162. if (this.unparsedVttFrags.length) {
  5163. this.unparsedVttFrags.forEach(function (frag) {
  5164. _this2.onFragLoaded(frag);
  5165. });
  5166. this.unparsedVttFrags = [];
  5167. }
  5168. }
  5169. }, {
  5170. key: 'getExistingTrack',
  5171. value: function getExistingTrack(channelNumber) {
  5172. var media = this.media;
  5173. if (media) {
  5174. for (var i = 0; i < media.textTracks.length; i++) {
  5175. var textTrack = media.textTracks[i];
  5176. var propName = 'textTrack' + channelNumber;
  5177. if (textTrack[propName] === true) {
  5178. return textTrack;
  5179. }
  5180. }
  5181. }
  5182. return null;
  5183. }
  5184. }, {
  5185. key: 'createTextTrack',
  5186. value: function createTextTrack(kind, label, lang) {
  5187. var media = this.media;
  5188. if (media) {
  5189. return media.addTextTrack(kind, label, lang);
  5190. }
  5191. }
  5192. }, {
  5193. key: 'destroy',
  5194. value: function destroy() {
  5195. _eventHandler2.default.prototype.destroy.call(this);
  5196. }
  5197. }, {
  5198. key: 'onMediaAttaching',
  5199. value: function onMediaAttaching(data) {
  5200. this.media = data.media;
  5201. }
  5202. }, {
  5203. key: 'onMediaDetaching',
  5204. value: function onMediaDetaching() {
  5205. clearCurrentCues(this.textTrack1);
  5206. clearCurrentCues(this.textTrack2);
  5207. }
  5208. }, {
  5209. key: 'onManifestLoading',
  5210. value: function onManifestLoading() {
  5211. this.lastSn = -1; // Detect discontiguity in fragment parsing
  5212. this.prevCC = -1;
  5213. this.vttCCs = { ccOffset: 0, presentationOffset: 0 }; // Detect discontinuity in subtitle manifests
  5214. // clear outdated subtitles
  5215. var media = this.media;
  5216. if (media) {
  5217. var textTracks = media.textTracks;
  5218. if (textTracks) {
  5219. for (var i = 0; i < textTracks.length; i++) {
  5220. clearCurrentCues(textTracks[i]);
  5221. }
  5222. }
  5223. }
  5224. }
  5225. }, {
  5226. key: 'onManifestLoaded',
  5227. value: function onManifestLoaded(data) {
  5228. var _this3 = this;
  5229. this.textTracks = [];
  5230. this.unparsedVttFrags = this.unparsedVttFrags || [];
  5231. this.initPTS = undefined;
  5232. this.cueRanges = [];
  5233. if (this.config.enableWebVTT) {
  5234. this.tracks = data.subtitles || [];
  5235. var inUseTracks = this.media ? this.media.textTracks : [];
  5236. this.tracks.forEach(function (track, index) {
  5237. var textTrack = void 0;
  5238. if (index < inUseTracks.length) {
  5239. var inUseTrack = inUseTracks[index];
  5240. // Reuse tracks with the same label, but do not reuse 608/708 tracks
  5241. if (reuseVttTextTrack(inUseTrack, track)) {
  5242. textTrack = inUseTrack;
  5243. }
  5244. }
  5245. if (!textTrack) {
  5246. textTrack = _this3.createTextTrack('subtitles', track.name, track.lang);
  5247. }
  5248. textTrack.mode = track.default ? 'showing' : 'hidden';
  5249. _this3.textTracks.push(textTrack);
  5250. });
  5251. }
  5252. }
  5253. }, {
  5254. key: 'onLevelSwitching',
  5255. value: function onLevelSwitching() {
  5256. this.enabled = this.hls.currentLevel.closedCaptions !== 'NONE';
  5257. }
  5258. }, {
  5259. key: 'onFragLoaded',
  5260. value: function onFragLoaded(data) {
  5261. var frag = data.frag,
  5262. payload = data.payload;
  5263. if (frag.type === 'main') {
  5264. var sn = frag.sn;
  5265. // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
  5266. if (sn !== this.lastSn + 1) {
  5267. this.cea608Parser.reset();
  5268. }
  5269. this.lastSn = sn;
  5270. }
  5271. // If fragment is subtitle type, parse as WebVTT.
  5272. else if (frag.type === 'subtitle') {
  5273. if (payload.byteLength) {
  5274. // We need an initial synchronisation PTS. Store fragments as long as none has arrived.
  5275. if (typeof this.initPTS === 'undefined') {
  5276. this.unparsedVttFrags.push(data);
  5277. return;
  5278. }
  5279. var vttCCs = this.vttCCs;
  5280. if (!vttCCs[frag.cc]) {
  5281. vttCCs[frag.cc] = { start: frag.start, prevCC: this.prevCC, new: true };
  5282. this.prevCC = frag.cc;
  5283. }
  5284. var textTracks = this.textTracks,
  5285. hls = this.hls;
  5286. // Parse the WebVTT file contents.
  5287. _webvttParser2.default.parse(payload, this.initPTS, vttCCs, frag.cc, function (cues) {
  5288. // Add cues and trigger event with success true.
  5289. cues.forEach(function (cue) {
  5290. textTracks[frag.trackId].addCue(cue);
  5291. });
  5292. hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: true, frag: frag });
  5293. }, function (e) {
  5294. // Something went wrong while parsing. Trigger event with success false.
  5295. _logger.logger.log('Failed to parse VTT cue: ' + e);
  5296. hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  5297. });
  5298. } else {
  5299. // In case there is no payload, finish unsuccessfully.
  5300. this.hls.trigger(_events2.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  5301. }
  5302. }
  5303. }
  5304. }, {
  5305. key: 'onFragParsingUserdata',
  5306. value: function onFragParsingUserdata(data) {
  5307. // push all of the CEA-708 messages into the interpreter
  5308. // immediately. It will create the proper timestamps based on our PTS value
  5309. if (this.enabled && this.config.enableCEA708Captions) {
  5310. for (var i = 0; i < data.samples.length; i++) {
  5311. var ccdatas = this.extractCea608Data(data.samples[i].bytes);
  5312. this.cea608Parser.addData(data.samples[i].pts, ccdatas);
  5313. }
  5314. }
  5315. }
  5316. }, {
  5317. key: 'extractCea608Data',
  5318. value: function extractCea608Data(byteArray) {
  5319. var count = byteArray[0] & 31;
  5320. var position = 2;
  5321. var tmpByte, ccbyte1, ccbyte2, ccValid, ccType;
  5322. var actualCCBytes = [];
  5323. for (var j = 0; j < count; j++) {
  5324. tmpByte = byteArray[position++];
  5325. ccbyte1 = 0x7F & byteArray[position++];
  5326. ccbyte2 = 0x7F & byteArray[position++];
  5327. ccValid = (4 & tmpByte) !== 0;
  5328. ccType = 3 & tmpByte;
  5329. if (ccbyte1 === 0 && ccbyte2 === 0) {
  5330. continue;
  5331. }
  5332. if (ccValid) {
  5333. if (ccType === 0) // || ccType === 1
  5334. {
  5335. actualCCBytes.push(ccbyte1);
  5336. actualCCBytes.push(ccbyte2);
  5337. }
  5338. }
  5339. }
  5340. return actualCCBytes;
  5341. }
  5342. }]);
  5343. return TimelineController;
  5344. }(_eventHandler2.default);
  5345. exports.default = TimelineController;
  5346. },{"31":31,"32":32,"46":46,"50":50,"54":54}],16:[function(_dereq_,module,exports){
  5347. 'use strict';
  5348. Object.defineProperty(exports, "__esModule", {
  5349. value: true
  5350. });
  5351. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  5352. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5353. var AESCrypto = function () {
  5354. function AESCrypto(subtle, iv) {
  5355. _classCallCheck(this, AESCrypto);
  5356. this.subtle = subtle;
  5357. this.aesIV = iv;
  5358. }
  5359. _createClass(AESCrypto, [{
  5360. key: 'decrypt',
  5361. value: function decrypt(data, key) {
  5362. return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data);
  5363. }
  5364. }]);
  5365. return AESCrypto;
  5366. }();
  5367. exports.default = AESCrypto;
  5368. },{}],17:[function(_dereq_,module,exports){
  5369. 'use strict';
  5370. Object.defineProperty(exports, "__esModule", {
  5371. value: true
  5372. });
  5373. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  5374. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5375. var AESDecryptor = function () {
  5376. function AESDecryptor() {
  5377. _classCallCheck(this, AESDecryptor);
  5378. // Static after running initTable
  5379. this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  5380. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  5381. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  5382. this.sBox = new Uint32Array(256);
  5383. this.invSBox = new Uint32Array(256);
  5384. // Changes during runtime
  5385. this.key = new Uint32Array(0);
  5386. this.initTable();
  5387. }
  5388. // Using view.getUint32() also swaps the byte order.
  5389. _createClass(AESDecryptor, [{
  5390. key: 'uint8ArrayToUint32Array_',
  5391. value: function uint8ArrayToUint32Array_(arrayBuffer) {
  5392. var view = new DataView(arrayBuffer);
  5393. var newArray = new Uint32Array(4);
  5394. for (var i = 0; i < 4; i++) {
  5395. newArray[i] = view.getUint32(i * 4);
  5396. }
  5397. return newArray;
  5398. }
  5399. }, {
  5400. key: 'initTable',
  5401. value: function initTable() {
  5402. var sBox = this.sBox;
  5403. var invSBox = this.invSBox;
  5404. var subMix = this.subMix;
  5405. var subMix0 = subMix[0];
  5406. var subMix1 = subMix[1];
  5407. var subMix2 = subMix[2];
  5408. var subMix3 = subMix[3];
  5409. var invSubMix = this.invSubMix;
  5410. var invSubMix0 = invSubMix[0];
  5411. var invSubMix1 = invSubMix[1];
  5412. var invSubMix2 = invSubMix[2];
  5413. var invSubMix3 = invSubMix[3];
  5414. var d = new Uint32Array(256);
  5415. var x = 0;
  5416. var xi = 0;
  5417. var i = 0;
  5418. for (i = 0; i < 256; i++) {
  5419. if (i < 128) {
  5420. d[i] = i << 1;
  5421. } else {
  5422. d[i] = i << 1 ^ 0x11b;
  5423. }
  5424. }
  5425. for (i = 0; i < 256; i++) {
  5426. var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  5427. sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
  5428. sBox[x] = sx;
  5429. invSBox[sx] = x;
  5430. // Compute multiplication
  5431. var x2 = d[x];
  5432. var x4 = d[x2];
  5433. var x8 = d[x4];
  5434. // Compute sub/invSub bytes, mix columns tables
  5435. var t = d[sx] * 0x101 ^ sx * 0x1010100;
  5436. subMix0[x] = t << 24 | t >>> 8;
  5437. subMix1[x] = t << 16 | t >>> 16;
  5438. subMix2[x] = t << 8 | t >>> 24;
  5439. subMix3[x] = t;
  5440. // Compute inv sub bytes, inv mix columns tables
  5441. t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  5442. invSubMix0[sx] = t << 24 | t >>> 8;
  5443. invSubMix1[sx] = t << 16 | t >>> 16;
  5444. invSubMix2[sx] = t << 8 | t >>> 24;
  5445. invSubMix3[sx] = t;
  5446. // Compute next counter
  5447. if (!x) {
  5448. x = xi = 1;
  5449. } else {
  5450. x = x2 ^ d[d[d[x8 ^ x2]]];
  5451. xi ^= d[d[xi]];
  5452. }
  5453. }
  5454. }
  5455. }, {
  5456. key: 'expandKey',
  5457. value: function expandKey(keyBuffer) {
  5458. // convert keyBuffer to Uint32Array
  5459. var key = this.uint8ArrayToUint32Array_(keyBuffer);
  5460. var sameKey = true;
  5461. var offset = 0;
  5462. while (offset < key.length && sameKey) {
  5463. sameKey = key[offset] === this.key[offset];
  5464. offset++;
  5465. }
  5466. if (sameKey) {
  5467. return;
  5468. }
  5469. this.key = key;
  5470. var keySize = this.keySize = key.length;
  5471. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  5472. throw new Error('Invalid aes key size=' + keySize);
  5473. }
  5474. var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  5475. var ksRow = void 0;
  5476. var invKsRow = void 0;
  5477. var keySchedule = this.keySchedule = new Uint32Array(ksRows);
  5478. var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  5479. var sbox = this.sBox;
  5480. var rcon = this.rcon;
  5481. var invSubMix = this.invSubMix;
  5482. var invSubMix0 = invSubMix[0];
  5483. var invSubMix1 = invSubMix[1];
  5484. var invSubMix2 = invSubMix[2];
  5485. var invSubMix3 = invSubMix[3];
  5486. var prev = void 0;
  5487. var t = void 0;
  5488. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  5489. if (ksRow < keySize) {
  5490. prev = keySchedule[ksRow] = key[ksRow];
  5491. continue;
  5492. }
  5493. t = prev;
  5494. if (ksRow % keySize === 0) {
  5495. // Rot word
  5496. t = t << 8 | t >>> 24;
  5497. // Sub word
  5498. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  5499. // Mix Rcon
  5500. t ^= rcon[ksRow / keySize | 0] << 24;
  5501. } else if (keySize > 6 && ksRow % keySize === 4) {
  5502. // Sub word
  5503. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  5504. }
  5505. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  5506. }
  5507. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  5508. ksRow = ksRows - invKsRow;
  5509. if (invKsRow & 3) {
  5510. t = keySchedule[ksRow];
  5511. } else {
  5512. t = keySchedule[ksRow - 4];
  5513. }
  5514. if (invKsRow < 4 || ksRow <= 4) {
  5515. invKeySchedule[invKsRow] = t;
  5516. } else {
  5517. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
  5518. }
  5519. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  5520. }
  5521. }
  5522. // Adding this as a method greatly improves performance.
  5523. }, {
  5524. key: 'networkToHostOrderSwap',
  5525. value: function networkToHostOrderSwap(word) {
  5526. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  5527. }
  5528. }, {
  5529. key: 'decrypt',
  5530. value: function decrypt(inputArrayBuffer, offset, aesIV) {
  5531. var nRounds = this.keySize + 6;
  5532. var invKeySchedule = this.invKeySchedule;
  5533. var invSBOX = this.invSBox;
  5534. var invSubMix = this.invSubMix;
  5535. var invSubMix0 = invSubMix[0];
  5536. var invSubMix1 = invSubMix[1];
  5537. var invSubMix2 = invSubMix[2];
  5538. var invSubMix3 = invSubMix[3];
  5539. var initVector = this.uint8ArrayToUint32Array_(aesIV);
  5540. var initVector0 = initVector[0];
  5541. var initVector1 = initVector[1];
  5542. var initVector2 = initVector[2];
  5543. var initVector3 = initVector[3];
  5544. var inputInt32 = new Int32Array(inputArrayBuffer);
  5545. var outputInt32 = new Int32Array(inputInt32.length);
  5546. var t0 = void 0,
  5547. t1 = void 0,
  5548. t2 = void 0,
  5549. t3 = void 0;
  5550. var s0 = void 0,
  5551. s1 = void 0,
  5552. s2 = void 0,
  5553. s3 = void 0;
  5554. var inputWords0 = void 0,
  5555. inputWords1 = void 0,
  5556. inputWords2 = void 0,
  5557. inputWords3 = void 0;
  5558. var ksRow, i;
  5559. var swapWord = this.networkToHostOrderSwap;
  5560. while (offset < inputInt32.length) {
  5561. inputWords0 = swapWord(inputInt32[offset]);
  5562. inputWords1 = swapWord(inputInt32[offset + 1]);
  5563. inputWords2 = swapWord(inputInt32[offset + 2]);
  5564. inputWords3 = swapWord(inputInt32[offset + 3]);
  5565. s0 = inputWords0 ^ invKeySchedule[0];
  5566. s1 = inputWords3 ^ invKeySchedule[1];
  5567. s2 = inputWords2 ^ invKeySchedule[2];
  5568. s3 = inputWords1 ^ invKeySchedule[3];
  5569. ksRow = 4;
  5570. // Iterate through the rounds of decryption
  5571. for (i = 1; i < nRounds; i++) {
  5572. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
  5573. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  5574. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  5575. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  5576. // Update state
  5577. s0 = t0;
  5578. s1 = t1;
  5579. s2 = t2;
  5580. s3 = t3;
  5581. ksRow = ksRow + 4;
  5582. }
  5583. // Shift rows, sub bytes, add round key
  5584. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
  5585. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  5586. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  5587. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  5588. ksRow = ksRow + 3;
  5589. // Write
  5590. outputInt32[offset] = swapWord(t0 ^ initVector0);
  5591. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  5592. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  5593. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  5594. // reset initVector to last 4 unsigned int
  5595. initVector0 = inputWords0;
  5596. initVector1 = inputWords1;
  5597. initVector2 = inputWords2;
  5598. initVector3 = inputWords3;
  5599. offset = offset + 4;
  5600. }
  5601. return outputInt32.buffer;
  5602. }
  5603. }, {
  5604. key: 'destroy',
  5605. value: function destroy() {
  5606. this.key = undefined;
  5607. this.keySize = undefined;
  5608. this.ksRows = undefined;
  5609. this.sBox = undefined;
  5610. this.invSBox = undefined;
  5611. this.subMix = undefined;
  5612. this.invSubMix = undefined;
  5613. this.keySchedule = undefined;
  5614. this.invKeySchedule = undefined;
  5615. this.rcon = undefined;
  5616. }
  5617. }]);
  5618. return AESDecryptor;
  5619. }();
  5620. exports.default = AESDecryptor;
  5621. },{}],18:[function(_dereq_,module,exports){
  5622. 'use strict';
  5623. Object.defineProperty(exports, "__esModule", {
  5624. value: true
  5625. });
  5626. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  5627. var _aesCrypto = _dereq_(16);
  5628. var _aesCrypto2 = _interopRequireDefault(_aesCrypto);
  5629. var _fastAesKey = _dereq_(19);
  5630. var _fastAesKey2 = _interopRequireDefault(_fastAesKey);
  5631. var _aesDecryptor = _dereq_(17);
  5632. var _aesDecryptor2 = _interopRequireDefault(_aesDecryptor);
  5633. var _errors = _dereq_(30);
  5634. var _logger = _dereq_(50);
  5635. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5636. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5637. /*globals self: false */
  5638. var Decrypter = function () {
  5639. function Decrypter(observer, config) {
  5640. _classCallCheck(this, Decrypter);
  5641. this.observer = observer;
  5642. this.config = config;
  5643. this.logEnabled = true;
  5644. try {
  5645. var browserCrypto = crypto ? crypto : self.crypto;
  5646. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  5647. } catch (e) {}
  5648. this.disableWebCrypto = !this.subtle;
  5649. }
  5650. _createClass(Decrypter, [{
  5651. key: 'isSync',
  5652. value: function isSync() {
  5653. return this.disableWebCrypto && this.config.enableSoftwareAES;
  5654. }
  5655. }, {
  5656. key: 'decrypt',
  5657. value: function decrypt(data, key, iv, callback) {
  5658. var _this = this;
  5659. if (this.disableWebCrypto && this.config.enableSoftwareAES) {
  5660. if (this.logEnabled) {
  5661. _logger.logger.log('JS AES decrypt');
  5662. this.logEnabled = false;
  5663. }
  5664. var decryptor = this.decryptor;
  5665. if (!decryptor) {
  5666. this.decryptor = decryptor = new _aesDecryptor2.default();
  5667. }
  5668. decryptor.expandKey(key);
  5669. callback(decryptor.decrypt(data, 0, iv));
  5670. } else {
  5671. if (this.logEnabled) {
  5672. _logger.logger.log('WebCrypto AES decrypt');
  5673. this.logEnabled = false;
  5674. }
  5675. var subtle = this.subtle;
  5676. if (this.key !== key) {
  5677. this.key = key;
  5678. this.fastAesKey = new _fastAesKey2.default(subtle, key);
  5679. }
  5680. this.fastAesKey.expandKey().then(function (aesKey) {
  5681. // decrypt using web crypto
  5682. var crypto = new _aesCrypto2.default(subtle, iv);
  5683. crypto.decrypt(data, aesKey).catch(function (err) {
  5684. _this.onWebCryptoError(err, data, key, iv, callback);
  5685. }).then(function (result) {
  5686. callback(result);
  5687. });
  5688. }).catch(function (err) {
  5689. _this.onWebCryptoError(err, data, key, iv, callback);
  5690. });
  5691. }
  5692. }
  5693. }, {
  5694. key: 'onWebCryptoError',
  5695. value: function onWebCryptoError(err, data, key, iv, callback) {
  5696. if (this.config.enableSoftwareAES) {
  5697. _logger.logger.log('WebCrypto Error, disable WebCrypto API');
  5698. this.disableWebCrypto = true;
  5699. this.logEnabled = true;
  5700. this.decrypt(data, key, iv, callback);
  5701. } else {
  5702. _logger.logger.error('decrypting error : ' + err.message);
  5703. this.observer.trigger(Event.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_DECRYPT_ERROR, fatal: true, reason: err.message });
  5704. }
  5705. }
  5706. }, {
  5707. key: 'destroy',
  5708. value: function destroy() {
  5709. var decryptor = this.decryptor;
  5710. if (decryptor) {
  5711. decryptor.destroy();
  5712. this.decryptor = undefined;
  5713. }
  5714. }
  5715. }]);
  5716. return Decrypter;
  5717. }();
  5718. exports.default = Decrypter;
  5719. },{"16":16,"17":17,"19":19,"30":30,"50":50}],19:[function(_dereq_,module,exports){
  5720. 'use strict';
  5721. Object.defineProperty(exports, "__esModule", {
  5722. value: true
  5723. });
  5724. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  5725. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5726. var FastAESKey = function () {
  5727. function FastAESKey(subtle, key) {
  5728. _classCallCheck(this, FastAESKey);
  5729. this.subtle = subtle;
  5730. this.key = key;
  5731. }
  5732. _createClass(FastAESKey, [{
  5733. key: 'expandKey',
  5734. value: function expandKey() {
  5735. return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']);
  5736. }
  5737. }]);
  5738. return FastAESKey;
  5739. }();
  5740. exports.default = FastAESKey;
  5741. },{}],20:[function(_dereq_,module,exports){
  5742. 'use strict';
  5743. Object.defineProperty(exports, "__esModule", {
  5744. value: true
  5745. });
  5746. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  5747. * AAC demuxer
  5748. */
  5749. var _adts = _dereq_(21);
  5750. var _adts2 = _interopRequireDefault(_adts);
  5751. var _logger = _dereq_(50);
  5752. var _id = _dereq_(26);
  5753. var _id2 = _interopRequireDefault(_id);
  5754. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5755. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5756. var AACDemuxer = function () {
  5757. function AACDemuxer(observer, remuxer, config) {
  5758. _classCallCheck(this, AACDemuxer);
  5759. this.observer = observer;
  5760. this.config = config;
  5761. this.remuxer = remuxer;
  5762. }
  5763. _createClass(AACDemuxer, [{
  5764. key: 'resetInitSegment',
  5765. value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  5766. this._aacTrack = { container: 'audio/adts', type: 'audio', id: -1, sequenceNumber: 0, isAAC: true, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };
  5767. }
  5768. }, {
  5769. key: 'resetTimeStamp',
  5770. value: function resetTimeStamp() {}
  5771. }, {
  5772. key: 'append',
  5773. // feed incoming data to the front of the parsing pipeline
  5774. value: function append(data, timeOffset, contiguous, accurateTimeOffset) {
  5775. var track,
  5776. id3 = new _id2.default(data),
  5777. pts = 90 * id3.timeStamp,
  5778. config,
  5779. frameLength,
  5780. frameDuration,
  5781. frameIndex,
  5782. offset,
  5783. headerLength,
  5784. stamp,
  5785. len,
  5786. aacSample;
  5787. track = this._aacTrack;
  5788. // look for ADTS header (0xFFFx)
  5789. for (offset = id3.length, len = data.length; offset < len - 1; offset++) {
  5790. if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
  5791. break;
  5792. }
  5793. }
  5794. if (!track.samplerate) {
  5795. config = _adts2.default.getAudioConfig(this.observer, data, offset, track.manifestCodec);
  5796. track.config = config.config;
  5797. track.samplerate = config.samplerate;
  5798. track.channelCount = config.channelCount;
  5799. track.codec = config.codec;
  5800. _logger.logger.log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount);
  5801. }
  5802. frameIndex = 0;
  5803. frameDuration = 1024 * 90000 / track.samplerate;
  5804. while (offset + 5 < len) {
  5805. // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  5806. headerLength = !!(data[offset + 1] & 0x01) ? 7 : 9;
  5807. // retrieve frame size
  5808. frameLength = (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;
  5809. frameLength -= headerLength;
  5810. //stamp = pes.pts;
  5811. if (frameLength > 0 && offset + headerLength + frameLength <= len) {
  5812. stamp = pts + frameIndex * frameDuration;
  5813. //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
  5814. aacSample = { unit: data.subarray(offset + headerLength, offset + headerLength + frameLength), pts: stamp, dts: stamp };
  5815. track.samples.push(aacSample);
  5816. track.len += frameLength;
  5817. offset += frameLength + headerLength;
  5818. frameIndex++;
  5819. // look for ADTS header (0xFFFx)
  5820. for (; offset < len - 1; offset++) {
  5821. if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
  5822. break;
  5823. }
  5824. }
  5825. } else {
  5826. break;
  5827. }
  5828. }
  5829. this.remuxer.remux(track, { samples: [] }, { samples: [{ pts: pts, dts: pts, unit: id3.payload }] }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset);
  5830. }
  5831. }, {
  5832. key: 'destroy',
  5833. value: function destroy() {}
  5834. }], [{
  5835. key: 'probe',
  5836. value: function probe(data) {
  5837. // check if data contains ID3 timestamp and ADTS sync worc
  5838. var id3 = new _id2.default(data),
  5839. offset,
  5840. len;
  5841. if (id3.hasTimeStamp) {
  5842. // look for ADTS header (0xFFFx)
  5843. for (offset = id3.length, len = data.length; offset < len - 1; offset++) {
  5844. if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
  5845. //logger.log('ADTS sync word found !');
  5846. return true;
  5847. }
  5848. }
  5849. }
  5850. return false;
  5851. }
  5852. }]);
  5853. return AACDemuxer;
  5854. }();
  5855. exports.default = AACDemuxer;
  5856. },{"21":21,"26":26,"50":50}],21:[function(_dereq_,module,exports){
  5857. 'use strict';
  5858. var _logger = _dereq_(50);
  5859. var _errors = _dereq_(30);
  5860. /**
  5861. * ADTS parser helper
  5862. */
  5863. var ADTS = {
  5864. getAudioConfig: function getAudioConfig(observer, data, offset, audioCodec) {
  5865. var adtsObjectType,
  5866. // :int
  5867. adtsSampleingIndex,
  5868. // :int
  5869. adtsExtensionSampleingIndex,
  5870. // :int
  5871. adtsChanelConfig,
  5872. // :int
  5873. config,
  5874. userAgent = navigator.userAgent.toLowerCase(),
  5875. manifestCodec = audioCodec,
  5876. adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  5877. // byte 2
  5878. adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1;
  5879. adtsSampleingIndex = (data[offset + 2] & 0x3C) >>> 2;
  5880. if (adtsSampleingIndex > adtsSampleingRates.length - 1) {
  5881. observer.trigger(Event.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'invalid ADTS sampling index:' + adtsSampleingIndex });
  5882. return;
  5883. }
  5884. adtsChanelConfig = (data[offset + 2] & 0x01) << 2;
  5885. // byte 3
  5886. adtsChanelConfig |= (data[offset + 3] & 0xC0) >>> 6;
  5887. _logger.logger.log('manifest codec:' + audioCodec + ',ADTS data:type:' + adtsObjectType + ',sampleingIndex:' + adtsSampleingIndex + '[' + adtsSampleingRates[adtsSampleingIndex] + 'Hz],channelConfig:' + adtsChanelConfig);
  5888. // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
  5889. if (/firefox/i.test(userAgent)) {
  5890. if (adtsSampleingIndex >= 6) {
  5891. adtsObjectType = 5;
  5892. config = new Array(4);
  5893. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  5894. // there is a factor 2 between frame sample rate and output sample rate
  5895. // multiply frequency by 2 (see table below, equivalent to substract 3)
  5896. adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
  5897. } else {
  5898. adtsObjectType = 2;
  5899. config = new Array(2);
  5900. adtsExtensionSampleingIndex = adtsSampleingIndex;
  5901. }
  5902. // Android : always use AAC
  5903. } else if (userAgent.indexOf('android') !== -1) {
  5904. adtsObjectType = 2;
  5905. config = new Array(2);
  5906. adtsExtensionSampleingIndex = adtsSampleingIndex;
  5907. } else {
  5908. /* for other browsers (Chrome/Vivaldi/Opera ...)
  5909. always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
  5910. */
  5911. adtsObjectType = 5;
  5912. config = new Array(4);
  5913. // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
  5914. if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSampleingIndex >= 6) {
  5915. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  5916. // there is a factor 2 between frame sample rate and output sample rate
  5917. // multiply frequency by 2 (see table below, equivalent to substract 3)
  5918. adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
  5919. } else {
  5920. // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
  5921. // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
  5922. if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && adtsSampleingIndex >= 6 && adtsChanelConfig === 1 || !audioCodec && adtsChanelConfig === 1) {
  5923. adtsObjectType = 2;
  5924. config = new Array(2);
  5925. }
  5926. adtsExtensionSampleingIndex = adtsSampleingIndex;
  5927. }
  5928. }
  5929. /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  5930. ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
  5931. Audio Profile / Audio Object Type
  5932. 0: Null
  5933. 1: AAC Main
  5934. 2: AAC LC (Low Complexity)
  5935. 3: AAC SSR (Scalable Sample Rate)
  5936. 4: AAC LTP (Long Term Prediction)
  5937. 5: SBR (Spectral Band Replication)
  5938. 6: AAC Scalable
  5939. sampling freq
  5940. 0: 96000 Hz
  5941. 1: 88200 Hz
  5942. 2: 64000 Hz
  5943. 3: 48000 Hz
  5944. 4: 44100 Hz
  5945. 5: 32000 Hz
  5946. 6: 24000 Hz
  5947. 7: 22050 Hz
  5948. 8: 16000 Hz
  5949. 9: 12000 Hz
  5950. 10: 11025 Hz
  5951. 11: 8000 Hz
  5952. 12: 7350 Hz
  5953. 13: Reserved
  5954. 14: Reserved
  5955. 15: frequency is written explictly
  5956. Channel Configurations
  5957. These are the channel configurations:
  5958. 0: Defined in AOT Specifc Config
  5959. 1: 1 channel: front-center
  5960. 2: 2 channels: front-left, front-right
  5961. */
  5962. // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  5963. config[0] = adtsObjectType << 3;
  5964. // samplingFrequencyIndex
  5965. config[0] |= (adtsSampleingIndex & 0x0E) >> 1;
  5966. config[1] |= (adtsSampleingIndex & 0x01) << 7;
  5967. // channelConfiguration
  5968. config[1] |= adtsChanelConfig << 3;
  5969. if (adtsObjectType === 5) {
  5970. // adtsExtensionSampleingIndex
  5971. config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1;
  5972. config[2] = (adtsExtensionSampleingIndex & 0x01) << 7;
  5973. // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
  5974. // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
  5975. config[2] |= 2 << 2;
  5976. config[3] = 0;
  5977. }
  5978. return { config: config, samplerate: adtsSampleingRates[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: 'mp4a.40.' + adtsObjectType, manifestCodec: manifestCodec };
  5979. }
  5980. };
  5981. module.exports = ADTS;
  5982. },{"30":30,"50":50}],22:[function(_dereq_,module,exports){
  5983. 'use strict';
  5984. Object.defineProperty(exports, "__esModule", {
  5985. value: true
  5986. });
  5987. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; 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.
  5988. * probe fragments and instantiate appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)
  5989. */
  5990. var _events = _dereq_(32);
  5991. var _events2 = _interopRequireDefault(_events);
  5992. var _errors = _dereq_(30);
  5993. var _decrypter = _dereq_(18);
  5994. var _decrypter2 = _interopRequireDefault(_decrypter);
  5995. var _aacdemuxer = _dereq_(20);
  5996. var _aacdemuxer2 = _interopRequireDefault(_aacdemuxer);
  5997. var _mp4demuxer = _dereq_(27);
  5998. var _mp4demuxer2 = _interopRequireDefault(_mp4demuxer);
  5999. var _tsdemuxer = _dereq_(29);
  6000. var _tsdemuxer2 = _interopRequireDefault(_tsdemuxer);
  6001. var _mp4Remuxer = _dereq_(42);
  6002. var _mp4Remuxer2 = _interopRequireDefault(_mp4Remuxer);
  6003. var _passthroughRemuxer = _dereq_(43);
  6004. var _passthroughRemuxer2 = _interopRequireDefault(_passthroughRemuxer);
  6005. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6006. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6007. var DemuxerInline = function () {
  6008. function DemuxerInline(observer, typeSupported, config, vendor) {
  6009. _classCallCheck(this, DemuxerInline);
  6010. this.observer = observer;
  6011. this.typeSupported = typeSupported;
  6012. this.config = config;
  6013. this.vendor = vendor;
  6014. }
  6015. _createClass(DemuxerInline, [{
  6016. key: 'destroy',
  6017. value: function destroy() {
  6018. var demuxer = this.demuxer;
  6019. if (demuxer) {
  6020. demuxer.destroy();
  6021. }
  6022. }
  6023. }, {
  6024. key: 'push',
  6025. value: function push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
  6026. if (data.byteLength > 0 && decryptdata != null && decryptdata.key != null && decryptdata.method === 'AES-128') {
  6027. var decrypter = this.decrypter;
  6028. if (decrypter == null) {
  6029. decrypter = this.decrypter = new _decrypter2.default(this.observer, this.config);
  6030. }
  6031. var localthis = this;
  6032. // performance.now() not available on WebWorker, at least on Safari Desktop
  6033. var startTime;
  6034. try {
  6035. startTime = performance.now();
  6036. } catch (error) {
  6037. startTime = Date.now();
  6038. }
  6039. decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) {
  6040. var endTime;
  6041. try {
  6042. endTime = performance.now();
  6043. } catch (error) {
  6044. endTime = Date.now();
  6045. }
  6046. localthis.observer.trigger(_events2.default.FRAG_DECRYPTED, { stats: { tstart: startTime, tdecrypt: endTime } });
  6047. localthis.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  6048. });
  6049. } else {
  6050. this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  6051. }
  6052. }
  6053. }, {
  6054. key: 'pushDecrypted',
  6055. value: function pushDecrypted(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
  6056. var demuxer = this.demuxer;
  6057. if (!demuxer ||
  6058. // in case of continuity change, we might switch from content type (AAC container to TS container for example)
  6059. // so let's check that current demuxer is still valid
  6060. discontinuity && !this.probe(data)) {
  6061. var observer = this.observer;
  6062. var typeSupported = this.typeSupported;
  6063. var config = this.config;
  6064. var muxConfig = [{ demux: _tsdemuxer2.default, remux: _mp4Remuxer2.default }, { demux: _aacdemuxer2.default, remux: _mp4Remuxer2.default }, { demux: _mp4demuxer2.default, remux: _passthroughRemuxer2.default }];
  6065. // probe for content type
  6066. for (var i in muxConfig) {
  6067. var mux = muxConfig[i];
  6068. var probe = mux.demux.probe;
  6069. if (probe(data)) {
  6070. var _remuxer = this.remuxer = new mux.remux(observer, config, typeSupported, this.vendor);
  6071. demuxer = new mux.demux(observer, _remuxer, config, typeSupported);
  6072. this.probe = probe;
  6073. break;
  6074. }
  6075. }
  6076. if (!demuxer) {
  6077. 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' });
  6078. return;
  6079. }
  6080. this.demuxer = demuxer;
  6081. }
  6082. var remuxer = this.remuxer;
  6083. if (discontinuity || trackSwitch) {
  6084. demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration);
  6085. remuxer.resetInitSegment();
  6086. }
  6087. if (discontinuity) {
  6088. demuxer.resetTimeStamp();
  6089. remuxer.resetTimeStamp(defaultInitPTS);
  6090. }
  6091. if (typeof demuxer.setDecryptData === 'function') {
  6092. demuxer.setDecryptData(decryptdata);
  6093. }
  6094. demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);
  6095. }
  6096. }]);
  6097. return DemuxerInline;
  6098. }();
  6099. exports.default = DemuxerInline;
  6100. },{"18":18,"20":20,"27":27,"29":29,"30":30,"32":32,"42":42,"43":43}],23:[function(_dereq_,module,exports){
  6101. 'use strict';
  6102. Object.defineProperty(exports, "__esModule", {
  6103. value: true
  6104. });
  6105. var _demuxerInline = _dereq_(22);
  6106. var _demuxerInline2 = _interopRequireDefault(_demuxerInline);
  6107. var _events = _dereq_(32);
  6108. var _events2 = _interopRequireDefault(_events);
  6109. var _logger = _dereq_(50);
  6110. var _events3 = _dereq_(1);
  6111. var _events4 = _interopRequireDefault(_events3);
  6112. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6113. /* demuxer web worker.
  6114. * - listen to worker message, and trigger DemuxerInline upon reception of Fragments.
  6115. * - 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.
  6116. */
  6117. var DemuxerWorker = function DemuxerWorker(self) {
  6118. // observer setup
  6119. var observer = new _events4.default();
  6120. observer.trigger = function trigger(event) {
  6121. for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  6122. data[_key - 1] = arguments[_key];
  6123. }
  6124. observer.emit.apply(observer, [event, event].concat(data));
  6125. };
  6126. observer.off = function off(event) {
  6127. for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  6128. data[_key2 - 1] = arguments[_key2];
  6129. }
  6130. observer.removeListener.apply(observer, [event].concat(data));
  6131. };
  6132. var forwardMessage = function forwardMessage(ev, data) {
  6133. self.postMessage({ event: ev, data: data });
  6134. };
  6135. self.addEventListener('message', function (ev) {
  6136. var data = ev.data;
  6137. //console.log('demuxer cmd:' + data.cmd);
  6138. switch (data.cmd) {
  6139. case 'init':
  6140. var config = JSON.parse(data.config);
  6141. self.demuxer = new _demuxerInline2.default(observer, data.typeSupported, config, data.vendor);
  6142. try {
  6143. (0, _logger.enableLogs)(config.debug === true);
  6144. } catch (err) {
  6145. console.warn('demuxerWorker: unable to enable logs');
  6146. }
  6147. // signal end of worker init
  6148. forwardMessage('init', null);
  6149. break;
  6150. case 'demux':
  6151. 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);
  6152. break;
  6153. default:
  6154. break;
  6155. }
  6156. });
  6157. // forward events to main thread
  6158. observer.on(_events2.default.FRAG_DECRYPTED, forwardMessage);
  6159. observer.on(_events2.default.FRAG_PARSING_INIT_SEGMENT, forwardMessage);
  6160. observer.on(_events2.default.FRAG_PARSED, forwardMessage);
  6161. observer.on(_events2.default.ERROR, forwardMessage);
  6162. observer.on(_events2.default.FRAG_PARSING_METADATA, forwardMessage);
  6163. observer.on(_events2.default.FRAG_PARSING_USERDATA, forwardMessage);
  6164. observer.on(_events2.default.INIT_PTS_FOUND, forwardMessage);
  6165. // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy)
  6166. observer.on(_events2.default.FRAG_PARSING_DATA, function (ev, data) {
  6167. var transferable = [];
  6168. var message = { event: ev, data: data };
  6169. if (data.data1) {
  6170. message.data1 = data.data1.buffer;
  6171. transferable.push(data.data1.buffer);
  6172. delete data.data1;
  6173. }
  6174. if (data.data2) {
  6175. message.data2 = data.data2.buffer;
  6176. transferable.push(data.data2.buffer);
  6177. delete data.data2;
  6178. }
  6179. self.postMessage(message, transferable);
  6180. });
  6181. };
  6182. exports.default = DemuxerWorker;
  6183. },{"1":1,"22":22,"32":32,"50":50}],24:[function(_dereq_,module,exports){
  6184. 'use strict';
  6185. Object.defineProperty(exports, "__esModule", {
  6186. value: true
  6187. });
  6188. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  6189. var _events = _dereq_(32);
  6190. var _events2 = _interopRequireDefault(_events);
  6191. var _demuxerInline = _dereq_(22);
  6192. var _demuxerInline2 = _interopRequireDefault(_demuxerInline);
  6193. var _demuxerWorker = _dereq_(23);
  6194. var _demuxerWorker2 = _interopRequireDefault(_demuxerWorker);
  6195. var _logger = _dereq_(50);
  6196. var _errors = _dereq_(30);
  6197. var _events3 = _dereq_(1);
  6198. var _events4 = _interopRequireDefault(_events3);
  6199. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6200. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6201. var Demuxer = function () {
  6202. function Demuxer(hls, id) {
  6203. _classCallCheck(this, Demuxer);
  6204. this.hls = hls;
  6205. this.id = id;
  6206. // observer setup
  6207. var observer = this.observer = new _events4.default();
  6208. var config = hls.config;
  6209. observer.trigger = function trigger(event) {
  6210. for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  6211. data[_key - 1] = arguments[_key];
  6212. }
  6213. observer.emit.apply(observer, [event, event].concat(data));
  6214. };
  6215. observer.off = function off(event) {
  6216. for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  6217. data[_key2 - 1] = arguments[_key2];
  6218. }
  6219. observer.removeListener.apply(observer, [event].concat(data));
  6220. };
  6221. var forwardMessage = function (ev, data) {
  6222. data = data || {};
  6223. data.frag = this.frag;
  6224. data.id = this.id;
  6225. hls.trigger(ev, data);
  6226. }.bind(this);
  6227. // forward events to main thread
  6228. observer.on(_events2.default.FRAG_DECRYPTED, forwardMessage);
  6229. observer.on(_events2.default.FRAG_PARSING_INIT_SEGMENT, forwardMessage);
  6230. observer.on(_events2.default.FRAG_PARSING_DATA, forwardMessage);
  6231. observer.on(_events2.default.FRAG_PARSED, forwardMessage);
  6232. observer.on(_events2.default.ERROR, forwardMessage);
  6233. observer.on(_events2.default.FRAG_PARSING_METADATA, forwardMessage);
  6234. observer.on(_events2.default.FRAG_PARSING_USERDATA, forwardMessage);
  6235. observer.on(_events2.default.INIT_PTS_FOUND, forwardMessage);
  6236. var typeSupported = {
  6237. mp4: MediaSource.isTypeSupported('video/mp4'),
  6238. mpeg: MediaSource.isTypeSupported('audio/mpeg'),
  6239. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"')
  6240. };
  6241. // navigator.vendor is not always available in Web Worker
  6242. // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator
  6243. var vendor = navigator.vendor;
  6244. if (config.enableWorker && typeof Worker !== 'undefined') {
  6245. _logger.logger.log('demuxing in webworker');
  6246. var w = void 0;
  6247. try {
  6248. var work = _dereq_(3);
  6249. w = this.w = work(_demuxerWorker2.default);
  6250. this.onwmsg = this.onWorkerMessage.bind(this);
  6251. w.addEventListener('message', this.onwmsg);
  6252. w.onerror = function (event) {
  6253. hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.INTERNAL_EXCEPTION, fatal: true, event: 'demuxerWorker', err: { message: event.message + ' (' + event.filename + ':' + event.lineno + ')' } });
  6254. };
  6255. w.postMessage({ cmd: 'init', typeSupported: typeSupported, vendor: vendor, id: id, config: JSON.stringify(config) });
  6256. } catch (err) {
  6257. _logger.logger.error('error while initializing DemuxerWorker, fallback on DemuxerInline');
  6258. if (w) {
  6259. // revoke the Object URL that was used to create demuxer worker, so as not to leak it
  6260. URL.revokeObjectURL(w.objectURL);
  6261. }
  6262. this.demuxer = new _demuxerInline2.default(observer, typeSupported, config, vendor);
  6263. this.w = undefined;
  6264. }
  6265. } else {
  6266. this.demuxer = new _demuxerInline2.default(observer, typeSupported, config, vendor);
  6267. }
  6268. }
  6269. _createClass(Demuxer, [{
  6270. key: 'destroy',
  6271. value: function destroy() {
  6272. var w = this.w;
  6273. if (w) {
  6274. w.removeEventListener('message', this.onwmsg);
  6275. w.terminate();
  6276. this.w = null;
  6277. } else {
  6278. var demuxer = this.demuxer;
  6279. if (demuxer) {
  6280. demuxer.destroy();
  6281. this.demuxer = null;
  6282. }
  6283. }
  6284. var observer = this.observer;
  6285. if (observer) {
  6286. observer.removeAllListeners();
  6287. this.observer = null;
  6288. }
  6289. }
  6290. }, {
  6291. key: 'push',
  6292. value: function push(data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) {
  6293. var w = this.w;
  6294. var timeOffset = !isNaN(frag.startDTS) ? frag.startDTS : frag.start;
  6295. var decryptdata = frag.decryptdata;
  6296. var lastFrag = this.frag;
  6297. var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  6298. var trackSwitch = !(lastFrag && frag.level === lastFrag.level);
  6299. var nextSN = lastFrag && frag.sn === lastFrag.sn + 1;
  6300. var contiguous = !trackSwitch && nextSN;
  6301. if (discontinuity) {
  6302. _logger.logger.log(this.id + ':discontinuity detected');
  6303. }
  6304. if (trackSwitch) {
  6305. _logger.logger.log(this.id + ':switch detected');
  6306. }
  6307. this.frag = frag;
  6308. if (w) {
  6309. // post fragment payload as transferable objects (no copy)
  6310. 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]);
  6311. } else {
  6312. var demuxer = this.demuxer;
  6313. if (demuxer) {
  6314. demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  6315. }
  6316. }
  6317. }
  6318. }, {
  6319. key: 'onWorkerMessage',
  6320. value: function onWorkerMessage(ev) {
  6321. var data = ev.data,
  6322. hls = this.hls;
  6323. //console.log('onWorkerMessage:' + data.event);
  6324. switch (data.event) {
  6325. case 'init':
  6326. // revoke the Object URL that was used to create demuxer worker, so as not to leak it
  6327. URL.revokeObjectURL(this.w.objectURL);
  6328. break;
  6329. // special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects
  6330. case _events2.default.FRAG_PARSING_DATA:
  6331. data.data.data1 = new Uint8Array(data.data1);
  6332. if (data.data2) {
  6333. data.data.data2 = new Uint8Array(data.data2);
  6334. }
  6335. /* falls through */
  6336. default:
  6337. data.data = data.data || {};
  6338. data.data.frag = this.frag;
  6339. data.data.id = this.id;
  6340. hls.trigger(data.event, data.data);
  6341. break;
  6342. }
  6343. }
  6344. }]);
  6345. return Demuxer;
  6346. }();
  6347. exports.default = Demuxer;
  6348. },{"1":1,"22":22,"23":23,"3":3,"30":30,"32":32,"50":50}],25:[function(_dereq_,module,exports){
  6349. 'use strict';
  6350. Object.defineProperty(exports, "__esModule", {
  6351. value: true
  6352. });
  6353. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  6354. * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
  6355. */
  6356. var _logger = _dereq_(50);
  6357. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6358. var ExpGolomb = function () {
  6359. function ExpGolomb(data) {
  6360. _classCallCheck(this, ExpGolomb);
  6361. this.data = data;
  6362. // the number of bytes left to examine in this.data
  6363. this.bytesAvailable = data.byteLength;
  6364. // the current word being examined
  6365. this.word = 0; // :uint
  6366. // the number of bits left to examine in the current word
  6367. this.bitsAvailable = 0; // :uint
  6368. }
  6369. // ():void
  6370. _createClass(ExpGolomb, [{
  6371. key: 'loadWord',
  6372. value: function loadWord() {
  6373. var data = this.data,
  6374. bytesAvailable = this.bytesAvailable,
  6375. position = data.byteLength - bytesAvailable,
  6376. workingBytes = new Uint8Array(4),
  6377. availableBytes = Math.min(4, bytesAvailable);
  6378. if (availableBytes === 0) {
  6379. throw new Error('no bytes available');
  6380. }
  6381. workingBytes.set(data.subarray(position, position + availableBytes));
  6382. this.word = new DataView(workingBytes.buffer).getUint32(0);
  6383. // track the amount of this.data that has been processed
  6384. this.bitsAvailable = availableBytes * 8;
  6385. this.bytesAvailable -= availableBytes;
  6386. }
  6387. // (count:int):void
  6388. }, {
  6389. key: 'skipBits',
  6390. value: function skipBits(count) {
  6391. var skipBytes; // :int
  6392. if (this.bitsAvailable > count) {
  6393. this.word <<= count;
  6394. this.bitsAvailable -= count;
  6395. } else {
  6396. count -= this.bitsAvailable;
  6397. skipBytes = count >> 3;
  6398. count -= skipBytes >> 3;
  6399. this.bytesAvailable -= skipBytes;
  6400. this.loadWord();
  6401. this.word <<= count;
  6402. this.bitsAvailable -= count;
  6403. }
  6404. }
  6405. // (size:int):uint
  6406. }, {
  6407. key: 'readBits',
  6408. value: function readBits(size) {
  6409. var bits = Math.min(this.bitsAvailable, size),
  6410. // :uint
  6411. valu = this.word >>> 32 - bits; // :uint
  6412. if (size > 32) {
  6413. _logger.logger.error('Cannot read more than 32 bits at a time');
  6414. }
  6415. this.bitsAvailable -= bits;
  6416. if (this.bitsAvailable > 0) {
  6417. this.word <<= bits;
  6418. } else if (this.bytesAvailable > 0) {
  6419. this.loadWord();
  6420. }
  6421. bits = size - bits;
  6422. if (bits > 0 && this.bitsAvailable) {
  6423. return valu << bits | this.readBits(bits);
  6424. } else {
  6425. return valu;
  6426. }
  6427. }
  6428. // ():uint
  6429. }, {
  6430. key: 'skipLZ',
  6431. value: function skipLZ() {
  6432. var leadingZeroCount; // :uint
  6433. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  6434. if (0 !== (this.word & 0x80000000 >>> leadingZeroCount)) {
  6435. // the first bit of working word is 1
  6436. this.word <<= leadingZeroCount;
  6437. this.bitsAvailable -= leadingZeroCount;
  6438. return leadingZeroCount;
  6439. }
  6440. }
  6441. // we exhausted word and still have not found a 1
  6442. this.loadWord();
  6443. return leadingZeroCount + this.skipLZ();
  6444. }
  6445. // ():void
  6446. }, {
  6447. key: 'skipUEG',
  6448. value: function skipUEG() {
  6449. this.skipBits(1 + this.skipLZ());
  6450. }
  6451. // ():void
  6452. }, {
  6453. key: 'skipEG',
  6454. value: function skipEG() {
  6455. this.skipBits(1 + this.skipLZ());
  6456. }
  6457. // ():uint
  6458. }, {
  6459. key: 'readUEG',
  6460. value: function readUEG() {
  6461. var clz = this.skipLZ(); // :uint
  6462. return this.readBits(clz + 1) - 1;
  6463. }
  6464. // ():int
  6465. }, {
  6466. key: 'readEG',
  6467. value: function readEG() {
  6468. var valu = this.readUEG(); // :int
  6469. if (0x01 & valu) {
  6470. // the number is odd if the low order bit is set
  6471. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  6472. } else {
  6473. return -1 * (valu >>> 1); // divide by two then make it negative
  6474. }
  6475. }
  6476. // Some convenience functions
  6477. // :Boolean
  6478. }, {
  6479. key: 'readBoolean',
  6480. value: function readBoolean() {
  6481. return 1 === this.readBits(1);
  6482. }
  6483. // ():int
  6484. }, {
  6485. key: 'readUByte',
  6486. value: function readUByte() {
  6487. return this.readBits(8);
  6488. }
  6489. // ():int
  6490. }, {
  6491. key: 'readUShort',
  6492. value: function readUShort() {
  6493. return this.readBits(16);
  6494. }
  6495. // ():int
  6496. }, {
  6497. key: 'readUInt',
  6498. value: function readUInt() {
  6499. return this.readBits(32);
  6500. }
  6501. /**
  6502. * Advance the ExpGolomb decoder past a scaling list. The scaling
  6503. * list is optionally transmitted as part of a sequence parameter
  6504. * set and is not relevant to transmuxing.
  6505. * @param count {number} the number of entries in this scaling list
  6506. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  6507. */
  6508. }, {
  6509. key: 'skipScalingList',
  6510. value: function skipScalingList(count) {
  6511. var lastScale = 8,
  6512. nextScale = 8,
  6513. j,
  6514. deltaScale;
  6515. for (j = 0; j < count; j++) {
  6516. if (nextScale !== 0) {
  6517. deltaScale = this.readEG();
  6518. nextScale = (lastScale + deltaScale + 256) % 256;
  6519. }
  6520. lastScale = nextScale === 0 ? lastScale : nextScale;
  6521. }
  6522. }
  6523. /**
  6524. * Read a sequence parameter set and return some interesting video
  6525. * properties. A sequence parameter set is the H264 metadata that
  6526. * describes the properties of upcoming video frames.
  6527. * @param data {Uint8Array} the bytes of a sequence parameter set
  6528. * @return {object} an object with configuration parsed from the
  6529. * sequence parameter set, including the dimensions of the
  6530. * associated video frames.
  6531. */
  6532. }, {
  6533. key: 'readSPS',
  6534. value: function readSPS() {
  6535. var frameCropLeftOffset = 0,
  6536. frameCropRightOffset = 0,
  6537. frameCropTopOffset = 0,
  6538. frameCropBottomOffset = 0,
  6539. profileIdc,
  6540. profileCompat,
  6541. levelIdc,
  6542. numRefFramesInPicOrderCntCycle,
  6543. picWidthInMbsMinus1,
  6544. picHeightInMapUnitsMinus1,
  6545. frameMbsOnlyFlag,
  6546. scalingListCount,
  6547. i,
  6548. readUByte = this.readUByte.bind(this),
  6549. readBits = this.readBits.bind(this),
  6550. readUEG = this.readUEG.bind(this),
  6551. readBoolean = this.readBoolean.bind(this),
  6552. skipBits = this.skipBits.bind(this),
  6553. skipEG = this.skipEG.bind(this),
  6554. skipUEG = this.skipUEG.bind(this),
  6555. skipScalingList = this.skipScalingList.bind(this);
  6556. readUByte();
  6557. profileIdc = readUByte(); // profile_idc
  6558. profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5)
  6559. skipBits(3); // reserved_zero_3bits u(3),
  6560. levelIdc = readUByte(); //level_idc u(8)
  6561. skipUEG(); // seq_parameter_set_id
  6562. // some profiles have more optional data we don't need
  6563. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  6564. var chromaFormatIdc = readUEG();
  6565. if (chromaFormatIdc === 3) {
  6566. skipBits(1); // separate_colour_plane_flag
  6567. }
  6568. skipUEG(); // bit_depth_luma_minus8
  6569. skipUEG(); // bit_depth_chroma_minus8
  6570. skipBits(1); // qpprime_y_zero_transform_bypass_flag
  6571. if (readBoolean()) {
  6572. // seq_scaling_matrix_present_flag
  6573. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  6574. for (i = 0; i < scalingListCount; i++) {
  6575. if (readBoolean()) {
  6576. // seq_scaling_list_present_flag[ i ]
  6577. if (i < 6) {
  6578. skipScalingList(16);
  6579. } else {
  6580. skipScalingList(64);
  6581. }
  6582. }
  6583. }
  6584. }
  6585. }
  6586. skipUEG(); // log2_max_frame_num_minus4
  6587. var picOrderCntType = readUEG();
  6588. if (picOrderCntType === 0) {
  6589. readUEG(); //log2_max_pic_order_cnt_lsb_minus4
  6590. } else if (picOrderCntType === 1) {
  6591. skipBits(1); // delta_pic_order_always_zero_flag
  6592. skipEG(); // offset_for_non_ref_pic
  6593. skipEG(); // offset_for_top_to_bottom_field
  6594. numRefFramesInPicOrderCntCycle = readUEG();
  6595. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  6596. skipEG(); // offset_for_ref_frame[ i ]
  6597. }
  6598. }
  6599. skipUEG(); // max_num_ref_frames
  6600. skipBits(1); // gaps_in_frame_num_value_allowed_flag
  6601. picWidthInMbsMinus1 = readUEG();
  6602. picHeightInMapUnitsMinus1 = readUEG();
  6603. frameMbsOnlyFlag = readBits(1);
  6604. if (frameMbsOnlyFlag === 0) {
  6605. skipBits(1); // mb_adaptive_frame_field_flag
  6606. }
  6607. skipBits(1); // direct_8x8_inference_flag
  6608. if (readBoolean()) {
  6609. // frame_cropping_flag
  6610. frameCropLeftOffset = readUEG();
  6611. frameCropRightOffset = readUEG();
  6612. frameCropTopOffset = readUEG();
  6613. frameCropBottomOffset = readUEG();
  6614. }
  6615. var pixelRatio = [1, 1];
  6616. if (readBoolean()) {
  6617. // vui_parameters_present_flag
  6618. if (readBoolean()) {
  6619. // aspect_ratio_info_present_flag
  6620. var aspectRatioIdc = readUByte();
  6621. switch (aspectRatioIdc) {
  6622. case 1:
  6623. pixelRatio = [1, 1];break;
  6624. case 2:
  6625. pixelRatio = [12, 11];break;
  6626. case 3:
  6627. pixelRatio = [10, 11];break;
  6628. case 4:
  6629. pixelRatio = [16, 11];break;
  6630. case 5:
  6631. pixelRatio = [40, 33];break;
  6632. case 6:
  6633. pixelRatio = [24, 11];break;
  6634. case 7:
  6635. pixelRatio = [20, 11];break;
  6636. case 8:
  6637. pixelRatio = [32, 11];break;
  6638. case 9:
  6639. pixelRatio = [80, 33];break;
  6640. case 10:
  6641. pixelRatio = [18, 11];break;
  6642. case 11:
  6643. pixelRatio = [15, 11];break;
  6644. case 12:
  6645. pixelRatio = [64, 33];break;
  6646. case 13:
  6647. pixelRatio = [160, 99];break;
  6648. case 14:
  6649. pixelRatio = [4, 3];break;
  6650. case 15:
  6651. pixelRatio = [3, 2];break;
  6652. case 16:
  6653. pixelRatio = [2, 1];break;
  6654. case 255:
  6655. {
  6656. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  6657. break;
  6658. }
  6659. }
  6660. }
  6661. }
  6662. return {
  6663. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  6664. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  6665. pixelRatio: pixelRatio
  6666. };
  6667. }
  6668. }, {
  6669. key: 'readSliceType',
  6670. value: function readSliceType() {
  6671. // skip NALu type
  6672. this.readUByte();
  6673. // discard first_mb_in_slice
  6674. this.readUEG();
  6675. // return slice_type
  6676. return this.readUEG();
  6677. }
  6678. }]);
  6679. return ExpGolomb;
  6680. }();
  6681. exports.default = ExpGolomb;
  6682. },{"50":50}],26:[function(_dereq_,module,exports){
  6683. 'use strict';
  6684. Object.defineProperty(exports, "__esModule", {
  6685. value: true
  6686. });
  6687. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  6688. * ID3 parser
  6689. */
  6690. var _logger = _dereq_(50);
  6691. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6692. //import Hex from '../utils/hex';
  6693. var ID3 = function () {
  6694. function ID3(data) {
  6695. _classCallCheck(this, ID3);
  6696. this._hasTimeStamp = false;
  6697. var offset = 0,
  6698. byte1,
  6699. byte2,
  6700. byte3,
  6701. byte4,
  6702. tagSize,
  6703. endPos,
  6704. header,
  6705. len;
  6706. do {
  6707. header = this.readUTF(data, offset, 3);
  6708. offset += 3;
  6709. // first check for ID3 header
  6710. if (header === 'ID3') {
  6711. // skip 24 bits
  6712. offset += 3;
  6713. // retrieve tag(s) length
  6714. byte1 = data[offset++] & 0x7f;
  6715. byte2 = data[offset++] & 0x7f;
  6716. byte3 = data[offset++] & 0x7f;
  6717. byte4 = data[offset++] & 0x7f;
  6718. tagSize = (byte1 << 21) + (byte2 << 14) + (byte3 << 7) + byte4;
  6719. endPos = offset + tagSize;
  6720. //logger.log(`ID3 tag found, size/end: ${tagSize}/${endPos}`);
  6721. // read ID3 tags
  6722. this._parseID3Frames(data, offset, endPos);
  6723. offset = endPos;
  6724. } else if (header === '3DI') {
  6725. // http://id3.org/id3v2.4.0-structure chapter 3.4. ID3v2 footer
  6726. offset += 7;
  6727. _logger.logger.log('3DI footer found, end: ' + offset);
  6728. } else {
  6729. offset -= 3;
  6730. len = offset;
  6731. if (len) {
  6732. //logger.log(`ID3 len: ${len}`);
  6733. if (!this.hasTimeStamp) {
  6734. _logger.logger.warn('ID3 tag found, but no timestamp');
  6735. }
  6736. this._length = len;
  6737. this._payload = data.subarray(0, len);
  6738. }
  6739. return;
  6740. }
  6741. } while (true);
  6742. }
  6743. _createClass(ID3, [{
  6744. key: 'readUTF',
  6745. value: function readUTF(data, start, len) {
  6746. var result = '',
  6747. offset = start,
  6748. end = start + len;
  6749. do {
  6750. result += String.fromCharCode(data[offset++]);
  6751. } while (offset < end);
  6752. return result;
  6753. }
  6754. }, {
  6755. key: '_parseID3Frames',
  6756. value: function _parseID3Frames(data, offset, endPos) {
  6757. var tagId, tagLen, tagStart, tagFlags, timestamp;
  6758. while (offset + 8 <= endPos) {
  6759. tagId = this.readUTF(data, offset, 4);
  6760. offset += 4;
  6761. tagLen = data[offset++] << 24 + data[offset++] << 16 + data[offset++] << 8 + data[offset++];
  6762. tagFlags = data[offset++] << 8 + data[offset++];
  6763. tagStart = offset;
  6764. //logger.log("ID3 tag id:" + tagId);
  6765. switch (tagId) {
  6766. case 'PRIV':
  6767. //logger.log('parse frame:' + Hex.hexDump(data.subarray(offset,endPos)));
  6768. // owner should be "com.apple.streaming.transportStreamTimestamp"
  6769. if (this.readUTF(data, offset, 44) === 'com.apple.streaming.transportStreamTimestamp') {
  6770. offset += 44;
  6771. // smelling even better ! we found the right descriptor
  6772. // skip null character (string end) + 3 first bytes
  6773. offset += 4;
  6774. // timestamp is 33 bit expressed as a big-endian eight-octet number, with the upper 31 bits set to zero.
  6775. var pts33Bit = data[offset++] & 0x1;
  6776. this._hasTimeStamp = true;
  6777. timestamp = ((data[offset++] << 23) + (data[offset++] << 15) + (data[offset++] << 7) + data[offset++]) / 45;
  6778. if (pts33Bit) {
  6779. timestamp += 47721858.84; // 2^32 / 90
  6780. }
  6781. timestamp = Math.round(timestamp);
  6782. _logger.logger.trace('ID3 timestamp found: ' + timestamp);
  6783. this._timeStamp = timestamp;
  6784. }
  6785. break;
  6786. default:
  6787. break;
  6788. }
  6789. }
  6790. }
  6791. }, {
  6792. key: 'hasTimeStamp',
  6793. get: function get() {
  6794. return this._hasTimeStamp;
  6795. }
  6796. }, {
  6797. key: 'timeStamp',
  6798. get: function get() {
  6799. return this._timeStamp;
  6800. }
  6801. }, {
  6802. key: 'length',
  6803. get: function get() {
  6804. return this._length;
  6805. }
  6806. }, {
  6807. key: 'payload',
  6808. get: function get() {
  6809. return this._payload;
  6810. }
  6811. }]);
  6812. return ID3;
  6813. }();
  6814. exports.default = ID3;
  6815. },{"50":50}],27:[function(_dereq_,module,exports){
  6816. 'use strict';
  6817. Object.defineProperty(exports, "__esModule", {
  6818. value: true
  6819. });
  6820. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  6821. * MP4 demuxer
  6822. */
  6823. //import {logger} from '../utils/logger';
  6824. var _events = _dereq_(32);
  6825. var _events2 = _interopRequireDefault(_events);
  6826. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6827. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6828. var MP4Demuxer = function () {
  6829. function MP4Demuxer(observer, remuxer) {
  6830. _classCallCheck(this, MP4Demuxer);
  6831. this.observer = observer;
  6832. this.remuxer = remuxer;
  6833. }
  6834. _createClass(MP4Demuxer, [{
  6835. key: 'resetTimeStamp',
  6836. value: function resetTimeStamp() {}
  6837. }, {
  6838. key: 'resetInitSegment',
  6839. value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  6840. //jshint unused:false
  6841. var initData = this.initData = MP4Demuxer.parseInitSegment(initSegment);
  6842. var tracks = {};
  6843. if (initData.audio) {
  6844. tracks.audio = { container: 'audio/mp4', codec: audioCodec, initSegment: initSegment };
  6845. }
  6846. if (initData.video) {
  6847. tracks.video = { container: 'video/mp4', codec: videoCodec, initSegment: initSegment };
  6848. }
  6849. this.observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, { tracks: tracks });
  6850. }
  6851. }, {
  6852. key: 'append',
  6853. // feed incoming data to the front of the parsing pipeline
  6854. value: function append(data, timeOffset, contiguous, accurateTimeOffset) {
  6855. var initData = this.initData;
  6856. var startDTS = MP4Demuxer.startDTS(initData, data);
  6857. this.remuxer.remux(initData.audio, initData.video, null, null, startDTS, contiguous, accurateTimeOffset, data);
  6858. }
  6859. }, {
  6860. key: 'destroy',
  6861. value: function destroy() {}
  6862. }], [{
  6863. key: 'probe',
  6864. value: function probe(data) {
  6865. if (data.length >= 8) {
  6866. var dataType = MP4Demuxer.bin2str(data.subarray(4, 8));
  6867. return ['moof', 'ftyp', 'styp'].indexOf(dataType) >= 0;
  6868. }
  6869. return false;
  6870. }
  6871. }, {
  6872. key: 'bin2str',
  6873. value: function bin2str(buffer) {
  6874. return String.fromCharCode.apply(null, buffer);
  6875. }
  6876. // Find the data for a box specified by its path
  6877. }, {
  6878. key: 'findBox',
  6879. value: function findBox(data, path) {
  6880. var results = [],
  6881. i,
  6882. size,
  6883. type,
  6884. end,
  6885. subresults;
  6886. if (!path.length) {
  6887. // short-circuit the search for empty paths
  6888. return null;
  6889. }
  6890. for (i = 0; i < data.byteLength;) {
  6891. size = data[i] << 24;
  6892. size |= data[i + 1] << 16;
  6893. size |= data[i + 2] << 8;
  6894. size |= data[i + 3];
  6895. type = MP4Demuxer.bin2str(data.subarray(i + 4, i + 8));
  6896. end = size > 1 ? i + size : data.byteLength;
  6897. if (type === path[0]) {
  6898. if (path.length === 1) {
  6899. // this is the end of the path and we've found the box we were
  6900. // looking for
  6901. results.push(data.subarray(i + 8, end));
  6902. } else {
  6903. // recursively search for the next box along the path
  6904. subresults = MP4Demuxer.findBox(data.subarray(i + 8, end), path.slice(1));
  6905. if (subresults.length) {
  6906. results = results.concat(subresults);
  6907. }
  6908. }
  6909. }
  6910. i = end;
  6911. }
  6912. // we've finished searching all of data
  6913. return results;
  6914. }
  6915. /**
  6916. * Parses an MP4 initialization segment and extracts stream type and
  6917. * timescale values for any declared tracks. Timescale values indicate the
  6918. * number of clock ticks per second to assume for time-based values
  6919. * elsewhere in the MP4.
  6920. *
  6921. * To determine the start time of an MP4, you need two pieces of
  6922. * information: the timescale unit and the earliest base media decode
  6923. * time. Multiple timescales can be specified within an MP4 but the
  6924. * base media decode time is always expressed in the timescale from
  6925. * the media header box for the track:
  6926. * ```
  6927. * moov > trak > mdia > mdhd.timescale
  6928. * moov > trak > mdia > hdlr
  6929. * ```
  6930. * @param init {Uint8Array} the bytes of the init segment
  6931. * @return {object} a hash of track type to timescale values or null if
  6932. * the init segment is malformed.
  6933. */
  6934. }, {
  6935. key: 'parseInitSegment',
  6936. value: function parseInitSegment(initSegment) {
  6937. var result = [];
  6938. var traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']);
  6939. traks.forEach(function (trak) {
  6940. var tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0];
  6941. if (tkhd) {
  6942. var version = tkhd[0];
  6943. var index = version === 0 ? 12 : 20;
  6944. var trackId = tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3];
  6945. trackId = trackId < 0 ? 4294967296 + trackId : trackId;
  6946. var mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0];
  6947. if (mdhd) {
  6948. version = mdhd[0];
  6949. index = version === 0 ? 12 : 20;
  6950. var timescale = mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3];
  6951. var hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0];
  6952. if (hdlr) {
  6953. var hdlrType = MP4Demuxer.bin2str(hdlr.subarray(8, 12));
  6954. var type = { 'soun': 'audio', 'vide': 'video' }[hdlrType];
  6955. if (type) {
  6956. result[trackId] = { timescale: timescale, type: type };
  6957. result[type] = { timescale: timescale, id: trackId };
  6958. }
  6959. }
  6960. }
  6961. }
  6962. });
  6963. return result;
  6964. }
  6965. /**
  6966. * Determine the base media decode start time, in seconds, for an MP4
  6967. * fragment. If multiple fragments are specified, the earliest time is
  6968. * returned.
  6969. *
  6970. * The base media decode time can be parsed from track fragment
  6971. * metadata:
  6972. * ```
  6973. * moof > traf > tfdt.baseMediaDecodeTime
  6974. * ```
  6975. * It requires the timescale value from the mdhd to interpret.
  6976. *
  6977. * @param timescale {object} a hash of track ids to timescale values.
  6978. * @return {number} the earliest base media decode start time for the
  6979. * fragment, in seconds
  6980. */
  6981. }, {
  6982. key: 'startDTS',
  6983. value: function startDTS(initData, fragment) {
  6984. var trafs, baseTimes, result;
  6985. // we need info from two childrend of each track fragment box
  6986. trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']);
  6987. // determine the start times for each track
  6988. baseTimes = [].concat.apply([], trafs.map(function (traf) {
  6989. return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
  6990. var id, scale, baseTime;
  6991. // get the track id from the tfhd
  6992. id = tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7];
  6993. // assume a 90kHz clock if no timescale was specified
  6994. scale = initData[id].timescale || 90e3;
  6995. // get the base media decode time from the tfdt
  6996. baseTime = MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
  6997. var version, result;
  6998. version = tfdt[0];
  6999. result = tfdt[4] << 24 | tfdt[5] << 16 | tfdt[6] << 8 | tfdt[7];
  7000. if (version === 1) {
  7001. result *= Math.pow(2, 32);
  7002. result += tfdt[8] << 24 | tfdt[9] << 16 | tfdt[10] << 8 | tfdt[11];
  7003. }
  7004. return result;
  7005. })[0];
  7006. baseTime = baseTime || Infinity;
  7007. // convert base time to seconds
  7008. return baseTime / scale;
  7009. });
  7010. }));
  7011. // return the minimum
  7012. result = Math.min.apply(null, baseTimes);
  7013. return isFinite(result) ? result : 0;
  7014. }
  7015. }]);
  7016. return MP4Demuxer;
  7017. }();
  7018. exports.default = MP4Demuxer;
  7019. },{"32":32}],28:[function(_dereq_,module,exports){
  7020. 'use strict';
  7021. Object.defineProperty(exports, "__esModule", {
  7022. value: true
  7023. });
  7024. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  7025. * SAMPLE-AES decrypter
  7026. */
  7027. var _decrypter = _dereq_(18);
  7028. var _decrypter2 = _interopRequireDefault(_decrypter);
  7029. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  7030. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7031. var SampleAesDecrypter = function () {
  7032. function SampleAesDecrypter(observer, config, decryptdata, discardEPB) {
  7033. _classCallCheck(this, SampleAesDecrypter);
  7034. this.decryptdata = decryptdata;
  7035. this.discardEPB = discardEPB;
  7036. this.decrypter = new _decrypter2.default(observer, config);
  7037. }
  7038. _createClass(SampleAesDecrypter, [{
  7039. key: 'decryptBuffer',
  7040. value: function decryptBuffer(encryptedData, callback) {
  7041. this.decrypter.decrypt(encryptedData, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, callback);
  7042. }
  7043. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  7044. }, {
  7045. key: 'decryptAacSample',
  7046. value: function decryptAacSample(samples, sampleIndex, callback, sync) {
  7047. var curUnit = samples[sampleIndex].unit;
  7048. var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  7049. var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  7050. var localthis = this;
  7051. this.decryptBuffer(encryptedBuffer, function (decryptedData) {
  7052. decryptedData = new Uint8Array(decryptedData);
  7053. curUnit.set(decryptedData, 16);
  7054. if (!sync) {
  7055. localthis.decryptAacSamples(samples, sampleIndex + 1, callback);
  7056. }
  7057. });
  7058. }
  7059. }, {
  7060. key: 'decryptAacSamples',
  7061. value: function decryptAacSamples(samples, sampleIndex, callback) {
  7062. for (;; sampleIndex++) {
  7063. if (sampleIndex >= samples.length) {
  7064. callback();
  7065. return;
  7066. }
  7067. if (samples[sampleIndex].unit.length < 32) {
  7068. continue;
  7069. }
  7070. var sync = this.decrypter.isSync();
  7071. this.decryptAacSample(samples, sampleIndex, callback, sync);
  7072. if (!sync) {
  7073. return;
  7074. }
  7075. }
  7076. }
  7077. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  7078. }, {
  7079. key: 'getAvcEncryptedData',
  7080. value: function getAvcEncryptedData(decodedData) {
  7081. var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  7082. var encryptedData = new Int8Array(encryptedDataLen);
  7083. var outputPos = 0;
  7084. for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {
  7085. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  7086. }
  7087. return encryptedData;
  7088. }
  7089. }, {
  7090. key: 'getAvcDecryptedUnit',
  7091. value: function getAvcDecryptedUnit(decodedData, decryptedData) {
  7092. decryptedData = new Uint8Array(decryptedData);
  7093. var inputPos = 0;
  7094. for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {
  7095. decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos);
  7096. }
  7097. return decodedData;
  7098. }
  7099. }, {
  7100. key: 'decryptAvcSample',
  7101. value: function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {
  7102. var decodedData = this.discardEPB(curUnit.data);
  7103. var encryptedData = this.getAvcEncryptedData(decodedData);
  7104. var localthis = this;
  7105. this.decryptBuffer(encryptedData.buffer, function (decryptedData) {
  7106. curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedData);
  7107. if (!sync) {
  7108. localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  7109. }
  7110. });
  7111. }
  7112. }, {
  7113. key: 'decryptAvcSamples',
  7114. value: function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  7115. for (;; sampleIndex++, unitIndex = 0) {
  7116. if (sampleIndex >= samples.length) {
  7117. callback();
  7118. return;
  7119. }
  7120. var curUnits = samples[sampleIndex].units;
  7121. for (;; unitIndex++) {
  7122. if (unitIndex >= curUnits.length) {
  7123. break;
  7124. }
  7125. var curUnit = curUnits[unitIndex];
  7126. if (curUnit.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  7127. continue;
  7128. }
  7129. var sync = this.decrypter.isSync();
  7130. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);
  7131. if (!sync) {
  7132. return;
  7133. }
  7134. }
  7135. }
  7136. }
  7137. }]);
  7138. return SampleAesDecrypter;
  7139. }();
  7140. exports.default = SampleAesDecrypter;
  7141. },{"18":18}],29:[function(_dereq_,module,exports){
  7142. 'use strict';
  7143. Object.defineProperty(exports, "__esModule", {
  7144. value: true
  7145. });
  7146. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  7147. * highly optimized TS demuxer:
  7148. * parse PAT, PMT
  7149. * extract PES packet from audio and video PIDs
  7150. * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet
  7151. * trigger the remuxer upon parsing completion
  7152. * 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.
  7153. * it also controls the remuxing process :
  7154. * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.
  7155. */
  7156. // import Hex from '../utils/hex';
  7157. var _adts = _dereq_(21);
  7158. var _adts2 = _interopRequireDefault(_adts);
  7159. var _events = _dereq_(32);
  7160. var _events2 = _interopRequireDefault(_events);
  7161. var _expGolomb = _dereq_(25);
  7162. var _expGolomb2 = _interopRequireDefault(_expGolomb);
  7163. var _sampleAes = _dereq_(28);
  7164. var _sampleAes2 = _interopRequireDefault(_sampleAes);
  7165. var _logger = _dereq_(50);
  7166. var _errors = _dereq_(30);
  7167. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  7168. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7169. var TSDemuxer = function () {
  7170. function TSDemuxer(observer, remuxer, config, typeSupported) {
  7171. _classCallCheck(this, TSDemuxer);
  7172. this.observer = observer;
  7173. this.config = config;
  7174. this.typeSupported = typeSupported;
  7175. this.remuxer = remuxer;
  7176. this.sampleAes = null;
  7177. }
  7178. _createClass(TSDemuxer, [{
  7179. key: 'setDecryptData',
  7180. value: function setDecryptData(decryptdata) {
  7181. if (decryptdata != null && decryptdata.key != null && decryptdata.method === 'SAMPLE-AES') {
  7182. this.sampleAes = new _sampleAes2.default(this.observer, this.config, decryptdata, this.discardEPB);
  7183. } else {
  7184. this.sampleAes = null;
  7185. }
  7186. }
  7187. }, {
  7188. key: 'resetInitSegment',
  7189. value: function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  7190. this.pmtParsed = false;
  7191. this._pmtId = -1;
  7192. this._avcTrack = { container: 'video/mp2t', type: 'video', id: -1, inputTimeScale: 90000, sequenceNumber: 0, samples: [], len: 0, dropped: 0 };
  7193. this._audioTrack = { container: 'video/mp2t', type: 'audio', id: -1, inputTimeScale: 90000, sequenceNumber: 0, samples: [], len: 0, isAAC: true };
  7194. this._id3Track = { type: 'id3', id: -1, inputTimeScale: 90000, sequenceNumber: 0, samples: [], len: 0 };
  7195. this._txtTrack = { type: 'text', id: -1, inputTimeScale: 90000, sequenceNumber: 0, samples: [], len: 0 };
  7196. // flush any partial content
  7197. this.aacOverFlow = null;
  7198. this.aacLastPTS = null;
  7199. this.avcSample = null;
  7200. this.audioCodec = audioCodec;
  7201. this.videoCodec = videoCodec;
  7202. this._duration = duration;
  7203. }
  7204. }, {
  7205. key: 'resetTimeStamp',
  7206. value: function resetTimeStamp() {}
  7207. // feed incoming data to the front of the parsing pipeline
  7208. }, {
  7209. key: 'append',
  7210. value: function append(data, timeOffset, contiguous, accurateTimeOffset) {
  7211. var start,
  7212. len = data.length,
  7213. stt,
  7214. pid,
  7215. atf,
  7216. offset,
  7217. pes,
  7218. unknownPIDs = false;
  7219. this.contiguous = contiguous;
  7220. var pmtParsed = this.pmtParsed,
  7221. avcTrack = this._avcTrack,
  7222. audioTrack = this._audioTrack,
  7223. id3Track = this._id3Track,
  7224. avcId = avcTrack.id,
  7225. audioId = audioTrack.id,
  7226. id3Id = id3Track.id,
  7227. pmtId = this._pmtId,
  7228. avcData = avcTrack.pesData,
  7229. audioData = audioTrack.pesData,
  7230. id3Data = id3Track.pesData,
  7231. parsePAT = this._parsePAT,
  7232. parsePMT = this._parsePMT,
  7233. parsePES = this._parsePES,
  7234. parseAVCPES = this._parseAVCPES.bind(this),
  7235. parseAACPES = this._parseAACPES.bind(this),
  7236. parseMPEGPES = this._parseMPEGPES.bind(this),
  7237. parseID3PES = this._parseID3PES.bind(this);
  7238. // don't parse last TS packet if incomplete
  7239. len -= len % 188;
  7240. // loop through TS packets
  7241. for (start = 0; start < len; start += 188) {
  7242. if (data[start] === 0x47) {
  7243. stt = !!(data[start + 1] & 0x40);
  7244. // pid is a 13-bit field starting at the last bit of TS[1]
  7245. pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
  7246. atf = (data[start + 3] & 0x30) >> 4;
  7247. // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
  7248. if (atf > 1) {
  7249. offset = start + 5 + data[start + 4];
  7250. // continue if there is only adaptation field
  7251. if (offset === start + 188) {
  7252. continue;
  7253. }
  7254. } else {
  7255. offset = start + 4;
  7256. }
  7257. switch (pid) {
  7258. case avcId:
  7259. if (stt) {
  7260. if (avcData && (pes = parsePES(avcData))) {
  7261. parseAVCPES(pes, false);
  7262. }
  7263. avcData = { data: [], size: 0 };
  7264. }
  7265. if (avcData) {
  7266. avcData.data.push(data.subarray(offset, start + 188));
  7267. avcData.size += start + 188 - offset;
  7268. }
  7269. break;
  7270. case audioId:
  7271. if (stt) {
  7272. if (audioData && (pes = parsePES(audioData))) {
  7273. if (audioTrack.isAAC) {
  7274. parseAACPES(pes);
  7275. } else {
  7276. parseMPEGPES(pes);
  7277. }
  7278. }
  7279. audioData = { data: [], size: 0 };
  7280. }
  7281. if (audioData) {
  7282. audioData.data.push(data.subarray(offset, start + 188));
  7283. audioData.size += start + 188 - offset;
  7284. }
  7285. break;
  7286. case id3Id:
  7287. if (stt) {
  7288. if (id3Data && (pes = parsePES(id3Data))) {
  7289. parseID3PES(pes);
  7290. }
  7291. id3Data = { data: [], size: 0 };
  7292. }
  7293. if (id3Data) {
  7294. id3Data.data.push(data.subarray(offset, start + 188));
  7295. id3Data.size += start + 188 - offset;
  7296. }
  7297. break;
  7298. case 0:
  7299. if (stt) {
  7300. offset += data[offset] + 1;
  7301. }
  7302. pmtId = this._pmtId = parsePAT(data, offset);
  7303. break;
  7304. case pmtId:
  7305. if (stt) {
  7306. offset += data[offset] + 1;
  7307. }
  7308. var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, this.sampleAes != null);
  7309. // only update track id if track PID found while parsing PMT
  7310. // this is to avoid resetting the PID to -1 in case
  7311. // track PID transiently disappears from the stream
  7312. // this could happen in case of transient missing audio samples for example
  7313. avcId = parsedPIDs.avc;
  7314. if (avcId > 0) {
  7315. avcTrack.id = avcId;
  7316. }
  7317. audioId = parsedPIDs.audio;
  7318. if (audioId > 0) {
  7319. audioTrack.id = audioId;
  7320. audioTrack.isAAC = parsedPIDs.isAAC;
  7321. }
  7322. id3Id = parsedPIDs.id3;
  7323. if (id3Id > 0) {
  7324. id3Track.id = id3Id;
  7325. }
  7326. if (unknownPIDs && !pmtParsed) {
  7327. _logger.logger.log('reparse from beginning');
  7328. unknownPIDs = false;
  7329. // we set it to -188, the += 188 in the for loop will reset start to 0
  7330. start = -188;
  7331. }
  7332. pmtParsed = this.pmtParsed = true;
  7333. break;
  7334. case 17:
  7335. case 0x1fff:
  7336. break;
  7337. default:
  7338. unknownPIDs = true;
  7339. break;
  7340. }
  7341. } else {
  7342. 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' });
  7343. }
  7344. }
  7345. // try to parse last PES packets
  7346. if (avcData && (pes = parsePES(avcData))) {
  7347. parseAVCPES(pes, true);
  7348. avcTrack.pesData = null;
  7349. } else {
  7350. // either avcData null or PES truncated, keep it for next frag parsing
  7351. avcTrack.pesData = avcData;
  7352. }
  7353. if (audioData && (pes = parsePES(audioData))) {
  7354. if (audioTrack.isAAC) {
  7355. parseAACPES(pes);
  7356. } else {
  7357. parseMPEGPES(pes);
  7358. }
  7359. audioTrack.pesData = null;
  7360. } else {
  7361. if (audioData && audioData.size) {
  7362. _logger.logger.log('last AAC PES packet truncated,might overlap between fragments');
  7363. }
  7364. // either audioData null or PES truncated, keep it for next frag parsing
  7365. audioTrack.pesData = audioData;
  7366. }
  7367. if (id3Data && (pes = parsePES(id3Data))) {
  7368. parseID3PES(pes);
  7369. id3Track.pesData = null;
  7370. } else {
  7371. // either id3Data null or PES truncated, keep it for next frag parsing
  7372. id3Track.pesData = id3Data;
  7373. }
  7374. if (this.sampleAes == null) {
  7375. this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
  7376. } else {
  7377. this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
  7378. }
  7379. }
  7380. }, {
  7381. key: 'decryptAndRemux',
  7382. value: function decryptAndRemux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  7383. if (audioTrack.samples && audioTrack.isAAC) {
  7384. var localthis = this;
  7385. this.sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
  7386. localthis.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  7387. });
  7388. } else {
  7389. this.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  7390. }
  7391. }
  7392. }, {
  7393. key: 'decryptAndRemuxAvc',
  7394. value: function decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  7395. if (videoTrack.samples) {
  7396. var localthis = this;
  7397. this.sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
  7398. localthis.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  7399. });
  7400. } else {
  7401. this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  7402. }
  7403. }
  7404. }, {
  7405. key: 'destroy',
  7406. value: function destroy() {
  7407. this._initPTS = this._initDTS = undefined;
  7408. this._duration = 0;
  7409. }
  7410. }, {
  7411. key: '_parsePAT',
  7412. value: function _parsePAT(data, offset) {
  7413. // skip the PSI header and parse the first PMT entry
  7414. return (data[offset + 10] & 0x1F) << 8 | data[offset + 11];
  7415. //logger.log('PMT PID:' + this._pmtId);
  7416. }
  7417. }, {
  7418. key: '_parsePMT',
  7419. value: function _parsePMT(data, offset, mpegSupported, isSampleAes) {
  7420. var sectionLength,
  7421. tableEnd,
  7422. programInfoLength,
  7423. pid,
  7424. result = { audio: -1, avc: -1, id3: -1, isAAC: true };
  7425. sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
  7426. tableEnd = offset + 3 + sectionLength - 4;
  7427. // to determine where the table is, we have to figure out how
  7428. // long the program info descriptors are
  7429. programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
  7430. // advance the offset to the first entry in the mapping table
  7431. offset += 12 + programInfoLength;
  7432. while (offset < tableEnd) {
  7433. pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];
  7434. switch (data[offset]) {
  7435. case 0xcf:
  7436. // SAMPLE-AES AAC
  7437. if (!isSampleAes) {
  7438. _logger.logger.log('unkown stream type:' + data[offset]);
  7439. break;
  7440. }
  7441. /* falls through */
  7442. // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
  7443. case 0x0f:
  7444. //logger.log('AAC PID:' + pid);
  7445. if (result.audio === -1) {
  7446. result.audio = pid;
  7447. }
  7448. break;
  7449. // Packetized metadata (ID3)
  7450. case 0x15:
  7451. //logger.log('ID3 PID:' + pid);
  7452. if (result.id3 === -1) {
  7453. result.id3 = pid;
  7454. }
  7455. break;
  7456. case 0xdb:
  7457. // SAMPLE-AES AVC
  7458. if (!isSampleAes) {
  7459. _logger.logger.log('unkown stream type:' + data[offset]);
  7460. break;
  7461. }
  7462. /* falls through */
  7463. // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
  7464. case 0x1b:
  7465. //logger.log('AVC PID:' + pid);
  7466. if (result.avc === -1) {
  7467. result.avc = pid;
  7468. }
  7469. break;
  7470. // ISO/IEC 11172-3 (MPEG-1 audio)
  7471. // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
  7472. case 0x03:
  7473. case 0x04:
  7474. //logger.log('MPEG PID:' + pid);
  7475. if (!mpegSupported) {
  7476. _logger.logger.log('MPEG audio found, not supported in this browser for now');
  7477. } else if (result.audio === -1) {
  7478. result.audio = pid;
  7479. result.isAAC = false;
  7480. }
  7481. break;
  7482. case 0x24:
  7483. _logger.logger.warn('HEVC stream type found, not supported for now');
  7484. break;
  7485. default:
  7486. _logger.logger.log('unkown stream type:' + data[offset]);
  7487. break;
  7488. }
  7489. // move to the next table entry
  7490. // skip past the elementary stream descriptors, if present
  7491. offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;
  7492. }
  7493. return result;
  7494. }
  7495. }, {
  7496. key: '_parsePES',
  7497. value: function _parsePES(stream) {
  7498. var i = 0,
  7499. frag,
  7500. pesFlags,
  7501. pesPrefix,
  7502. pesLen,
  7503. pesHdrLen,
  7504. pesData,
  7505. pesPts,
  7506. pesDts,
  7507. payloadStartOffset,
  7508. data = stream.data;
  7509. // safety check
  7510. if (!stream || stream.size === 0) {
  7511. return null;
  7512. }
  7513. // we might need up to 19 bytes to read PES header
  7514. // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
  7515. // usually only one merge is needed (and this is rare ...)
  7516. while (data[0].length < 19 && data.length > 1) {
  7517. var newData = new Uint8Array(data[0].length + data[1].length);
  7518. newData.set(data[0]);
  7519. newData.set(data[1], data[0].length);
  7520. data[0] = newData;
  7521. data.splice(1, 1);
  7522. }
  7523. //retrieve PTS/DTS from first fragment
  7524. frag = data[0];
  7525. pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  7526. if (pesPrefix === 1) {
  7527. pesLen = (frag[4] << 8) + frag[5];
  7528. // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
  7529. // minus 6 : PES header size
  7530. if (pesLen && pesLen > stream.size - 6) {
  7531. return null;
  7532. }
  7533. pesFlags = frag[7];
  7534. if (pesFlags & 0xC0) {
  7535. /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  7536. as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
  7537. as Bitwise operators treat their operands as a sequence of 32 bits */
  7538. pesPts = (frag[9] & 0x0E) * 536870912 + // 1 << 29
  7539. (frag[10] & 0xFF) * 4194304 + // 1 << 22
  7540. (frag[11] & 0xFE) * 16384 + // 1 << 14
  7541. (frag[12] & 0xFF) * 128 + // 1 << 7
  7542. (frag[13] & 0xFE) / 2;
  7543. // check if greater than 2^32 -1
  7544. if (pesPts > 4294967295) {
  7545. // decrement 2^33
  7546. pesPts -= 8589934592;
  7547. }
  7548. if (pesFlags & 0x40) {
  7549. pesDts = (frag[14] & 0x0E) * 536870912 + // 1 << 29
  7550. (frag[15] & 0xFF) * 4194304 + // 1 << 22
  7551. (frag[16] & 0xFE) * 16384 + // 1 << 14
  7552. (frag[17] & 0xFF) * 128 + // 1 << 7
  7553. (frag[18] & 0xFE) / 2;
  7554. // check if greater than 2^32 -1
  7555. if (pesDts > 4294967295) {
  7556. // decrement 2^33
  7557. pesDts -= 8589934592;
  7558. }
  7559. if (pesPts - pesDts > 60 * 90000) {
  7560. _logger.logger.warn(Math.round((pesPts - pesDts) / 90000) + 's delta between PTS and DTS, align them');
  7561. pesPts = pesDts;
  7562. }
  7563. } else {
  7564. pesDts = pesPts;
  7565. }
  7566. }
  7567. pesHdrLen = frag[8];
  7568. // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
  7569. payloadStartOffset = pesHdrLen + 9;
  7570. stream.size -= payloadStartOffset;
  7571. //reassemble PES packet
  7572. pesData = new Uint8Array(stream.size);
  7573. for (var j = 0, dataLen = data.length; j < dataLen; j++) {
  7574. frag = data[j];
  7575. var len = frag.byteLength;
  7576. if (payloadStartOffset) {
  7577. if (payloadStartOffset > len) {
  7578. // trim full frag if PES header bigger than frag
  7579. payloadStartOffset -= len;
  7580. continue;
  7581. } else {
  7582. // trim partial frag if PES header smaller than frag
  7583. frag = frag.subarray(payloadStartOffset);
  7584. len -= payloadStartOffset;
  7585. payloadStartOffset = 0;
  7586. }
  7587. }
  7588. pesData.set(frag, i);
  7589. i += len;
  7590. }
  7591. if (pesLen) {
  7592. // payload size : remove PES header + PES extension
  7593. pesLen -= pesHdrLen + 3;
  7594. }
  7595. return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen };
  7596. } else {
  7597. return null;
  7598. }
  7599. }
  7600. }, {
  7601. key: 'pushAccesUnit',
  7602. value: function pushAccesUnit(avcSample, avcTrack) {
  7603. if (avcSample.units.length && avcSample.frame) {
  7604. var samples = avcTrack.samples;
  7605. var nbSamples = samples.length;
  7606. // only push AVC sample if starting with a keyframe is not mandatory OR
  7607. // if keyframe already found in this fragment OR
  7608. // keyframe found in last fragment (track.sps) AND
  7609. // samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous
  7610. if (!this.config.forceKeyFrameOnDiscontinuity || avcSample.key === true || avcTrack.sps && (nbSamples || this.contiguous)) {
  7611. avcSample.id = nbSamples;
  7612. samples.push(avcSample);
  7613. } else {
  7614. // dropped samples, track it
  7615. avcTrack.dropped++;
  7616. }
  7617. }
  7618. if (avcSample.debug.length) {
  7619. _logger.logger.log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);
  7620. }
  7621. }
  7622. }, {
  7623. key: '_parseAVCPES',
  7624. value: function _parseAVCPES(pes, last) {
  7625. var _this = this;
  7626. //logger.log('parse new PES');
  7627. var track = this._avcTrack,
  7628. units = this._parseAVCNALu(pes.data),
  7629. debug = false,
  7630. expGolombDecoder,
  7631. avcSample = this.avcSample,
  7632. push,
  7633. i;
  7634. //free pes.data to save up some memory
  7635. pes.data = null;
  7636. units.forEach(function (unit) {
  7637. switch (unit.type) {
  7638. //NDR
  7639. case 1:
  7640. push = true;
  7641. if (debug && avcSample) {
  7642. avcSample.debug += 'NDR ';
  7643. }
  7644. avcSample.frame = true;
  7645. // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
  7646. var data = unit.data;
  7647. if (data.length > 4) {
  7648. var sliceType = new _expGolomb2.default(data).readSliceType();
  7649. // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
  7650. // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
  7651. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
  7652. // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
  7653. //if (sliceType === 2 || sliceType === 7) {
  7654. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  7655. avcSample.key = true;
  7656. }
  7657. }
  7658. break;
  7659. //IDR
  7660. case 5:
  7661. push = true;
  7662. // handle PES not starting with AUD
  7663. if (!avcSample) {
  7664. avcSample = _this.avcSample = _this._createAVCSample(true, pes.pts, pes.dts, '');
  7665. }
  7666. if (debug) {
  7667. avcSample.debug += 'IDR ';
  7668. }
  7669. avcSample.key = true;
  7670. avcSample.frame = true;
  7671. break;
  7672. //SEI
  7673. case 6:
  7674. push = true;
  7675. if (debug && avcSample) {
  7676. avcSample.debug += 'SEI ';
  7677. }
  7678. expGolombDecoder = new _expGolomb2.default(_this.discardEPB(unit.data));
  7679. // skip frameType
  7680. expGolombDecoder.readUByte();
  7681. var payloadType = 0;
  7682. var payloadSize = 0;
  7683. var endOfCaptions = false;
  7684. var b = 0;
  7685. while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {
  7686. payloadType = 0;
  7687. do {
  7688. b = expGolombDecoder.readUByte();
  7689. payloadType += b;
  7690. } while (b === 0xFF);
  7691. // Parse payload size.
  7692. payloadSize = 0;
  7693. do {
  7694. b = expGolombDecoder.readUByte();
  7695. payloadSize += b;
  7696. } while (b === 0xFF);
  7697. // TODO: there can be more than one payload in an SEI packet...
  7698. // TODO: need to read type and size in a while loop to get them all
  7699. if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {
  7700. endOfCaptions = true;
  7701. var countryCode = expGolombDecoder.readUByte();
  7702. if (countryCode === 181) {
  7703. var providerCode = expGolombDecoder.readUShort();
  7704. if (providerCode === 49) {
  7705. var userStructure = expGolombDecoder.readUInt();
  7706. if (userStructure === 0x47413934) {
  7707. var userDataType = expGolombDecoder.readUByte();
  7708. // Raw CEA-608 bytes wrapped in CEA-708 packet
  7709. if (userDataType === 3) {
  7710. var firstByte = expGolombDecoder.readUByte();
  7711. var secondByte = expGolombDecoder.readUByte();
  7712. var totalCCs = 31 & firstByte;
  7713. var byteArray = [firstByte, secondByte];
  7714. for (i = 0; i < totalCCs; i++) {
  7715. // 3 bytes per CC
  7716. byteArray.push(expGolombDecoder.readUByte());
  7717. byteArray.push(expGolombDecoder.readUByte());
  7718. byteArray.push(expGolombDecoder.readUByte());
  7719. }
  7720. _this._insertSampleInOrder(_this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray });
  7721. }
  7722. }
  7723. }
  7724. }
  7725. } else if (payloadSize < expGolombDecoder.bytesAvailable) {
  7726. for (i = 0; i < payloadSize; i++) {
  7727. expGolombDecoder.readUByte();
  7728. }
  7729. }
  7730. }
  7731. break;
  7732. //SPS
  7733. case 7:
  7734. push = true;
  7735. if (debug && avcSample) {
  7736. avcSample.debug += 'SPS ';
  7737. }
  7738. if (!track.sps) {
  7739. expGolombDecoder = new _expGolomb2.default(unit.data);
  7740. var config = expGolombDecoder.readSPS();
  7741. track.width = config.width;
  7742. track.height = config.height;
  7743. track.pixelRatio = config.pixelRatio;
  7744. track.sps = [unit.data];
  7745. track.duration = _this._duration;
  7746. var codecarray = unit.data.subarray(1, 4);
  7747. var codecstring = 'avc1.';
  7748. for (i = 0; i < 3; i++) {
  7749. var h = codecarray[i].toString(16);
  7750. if (h.length < 2) {
  7751. h = '0' + h;
  7752. }
  7753. codecstring += h;
  7754. }
  7755. track.codec = codecstring;
  7756. }
  7757. break;
  7758. //PPS
  7759. case 8:
  7760. push = true;
  7761. if (debug && avcSample) {
  7762. avcSample.debug += 'PPS ';
  7763. }
  7764. if (!track.pps) {
  7765. track.pps = [unit.data];
  7766. }
  7767. break;
  7768. // AUD
  7769. case 9:
  7770. push = false;
  7771. if (avcSample) {
  7772. _this.pushAccesUnit(avcSample, track);
  7773. }
  7774. avcSample = _this.avcSample = _this._createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');
  7775. break;
  7776. // Filler Data
  7777. case 12:
  7778. push = false;
  7779. break;
  7780. default:
  7781. push = false;
  7782. if (avcSample) {
  7783. avcSample.debug += 'unknown NAL ' + unit.type + ' ';
  7784. }
  7785. break;
  7786. }
  7787. if (avcSample && push) {
  7788. var _units = avcSample.units;
  7789. _units.push(unit);
  7790. }
  7791. });
  7792. // if last PES packet, push samples
  7793. if (last && avcSample) {
  7794. this.pushAccesUnit(avcSample, track);
  7795. this.avcSample = null;
  7796. }
  7797. }
  7798. }, {
  7799. key: '_createAVCSample',
  7800. value: function _createAVCSample(key, pts, dts, debug) {
  7801. return { key: key, pts: pts, dts: dts, units: [], debug: debug };
  7802. }
  7803. }, {
  7804. key: '_insertSampleInOrder',
  7805. value: function _insertSampleInOrder(arr, data) {
  7806. var len = arr.length;
  7807. if (len > 0) {
  7808. if (data.pts >= arr[len - 1].pts) {
  7809. arr.push(data);
  7810. } else {
  7811. for (var pos = len - 1; pos >= 0; pos--) {
  7812. if (data.pts < arr[pos].pts) {
  7813. arr.splice(pos, 0, data);
  7814. break;
  7815. }
  7816. }
  7817. }
  7818. } else {
  7819. arr.push(data);
  7820. }
  7821. }
  7822. }, {
  7823. key: '_getLastNalUnit',
  7824. value: function _getLastNalUnit() {
  7825. var avcSample = this.avcSample,
  7826. lastUnit = void 0;
  7827. // try to fallback to previous sample if current one is empty
  7828. if (!avcSample || avcSample.units.length === 0) {
  7829. var track = this._avcTrack,
  7830. samples = track.samples;
  7831. avcSample = samples[samples.length - 1];
  7832. }
  7833. if (avcSample) {
  7834. var units = avcSample.units;
  7835. lastUnit = units[units.length - 1];
  7836. }
  7837. return lastUnit;
  7838. }
  7839. }, {
  7840. key: '_parseAVCNALu',
  7841. value: function _parseAVCNALu(array) {
  7842. var i = 0,
  7843. len = array.byteLength,
  7844. value,
  7845. overflow,
  7846. track = this._avcTrack,
  7847. state = track.naluState || 0,
  7848. lastState = state;
  7849. var units = [],
  7850. unit,
  7851. unitType,
  7852. lastUnitStart = -1,
  7853. lastUnitType;
  7854. //logger.log('PES:' + Hex.hexDump(array));
  7855. if (state === -1) {
  7856. // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
  7857. lastUnitStart = 0;
  7858. // NALu type is value read from offset 0
  7859. lastUnitType = array[0] & 0x1f;
  7860. state = 0;
  7861. i = 1;
  7862. }
  7863. while (i < len) {
  7864. value = array[i++];
  7865. // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
  7866. if (!state) {
  7867. state = value ? 0 : 1;
  7868. continue;
  7869. }
  7870. if (state === 1) {
  7871. state = value ? 0 : 2;
  7872. continue;
  7873. }
  7874. // here we have state either equal to 2 or 3
  7875. if (!value) {
  7876. state = 3;
  7877. } else if (value === 1) {
  7878. if (lastUnitStart >= 0) {
  7879. unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType };
  7880. //logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  7881. units.push(unit);
  7882. } else {
  7883. // lastUnitStart is undefined => this is the first start code found in this PES packet
  7884. // first check if start code delimiter is overlapping between 2 PES packets,
  7885. // ie it started in last packet (lastState not zero)
  7886. // and ended at the beginning of this PES packet (i <= 4 - lastState)
  7887. var lastUnit = this._getLastNalUnit();
  7888. if (lastUnit) {
  7889. if (lastState && i <= 4 - lastState) {
  7890. // start delimiter overlapping between PES packets
  7891. // strip start delimiter bytes from the end of last NAL unit
  7892. // check if lastUnit had a state different from zero
  7893. if (lastUnit.state) {
  7894. // strip last bytes
  7895. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  7896. }
  7897. }
  7898. // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
  7899. overflow = i - state - 1;
  7900. if (overflow > 0) {
  7901. //logger.log('first NALU found with overflow:' + overflow);
  7902. var tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
  7903. tmp.set(lastUnit.data, 0);
  7904. tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
  7905. lastUnit.data = tmp;
  7906. }
  7907. }
  7908. }
  7909. // check if we can read unit type
  7910. if (i < len) {
  7911. unitType = array[i] & 0x1f;
  7912. //logger.log('find NALU @ offset:' + i + ',type:' + unitType);
  7913. lastUnitStart = i;
  7914. lastUnitType = unitType;
  7915. state = 0;
  7916. } else {
  7917. // not enough byte to read unit type. let's read it on next PES parsing
  7918. state = -1;
  7919. }
  7920. } else {
  7921. state = 0;
  7922. }
  7923. }
  7924. if (lastUnitStart >= 0 && state >= 0) {
  7925. unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType, state: state };
  7926. units.push(unit);
  7927. //logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
  7928. }
  7929. // no NALu found
  7930. if (units.length === 0) {
  7931. // append pes.data to previous NAL unit
  7932. var _lastUnit = this._getLastNalUnit();
  7933. if (_lastUnit) {
  7934. var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength);
  7935. _tmp.set(_lastUnit.data, 0);
  7936. _tmp.set(array, _lastUnit.data.byteLength);
  7937. _lastUnit.data = _tmp;
  7938. }
  7939. }
  7940. track.naluState = state;
  7941. return units;
  7942. }
  7943. /**
  7944. * remove Emulation Prevention bytes from a RBSP
  7945. */
  7946. }, {
  7947. key: 'discardEPB',
  7948. value: function discardEPB(data) {
  7949. var length = data.byteLength,
  7950. EPBPositions = [],
  7951. i = 1,
  7952. newLength,
  7953. newData;
  7954. // Find all `Emulation Prevention Bytes`
  7955. while (i < length - 2) {
  7956. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  7957. EPBPositions.push(i + 2);
  7958. i += 2;
  7959. } else {
  7960. i++;
  7961. }
  7962. }
  7963. // If no Emulation Prevention Bytes were found just return the original
  7964. // array
  7965. if (EPBPositions.length === 0) {
  7966. return data;
  7967. }
  7968. // Create a new array to hold the NAL unit data
  7969. newLength = length - EPBPositions.length;
  7970. newData = new Uint8Array(newLength);
  7971. var sourceIndex = 0;
  7972. for (i = 0; i < newLength; sourceIndex++, i++) {
  7973. if (sourceIndex === EPBPositions[0]) {
  7974. // Skip this byte
  7975. sourceIndex++;
  7976. // Remove this position index
  7977. EPBPositions.shift();
  7978. }
  7979. newData[i] = data[sourceIndex];
  7980. }
  7981. return newData;
  7982. }
  7983. }, {
  7984. key: '_parseAACPES',
  7985. value: function _parseAACPES(pes) {
  7986. var track = this._audioTrack,
  7987. data = pes.data,
  7988. pts = pes.pts,
  7989. startOffset = 0,
  7990. aacOverFlow = this.aacOverFlow,
  7991. aacLastPTS = this.aacLastPTS,
  7992. config,
  7993. frameLength,
  7994. frameDuration,
  7995. frameIndex,
  7996. offset,
  7997. headerLength,
  7998. stamp,
  7999. len,
  8000. aacSample;
  8001. if (aacOverFlow) {
  8002. var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);
  8003. tmp.set(aacOverFlow, 0);
  8004. tmp.set(data, aacOverFlow.byteLength);
  8005. //logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);
  8006. data = tmp;
  8007. }
  8008. // look for ADTS header (0xFFFx)
  8009. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  8010. if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
  8011. break;
  8012. }
  8013. }
  8014. // if ADTS header does not start straight from the beginning of the PES payload, raise an error
  8015. if (offset) {
  8016. var reason, fatal;
  8017. if (offset < len - 1) {
  8018. reason = 'AAC PES did not start with ADTS header,offset:' + offset;
  8019. fatal = false;
  8020. } else {
  8021. reason = 'no ADTS header found in AAC PES';
  8022. fatal = true;
  8023. }
  8024. _logger.logger.warn('parsing error:' + reason);
  8025. this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: fatal, reason: reason });
  8026. if (fatal) {
  8027. return;
  8028. }
  8029. }
  8030. if (!track.samplerate) {
  8031. var audioCodec = this.audioCodec;
  8032. config = _adts2.default.getAudioConfig(this.observer, data, offset, audioCodec);
  8033. track.config = config.config;
  8034. track.samplerate = config.samplerate;
  8035. track.channelCount = config.channelCount;
  8036. track.codec = config.codec;
  8037. track.manifestCodec = config.manifestCodec;
  8038. track.duration = this._duration;
  8039. _logger.logger.log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount);
  8040. }
  8041. frameIndex = 0;
  8042. frameDuration = 1024 * 90000 / track.samplerate;
  8043. // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
  8044. // first sample PTS should be equal to last sample PTS + frameDuration
  8045. if (aacOverFlow && aacLastPTS) {
  8046. var newPTS = aacLastPTS + frameDuration;
  8047. if (Math.abs(newPTS - pts) > 1) {
  8048. _logger.logger.log('AAC: align PTS for overlapping frames by ' + Math.round((newPTS - pts) / 90));
  8049. pts = newPTS;
  8050. }
  8051. }
  8052. while (offset + 5 < len) {
  8053. // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  8054. headerLength = !!(data[offset + 1] & 0x01) ? 7 : 9;
  8055. // retrieve frame size
  8056. frameLength = (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;
  8057. frameLength -= headerLength;
  8058. //stamp = pes.pts;
  8059. if (frameLength > 0 && offset + headerLength + frameLength <= len) {
  8060. stamp = pts + frameIndex * frameDuration;
  8061. //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
  8062. aacSample = { unit: data.subarray(offset + headerLength, offset + headerLength + frameLength), pts: stamp, dts: stamp };
  8063. track.samples.push(aacSample);
  8064. track.len += frameLength;
  8065. offset += frameLength + headerLength;
  8066. frameIndex++;
  8067. // look for ADTS header (0xFFFx)
  8068. for (; offset < len - 1; offset++) {
  8069. if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
  8070. break;
  8071. }
  8072. }
  8073. } else {
  8074. break;
  8075. }
  8076. }
  8077. if (offset < len) {
  8078. aacOverFlow = data.subarray(offset, len);
  8079. //logger.log(`AAC: overflow detected:${len-offset}`);
  8080. } else {
  8081. aacOverFlow = null;
  8082. }
  8083. this.aacOverFlow = aacOverFlow;
  8084. this.aacLastPTS = stamp;
  8085. }
  8086. }, {
  8087. key: '_parseMPEGPES',
  8088. value: function _parseMPEGPES(pes) {
  8089. var data = pes.data;
  8090. var pts = pes.pts;
  8091. var length = data.length;
  8092. var frameIndex = 0;
  8093. var offset = 0;
  8094. var parsed;
  8095. while (offset < length && (parsed = this._parseMpeg(data, offset, length, frameIndex++, pts)) > 0) {
  8096. offset += parsed;
  8097. }
  8098. }
  8099. }, {
  8100. key: '_onMpegFrame',
  8101. value: function _onMpegFrame(data, bitRate, sampleRate, channelCount, frameIndex, pts) {
  8102. var frameDuration = 1152 / sampleRate * 1000;
  8103. var stamp = pts + frameIndex * frameDuration;
  8104. var track = this._audioTrack;
  8105. track.config = [];
  8106. track.channelCount = channelCount;
  8107. track.samplerate = sampleRate;
  8108. track.duration = this._duration;
  8109. track.samples.push({ unit: data, pts: stamp, dts: stamp });
  8110. track.len += data.length;
  8111. }
  8112. }, {
  8113. key: '_onMpegNoise',
  8114. value: function _onMpegNoise(data) {
  8115. _logger.logger.warn('mpeg audio has noise: ' + data.length + ' bytes');
  8116. }
  8117. }, {
  8118. key: '_parseMpeg',
  8119. value: function _parseMpeg(data, start, end, frameIndex, pts) {
  8120. var 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];
  8121. var SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];
  8122. if (start + 2 > end) {
  8123. return -1; // we need at least 2 bytes to detect sync pattern
  8124. }
  8125. if (data[start] === 0xFF || (data[start + 1] & 0xE0) === 0xE0) {
  8126. // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
  8127. if (start + 24 > end) {
  8128. return -1;
  8129. }
  8130. var headerB = data[start + 1] >> 3 & 3;
  8131. var headerC = data[start + 1] >> 1 & 3;
  8132. var headerE = data[start + 2] >> 4 & 15;
  8133. var headerF = data[start + 2] >> 2 & 3;
  8134. var headerG = !!(data[start + 2] & 2);
  8135. if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {
  8136. var columnInBitrates = headerB === 3 ? 3 - headerC : headerC === 3 ? 3 : 4;
  8137. var bitRate = BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;
  8138. var columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;
  8139. var sampleRate = SamplingRateMap[columnInSampleRates * 3 + headerF];
  8140. var padding = headerG ? 1 : 0;
  8141. var channelCount = data[start + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
  8142. var frameLength = headerC === 3 ? (headerB === 3 ? 12 : 6) * bitRate / sampleRate + padding << 2 : (headerB === 3 ? 144 : 72) * bitRate / sampleRate + padding | 0;
  8143. if (start + frameLength > end) {
  8144. return -1;
  8145. }
  8146. if (this._onMpegFrame) {
  8147. this._onMpegFrame(data.subarray(start, start + frameLength), bitRate, sampleRate, channelCount, frameIndex, pts);
  8148. }
  8149. return frameLength;
  8150. }
  8151. }
  8152. // noise or ID3, trying to skip
  8153. var offset = start + 2;
  8154. while (offset < end) {
  8155. if (data[offset - 1] === 0xFF && (data[offset] & 0xE0) === 0xE0) {
  8156. // sync pattern is found
  8157. if (this._onMpegNoise) {
  8158. this._onMpegNoise(data.subarray(start, offset - 1));
  8159. }
  8160. return offset - start - 1;
  8161. }
  8162. offset++;
  8163. }
  8164. return -1;
  8165. }
  8166. }, {
  8167. key: '_parseID3PES',
  8168. value: function _parseID3PES(pes) {
  8169. this._id3Track.samples.push(pes);
  8170. }
  8171. }], [{
  8172. key: 'probe',
  8173. value: function probe(data) {
  8174. // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
  8175. if (data.length >= 3 * 188 && data[0] === 0x47 && data[188] === 0x47 && data[2 * 188] === 0x47) {
  8176. return true;
  8177. } else {
  8178. return false;
  8179. }
  8180. }
  8181. }]);
  8182. return TSDemuxer;
  8183. }();
  8184. exports.default = TSDemuxer;
  8185. },{"21":21,"25":25,"28":28,"30":30,"32":32,"50":50}],30:[function(_dereq_,module,exports){
  8186. 'use strict';
  8187. Object.defineProperty(exports, "__esModule", {
  8188. value: true
  8189. });
  8190. var ErrorTypes = exports.ErrorTypes = {
  8191. // Identifier for a network error (loading error / timeout ...)
  8192. NETWORK_ERROR: 'networkError',
  8193. // Identifier for a media Error (video/parsing/mediasource error)
  8194. MEDIA_ERROR: 'mediaError',
  8195. // Identifier for a mux Error (demuxing/remuxing)
  8196. MUX_ERROR: 'muxError',
  8197. // Identifier for all other errors
  8198. OTHER_ERROR: 'otherError'
  8199. };
  8200. var ErrorDetails = exports.ErrorDetails = {
  8201. // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  8202. MANIFEST_LOAD_ERROR: 'manifestLoadError',
  8203. // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  8204. MANIFEST_LOAD_TIMEOUT: 'manifestLoadTimeOut',
  8205. // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}
  8206. MANIFEST_PARSING_ERROR: 'manifestParsingError',
  8207. // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}
  8208. MANIFEST_INCOMPATIBLE_CODECS_ERROR: 'manifestIncompatibleCodecsError',
  8209. // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  8210. LEVEL_LOAD_ERROR: 'levelLoadError',
  8211. // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  8212. LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut',
  8213. // Identifier for a level switch error - data: { level : faulty level Id, event : error description}
  8214. LEVEL_SWITCH_ERROR: 'levelSwitchError',
  8215. // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  8216. AUDIO_TRACK_LOAD_ERROR: 'audioTrackLoadError',
  8217. // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  8218. AUDIO_TRACK_LOAD_TIMEOUT: 'audioTrackLoadTimeOut',
  8219. // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  8220. FRAG_LOAD_ERROR: 'fragLoadError',
  8221. // Identifier for fragment loop loading error - data: { frag : fragment object}
  8222. FRAG_LOOP_LOADING_ERROR: 'fragLoopLoadingError',
  8223. // Identifier for fragment load timeout error - data: { frag : fragment object}
  8224. FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut',
  8225. // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }
  8226. FRAG_DECRYPT_ERROR: 'fragDecryptError',
  8227. // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }
  8228. // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release
  8229. FRAG_PARSING_ERROR: 'fragParsingError',
  8230. // 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 }
  8231. REMUX_ALLOC_ERROR: 'remuxAllocError',
  8232. // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  8233. KEY_LOAD_ERROR: 'keyLoadError',
  8234. // Identifier for decrypt key load timeout error - data: { frag : fragment object}
  8235. KEY_LOAD_TIMEOUT: 'keyLoadTimeOut',
  8236. // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { err : exception , mimeType : mimeType }
  8237. BUFFER_ADD_CODEC_ERROR: 'bufferAddCodecError',
  8238. // Identifier for a buffer append error - data: append error description
  8239. BUFFER_APPEND_ERROR: 'bufferAppendError',
  8240. // Identifier for a buffer appending error event - data: appending error description
  8241. BUFFER_APPENDING_ERROR: 'bufferAppendingError',
  8242. // Identifier for a buffer stalled error event
  8243. BUFFER_STALLED_ERROR: 'bufferStalledError',
  8244. // Identifier for a buffer full event
  8245. BUFFER_FULL_ERROR: 'bufferFullError',
  8246. // Identifier for a buffer seek over hole event
  8247. BUFFER_SEEK_OVER_HOLE: 'bufferSeekOverHole',
  8248. // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)
  8249. BUFFER_NUDGE_ON_STALL: 'bufferNudgeOnStall',
  8250. // Identifier for an internal exception happening inside hls.js while handling an event
  8251. INTERNAL_EXCEPTION: 'internalException',
  8252. // Malformed WebVTT contents
  8253. WEBVTT_EXCEPTION: 'webVTTException'
  8254. };
  8255. },{}],31:[function(_dereq_,module,exports){
  8256. 'use strict';
  8257. Object.defineProperty(exports, "__esModule", {
  8258. value: true
  8259. });
  8260. 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; };
  8261. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  8262. *
  8263. * All objects in the event handling chain should inherit from this class
  8264. *
  8265. */
  8266. var _logger = _dereq_(50);
  8267. var _errors = _dereq_(30);
  8268. var _events = _dereq_(32);
  8269. var _events2 = _interopRequireDefault(_events);
  8270. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8271. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8272. var EventHandler = function () {
  8273. function EventHandler(hls) {
  8274. _classCallCheck(this, EventHandler);
  8275. this.hls = hls;
  8276. this.onEvent = this.onEvent.bind(this);
  8277. for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  8278. events[_key - 1] = arguments[_key];
  8279. }
  8280. this.handledEvents = events;
  8281. this.useGenericHandler = true;
  8282. this.registerListeners();
  8283. }
  8284. _createClass(EventHandler, [{
  8285. key: 'destroy',
  8286. value: function destroy() {
  8287. this.unregisterListeners();
  8288. }
  8289. }, {
  8290. key: 'isEventHandler',
  8291. value: function isEventHandler() {
  8292. return _typeof(this.handledEvents) === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';
  8293. }
  8294. }, {
  8295. key: 'registerListeners',
  8296. value: function registerListeners() {
  8297. if (this.isEventHandler()) {
  8298. this.handledEvents.forEach(function (event) {
  8299. if (event === 'hlsEventGeneric') {
  8300. throw new Error('Forbidden event name: ' + event);
  8301. }
  8302. this.hls.on(event, this.onEvent);
  8303. }.bind(this));
  8304. }
  8305. }
  8306. }, {
  8307. key: 'unregisterListeners',
  8308. value: function unregisterListeners() {
  8309. if (this.isEventHandler()) {
  8310. this.handledEvents.forEach(function (event) {
  8311. this.hls.off(event, this.onEvent);
  8312. }.bind(this));
  8313. }
  8314. }
  8315. /**
  8316. * arguments: event (string), data (any)
  8317. */
  8318. }, {
  8319. key: 'onEvent',
  8320. value: function onEvent(event, data) {
  8321. this.onEventGeneric(event, data);
  8322. }
  8323. }, {
  8324. key: 'onEventGeneric',
  8325. value: function onEventGeneric(event, data) {
  8326. var eventToFunction = function eventToFunction(event, data) {
  8327. var funcName = 'on' + event.replace('hls', '');
  8328. if (typeof this[funcName] !== 'function') {
  8329. throw new Error('Event ' + event + ' has no generic handler in this ' + this.constructor.name + ' class (tried ' + funcName + ')');
  8330. }
  8331. return this[funcName].bind(this, data);
  8332. };
  8333. try {
  8334. eventToFunction.call(this, event, data).call();
  8335. } catch (err) {
  8336. _logger.logger.error('internal error happened while processing ' + event + ':' + err.message);
  8337. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.INTERNAL_EXCEPTION, fatal: false, event: event, err: err });
  8338. }
  8339. }
  8340. }]);
  8341. return EventHandler;
  8342. }();
  8343. exports.default = EventHandler;
  8344. },{"30":30,"32":32,"50":50}],32:[function(_dereq_,module,exports){
  8345. 'use strict';
  8346. module.exports = {
  8347. // fired before MediaSource is attaching to media element - data: { media }
  8348. MEDIA_ATTACHING: 'hlsMediaAttaching',
  8349. // fired when MediaSource has been succesfully attached to media element - data: { }
  8350. MEDIA_ATTACHED: 'hlsMediaAttached',
  8351. // fired before detaching MediaSource from media element - data: { }
  8352. MEDIA_DETACHING: 'hlsMediaDetaching',
  8353. // fired when MediaSource has been detached from media element - data: { }
  8354. MEDIA_DETACHED: 'hlsMediaDetached',
  8355. // fired when we buffer is going to be resetted
  8356. BUFFER_RESET: 'hlsBufferReset',
  8357. // fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}
  8358. BUFFER_CODECS: 'hlsBufferCodecs',
  8359. // fired when sourcebuffers have been created data: { tracks : tracks}
  8360. BUFFER_CREATED: 'hlsBufferCreated',
  8361. // fired when we append a segment to the buffer - data: { segment: segment object }
  8362. BUFFER_APPENDING: 'hlsBufferAppending',
  8363. // 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}
  8364. BUFFER_APPENDED: 'hlsBufferAppended',
  8365. // fired when the stream is finished and we want to notify the media buffer that there will be no more data
  8366. BUFFER_EOS: 'hlsBufferEos',
  8367. // fired when the media buffer should be flushed - data {startOffset, endOffset}
  8368. BUFFER_FLUSHING: 'hlsBufferFlushing',
  8369. // fired when the media has been flushed
  8370. BUFFER_FLUSHED: 'hlsBufferFlushed',
  8371. // fired to signal that a manifest loading starts - data: { url : manifestURL}
  8372. MANIFEST_LOADING: 'hlsManifestLoading',
  8373. // fired after manifest has been loaded - data: { levels : [available quality levels] , audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}}
  8374. MANIFEST_LOADED: 'hlsManifestLoaded',
  8375. // fired after manifest has been parsed - data: { levels : [available quality levels] , firstLevel : index of first quality level appearing in Manifest}
  8376. MANIFEST_PARSED: 'hlsManifestParsed',
  8377. // fired when a level switch is requested - data: { level : id of new level } // deprecated in favor LEVEL_SWITCHING
  8378. LEVEL_SWITCH: 'hlsLevelSwitch',
  8379. // fired when a level switch is requested - data: { level : id of new level }
  8380. LEVEL_SWITCHING: 'hlsLevelSwitching',
  8381. // fired when a level switch is effective - data: { level : id of new level }
  8382. LEVEL_SWITCHED: 'hlsLevelSwitched',
  8383. // fired when a level playlist loading starts - data: { url : level URL level : id of level being loaded}
  8384. LEVEL_LOADING: 'hlsLevelLoading',
  8385. // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }
  8386. LEVEL_LOADED: 'hlsLevelLoaded',
  8387. // 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 }
  8388. LEVEL_UPDATED: 'hlsLevelUpdated',
  8389. // 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 }
  8390. LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',
  8391. // fired to notify that audio track lists has been updated data: { audioTracks : audioTracks}
  8392. AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated',
  8393. // fired when an audio track switch occurs - data: { id : audio track id} // deprecated in favor AUDIO_TRACK_SWITCHING
  8394. AUDIO_TRACK_SWITCH: 'hlsAudioTrackSwitch',
  8395. // fired when an audio track switching is requested - data: { id : audio track id}
  8396. AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching',
  8397. // fired when an audio track switch actually occurs - data: { id : audio track id}
  8398. AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched',
  8399. // fired when an audio track loading starts - data: { url : audio track URL id : audio track id}
  8400. AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading',
  8401. // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime} }
  8402. AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded',
  8403. // fired to notify that subtitle track lists has been updated data: { subtitleTracks : subtitleTracks}
  8404. SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated',
  8405. // fired when an subtitle track switch occurs - data: { id : subtitle track id}
  8406. SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch',
  8407. // fired when an subtitle track loading starts - data: { url : subtitle track URL id : subtitle track id}
  8408. SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading',
  8409. // fired when an subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime} }
  8410. SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded',
  8411. // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag}
  8412. SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed',
  8413. // fired when the first timestamp is found. - data: { id : demuxer id, initPTS: initPTS , frag : fragment object}
  8414. INIT_PTS_FOUND: 'hlsInitPtsFound',
  8415. // fired when a fragment loading starts - data: { frag : fragment object}
  8416. FRAG_LOADING: 'hlsFragLoading',
  8417. // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded}}
  8418. FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',
  8419. // Identifier for fragment load aborting for emergency switch down - data: {frag : fragment object}
  8420. FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',
  8421. // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length}}
  8422. FRAG_LOADED: 'hlsFragLoaded',
  8423. // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, stats : {tstart,tdecrypt} }
  8424. FRAG_DECRYPTED: 'hlsFragDecrypted',
  8425. // 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}
  8426. FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',
  8427. // fired when parsing sei text is completed - data: { id : demuxer id, , frag: fragment object, samples : [ sei samples pes ] }
  8428. FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',
  8429. // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }
  8430. FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',
  8431. // 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}
  8432. FRAG_PARSING_DATA: 'hlsFragParsingData',
  8433. // fired when fragment parsing is completed - data: { id : demuxer id,frag: fragment object }
  8434. FRAG_PARSED: 'hlsFragParsed',
  8435. // 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} }
  8436. FRAG_BUFFERED: 'hlsFragBuffered',
  8437. // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }
  8438. FRAG_CHANGED: 'hlsFragChanged',
  8439. // Identifier for a FPS drop event - data: {curentDropped, currentDecoded, totalDroppedFrames}
  8440. FPS_DROP: 'hlsFpsDrop',
  8441. //triggered when FPS drop triggers auto level capping - data: {level, droppedlevel}
  8442. FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',
  8443. // 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}
  8444. ERROR: 'hlsError',
  8445. // 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
  8446. DESTROYING: 'hlsDestroying',
  8447. // fired when a decrypt key loading starts - data: { frag : fragment object}
  8448. KEY_LOADING: 'hlsKeyLoading',
  8449. // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length}}
  8450. KEY_LOADED: 'hlsKeyLoaded',
  8451. // fired upon stream controller state transitions - data: {previousState, nextState}
  8452. STREAM_STATE_TRANSITION: 'hlsStreamStateTransition'
  8453. };
  8454. },{}],33:[function(_dereq_,module,exports){
  8455. 'use strict';
  8456. Object.defineProperty(exports, "__esModule", {
  8457. value: true
  8458. });
  8459. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  8460. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8461. /**
  8462. * AAC helper
  8463. */
  8464. var AAC = function () {
  8465. function AAC() {
  8466. _classCallCheck(this, AAC);
  8467. }
  8468. _createClass(AAC, null, [{
  8469. key: 'getSilentFrame',
  8470. value: function getSilentFrame(codec, channelCount) {
  8471. switch (codec) {
  8472. case 'mp4a.40.2':
  8473. if (channelCount === 1) {
  8474. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  8475. } else if (channelCount === 2) {
  8476. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  8477. } else if (channelCount === 3) {
  8478. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  8479. } else if (channelCount === 4) {
  8480. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  8481. } else if (channelCount === 5) {
  8482. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  8483. } else if (channelCount === 6) {
  8484. 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]);
  8485. }
  8486. break;
  8487. // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
  8488. default:
  8489. if (channelCount === 1) {
  8490. // 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
  8491. 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]);
  8492. } else if (channelCount === 2) {
  8493. // 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
  8494. 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]);
  8495. } else if (channelCount === 3) {
  8496. // 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
  8497. 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]);
  8498. }
  8499. break;
  8500. }
  8501. return null;
  8502. }
  8503. }]);
  8504. return AAC;
  8505. }();
  8506. exports.default = AAC;
  8507. },{}],34:[function(_dereq_,module,exports){
  8508. "use strict";
  8509. /**
  8510. * Buffer Helper utils, providing methods dealing buffer length retrieval
  8511. */
  8512. var BufferHelper = {
  8513. isBuffered: function isBuffered(media, position) {
  8514. if (media) {
  8515. var buffered = media.buffered;
  8516. for (var i = 0; i < buffered.length; i++) {
  8517. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  8518. return true;
  8519. }
  8520. }
  8521. }
  8522. return false;
  8523. },
  8524. bufferInfo: function bufferInfo(media, pos, maxHoleDuration) {
  8525. if (media) {
  8526. var vbuffered = media.buffered,
  8527. buffered = [],
  8528. i;
  8529. for (i = 0; i < vbuffered.length; i++) {
  8530. buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) });
  8531. }
  8532. return this.bufferedInfo(buffered, pos, maxHoleDuration);
  8533. } else {
  8534. return { len: 0, start: pos, end: pos, nextStart: undefined };
  8535. }
  8536. },
  8537. bufferedInfo: function bufferedInfo(buffered, pos, maxHoleDuration) {
  8538. var buffered2 = [],
  8539. // bufferStart and bufferEnd are buffer boundaries around current video position
  8540. bufferLen,
  8541. bufferStart,
  8542. bufferEnd,
  8543. bufferStartNext,
  8544. i;
  8545. // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
  8546. buffered.sort(function (a, b) {
  8547. var diff = a.start - b.start;
  8548. if (diff) {
  8549. return diff;
  8550. } else {
  8551. return b.end - a.end;
  8552. }
  8553. });
  8554. // there might be some small holes between buffer time range
  8555. // consider that holes smaller than maxHoleDuration are irrelevant and build another
  8556. // buffer time range representations that discards those holes
  8557. for (i = 0; i < buffered.length; i++) {
  8558. var buf2len = buffered2.length;
  8559. if (buf2len) {
  8560. var buf2end = buffered2[buf2len - 1].end;
  8561. // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
  8562. if (buffered[i].start - buf2end < maxHoleDuration) {
  8563. // merge overlapping time ranges
  8564. // update lastRange.end only if smaller than item.end
  8565. // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
  8566. // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
  8567. if (buffered[i].end > buf2end) {
  8568. buffered2[buf2len - 1].end = buffered[i].end;
  8569. }
  8570. } else {
  8571. // big hole
  8572. buffered2.push(buffered[i]);
  8573. }
  8574. } else {
  8575. // first value
  8576. buffered2.push(buffered[i]);
  8577. }
  8578. }
  8579. for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) {
  8580. var start = buffered2[i].start,
  8581. end = buffered2[i].end;
  8582. //logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
  8583. if (pos + maxHoleDuration >= start && pos < end) {
  8584. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  8585. bufferStart = start;
  8586. bufferEnd = end;
  8587. bufferLen = bufferEnd - pos;
  8588. } else if (pos + maxHoleDuration < start) {
  8589. bufferStartNext = start;
  8590. break;
  8591. }
  8592. }
  8593. return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext };
  8594. }
  8595. };
  8596. module.exports = BufferHelper;
  8597. },{}],35:[function(_dereq_,module,exports){
  8598. 'use strict';
  8599. var _logger = _dereq_(50);
  8600. var LevelHelper = {
  8601. mergeDetails: function mergeDetails(oldDetails, newDetails) {
  8602. var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN,
  8603. end = Math.min(oldDetails.endSN, newDetails.endSN) - newDetails.startSN,
  8604. delta = newDetails.startSN - oldDetails.startSN,
  8605. oldfragments = oldDetails.fragments,
  8606. newfragments = newDetails.fragments,
  8607. ccOffset = 0,
  8608. PTSFrag;
  8609. // check if old/new playlists have fragments in common
  8610. if (end < start) {
  8611. newDetails.PTSKnown = false;
  8612. return;
  8613. }
  8614. // loop through overlapping SN and update startPTS , cc, and duration if any found
  8615. for (var i = start; i <= end; i++) {
  8616. var oldFrag = oldfragments[delta + i],
  8617. newFrag = newfragments[i];
  8618. if (newFrag && oldFrag) {
  8619. ccOffset = oldFrag.cc - newFrag.cc;
  8620. if (!isNaN(oldFrag.startPTS)) {
  8621. newFrag.start = newFrag.startPTS = oldFrag.startPTS;
  8622. newFrag.endPTS = oldFrag.endPTS;
  8623. newFrag.duration = oldFrag.duration;
  8624. PTSFrag = newFrag;
  8625. }
  8626. }
  8627. }
  8628. if (ccOffset) {
  8629. _logger.logger.log('discontinuity sliding from playlist, take drift into account');
  8630. for (i = 0; i < newfragments.length; i++) {
  8631. newfragments[i].cc += ccOffset;
  8632. }
  8633. }
  8634. // if at least one fragment contains PTS info, recompute PTS information for all fragments
  8635. if (PTSFrag) {
  8636. LevelHelper.updateFragPTSDTS(newDetails, PTSFrag.sn, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  8637. } else {
  8638. // ensure that delta is within oldfragments range
  8639. // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
  8640. // in that case we also need to adjust start offset of all fragments
  8641. if (delta >= 0 && delta < oldfragments.length) {
  8642. // adjust start by sliding offset
  8643. var sliding = oldfragments[delta].start;
  8644. for (i = 0; i < newfragments.length; i++) {
  8645. newfragments[i].start += sliding;
  8646. }
  8647. }
  8648. }
  8649. // if we are here, it means we have fragments overlapping between
  8650. // old and new level. reliable PTS info is thus relying on old level
  8651. newDetails.PTSKnown = oldDetails.PTSKnown;
  8652. return;
  8653. },
  8654. updateFragPTSDTS: function updateFragPTSDTS(details, sn, startPTS, endPTS, startDTS, endDTS) {
  8655. var fragIdx, fragments, frag, i;
  8656. // exit if sn out of range
  8657. if (!details || sn < details.startSN || sn > details.endSN) {
  8658. return 0;
  8659. }
  8660. fragIdx = sn - details.startSN;
  8661. fragments = details.fragments;
  8662. frag = fragments[fragIdx];
  8663. if (!isNaN(frag.startPTS)) {
  8664. // delta PTS between audio and video
  8665. var deltaPTS = Math.abs(frag.startPTS - startPTS);
  8666. if (isNaN(frag.deltaPTS)) {
  8667. frag.deltaPTS = deltaPTS;
  8668. } else {
  8669. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  8670. }
  8671. startPTS = Math.min(startPTS, frag.startPTS);
  8672. endPTS = Math.max(endPTS, frag.endPTS);
  8673. startDTS = Math.min(startDTS, frag.startDTS);
  8674. endDTS = Math.max(endDTS, frag.endDTS);
  8675. }
  8676. var drift = startPTS - frag.start;
  8677. frag.start = frag.startPTS = startPTS;
  8678. frag.endPTS = endPTS;
  8679. frag.startDTS = startDTS;
  8680. frag.endDTS = endDTS;
  8681. frag.duration = endPTS - startPTS;
  8682. // adjust fragment PTS/duration from seqnum-1 to frag 0
  8683. for (i = fragIdx; i > 0; i--) {
  8684. LevelHelper.updatePTS(fragments, i, i - 1);
  8685. }
  8686. // adjust fragment PTS/duration from seqnum to last frag
  8687. for (i = fragIdx; i < fragments.length - 1; i++) {
  8688. LevelHelper.updatePTS(fragments, i, i + 1);
  8689. }
  8690. details.PTSKnown = true;
  8691. //logger.log(` frag start/end:${startPTS.toFixed(3)}/${endPTS.toFixed(3)}`);
  8692. return drift;
  8693. },
  8694. updatePTS: function updatePTS(fragments, fromIdx, toIdx) {
  8695. var fragFrom = fragments[fromIdx],
  8696. fragTo = fragments[toIdx],
  8697. fragToPTS = fragTo.startPTS;
  8698. // if we know startPTS[toIdx]
  8699. if (!isNaN(fragToPTS)) {
  8700. // update fragment duration.
  8701. // it helps to fix drifts between playlist reported duration and fragment real duration
  8702. if (toIdx > fromIdx) {
  8703. fragFrom.duration = fragToPTS - fragFrom.start;
  8704. if (fragFrom.duration < 0) {
  8705. _logger.logger.warn('negative duration computed for frag ' + fragFrom.sn + ',level ' + fragFrom.level + ', there should be some duration drift between playlist and fragment!');
  8706. }
  8707. } else {
  8708. fragTo.duration = fragFrom.start - fragToPTS;
  8709. if (fragTo.duration < 0) {
  8710. _logger.logger.warn('negative duration computed for frag ' + fragTo.sn + ',level ' + fragTo.level + ', there should be some duration drift between playlist and fragment!');
  8711. }
  8712. }
  8713. } else {
  8714. // we dont know startPTS[toIdx]
  8715. if (toIdx > fromIdx) {
  8716. fragTo.start = fragFrom.start + fragFrom.duration;
  8717. } else {
  8718. fragTo.start = fragFrom.start - fragTo.duration;
  8719. }
  8720. }
  8721. }
  8722. }; /**
  8723. * Level Helper class, providing methods dealing with playlist sliding and drift
  8724. */
  8725. module.exports = LevelHelper;
  8726. },{"50":50}],36:[function(_dereq_,module,exports){
  8727. /**
  8728. * HLS interface
  8729. */
  8730. 'use strict';
  8731. Object.defineProperty(exports, "__esModule", {
  8732. value: true
  8733. });
  8734. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  8735. var _urlToolkit = _dereq_(2);
  8736. var _urlToolkit2 = _interopRequireDefault(_urlToolkit);
  8737. var _events = _dereq_(32);
  8738. var _events2 = _interopRequireDefault(_events);
  8739. var _errors = _dereq_(30);
  8740. var _playlistLoader = _dereq_(40);
  8741. var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
  8742. var _fragmentLoader = _dereq_(38);
  8743. var _fragmentLoader2 = _interopRequireDefault(_fragmentLoader);
  8744. var _keyLoader = _dereq_(39);
  8745. var _keyLoader2 = _interopRequireDefault(_keyLoader);
  8746. var _streamController = _dereq_(12);
  8747. var _streamController2 = _interopRequireDefault(_streamController);
  8748. var _levelController = _dereq_(11);
  8749. var _levelController2 = _interopRequireDefault(_levelController);
  8750. var _logger = _dereq_(50);
  8751. var _events3 = _dereq_(1);
  8752. var _events4 = _interopRequireDefault(_events3);
  8753. var _config = _dereq_(4);
  8754. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8755. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8756. var Hls = function () {
  8757. _createClass(Hls, null, [{
  8758. key: 'isSupported',
  8759. value: function isSupported() {
  8760. window.MediaSource = window.MediaSource || window.WebKitMediaSource;
  8761. return window.MediaSource && typeof window.MediaSource.isTypeSupported === 'function' && window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
  8762. }
  8763. }, {
  8764. key: 'version',
  8765. get: function get() {
  8766. // replaced with browserify-versionify transform
  8767. return '0.7.5';
  8768. }
  8769. }, {
  8770. key: 'Events',
  8771. get: function get() {
  8772. return _events2.default;
  8773. }
  8774. }, {
  8775. key: 'ErrorTypes',
  8776. get: function get() {
  8777. return _errors.ErrorTypes;
  8778. }
  8779. }, {
  8780. key: 'ErrorDetails',
  8781. get: function get() {
  8782. return _errors.ErrorDetails;
  8783. }
  8784. }, {
  8785. key: 'DefaultConfig',
  8786. get: function get() {
  8787. if (!Hls.defaultConfig) {
  8788. return _config.hlsDefaultConfig;
  8789. }
  8790. return Hls.defaultConfig;
  8791. },
  8792. set: function set(defaultConfig) {
  8793. Hls.defaultConfig = defaultConfig;
  8794. }
  8795. }]);
  8796. function Hls() {
  8797. var _this = this;
  8798. var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  8799. _classCallCheck(this, Hls);
  8800. var defaultConfig = Hls.DefaultConfig;
  8801. if ((config.liveSyncDurationCount || config.liveMaxLatencyDurationCount) && (config.liveSyncDuration || config.liveMaxLatencyDuration)) {
  8802. throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');
  8803. }
  8804. for (var prop in defaultConfig) {
  8805. if (prop in config) {
  8806. continue;
  8807. }
  8808. config[prop] = defaultConfig[prop];
  8809. }
  8810. if (config.liveMaxLatencyDurationCount !== undefined && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {
  8811. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');
  8812. }
  8813. if (config.liveMaxLatencyDuration !== undefined && (config.liveMaxLatencyDuration <= config.liveSyncDuration || config.liveSyncDuration === undefined)) {
  8814. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');
  8815. }
  8816. (0, _logger.enableLogs)(config.debug);
  8817. this.config = config;
  8818. this._autoLevelCapping = -1;
  8819. // observer setup
  8820. var observer = this.observer = new _events4.default();
  8821. observer.trigger = function trigger(event) {
  8822. for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  8823. data[_key - 1] = arguments[_key];
  8824. }
  8825. observer.emit.apply(observer, [event, event].concat(data));
  8826. };
  8827. observer.off = function off(event) {
  8828. for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  8829. data[_key2 - 1] = arguments[_key2];
  8830. }
  8831. observer.removeListener.apply(observer, [event].concat(data));
  8832. };
  8833. this.on = observer.on.bind(observer);
  8834. this.off = observer.off.bind(observer);
  8835. this.trigger = observer.trigger.bind(observer);
  8836. // core controllers and network loaders
  8837. var abrController = this.abrController = new config.abrController(this);
  8838. var bufferController = new config.bufferController(this);
  8839. var capLevelController = new config.capLevelController(this);
  8840. var fpsController = new config.fpsController(this);
  8841. var playListLoader = new _playlistLoader2.default(this);
  8842. var fragmentLoader = new _fragmentLoader2.default(this);
  8843. var keyLoader = new _keyLoader2.default(this);
  8844. // network controllers
  8845. var levelController = this.levelController = new _levelController2.default(this);
  8846. var streamController = this.streamController = new _streamController2.default(this);
  8847. var networkControllers = [levelController, streamController];
  8848. // optional audio stream controller
  8849. var Controller = config.audioStreamController;
  8850. if (Controller) {
  8851. networkControllers.push(new Controller(this));
  8852. }
  8853. this.networkControllers = networkControllers;
  8854. var coreComponents = [playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController];
  8855. // optional audio track and subtitle controller
  8856. Controller = config.audioTrackController;
  8857. if (Controller) {
  8858. var audioTrackController = new Controller(this);
  8859. this.audioTrackController = audioTrackController;
  8860. coreComponents.push(audioTrackController);
  8861. }
  8862. Controller = config.subtitleTrackController;
  8863. if (Controller) {
  8864. var subtitleTrackController = new Controller(this);
  8865. this.subtitleTrackController = subtitleTrackController;
  8866. coreComponents.push(subtitleTrackController);
  8867. }
  8868. // optional subtitle controller
  8869. [config.subtitleStreamController, config.timelineController].forEach(function (Controller) {
  8870. if (Controller) {
  8871. coreComponents.push(new Controller(_this));
  8872. }
  8873. });
  8874. this.coreComponents = coreComponents;
  8875. }
  8876. _createClass(Hls, [{
  8877. key: 'destroy',
  8878. value: function destroy() {
  8879. _logger.logger.log('destroy');
  8880. this.trigger(_events2.default.DESTROYING);
  8881. this.detachMedia();
  8882. this.coreComponents.concat(this.networkControllers).forEach(function (component) {
  8883. component.destroy();
  8884. });
  8885. this.url = null;
  8886. this.observer.removeAllListeners();
  8887. this._autoLevelCapping = -1;
  8888. }
  8889. }, {
  8890. key: 'attachMedia',
  8891. value: function attachMedia(media) {
  8892. _logger.logger.log('attachMedia');
  8893. this.media = media;
  8894. this.trigger(_events2.default.MEDIA_ATTACHING, { media: media });
  8895. }
  8896. }, {
  8897. key: 'detachMedia',
  8898. value: function detachMedia() {
  8899. _logger.logger.log('detachMedia');
  8900. this.trigger(_events2.default.MEDIA_DETACHING);
  8901. this.media = null;
  8902. }
  8903. }, {
  8904. key: 'loadSource',
  8905. value: function loadSource(url) {
  8906. url = _urlToolkit2.default.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true });
  8907. _logger.logger.log('loadSource:' + url);
  8908. this.url = url;
  8909. // when attaching to a source URL, trigger a playlist load
  8910. this.trigger(_events2.default.MANIFEST_LOADING, { url: url });
  8911. }
  8912. }, {
  8913. key: 'startLoad',
  8914. value: function startLoad() {
  8915. var startPosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1;
  8916. _logger.logger.log('startLoad(' + startPosition + ')');
  8917. this.networkControllers.forEach(function (controller) {
  8918. controller.startLoad(startPosition);
  8919. });
  8920. }
  8921. }, {
  8922. key: 'stopLoad',
  8923. value: function stopLoad() {
  8924. _logger.logger.log('stopLoad');
  8925. this.networkControllers.forEach(function (controller) {
  8926. controller.stopLoad();
  8927. });
  8928. }
  8929. }, {
  8930. key: 'swapAudioCodec',
  8931. value: function swapAudioCodec() {
  8932. _logger.logger.log('swapAudioCodec');
  8933. this.streamController.swapAudioCodec();
  8934. }
  8935. }, {
  8936. key: 'recoverMediaError',
  8937. value: function recoverMediaError() {
  8938. _logger.logger.log('recoverMediaError');
  8939. var media = this.media;
  8940. this.detachMedia();
  8941. this.attachMedia(media);
  8942. }
  8943. /** Return all quality levels **/
  8944. }, {
  8945. key: 'levels',
  8946. get: function get() {
  8947. return this.levelController.levels;
  8948. }
  8949. /** Return current playback quality level **/
  8950. }, {
  8951. key: 'currentLevel',
  8952. get: function get() {
  8953. return this.streamController.currentLevel;
  8954. }
  8955. /* set quality level immediately (-1 for automatic level selection) */
  8956. ,
  8957. set: function set(newLevel) {
  8958. _logger.logger.log('set currentLevel:' + newLevel);
  8959. this.loadLevel = newLevel;
  8960. this.streamController.immediateLevelSwitch();
  8961. }
  8962. /** Return next playback quality level (quality level of next fragment) **/
  8963. }, {
  8964. key: 'nextLevel',
  8965. get: function get() {
  8966. return this.streamController.nextLevel;
  8967. }
  8968. /* set quality level for next fragment (-1 for automatic level selection) */
  8969. ,
  8970. set: function set(newLevel) {
  8971. _logger.logger.log('set nextLevel:' + newLevel);
  8972. this.levelController.manualLevel = newLevel;
  8973. this.streamController.nextLevelSwitch();
  8974. }
  8975. /** Return the quality level of current/last loaded fragment **/
  8976. }, {
  8977. key: 'loadLevel',
  8978. get: function get() {
  8979. return this.levelController.level;
  8980. }
  8981. /* set quality level for current/next loaded fragment (-1 for automatic level selection) */
  8982. ,
  8983. set: function set(newLevel) {
  8984. _logger.logger.log('set loadLevel:' + newLevel);
  8985. this.levelController.manualLevel = newLevel;
  8986. }
  8987. /** Return the quality level of next loaded fragment **/
  8988. }, {
  8989. key: 'nextLoadLevel',
  8990. get: function get() {
  8991. return this.levelController.nextLoadLevel;
  8992. }
  8993. /** set quality level of next loaded fragment **/
  8994. ,
  8995. set: function set(level) {
  8996. this.levelController.nextLoadLevel = level;
  8997. }
  8998. /** Return first level (index of first level referenced in manifest)
  8999. **/
  9000. }, {
  9001. key: 'firstLevel',
  9002. get: function get() {
  9003. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  9004. }
  9005. /** set first level (index of first level referenced in manifest)
  9006. **/
  9007. ,
  9008. set: function set(newLevel) {
  9009. _logger.logger.log('set firstLevel:' + newLevel);
  9010. this.levelController.firstLevel = newLevel;
  9011. }
  9012. /** Return start level (level of first fragment that will be played back)
  9013. if not overrided by user, first level appearing in manifest will be used as start level
  9014. if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
  9015. **/
  9016. }, {
  9017. key: 'startLevel',
  9018. get: function get() {
  9019. return this.levelController.startLevel;
  9020. }
  9021. /** set start level (level of first fragment that will be played back)
  9022. if not overrided by user, first level appearing in manifest will be used as start level
  9023. if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
  9024. **/
  9025. ,
  9026. set: function set(newLevel) {
  9027. _logger.logger.log('set startLevel:' + newLevel);
  9028. var hls = this;
  9029. // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
  9030. if (newLevel !== -1) {
  9031. newLevel = Math.max(newLevel, hls.minAutoLevel);
  9032. }
  9033. hls.levelController.startLevel = newLevel;
  9034. }
  9035. /** Return the capping/max level value that could be used by automatic level selection algorithm **/
  9036. }, {
  9037. key: 'autoLevelCapping',
  9038. get: function get() {
  9039. return this._autoLevelCapping;
  9040. }
  9041. /** set the capping/max level value that could be used by automatic level selection algorithm **/
  9042. ,
  9043. set: function set(newLevel) {
  9044. _logger.logger.log('set autoLevelCapping:' + newLevel);
  9045. this._autoLevelCapping = newLevel;
  9046. }
  9047. /* check if we are in automatic level selection mode */
  9048. }, {
  9049. key: 'autoLevelEnabled',
  9050. get: function get() {
  9051. return this.levelController.manualLevel === -1;
  9052. }
  9053. /* return manual level */
  9054. }, {
  9055. key: 'manualLevel',
  9056. get: function get() {
  9057. return this.levelController.manualLevel;
  9058. }
  9059. /* return min level selectable in auto mode according to config.minAutoBitrate */
  9060. }, {
  9061. key: 'minAutoLevel',
  9062. get: function get() {
  9063. var hls = this,
  9064. levels = hls.levels,
  9065. minAutoBitrate = hls.config.minAutoBitrate,
  9066. len = levels ? levels.length : 0;
  9067. for (var i = 0; i < len; i++) {
  9068. var levelNextBitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate;
  9069. if (levelNextBitrate > minAutoBitrate) {
  9070. return i;
  9071. }
  9072. }
  9073. return 0;
  9074. }
  9075. /* return max level selectable in auto mode according to autoLevelCapping */
  9076. }, {
  9077. key: 'maxAutoLevel',
  9078. get: function get() {
  9079. var hls = this;
  9080. var levels = hls.levels;
  9081. var autoLevelCapping = hls.autoLevelCapping;
  9082. var maxAutoLevel = void 0;
  9083. if (autoLevelCapping === -1 && levels && levels.length) {
  9084. maxAutoLevel = levels.length - 1;
  9085. } else {
  9086. maxAutoLevel = autoLevelCapping;
  9087. }
  9088. return maxAutoLevel;
  9089. }
  9090. // return next auto level
  9091. }, {
  9092. key: 'nextAutoLevel',
  9093. get: function get() {
  9094. var hls = this;
  9095. // ensure next auto level is between min and max auto level
  9096. return Math.min(Math.max(hls.abrController.nextAutoLevel, hls.minAutoLevel), hls.maxAutoLevel);
  9097. }
  9098. // this setter is used to force next auto level
  9099. // 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)
  9100. // forced value is valid for one fragment. upon succesful frag loading at forced level, this value will be resetted to -1 by ABR controller
  9101. ,
  9102. set: function set(nextLevel) {
  9103. var hls = this;
  9104. hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel);
  9105. }
  9106. /** get alternate audio tracks list from playlist **/
  9107. }, {
  9108. key: 'audioTracks',
  9109. get: function get() {
  9110. var audioTrackController = this.audioTrackController;
  9111. return audioTrackController ? audioTrackController.audioTracks : [];
  9112. }
  9113. /** get index of the selected audio track (index in audio track lists) **/
  9114. }, {
  9115. key: 'audioTrack',
  9116. get: function get() {
  9117. var audioTrackController = this.audioTrackController;
  9118. return audioTrackController ? audioTrackController.audioTrack : -1;
  9119. }
  9120. /** select an audio track, based on its index in audio track lists**/
  9121. ,
  9122. set: function set(audioTrackId) {
  9123. var audioTrackController = this.audioTrackController;
  9124. if (audioTrackController) {
  9125. audioTrackController.audioTrack = audioTrackId;
  9126. }
  9127. }
  9128. }, {
  9129. key: 'liveSyncPosition',
  9130. get: function get() {
  9131. return this.streamController.liveSyncPosition;
  9132. }
  9133. /** get alternate subtitle tracks list from playlist **/
  9134. }, {
  9135. key: 'subtitleTracks',
  9136. get: function get() {
  9137. var subtitleTrackController = this.subtitleTrackController;
  9138. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  9139. }
  9140. /** get index of the selected subtitle track (index in subtitle track lists) **/
  9141. }, {
  9142. key: 'subtitleTrack',
  9143. get: function get() {
  9144. var subtitleTrackController = this.subtitleTrackController;
  9145. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  9146. }
  9147. /** select an subtitle track, based on its index in subtitle track lists**/
  9148. ,
  9149. set: function set(subtitleTrackId) {
  9150. var subtitleTrackController = this.subtitleTrackController;
  9151. if (subtitleTrackController) {
  9152. subtitleTrackController.subtitleTrack = subtitleTrackId;
  9153. }
  9154. }
  9155. }]);
  9156. return Hls;
  9157. }();
  9158. exports.default = Hls;
  9159. },{"1":1,"11":11,"12":12,"2":2,"30":30,"32":32,"38":38,"39":39,"4":4,"40":40,"50":50}],37:[function(_dereq_,module,exports){
  9160. 'use strict';
  9161. // This is mostly for support of the es6 module export
  9162. // syntax with the babel compiler, it looks like it doesnt support
  9163. // function exports like we are used to in node/commonjs
  9164. module.exports = _dereq_(36).default;
  9165. },{"36":36}],38:[function(_dereq_,module,exports){
  9166. 'use strict';
  9167. Object.defineProperty(exports, "__esModule", {
  9168. value: true
  9169. });
  9170. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  9171. var _events = _dereq_(32);
  9172. var _events2 = _interopRequireDefault(_events);
  9173. var _eventHandler = _dereq_(31);
  9174. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  9175. var _errors = _dereq_(30);
  9176. var _logger = _dereq_(50);
  9177. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9178. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9179. 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; }
  9180. 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; } /*
  9181. * Fragment Loader
  9182. */
  9183. var FragmentLoader = function (_EventHandler) {
  9184. _inherits(FragmentLoader, _EventHandler);
  9185. function FragmentLoader(hls) {
  9186. _classCallCheck(this, FragmentLoader);
  9187. var _this = _possibleConstructorReturn(this, (FragmentLoader.__proto__ || Object.getPrototypeOf(FragmentLoader)).call(this, hls, _events2.default.FRAG_LOADING));
  9188. _this.loaders = {};
  9189. return _this;
  9190. }
  9191. _createClass(FragmentLoader, [{
  9192. key: 'destroy',
  9193. value: function destroy() {
  9194. var loaders = this.loaders;
  9195. for (var loaderName in loaders) {
  9196. var loader = loaders[loaderName];
  9197. if (loader) {
  9198. loader.destroy();
  9199. }
  9200. }
  9201. this.loaders = {};
  9202. _eventHandler2.default.prototype.destroy.call(this);
  9203. }
  9204. }, {
  9205. key: 'onFragLoading',
  9206. value: function onFragLoading(data) {
  9207. var frag = data.frag,
  9208. type = frag.type,
  9209. loader = this.loaders[type],
  9210. config = this.hls.config;
  9211. frag.loaded = 0;
  9212. if (loader) {
  9213. _logger.logger.warn('abort previous fragment loader for type:' + type);
  9214. loader.abort();
  9215. }
  9216. loader = this.loaders[type] = frag.loader = typeof config.fLoader !== 'undefined' ? new config.fLoader(config) : new config.loader(config);
  9217. var loaderContext = void 0,
  9218. loaderConfig = void 0,
  9219. loaderCallbacks = void 0;
  9220. loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false };
  9221. var start = frag.byteRangeStartOffset,
  9222. end = frag.byteRangeEndOffset;
  9223. if (!isNaN(start) && !isNaN(end)) {
  9224. loaderContext.rangeStart = start;
  9225. loaderContext.rangeEnd = end;
  9226. }
  9227. loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: 0, retryDelay: 0, maxRetryDelay: config.fragLoadingMaxRetryTimeout };
  9228. loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this), onProgress: this.loadprogress.bind(this) };
  9229. loader.load(loaderContext, loaderConfig, loaderCallbacks);
  9230. }
  9231. }, {
  9232. key: 'loadsuccess',
  9233. value: function loadsuccess(response, stats, context) {
  9234. var payload = response.data,
  9235. frag = context.frag;
  9236. // detach fragment loader on load success
  9237. frag.loader = undefined;
  9238. this.loaders[frag.type] = undefined;
  9239. this.hls.trigger(_events2.default.FRAG_LOADED, { payload: payload, frag: frag, stats: stats });
  9240. }
  9241. }, {
  9242. key: 'loaderror',
  9243. value: function loaderror(response, context) {
  9244. var loader = context.loader;
  9245. if (loader) {
  9246. loader.abort();
  9247. }
  9248. this.loaders[context.type] = undefined;
  9249. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.FRAG_LOAD_ERROR, fatal: false, frag: context.frag, response: response });
  9250. }
  9251. }, {
  9252. key: 'loadtimeout',
  9253. value: function loadtimeout(stats, context) {
  9254. var loader = context.loader;
  9255. if (loader) {
  9256. loader.abort();
  9257. }
  9258. this.loaders[context.type] = undefined;
  9259. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag });
  9260. }
  9261. // data will be used for progressive parsing
  9262. }, {
  9263. key: 'loadprogress',
  9264. value: function loadprogress(stats, context, data) {
  9265. // jshint ignore:line
  9266. var frag = context.frag;
  9267. frag.loaded = stats.loaded;
  9268. this.hls.trigger(_events2.default.FRAG_LOAD_PROGRESS, { frag: frag, stats: stats });
  9269. }
  9270. }]);
  9271. return FragmentLoader;
  9272. }(_eventHandler2.default);
  9273. exports.default = FragmentLoader;
  9274. },{"30":30,"31":31,"32":32,"50":50}],39:[function(_dereq_,module,exports){
  9275. 'use strict';
  9276. Object.defineProperty(exports, "__esModule", {
  9277. value: true
  9278. });
  9279. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  9280. var _events = _dereq_(32);
  9281. var _events2 = _interopRequireDefault(_events);
  9282. var _eventHandler = _dereq_(31);
  9283. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  9284. var _errors = _dereq_(30);
  9285. var _logger = _dereq_(50);
  9286. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9287. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9288. 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; }
  9289. 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; } /*
  9290. * Decrypt key Loader
  9291. */
  9292. var KeyLoader = function (_EventHandler) {
  9293. _inherits(KeyLoader, _EventHandler);
  9294. function KeyLoader(hls) {
  9295. _classCallCheck(this, KeyLoader);
  9296. var _this = _possibleConstructorReturn(this, (KeyLoader.__proto__ || Object.getPrototypeOf(KeyLoader)).call(this, hls, _events2.default.KEY_LOADING));
  9297. _this.loaders = {};
  9298. _this.decryptkey = null;
  9299. _this.decrypturl = null;
  9300. return _this;
  9301. }
  9302. _createClass(KeyLoader, [{
  9303. key: 'destroy',
  9304. value: function destroy() {
  9305. for (var loaderName in this.loaders) {
  9306. var loader = this.loaders[loaderName];
  9307. if (loader) {
  9308. loader.destroy();
  9309. }
  9310. }
  9311. this.loaders = {};
  9312. _eventHandler2.default.prototype.destroy.call(this);
  9313. }
  9314. }, {
  9315. key: 'onKeyLoading',
  9316. value: function onKeyLoading(data) {
  9317. var frag = data.frag,
  9318. type = frag.type,
  9319. loader = this.loaders[type],
  9320. decryptdata = frag.decryptdata,
  9321. uri = decryptdata.uri;
  9322. // if uri is different from previous one or if decrypt key not retrieved yet
  9323. if (uri !== this.decrypturl || this.decryptkey === null) {
  9324. var config = this.hls.config;
  9325. if (loader) {
  9326. _logger.logger.warn('abort previous key loader for type:' + type);
  9327. loader.abort();
  9328. }
  9329. frag.loader = this.loaders[type] = new config.loader(config);
  9330. this.decrypturl = uri;
  9331. this.decryptkey = null;
  9332. var loaderContext = void 0,
  9333. loaderConfig = void 0,
  9334. loaderCallbacks = void 0;
  9335. loaderContext = { url: uri, frag: frag, responseType: 'arraybuffer' };
  9336. loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: config.fragLoadingMaxRetry, retryDelay: config.fragLoadingRetryDelay, maxRetryDelay: config.fragLoadingMaxRetryTimeout };
  9337. loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) };
  9338. frag.loader.load(loaderContext, loaderConfig, loaderCallbacks);
  9339. } else if (this.decryptkey) {
  9340. // we already loaded this key, return it
  9341. decryptdata.key = this.decryptkey;
  9342. this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag });
  9343. }
  9344. }
  9345. }, {
  9346. key: 'loadsuccess',
  9347. value: function loadsuccess(response, stats, context) {
  9348. var frag = context.frag;
  9349. this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data);
  9350. // detach fragment loader on load success
  9351. frag.loader = undefined;
  9352. this.loaders[frag.type] = undefined;
  9353. this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag });
  9354. }
  9355. }, {
  9356. key: 'loaderror',
  9357. value: function loaderror(response, context) {
  9358. var frag = context.frag,
  9359. loader = frag.loader;
  9360. if (loader) {
  9361. loader.abort();
  9362. }
  9363. this.loaders[context.type] = undefined;
  9364. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: frag, response: response });
  9365. }
  9366. }, {
  9367. key: 'loadtimeout',
  9368. value: function loadtimeout(stats, context) {
  9369. var frag = context.frag,
  9370. loader = frag.loader;
  9371. if (loader) {
  9372. loader.abort();
  9373. }
  9374. this.loaders[context.type] = undefined;
  9375. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_TIMEOUT, fatal: false, frag: frag });
  9376. }
  9377. }]);
  9378. return KeyLoader;
  9379. }(_eventHandler2.default);
  9380. exports.default = KeyLoader;
  9381. },{"30":30,"31":31,"32":32,"50":50}],40:[function(_dereq_,module,exports){
  9382. 'use strict';
  9383. Object.defineProperty(exports, "__esModule", {
  9384. value: true
  9385. });
  9386. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  9387. * Playlist Loader
  9388. */
  9389. var _urlToolkit = _dereq_(2);
  9390. var _urlToolkit2 = _interopRequireDefault(_urlToolkit);
  9391. var _events = _dereq_(32);
  9392. var _events2 = _interopRequireDefault(_events);
  9393. var _eventHandler = _dereq_(31);
  9394. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  9395. var _errors = _dereq_(30);
  9396. var _attrList = _dereq_(44);
  9397. var _attrList2 = _interopRequireDefault(_attrList);
  9398. var _logger = _dereq_(50);
  9399. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9400. 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; }
  9401. 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; }
  9402. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9403. // https://regex101.com is your friend
  9404. var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g;
  9405. var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  9406. var LEVEL_PLAYLIST_REGEX_FAST = /#EXTINF:(\d*(?:\.\d+)?)(?:,(.*))?|(?!#)(\S.+)|#EXT-X-BYTERANGE: *(.+)|#EXT-X-PROGRAM-DATE-TIME:(.+)|#.*/g;
  9407. 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?/;
  9408. var LevelKey = function () {
  9409. function LevelKey() {
  9410. _classCallCheck(this, LevelKey);
  9411. this.method = null;
  9412. this.key = null;
  9413. this.iv = null;
  9414. this._uri = null;
  9415. }
  9416. _createClass(LevelKey, [{
  9417. key: 'uri',
  9418. get: function get() {
  9419. if (!this._uri && this.reluri) {
  9420. this._uri = _urlToolkit2.default.buildAbsoluteURL(this.baseuri, this.reluri, { alwaysNormalize: true });
  9421. }
  9422. return this._uri;
  9423. }
  9424. }]);
  9425. return LevelKey;
  9426. }();
  9427. var Fragment = function () {
  9428. function Fragment() {
  9429. _classCallCheck(this, Fragment);
  9430. this._url = null;
  9431. this._byteRange = null;
  9432. this._decryptdata = null;
  9433. this.tagList = [];
  9434. }
  9435. _createClass(Fragment, [{
  9436. key: 'createInitializationVector',
  9437. /**
  9438. * Utility method for parseLevelPlaylist to create an initialization vector for a given segment
  9439. * @returns {Uint8Array}
  9440. */
  9441. value: function createInitializationVector(segmentNumber) {
  9442. var uint8View = new Uint8Array(16);
  9443. for (var i = 12; i < 16; i++) {
  9444. uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
  9445. }
  9446. return uint8View;
  9447. }
  9448. /**
  9449. * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data
  9450. * @param levelkey - a playlist's encryption info
  9451. * @param segmentNumber - the fragment's segment number
  9452. * @returns {*} - an object to be applied as a fragment's decryptdata
  9453. */
  9454. }, {
  9455. key: 'fragmentDecryptdataFromLevelkey',
  9456. value: function fragmentDecryptdataFromLevelkey(levelkey, segmentNumber) {
  9457. var decryptdata = levelkey;
  9458. if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) {
  9459. decryptdata = new LevelKey();
  9460. decryptdata.method = levelkey.method;
  9461. decryptdata.baseuri = levelkey.baseuri;
  9462. decryptdata.reluri = levelkey.reluri;
  9463. decryptdata.iv = this.createInitializationVector(segmentNumber);
  9464. }
  9465. return decryptdata;
  9466. }
  9467. }, {
  9468. key: 'cloneObj',
  9469. value: function cloneObj(obj) {
  9470. return JSON.parse(JSON.stringify(obj));
  9471. }
  9472. }, {
  9473. key: 'url',
  9474. get: function get() {
  9475. if (!this._url && this.relurl) {
  9476. this._url = _urlToolkit2.default.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });
  9477. }
  9478. return this._url;
  9479. },
  9480. set: function set(value) {
  9481. this._url = value;
  9482. }
  9483. }, {
  9484. key: 'programDateTime',
  9485. get: function get() {
  9486. if (!this._programDateTime && this.rawProgramDateTime) {
  9487. this._programDateTime = new Date(Date.parse(this.rawProgramDateTime));
  9488. }
  9489. return this._programDateTime;
  9490. }
  9491. }, {
  9492. key: 'byteRange',
  9493. get: function get() {
  9494. if (!this._byteRange) {
  9495. var byteRange = this._byteRange = [];
  9496. if (this.rawByteRange) {
  9497. var params = this.rawByteRange.split('@', 2);
  9498. if (params.length === 1) {
  9499. var lastByteRangeEndOffset = this.lastByteRangeEndOffset;
  9500. byteRange[0] = lastByteRangeEndOffset ? lastByteRangeEndOffset : 0;
  9501. } else {
  9502. byteRange[0] = parseInt(params[1]);
  9503. }
  9504. byteRange[1] = parseInt(params[0]) + byteRange[0];
  9505. }
  9506. }
  9507. return this._byteRange;
  9508. }
  9509. }, {
  9510. key: 'byteRangeStartOffset',
  9511. get: function get() {
  9512. return this.byteRange[0];
  9513. }
  9514. }, {
  9515. key: 'byteRangeEndOffset',
  9516. get: function get() {
  9517. return this.byteRange[1];
  9518. }
  9519. }, {
  9520. key: 'decryptdata',
  9521. get: function get() {
  9522. if (!this._decryptdata) {
  9523. this._decryptdata = this.fragmentDecryptdataFromLevelkey(this.levelkey, this.sn);
  9524. }
  9525. return this._decryptdata;
  9526. }
  9527. }]);
  9528. return Fragment;
  9529. }();
  9530. var PlaylistLoader = function (_EventHandler) {
  9531. _inherits(PlaylistLoader, _EventHandler);
  9532. function PlaylistLoader(hls) {
  9533. _classCallCheck(this, PlaylistLoader);
  9534. 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));
  9535. _this.loaders = {};
  9536. return _this;
  9537. }
  9538. _createClass(PlaylistLoader, [{
  9539. key: 'destroy',
  9540. value: function destroy() {
  9541. for (var loaderName in this.loaders) {
  9542. var loader = this.loaders[loaderName];
  9543. if (loader) {
  9544. loader.destroy();
  9545. }
  9546. }
  9547. this.loaders = {};
  9548. _eventHandler2.default.prototype.destroy.call(this);
  9549. }
  9550. }, {
  9551. key: 'onManifestLoading',
  9552. value: function onManifestLoading(data) {
  9553. this.load(data.url, { type: 'manifest' });
  9554. }
  9555. }, {
  9556. key: 'onLevelLoading',
  9557. value: function onLevelLoading(data) {
  9558. this.load(data.url, { type: 'level', level: data.level, id: data.id });
  9559. }
  9560. }, {
  9561. key: 'onAudioTrackLoading',
  9562. value: function onAudioTrackLoading(data) {
  9563. this.load(data.url, { type: 'audioTrack', id: data.id });
  9564. }
  9565. }, {
  9566. key: 'onSubtitleTrackLoading',
  9567. value: function onSubtitleTrackLoading(data) {
  9568. this.load(data.url, { type: 'subtitleTrack', id: data.id });
  9569. }
  9570. }, {
  9571. key: 'load',
  9572. value: function load(url, context) {
  9573. var loader = this.loaders[context.type];
  9574. if (loader) {
  9575. var loaderContext = loader.context;
  9576. if (loaderContext && loaderContext.url === url) {
  9577. _logger.logger.trace('playlist request ongoing');
  9578. return;
  9579. } else {
  9580. _logger.logger.warn('abort previous loader for type:' + context.type);
  9581. loader.abort();
  9582. }
  9583. }
  9584. var config = this.hls.config,
  9585. retry = void 0,
  9586. timeout = void 0,
  9587. retryDelay = void 0,
  9588. maxRetryDelay = void 0;
  9589. if (context.type === 'manifest') {
  9590. retry = config.manifestLoadingMaxRetry;
  9591. timeout = config.manifestLoadingTimeOut;
  9592. retryDelay = config.manifestLoadingRetryDelay;
  9593. maxRetryDelay = config.manifestLoadingMaxRetryTimeout;
  9594. } else {
  9595. retry = config.levelLoadingMaxRetry;
  9596. timeout = config.levelLoadingTimeOut;
  9597. retryDelay = config.levelLoadingRetryDelay;
  9598. maxRetryDelay = config.levelLoadingMaxRetryTimeout;
  9599. _logger.logger.log('loading playlist for ' + context.type + ' ' + (context.level || context.id));
  9600. }
  9601. loader = this.loaders[context.type] = context.loader = typeof config.pLoader !== 'undefined' ? new config.pLoader(config) : new config.loader(config);
  9602. context.url = url;
  9603. context.responseType = '';
  9604. var loaderConfig = void 0,
  9605. loaderCallbacks = void 0;
  9606. loaderConfig = { timeout: timeout, maxRetry: retry, retryDelay: retryDelay, maxRetryDelay: maxRetryDelay };
  9607. loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) };
  9608. loader.load(context, loaderConfig, loaderCallbacks);
  9609. }
  9610. }, {
  9611. key: 'resolve',
  9612. value: function resolve(url, baseUrl) {
  9613. return _urlToolkit2.default.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });
  9614. }
  9615. }, {
  9616. key: 'parseMasterPlaylist',
  9617. value: function parseMasterPlaylist(string, baseurl) {
  9618. var levels = [],
  9619. result = void 0;
  9620. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  9621. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  9622. var level = {};
  9623. var attrs = level.attrs = new _attrList2.default(result[1]);
  9624. level.url = this.resolve(result[2], baseurl);
  9625. var resolution = attrs.decimalResolution('RESOLUTION');
  9626. if (resolution) {
  9627. level.width = resolution.width;
  9628. level.height = resolution.height;
  9629. }
  9630. level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');
  9631. level.name = attrs.NAME;
  9632. var codecs = attrs.CODECS;
  9633. if (codecs) {
  9634. codecs = codecs.split(/[ ,]+/);
  9635. for (var i = 0; i < codecs.length; i++) {
  9636. var codec = codecs[i];
  9637. if (codec.indexOf('avc1') !== -1) {
  9638. level.videoCodec = this.avc1toavcoti(codec);
  9639. } else {
  9640. level.audioCodec = codec;
  9641. }
  9642. }
  9643. }
  9644. levels.push(level);
  9645. }
  9646. return levels;
  9647. }
  9648. }, {
  9649. key: 'parseMasterPlaylistMedia',
  9650. value: function parseMasterPlaylistMedia(string, baseurl, type) {
  9651. var result = void 0,
  9652. medias = [],
  9653. id = 0;
  9654. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  9655. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) != null) {
  9656. var media = {};
  9657. var attrs = new _attrList2.default(result[1]);
  9658. if (attrs.TYPE === type) {
  9659. media.groupId = attrs['GROUP-ID'];
  9660. media.name = attrs.NAME;
  9661. media.type = type;
  9662. media.default = attrs.DEFAULT === 'YES';
  9663. media.autoselect = attrs.AUTOSELECT === 'YES';
  9664. media.forced = attrs.FORCED === 'YES';
  9665. if (attrs.URI) {
  9666. media.url = this.resolve(attrs.URI, baseurl);
  9667. }
  9668. media.lang = attrs.LANGUAGE;
  9669. if (!media.name) {
  9670. media.name = media.lang;
  9671. }
  9672. media.id = id++;
  9673. medias.push(media);
  9674. }
  9675. }
  9676. return medias;
  9677. }
  9678. }, {
  9679. key: 'avc1toavcoti',
  9680. value: function avc1toavcoti(codec) {
  9681. var result,
  9682. avcdata = codec.split('.');
  9683. if (avcdata.length > 2) {
  9684. result = avcdata.shift() + '.';
  9685. result += parseInt(avcdata.shift()).toString(16);
  9686. result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
  9687. } else {
  9688. result = codec;
  9689. }
  9690. return result;
  9691. }
  9692. }, {
  9693. key: 'parseLevelPlaylist',
  9694. value: function parseLevelPlaylist(string, baseurl, id, type) {
  9695. var currentSN = 0,
  9696. totalduration = 0,
  9697. level = { type: null, version: null, url: baseurl, fragments: [], live: true, startSN: 0 },
  9698. levelkey = new LevelKey(),
  9699. cc = 0,
  9700. prevFrag = null,
  9701. frag = new Fragment(),
  9702. result,
  9703. i;
  9704. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  9705. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  9706. var duration = result[1];
  9707. if (duration) {
  9708. // INF
  9709. frag.duration = parseFloat(duration);
  9710. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  9711. var title = (' ' + result[2]).slice(1);
  9712. frag.title = title ? title : null;
  9713. frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
  9714. } else if (result[3]) {
  9715. // url
  9716. if (!isNaN(frag.duration)) {
  9717. var sn = currentSN++;
  9718. frag.type = type;
  9719. frag.start = totalduration;
  9720. frag.levelkey = levelkey;
  9721. frag.sn = sn;
  9722. frag.level = id;
  9723. frag.cc = cc;
  9724. frag.baseurl = baseurl;
  9725. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  9726. frag.relurl = (' ' + result[3]).slice(1);
  9727. level.fragments.push(frag);
  9728. prevFrag = frag;
  9729. totalduration += frag.duration;
  9730. frag = new Fragment();
  9731. }
  9732. } else if (result[4]) {
  9733. // X-BYTERANGE
  9734. frag.rawByteRange = (' ' + result[4]).slice(1);
  9735. if (prevFrag) {
  9736. var lastByteRangeEndOffset = prevFrag.byteRangeEndOffset;
  9737. if (lastByteRangeEndOffset) {
  9738. frag.lastByteRangeEndOffset = lastByteRangeEndOffset;
  9739. }
  9740. }
  9741. } else if (result[5]) {
  9742. // PROGRAM-DATE-TIME
  9743. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  9744. frag.rawProgramDateTime = (' ' + result[5]).slice(1);
  9745. frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
  9746. } else {
  9747. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  9748. for (i = 1; i < result.length; i++) {
  9749. if (result[i] !== undefined) {
  9750. break;
  9751. }
  9752. }
  9753. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  9754. var value1 = (' ' + result[i + 1]).slice(1);
  9755. var value2 = (' ' + result[i + 2]).slice(1);
  9756. switch (result[i]) {
  9757. case '#':
  9758. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  9759. break;
  9760. case 'PLAYLIST-TYPE':
  9761. level.type = value1.toUpperCase();
  9762. break;
  9763. case 'MEDIA-SEQUENCE':
  9764. currentSN = level.startSN = parseInt(value1);
  9765. break;
  9766. case 'TARGETDURATION':
  9767. level.targetduration = parseFloat(value1);
  9768. break;
  9769. case 'VERSION':
  9770. level.version = parseInt(value1);
  9771. break;
  9772. case 'EXTM3U':
  9773. break;
  9774. case 'ENDLIST':
  9775. level.live = false;
  9776. break;
  9777. case 'DIS':
  9778. cc++;
  9779. frag.tagList.push(['DIS']);
  9780. break;
  9781. case 'DISCONTINUITY-SEQ':
  9782. cc = parseInt(value1);
  9783. break;
  9784. case 'KEY':
  9785. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4
  9786. var decryptparams = value1;
  9787. var keyAttrs = new _attrList2.default(decryptparams);
  9788. var decryptmethod = keyAttrs.enumeratedString('METHOD'),
  9789. decrypturi = keyAttrs.URI,
  9790. decryptiv = keyAttrs.hexadecimalInteger('IV');
  9791. if (decryptmethod) {
  9792. levelkey = new LevelKey();
  9793. if (decrypturi && ['AES-128', 'SAMPLE-AES'].indexOf(decryptmethod) >= 0) {
  9794. levelkey.method = decryptmethod;
  9795. // URI to get the key
  9796. levelkey.baseuri = baseurl;
  9797. levelkey.reluri = decrypturi;
  9798. levelkey.key = null;
  9799. // Initialization Vector (IV)
  9800. levelkey.iv = decryptiv;
  9801. }
  9802. }
  9803. break;
  9804. case 'START':
  9805. var startParams = value1;
  9806. var startAttrs = new _attrList2.default(startParams);
  9807. var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
  9808. //TIME-OFFSET can be 0
  9809. if (!isNaN(startTimeOffset)) {
  9810. level.startTimeOffset = startTimeOffset;
  9811. }
  9812. break;
  9813. case 'MAP':
  9814. var mapAttrs = new _attrList2.default(value1);
  9815. frag.relurl = mapAttrs.URI;
  9816. frag.rawByteRange = mapAttrs.BYTERANGE;
  9817. frag.baseurl = baseurl;
  9818. frag.level = id;
  9819. frag.type = type;
  9820. frag.sn = 'initSegment';
  9821. level.initSegment = frag;
  9822. frag = new Fragment();
  9823. break;
  9824. default:
  9825. _logger.logger.warn('line parsed but not handled: ' + result);
  9826. break;
  9827. }
  9828. }
  9829. }
  9830. frag = prevFrag;
  9831. //logger.log('found ' + level.fragments.length + ' fragments');
  9832. if (frag && !frag.relurl) {
  9833. level.fragments.pop();
  9834. totalduration -= frag.duration;
  9835. }
  9836. level.totalduration = totalduration;
  9837. level.averagetargetduration = totalduration / level.fragments.length;
  9838. level.endSN = currentSN - 1;
  9839. return level;
  9840. }
  9841. }, {
  9842. key: 'loadsuccess',
  9843. value: function loadsuccess(response, stats, context) {
  9844. var string = response.data,
  9845. url = response.url,
  9846. type = context.type,
  9847. id = context.id,
  9848. level = context.level,
  9849. hls = this.hls;
  9850. this.loaders[type] = undefined;
  9851. // responseURL not supported on some browsers (it is used to detect URL redirection)
  9852. // data-uri mode also not supported (but no need to detect redirection)
  9853. if (url === undefined || url.indexOf('data:') === 0) {
  9854. // fallback to initial URL
  9855. url = context.url;
  9856. }
  9857. stats.tload = performance.now();
  9858. //stats.mtime = new Date(target.getResponseHeader('Last-Modified'));
  9859. if (string.indexOf('#EXTM3U') === 0) {
  9860. if (string.indexOf('#EXTINF:') > 0) {
  9861. var isLevel = type !== 'audioTrack' && type !== 'subtitleTrack',
  9862. levelId = !isNaN(level) ? level : !isNaN(id) ? id : 0,
  9863. levelDetails = this.parseLevelPlaylist(string, url, levelId, type === 'audioTrack' ? 'audio' : type === 'subtitleTrack' ? 'subtitle' : 'main');
  9864. levelDetails.tload = stats.tload;
  9865. if (type === 'manifest') {
  9866. // first request, stream manifest (no master playlist), fire manifest loaded event with level details
  9867. hls.trigger(_events2.default.MANIFEST_LOADED, { levels: [{ url: url, details: levelDetails }], audioTracks: [], url: url, stats: stats });
  9868. }
  9869. stats.tparsed = performance.now();
  9870. if (levelDetails.targetduration) {
  9871. if (isLevel) {
  9872. hls.trigger(_events2.default.LEVEL_LOADED, { details: levelDetails, level: level || 0, id: id || 0, stats: stats });
  9873. } else {
  9874. if (type === 'audioTrack') {
  9875. hls.trigger(_events2.default.AUDIO_TRACK_LOADED, { details: levelDetails, id: id, stats: stats });
  9876. } else if (type === 'subtitleTrack') {
  9877. hls.trigger(_events2.default.SUBTITLE_TRACK_LOADED, { details: levelDetails, id: id, stats: stats });
  9878. }
  9879. }
  9880. } else {
  9881. hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'invalid targetduration' });
  9882. }
  9883. } else {
  9884. var levels = this.parseMasterPlaylist(string, url);
  9885. // multi level playlist, parse level info
  9886. if (levels.length) {
  9887. var audioTracks = this.parseMasterPlaylistMedia(string, url, 'AUDIO');
  9888. var subtitles = this.parseMasterPlaylistMedia(string, url, 'SUBTITLES');
  9889. if (audioTracks.length) {
  9890. // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
  9891. var embeddedAudioFound = false;
  9892. audioTracks.forEach(function (audioTrack) {
  9893. if (!audioTrack.url) {
  9894. embeddedAudioFound = true;
  9895. }
  9896. });
  9897. // if no embedded audio track defined, but audio codec signaled in quality level, we need to signal this main audio track
  9898. // 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
  9899. if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  9900. _logger.logger.log('audio codec signaled in quality level, but no embedded audio track signaled, create one');
  9901. audioTracks.unshift({ type: 'main', name: 'main' });
  9902. }
  9903. }
  9904. hls.trigger(_events2.default.MANIFEST_LOADED, { levels: levels, audioTracks: audioTracks, subtitles: subtitles, url: url, stats: stats });
  9905. } else {
  9906. hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no level found in manifest' });
  9907. }
  9908. }
  9909. } else {
  9910. hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no EXTM3U delimiter' });
  9911. }
  9912. }
  9913. }, {
  9914. key: 'loaderror',
  9915. value: function loaderror(response, context) {
  9916. var details,
  9917. fatal,
  9918. loader = context.loader;
  9919. switch (context.type) {
  9920. case 'manifest':
  9921. details = _errors.ErrorDetails.MANIFEST_LOAD_ERROR;
  9922. fatal = true;
  9923. break;
  9924. case 'level':
  9925. details = _errors.ErrorDetails.LEVEL_LOAD_ERROR;
  9926. fatal = false;
  9927. break;
  9928. case 'audioTrack':
  9929. details = _errors.ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  9930. fatal = false;
  9931. break;
  9932. }
  9933. if (loader) {
  9934. loader.abort();
  9935. this.loaders[context.type] = undefined;
  9936. }
  9937. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: loader.url, loader: loader, response: response, context: context });
  9938. }
  9939. }, {
  9940. key: 'loadtimeout',
  9941. value: function loadtimeout(stats, context) {
  9942. var details,
  9943. fatal,
  9944. loader = context.loader;
  9945. switch (context.type) {
  9946. case 'manifest':
  9947. details = _errors.ErrorDetails.MANIFEST_LOAD_TIMEOUT;
  9948. fatal = true;
  9949. break;
  9950. case 'level':
  9951. details = _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT;
  9952. fatal = false;
  9953. break;
  9954. case 'audioTrack':
  9955. details = _errors.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT;
  9956. fatal = false;
  9957. break;
  9958. }
  9959. if (loader) {
  9960. loader.abort();
  9961. this.loaders[context.type] = undefined;
  9962. }
  9963. this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: loader.url, loader: loader, context: context });
  9964. }
  9965. }]);
  9966. return PlaylistLoader;
  9967. }(_eventHandler2.default);
  9968. exports.default = PlaylistLoader;
  9969. },{"2":2,"30":30,"31":31,"32":32,"44":44,"50":50}],41:[function(_dereq_,module,exports){
  9970. 'use strict';
  9971. Object.defineProperty(exports, "__esModule", {
  9972. value: true
  9973. });
  9974. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  9975. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9976. /**
  9977. * Generate MP4 Box
  9978. */
  9979. //import Hex from '../utils/hex';
  9980. var UINT32_MAX = Math.pow(2, 32) - 1;
  9981. var MP4 = function () {
  9982. function MP4() {
  9983. _classCallCheck(this, MP4);
  9984. }
  9985. _createClass(MP4, null, [{
  9986. key: 'init',
  9987. value: function init() {
  9988. MP4.types = {
  9989. avc1: [], // codingname
  9990. avcC: [],
  9991. btrt: [],
  9992. dinf: [],
  9993. dref: [],
  9994. esds: [],
  9995. ftyp: [],
  9996. hdlr: [],
  9997. mdat: [],
  9998. mdhd: [],
  9999. mdia: [],
  10000. mfhd: [],
  10001. minf: [],
  10002. moof: [],
  10003. moov: [],
  10004. mp4a: [],
  10005. '.mp3': [],
  10006. mvex: [],
  10007. mvhd: [],
  10008. pasp: [],
  10009. sdtp: [],
  10010. stbl: [],
  10011. stco: [],
  10012. stsc: [],
  10013. stsd: [],
  10014. stsz: [],
  10015. stts: [],
  10016. tfdt: [],
  10017. tfhd: [],
  10018. traf: [],
  10019. trak: [],
  10020. trun: [],
  10021. trex: [],
  10022. tkhd: [],
  10023. vmhd: [],
  10024. smhd: []
  10025. };
  10026. var i;
  10027. for (i in MP4.types) {
  10028. if (MP4.types.hasOwnProperty(i)) {
  10029. MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  10030. }
  10031. }
  10032. var videoHdlr = new Uint8Array([0x00, // version 0
  10033. 0x00, 0x00, 0x00, // flags
  10034. 0x00, 0x00, 0x00, 0x00, // pre_defined
  10035. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  10036. 0x00, 0x00, 0x00, 0x00, // reserved
  10037. 0x00, 0x00, 0x00, 0x00, // reserved
  10038. 0x00, 0x00, 0x00, 0x00, // reserved
  10039. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  10040. ]);
  10041. var audioHdlr = new Uint8Array([0x00, // version 0
  10042. 0x00, 0x00, 0x00, // flags
  10043. 0x00, 0x00, 0x00, 0x00, // pre_defined
  10044. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  10045. 0x00, 0x00, 0x00, 0x00, // reserved
  10046. 0x00, 0x00, 0x00, 0x00, // reserved
  10047. 0x00, 0x00, 0x00, 0x00, // reserved
  10048. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  10049. ]);
  10050. MP4.HDLR_TYPES = {
  10051. 'video': videoHdlr,
  10052. 'audio': audioHdlr
  10053. };
  10054. var dref = new Uint8Array([0x00, // version 0
  10055. 0x00, 0x00, 0x00, // flags
  10056. 0x00, 0x00, 0x00, 0x01, // entry_count
  10057. 0x00, 0x00, 0x00, 0x0c, // entry_size
  10058. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  10059. 0x00, // version 0
  10060. 0x00, 0x00, 0x01 // entry_flags
  10061. ]);
  10062. var stco = new Uint8Array([0x00, // version
  10063. 0x00, 0x00, 0x00, // flags
  10064. 0x00, 0x00, 0x00, 0x00 // entry_count
  10065. ]);
  10066. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  10067. MP4.STSZ = new Uint8Array([0x00, // version
  10068. 0x00, 0x00, 0x00, // flags
  10069. 0x00, 0x00, 0x00, 0x00, // sample_size
  10070. 0x00, 0x00, 0x00, 0x00]);
  10071. MP4.VMHD = new Uint8Array([0x00, // version
  10072. 0x00, 0x00, 0x01, // flags
  10073. 0x00, 0x00, // graphicsmode
  10074. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  10075. ]);
  10076. MP4.SMHD = new Uint8Array([0x00, // version
  10077. 0x00, 0x00, 0x00, // flags
  10078. 0x00, 0x00, // balance
  10079. 0x00, 0x00 // reserved
  10080. ]);
  10081. MP4.STSD = new Uint8Array([0x00, // version 0
  10082. 0x00, 0x00, 0x00, // flags
  10083. 0x00, 0x00, 0x00, 0x01]); // entry_count
  10084. var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
  10085. var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
  10086. var minorVersion = new Uint8Array([0, 0, 0, 1]);
  10087. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  10088. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  10089. }
  10090. }, {
  10091. key: 'box',
  10092. value: function box(type) {
  10093. var payload = Array.prototype.slice.call(arguments, 1),
  10094. size = 8,
  10095. i = payload.length,
  10096. len = i,
  10097. result;
  10098. // calculate the total size we need to allocate
  10099. while (i--) {
  10100. size += payload[i].byteLength;
  10101. }
  10102. result = new Uint8Array(size);
  10103. result[0] = size >> 24 & 0xff;
  10104. result[1] = size >> 16 & 0xff;
  10105. result[2] = size >> 8 & 0xff;
  10106. result[3] = size & 0xff;
  10107. result.set(type, 4);
  10108. // copy the payload into the result
  10109. for (i = 0, size = 8; i < len; i++) {
  10110. // copy payload[i] array @ offset size
  10111. result.set(payload[i], size);
  10112. size += payload[i].byteLength;
  10113. }
  10114. return result;
  10115. }
  10116. }, {
  10117. key: 'hdlr',
  10118. value: function hdlr(type) {
  10119. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  10120. }
  10121. }, {
  10122. key: 'mdat',
  10123. value: function mdat(data) {
  10124. return MP4.box(MP4.types.mdat, data);
  10125. }
  10126. }, {
  10127. key: 'mdhd',
  10128. value: function mdhd(timescale, duration) {
  10129. duration *= timescale;
  10130. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  10131. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  10132. return MP4.box(MP4.types.mdhd, new Uint8Array([0x01, // version 1
  10133. 0x00, 0x00, 0x00, // flags
  10134. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
  10135. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
  10136. timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
  10137. 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)
  10138. 0x00, 0x00]));
  10139. }
  10140. }, {
  10141. key: 'mdia',
  10142. value: function mdia(track) {
  10143. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
  10144. }
  10145. }, {
  10146. key: 'mfhd',
  10147. value: function mfhd(sequenceNumber) {
  10148. return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
  10149. sequenceNumber >> 24, sequenceNumber >> 16 & 0xFF, sequenceNumber >> 8 & 0xFF, sequenceNumber & 0xFF]));
  10150. }
  10151. }, {
  10152. key: 'minf',
  10153. value: function minf(track) {
  10154. if (track.type === 'audio') {
  10155. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  10156. } else {
  10157. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  10158. }
  10159. }
  10160. }, {
  10161. key: 'moof',
  10162. value: function moof(sn, baseMediaDecodeTime, track) {
  10163. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  10164. }
  10165. /**
  10166. * @param tracks... (optional) {array} the tracks associated with this movie
  10167. */
  10168. }, {
  10169. key: 'moov',
  10170. value: function moov(tracks) {
  10171. var i = tracks.length,
  10172. boxes = [];
  10173. while (i--) {
  10174. boxes[i] = MP4.trak(tracks[i]);
  10175. }
  10176. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
  10177. }
  10178. }, {
  10179. key: 'mvex',
  10180. value: function mvex(tracks) {
  10181. var i = tracks.length,
  10182. boxes = [];
  10183. while (i--) {
  10184. boxes[i] = MP4.trex(tracks[i]);
  10185. }
  10186. return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
  10187. }
  10188. }, {
  10189. key: 'mvhd',
  10190. value: function mvhd(timescale, duration) {
  10191. duration *= timescale;
  10192. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  10193. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  10194. var bytes = new Uint8Array([0x01, // version 1
  10195. 0x00, 0x00, 0x00, // flags
  10196. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
  10197. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
  10198. timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
  10199. 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
  10200. 0x01, 0x00, // 1.0 volume
  10201. 0x00, 0x00, // reserved
  10202. 0x00, 0x00, 0x00, 0x00, // reserved
  10203. 0x00, 0x00, 0x00, 0x00, // reserved
  10204. 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
  10205. 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
  10206. 0xff, 0xff, 0xff, 0xff // next_track_ID
  10207. ]);
  10208. return MP4.box(MP4.types.mvhd, bytes);
  10209. }
  10210. }, {
  10211. key: 'sdtp',
  10212. value: function sdtp(track) {
  10213. var samples = track.samples || [],
  10214. bytes = new Uint8Array(4 + samples.length),
  10215. flags,
  10216. i;
  10217. // leave the full box header (4 bytes) all zero
  10218. // write the sample table
  10219. for (i = 0; i < samples.length; i++) {
  10220. flags = samples[i].flags;
  10221. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  10222. }
  10223. return MP4.box(MP4.types.sdtp, bytes);
  10224. }
  10225. }, {
  10226. key: 'stbl',
  10227. value: function stbl(track) {
  10228. 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));
  10229. }
  10230. }, {
  10231. key: 'avc1',
  10232. value: function avc1(track) {
  10233. var sps = [],
  10234. pps = [],
  10235. i,
  10236. data,
  10237. len;
  10238. // assemble the SPSs
  10239. for (i = 0; i < track.sps.length; i++) {
  10240. data = track.sps[i];
  10241. len = data.byteLength;
  10242. sps.push(len >>> 8 & 0xFF);
  10243. sps.push(len & 0xFF);
  10244. sps = sps.concat(Array.prototype.slice.call(data)); // SPS
  10245. }
  10246. // assemble the PPSs
  10247. for (i = 0; i < track.pps.length; i++) {
  10248. data = track.pps[i];
  10249. len = data.byteLength;
  10250. pps.push(len >>> 8 & 0xFF);
  10251. pps.push(len & 0xFF);
  10252. pps = pps.concat(Array.prototype.slice.call(data));
  10253. }
  10254. var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version
  10255. sps[3], // profile
  10256. sps[4], // profile compat
  10257. sps[5], // level
  10258. 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes
  10259. 0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
  10260. ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
  10261. ]).concat(pps))),
  10262. // "PPS"
  10263. width = track.width,
  10264. height = track.height,
  10265. hSpacing = track.pixelRatio[0],
  10266. vSpacing = track.pixelRatio[1];
  10267. //console.log('avcc:' + Hex.hexDump(avcc));
  10268. return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved
  10269. 0x00, 0x00, 0x00, // reserved
  10270. 0x00, 0x01, // data_reference_index
  10271. 0x00, 0x00, // pre_defined
  10272. 0x00, 0x00, // reserved
  10273. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  10274. width >> 8 & 0xFF, width & 0xff, // width
  10275. height >> 8 & 0xFF, height & 0xff, // height
  10276. 0x00, 0x48, 0x00, 0x00, // horizresolution
  10277. 0x00, 0x48, 0x00, 0x00, // vertresolution
  10278. 0x00, 0x00, 0x00, 0x00, // reserved
  10279. 0x00, 0x01, // frame_count
  10280. 0x12, 0x64, 0x61, 0x69, 0x6C, //dailymotion/hls.js
  10281. 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
  10282. 0x00, 0x18, // depth = 24
  10283. 0x11, 0x11]), // pre_defined = -1
  10284. avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  10285. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  10286. 0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate
  10287. MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24, // hSpacing
  10288. hSpacing >> 16 & 0xFF, hSpacing >> 8 & 0xFF, hSpacing & 0xFF, vSpacing >> 24, // vSpacing
  10289. vSpacing >> 16 & 0xFF, vSpacing >> 8 & 0xFF, vSpacing & 0xFF])));
  10290. }
  10291. }, {
  10292. key: 'esds',
  10293. value: function esds(track) {
  10294. var configlen = track.config.length;
  10295. return new Uint8Array([0x00, // version 0
  10296. 0x00, 0x00, 0x00, // flags
  10297. 0x03, // descriptor_type
  10298. 0x17 + configlen, // length
  10299. 0x00, 0x01, //es_id
  10300. 0x00, // stream_priority
  10301. 0x04, // descriptor_type
  10302. 0x0f + configlen, // length
  10303. 0x40, //codec : mpeg4_audio
  10304. 0x15, // stream_type
  10305. 0x00, 0x00, 0x00, // buffer_size
  10306. 0x00, 0x00, 0x00, 0x00, // maxBitrate
  10307. 0x00, 0x00, 0x00, 0x00, // avgBitrate
  10308. 0x05 // descriptor_type
  10309. ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
  10310. }
  10311. }, {
  10312. key: 'mp4a',
  10313. value: function mp4a(track) {
  10314. var samplerate = track.samplerate;
  10315. return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved
  10316. 0x00, 0x00, 0x00, // reserved
  10317. 0x00, 0x01, // data_reference_index
  10318. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  10319. 0x00, track.channelCount, // channelcount
  10320. 0x00, 0x10, // sampleSize:16bits
  10321. 0x00, 0x00, 0x00, 0x00, // reserved2
  10322. samplerate >> 8 & 0xFF, samplerate & 0xff, //
  10323. 0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
  10324. }
  10325. }, {
  10326. key: 'mp3',
  10327. value: function mp3(track) {
  10328. var samplerate = track.samplerate;
  10329. return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved
  10330. 0x00, 0x00, 0x00, // reserved
  10331. 0x00, 0x01, // data_reference_index
  10332. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  10333. 0x00, track.channelCount, // channelcount
  10334. 0x00, 0x10, // sampleSize:16bits
  10335. 0x00, 0x00, 0x00, 0x00, // reserved2
  10336. samplerate >> 8 & 0xFF, samplerate & 0xff, //
  10337. 0x00, 0x00]));
  10338. }
  10339. }, {
  10340. key: 'stsd',
  10341. value: function stsd(track) {
  10342. if (track.type === 'audio') {
  10343. if (!track.isAAC && track.codec === 'mp3') {
  10344. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  10345. }
  10346. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  10347. } else {
  10348. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  10349. }
  10350. }
  10351. }, {
  10352. key: 'tkhd',
  10353. value: function tkhd(track) {
  10354. var id = track.id,
  10355. duration = track.duration * track.timescale,
  10356. width = track.width,
  10357. height = track.height,
  10358. upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)),
  10359. lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  10360. return MP4.box(MP4.types.tkhd, new Uint8Array([0x01, // version 1
  10361. 0x00, 0x00, 0x07, // flags
  10362. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
  10363. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
  10364. id >> 24 & 0xFF, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID
  10365. 0x00, 0x00, 0x00, 0x00, // reserved
  10366. 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
  10367. 0x00, 0x00, // layer
  10368. 0x00, 0x00, // alternate_group
  10369. 0x00, 0x00, // non-audio track volume
  10370. 0x00, 0x00, // reserved
  10371. 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
  10372. width >> 8 & 0xFF, width & 0xFF, 0x00, 0x00, // width
  10373. height >> 8 & 0xFF, height & 0xFF, 0x00, 0x00 // height
  10374. ]));
  10375. }
  10376. }, {
  10377. key: 'traf',
  10378. value: function traf(track, baseMediaDecodeTime) {
  10379. var sampleDependencyTable = MP4.sdtp(track),
  10380. id = track.id,
  10381. upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)),
  10382. lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  10383. return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0
  10384. 0x00, 0x00, 0x00, // flags
  10385. id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1
  10386. 0x00, 0x00, 0x00, // flags
  10387. 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
  10388. 20 + // tfdt
  10389. 8 + // traf header
  10390. 16 + // mfhd
  10391. 8 + // moof header
  10392. 8), // mdat header
  10393. sampleDependencyTable);
  10394. }
  10395. /**
  10396. * Generate a track box.
  10397. * @param track {object} a track definition
  10398. * @return {Uint8Array} the track box
  10399. */
  10400. }, {
  10401. key: 'trak',
  10402. value: function trak(track) {
  10403. track.duration = track.duration || 0xffffffff;
  10404. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  10405. }
  10406. }, {
  10407. key: 'trex',
  10408. value: function trex(track) {
  10409. var id = track.id;
  10410. return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0
  10411. 0x00, 0x00, 0x00, // flags
  10412. id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF, // track_ID
  10413. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  10414. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  10415. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  10416. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  10417. ]));
  10418. }
  10419. }, {
  10420. key: 'trun',
  10421. value: function trun(track, offset) {
  10422. var samples = track.samples || [],
  10423. len = samples.length,
  10424. arraylen = 12 + 16 * len,
  10425. array = new Uint8Array(arraylen),
  10426. i,
  10427. sample,
  10428. duration,
  10429. size,
  10430. flags,
  10431. cts;
  10432. offset += 8 + arraylen;
  10433. array.set([0x00, // version 0
  10434. 0x00, 0x0f, 0x01, // flags
  10435. len >>> 24 & 0xFF, len >>> 16 & 0xFF, len >>> 8 & 0xFF, len & 0xFF, // sample_count
  10436. offset >>> 24 & 0xFF, offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF // data_offset
  10437. ], 0);
  10438. for (i = 0; i < len; i++) {
  10439. sample = samples[i];
  10440. duration = sample.duration;
  10441. size = sample.size;
  10442. flags = sample.flags;
  10443. cts = sample.cts;
  10444. array.set([duration >>> 24 & 0xFF, duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, // sample_duration
  10445. size >>> 24 & 0xFF, size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, // sample_size
  10446. 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
  10447. cts >>> 24 & 0xFF, cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF // sample_composition_time_offset
  10448. ], 12 + 16 * i);
  10449. }
  10450. return MP4.box(MP4.types.trun, array);
  10451. }
  10452. }, {
  10453. key: 'initSegment',
  10454. value: function initSegment(tracks) {
  10455. if (!MP4.types) {
  10456. MP4.init();
  10457. }
  10458. var movie = MP4.moov(tracks),
  10459. result;
  10460. result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
  10461. result.set(MP4.FTYP);
  10462. result.set(movie, MP4.FTYP.byteLength);
  10463. return result;
  10464. }
  10465. }]);
  10466. return MP4;
  10467. }();
  10468. exports.default = MP4;
  10469. },{}],42:[function(_dereq_,module,exports){
  10470. 'use strict';
  10471. Object.defineProperty(exports, "__esModule", {
  10472. value: true
  10473. });
  10474. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  10475. * fMP4 remuxer
  10476. */
  10477. var _aac = _dereq_(33);
  10478. var _aac2 = _interopRequireDefault(_aac);
  10479. var _events = _dereq_(32);
  10480. var _events2 = _interopRequireDefault(_events);
  10481. var _logger = _dereq_(50);
  10482. var _mp4Generator = _dereq_(41);
  10483. var _mp4Generator2 = _interopRequireDefault(_mp4Generator);
  10484. var _errors = _dereq_(30);
  10485. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  10486. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10487. var MP4Remuxer = function () {
  10488. function MP4Remuxer(observer, config, typeSupported, vendor) {
  10489. _classCallCheck(this, MP4Remuxer);
  10490. this.observer = observer;
  10491. this.config = config;
  10492. this.typeSupported = typeSupported;
  10493. var userAgent = navigator.userAgent;
  10494. this.isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS');
  10495. this.ISGenerated = false;
  10496. }
  10497. _createClass(MP4Remuxer, [{
  10498. key: 'destroy',
  10499. value: function destroy() {}
  10500. }, {
  10501. key: 'resetTimeStamp',
  10502. value: function resetTimeStamp(defaultTimeStamp) {
  10503. this._initPTS = this._initDTS = defaultTimeStamp;
  10504. }
  10505. }, {
  10506. key: 'resetInitSegment',
  10507. value: function resetInitSegment() {
  10508. this.ISGenerated = false;
  10509. }
  10510. }, {
  10511. key: 'remux',
  10512. value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  10513. // generate Init Segment if needed
  10514. if (!this.ISGenerated) {
  10515. this.generateIS(audioTrack, videoTrack, timeOffset);
  10516. }
  10517. if (this.ISGenerated) {
  10518. // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is
  10519. // calculated in remuxAudio.
  10520. //logger.log('nb AAC samples:' + audioTrack.samples.length);
  10521. if (audioTrack.samples.length) {
  10522. var audioData = this.remuxAudio(audioTrack, timeOffset, contiguous, accurateTimeOffset);
  10523. //logger.log('nb AVC samples:' + videoTrack.samples.length);
  10524. if (videoTrack.samples.length) {
  10525. var audioTrackLength = void 0;
  10526. if (audioData) {
  10527. audioTrackLength = audioData.endPTS - audioData.startPTS;
  10528. }
  10529. this.remuxVideo(videoTrack, timeOffset, contiguous, audioTrackLength);
  10530. }
  10531. } else {
  10532. var videoData = void 0;
  10533. //logger.log('nb AVC samples:' + videoTrack.samples.length);
  10534. if (videoTrack.samples.length) {
  10535. videoData = this.remuxVideo(videoTrack, timeOffset, contiguous);
  10536. }
  10537. if (videoData && audioTrack.codec) {
  10538. this.remuxEmptyAudio(audioTrack, timeOffset, contiguous, videoData);
  10539. }
  10540. }
  10541. }
  10542. //logger.log('nb ID3 samples:' + audioTrack.samples.length);
  10543. if (id3Track.samples.length) {
  10544. this.remuxID3(id3Track, timeOffset);
  10545. }
  10546. //logger.log('nb ID3 samples:' + audioTrack.samples.length);
  10547. if (textTrack.samples.length) {
  10548. this.remuxText(textTrack, timeOffset);
  10549. }
  10550. //notify end of parsing
  10551. this.observer.trigger(_events2.default.FRAG_PARSED);
  10552. }
  10553. }, {
  10554. key: 'generateIS',
  10555. value: function generateIS(audioTrack, videoTrack, timeOffset) {
  10556. var observer = this.observer,
  10557. audioSamples = audioTrack.samples,
  10558. videoSamples = videoTrack.samples,
  10559. typeSupported = this.typeSupported,
  10560. container = 'audio/mp4',
  10561. tracks = {},
  10562. data = { tracks: tracks },
  10563. computePTSDTS = this._initPTS === undefined,
  10564. initPTS,
  10565. initDTS;
  10566. if (computePTSDTS) {
  10567. initPTS = initDTS = Infinity;
  10568. }
  10569. if (audioTrack.config && audioSamples.length) {
  10570. // let's use audio sampling rate as MP4 time scale.
  10571. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
  10572. // using audio sampling rate here helps having an integer MP4 frame duration
  10573. // this avoids potential rounding issue and AV sync issue
  10574. audioTrack.timescale = audioTrack.samplerate;
  10575. _logger.logger.log('audio sampling rate : ' + audioTrack.samplerate);
  10576. if (!audioTrack.isAAC) {
  10577. if (typeSupported.mpeg) {
  10578. // Chrome and Safari
  10579. container = 'audio/mpeg';
  10580. audioTrack.codec = '';
  10581. } else if (typeSupported.mp3) {
  10582. // Firefox
  10583. audioTrack.codec = 'mp3';
  10584. }
  10585. }
  10586. tracks.audio = {
  10587. container: container,
  10588. codec: audioTrack.codec,
  10589. initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : _mp4Generator2.default.initSegment([audioTrack]),
  10590. metadata: {
  10591. channelCount: audioTrack.channelCount
  10592. }
  10593. };
  10594. if (computePTSDTS) {
  10595. // remember first PTS of this demuxing context. for audio, PTS = DTS
  10596. initPTS = initDTS = audioSamples[0].pts - audioTrack.inputTimeScale * timeOffset;
  10597. }
  10598. }
  10599. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  10600. // let's use input time scale as MP4 video timescale
  10601. // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
  10602. var inputTimeScale = videoTrack.inputTimeScale;
  10603. videoTrack.timescale = inputTimeScale;
  10604. tracks.video = {
  10605. container: 'video/mp4',
  10606. codec: videoTrack.codec,
  10607. initSegment: _mp4Generator2.default.initSegment([videoTrack]),
  10608. metadata: {
  10609. width: videoTrack.width,
  10610. height: videoTrack.height
  10611. }
  10612. };
  10613. if (computePTSDTS) {
  10614. initPTS = Math.min(initPTS, videoSamples[0].pts - inputTimeScale * timeOffset);
  10615. initDTS = Math.min(initDTS, videoSamples[0].dts - inputTimeScale * timeOffset);
  10616. this.observer.trigger(_events2.default.INIT_PTS_FOUND, { initPTS: initPTS });
  10617. }
  10618. }
  10619. if (Object.keys(tracks).length) {
  10620. observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, data);
  10621. this.ISGenerated = true;
  10622. if (computePTSDTS) {
  10623. this._initPTS = initPTS;
  10624. this._initDTS = initDTS;
  10625. }
  10626. } else {
  10627. observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' });
  10628. }
  10629. }
  10630. }, {
  10631. key: 'remuxVideo',
  10632. value: function remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
  10633. var offset = 8,
  10634. timeScale = track.timescale,
  10635. mp4SampleDuration,
  10636. mdat,
  10637. moof,
  10638. firstPTS,
  10639. firstDTS,
  10640. nextDTS,
  10641. lastPTS,
  10642. lastDTS,
  10643. inputSamples = track.samples,
  10644. outputSamples = [],
  10645. nbSamples = inputSamples.length,
  10646. ptsNormalize = this._PTSNormalize,
  10647. initDTS = this._initDTS;
  10648. // for (let i = 0; i < track.samples.length; i++) {
  10649. // let avcSample = track.samples[i];
  10650. // let units = avcSample.units;
  10651. // let unitsString = '';
  10652. // for (let j = 0; j < units.length ; j++) {
  10653. // unitsString += units[j].type + ',';
  10654. // if (units[j].data.length < 500) {
  10655. // unitsString += Hex.hexDump(units[j].data);
  10656. // }
  10657. // }
  10658. // logger.log(avcSample.pts + '/' + avcSample.dts + ',' + unitsString + avcSample.units.length);
  10659. // }
  10660. // sort video samples by DTS then PTS then demux id order
  10661. inputSamples.sort(function (a, b) {
  10662. var deltadts = a.dts - b.dts;
  10663. var deltapts = a.pts - b.pts;
  10664. return deltadts ? deltadts : deltapts ? deltapts : a.id - b.id;
  10665. });
  10666. // handle broken streams with PTS < DTS, tolerance up 200ms (18000 in 90kHz timescale)
  10667. var PTSDTSshift = inputSamples.reduce(function (prev, curr) {
  10668. return Math.max(Math.min(prev, curr.pts - curr.dts), -18000);
  10669. }, 0);
  10670. if (PTSDTSshift < 0) {
  10671. _logger.logger.warn('PTS < DTS detected in video samples, shifting DTS by ' + Math.round(PTSDTSshift / 90) + ' ms to overcome this issue');
  10672. for (var i = 0; i < inputSamples.length; i++) {
  10673. inputSamples[i].dts += PTSDTSshift;
  10674. }
  10675. }
  10676. // PTS is coded on 33bits, and can loop from -2^32 to 2^32
  10677. // ptsNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
  10678. var nextAvcDts = void 0;
  10679. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  10680. if (contiguous) {
  10681. // if parsed fragment is contiguous with last one, let's use last DTS value as reference
  10682. nextAvcDts = this.nextAvcDts;
  10683. } else {
  10684. // if not contiguous, let's use target timeOffset
  10685. nextAvcDts = timeOffset * timeScale;
  10686. }
  10687. // compute first DTS and last DTS, normalize them against reference value
  10688. var sample = inputSamples[0];
  10689. firstDTS = Math.max(ptsNormalize(sample.dts - initDTS, nextAvcDts), 0);
  10690. firstPTS = Math.max(ptsNormalize(sample.pts - initDTS, nextAvcDts), 0);
  10691. // check timestamp continuity accross consecutive fragments (this is to remove inter-fragment gap/hole)
  10692. var delta = Math.round((firstDTS - nextAvcDts) / 90);
  10693. // if fragment are contiguous, detect hole/overlapping between fragments
  10694. if (contiguous) {
  10695. if (delta) {
  10696. if (delta > 1) {
  10697. _logger.logger.log('AVC:' + delta + ' ms hole between fragments detected,filling it');
  10698. } else if (delta < -1) {
  10699. _logger.logger.log('AVC:' + -delta + ' ms overlapping between fragments detected');
  10700. }
  10701. // remove hole/gap : set DTS to next expected DTS
  10702. firstDTS = nextAvcDts;
  10703. inputSamples[0].dts = firstDTS + initDTS;
  10704. // offset PTS as well, ensure that PTS is smaller or equal than new DTS
  10705. firstPTS = Math.max(firstPTS - delta, nextAvcDts);
  10706. inputSamples[0].pts = firstPTS + initDTS;
  10707. _logger.logger.log('Video/PTS/DTS adjusted: ' + Math.round(firstPTS / 90) + '/' + Math.round(firstDTS / 90) + ',delta:' + delta + ' ms');
  10708. }
  10709. }
  10710. nextDTS = firstDTS;
  10711. // compute lastPTS/lastDTS
  10712. sample = inputSamples[inputSamples.length - 1];
  10713. lastDTS = Math.max(ptsNormalize(sample.dts - initDTS, nextAvcDts), 0);
  10714. lastPTS = Math.max(ptsNormalize(sample.pts - initDTS, nextAvcDts), 0);
  10715. lastPTS = Math.max(lastPTS, lastDTS);
  10716. var isSafari = this.isSafari;
  10717. // on Safari let's signal the same sample duration for all samples
  10718. // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
  10719. // set this constant duration as being the avg delta between consecutive DTS.
  10720. if (isSafari) {
  10721. mp4SampleDuration = Math.round((lastDTS - firstDTS) / (inputSamples.length - 1));
  10722. }
  10723. var nbNalu = 0,
  10724. naluLen = 0;
  10725. for (var _i = 0; _i < nbSamples; _i++) {
  10726. // compute total/avc sample length and nb of NAL units
  10727. var _sample = inputSamples[_i],
  10728. units = _sample.units,
  10729. nbUnits = units.length,
  10730. sampleLen = 0;
  10731. for (var j = 0; j < nbUnits; j++) {
  10732. sampleLen += units[j].data.length;
  10733. }
  10734. naluLen += sampleLen;
  10735. nbNalu += nbUnits;
  10736. _sample.length = sampleLen;
  10737. // normalize PTS/DTS
  10738. if (isSafari) {
  10739. // sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples
  10740. _sample.dts = firstDTS + _i * mp4SampleDuration;
  10741. } else {
  10742. // ensure sample monotonic DTS
  10743. _sample.dts = Math.max(ptsNormalize(_sample.dts - initDTS, nextAvcDts), firstDTS);
  10744. }
  10745. // we normalize PTS against nextAvcDts, we also substract initDTS (some streams don't start @ PTS O)
  10746. // and we ensure that computed value is greater or equal than sample DTS
  10747. _sample.pts = Math.max(ptsNormalize(_sample.pts - initDTS, nextAvcDts), _sample.dts);
  10748. }
  10749. /* concatenate the video data and construct the mdat in place
  10750. (need 8 more bytes to fill length and mpdat type) */
  10751. var mdatSize = naluLen + 4 * nbNalu + 8;
  10752. try {
  10753. mdat = new Uint8Array(mdatSize);
  10754. } catch (err) {
  10755. 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 });
  10756. return;
  10757. }
  10758. var view = new DataView(mdat.buffer);
  10759. view.setUint32(0, mdatSize);
  10760. mdat.set(_mp4Generator2.default.types.mdat, 4);
  10761. for (var _i2 = 0; _i2 < nbSamples; _i2++) {
  10762. var avcSample = inputSamples[_i2],
  10763. avcSampleUnits = avcSample.units,
  10764. mp4SampleLength = 0,
  10765. compositionTimeOffset = void 0;
  10766. // convert NALU bitstream to MP4 format (prepend NALU with size field)
  10767. for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) {
  10768. var unit = avcSampleUnits[_j],
  10769. unitData = unit.data,
  10770. unitDataLen = unit.data.byteLength;
  10771. view.setUint32(offset, unitDataLen);
  10772. offset += 4;
  10773. mdat.set(unitData, offset);
  10774. offset += unitDataLen;
  10775. mp4SampleLength += 4 + unitDataLen;
  10776. }
  10777. if (!isSafari) {
  10778. // expected sample duration is the Decoding Timestamp diff of consecutive samples
  10779. if (_i2 < nbSamples - 1) {
  10780. mp4SampleDuration = inputSamples[_i2 + 1].dts - avcSample.dts;
  10781. } else {
  10782. var config = this.config,
  10783. lastFrameDuration = avcSample.dts - inputSamples[_i2 > 0 ? _i2 - 1 : _i2].dts;
  10784. if (config.stretchShortVideoTrack) {
  10785. // In some cases, a segment's audio track duration may exceed the video track duration.
  10786. // Since we've already remuxed audio, and we know how long the audio track is, we look to
  10787. // see if the delta to the next segment is longer than the minimum of maxBufferHole and
  10788. // maxSeekHole. If so, playback would potentially get stuck, so we artificially inflate
  10789. // the duration of the last frame to minimize any potential gap between segments.
  10790. var maxBufferHole = config.maxBufferHole,
  10791. maxSeekHole = config.maxSeekHole,
  10792. gapTolerance = Math.floor(Math.min(maxBufferHole, maxSeekHole) * timeScale),
  10793. deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;
  10794. if (deltaToFrameEnd > gapTolerance) {
  10795. // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
  10796. // frame overlap. maxBufferHole/maxSeekHole should be >> lastFrameDuration anyway.
  10797. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  10798. if (mp4SampleDuration < 0) {
  10799. mp4SampleDuration = lastFrameDuration;
  10800. }
  10801. _logger.logger.log('It is approximately ' + deltaToFrameEnd / 90 + ' ms to the next segment; using duration ' + mp4SampleDuration / 90 + ' ms for the last video frame.');
  10802. } else {
  10803. mp4SampleDuration = lastFrameDuration;
  10804. }
  10805. } else {
  10806. mp4SampleDuration = lastFrameDuration;
  10807. }
  10808. }
  10809. compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);
  10810. } else {
  10811. compositionTimeOffset = Math.max(0, mp4SampleDuration * Math.round((avcSample.pts - avcSample.dts) / mp4SampleDuration));
  10812. }
  10813. //console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');
  10814. outputSamples.push({
  10815. size: mp4SampleLength,
  10816. // constant duration
  10817. duration: mp4SampleDuration,
  10818. cts: compositionTimeOffset,
  10819. flags: {
  10820. isLeading: 0,
  10821. isDependedOn: 0,
  10822. hasRedundancy: 0,
  10823. degradPrio: 0,
  10824. dependsOn: avcSample.key ? 2 : 1,
  10825. isNonSync: avcSample.key ? 0 : 1
  10826. }
  10827. });
  10828. }
  10829. // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
  10830. this.nextAvcDts = lastDTS + mp4SampleDuration;
  10831. var dropped = track.dropped;
  10832. track.len = 0;
  10833. track.nbNalu = 0;
  10834. track.dropped = 0;
  10835. if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
  10836. var flags = outputSamples[0].flags;
  10837. // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue
  10838. // https://code.google.com/p/chromium/issues/detail?id=229412
  10839. flags.dependsOn = 2;
  10840. flags.isNonSync = 0;
  10841. }
  10842. track.samples = outputSamples;
  10843. moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstDTS, track);
  10844. track.samples = [];
  10845. var data = {
  10846. data1: moof,
  10847. data2: mdat,
  10848. startPTS: firstPTS / timeScale,
  10849. endPTS: (lastPTS + mp4SampleDuration) / timeScale,
  10850. startDTS: firstDTS / timeScale,
  10851. endDTS: this.nextAvcDts / timeScale,
  10852. type: 'video',
  10853. nb: outputSamples.length,
  10854. dropped: dropped
  10855. };
  10856. this.observer.trigger(_events2.default.FRAG_PARSING_DATA, data);
  10857. return data;
  10858. }
  10859. }, {
  10860. key: 'remuxAudio',
  10861. value: function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset) {
  10862. var inputTimeScale = track.inputTimeScale,
  10863. mp4timeScale = track.timescale,
  10864. scaleFactor = inputTimeScale / mp4timeScale,
  10865. mp4SampleDuration = track.isAAC ? 1024 : 1152,
  10866. inputSampleDuration = mp4SampleDuration * scaleFactor,
  10867. ptsNormalize = this._PTSNormalize,
  10868. initDTS = this._initDTS,
  10869. rawMPEG = !track.isAAC && this.typeSupported.mpeg;
  10870. var view,
  10871. offset = rawMPEG ? 0 : 8,
  10872. audioSample,
  10873. mp4Sample,
  10874. unit,
  10875. mdat,
  10876. moof,
  10877. firstPTS,
  10878. firstDTS,
  10879. lastDTS,
  10880. pts,
  10881. dts,
  10882. ptsnorm,
  10883. dtsnorm,
  10884. outputSamples = [],
  10885. inputSamples = [],
  10886. fillFrame,
  10887. newStamp,
  10888. nextAudioPts;
  10889. track.samples.sort(function (a, b) {
  10890. return a.pts - b.pts;
  10891. });
  10892. inputSamples = track.samples;
  10893. // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
  10894. // for sake of clarity:
  10895. // consecutive fragments are frags with
  10896. // - less than 100ms gaps between new time offset and next expected PTS OR
  10897. // - less than 20 audio frames distance
  10898. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  10899. // this helps ensuring audio continuity
  10900. // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
  10901. nextAudioPts = this.nextAudioPts;
  10902. contiguous |= inputSamples.length && nextAudioPts && (Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAudioPts - initDTS) < 20 * inputSampleDuration);
  10903. if (!contiguous) {
  10904. // if fragments are not contiguous, let's use timeOffset to compute next Audio PTS
  10905. nextAudioPts = timeOffset * inputTimeScale;
  10906. }
  10907. // If the audio track is missing samples, the frames seem to get "left-shifted" within the
  10908. // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
  10909. // In an effort to prevent this from happening, we inject frames here where there are gaps.
  10910. // When possible, we inject a silent frame; when that's not possible, we duplicate the last
  10911. // frame.
  10912. // only inject/drop audio frames in case time offset is accurate
  10913. if (accurateTimeOffset && track.isAAC) {
  10914. for (var i = 0, nextPtsNorm = nextAudioPts; i < inputSamples.length;) {
  10915. // First, let's see how far off this frame is from where we expect it to be
  10916. var sample = inputSamples[i],
  10917. ptsNorm = ptsNormalize(sample.pts - initDTS, nextAudioPts),
  10918. delta = ptsNorm - nextPtsNorm;
  10919. // If we're overlapping by more than a duration, drop this sample
  10920. if (delta <= -inputSampleDuration) {
  10921. _logger.logger.warn('Dropping 1 audio frame @ ' + (nextPtsNorm / inputTimeScale).toFixed(3) + 's due to ' + Math.abs(1000 * delta / inputTimeScale) + ' ms overlap.');
  10922. inputSamples.splice(i, 1);
  10923. track.len -= sample.unit.length;
  10924. // Don't touch nextPtsNorm or i
  10925. }
  10926. // Otherwise, if we're more than a frame away from where we should be, insert missing frames
  10927. // also only inject silent audio frames if currentTime !== 0 (nextPtsNorm !== 0)
  10928. else if (delta >= inputSampleDuration && nextPtsNorm) {
  10929. var missing = Math.round(delta / inputSampleDuration);
  10930. _logger.logger.warn('Injecting ' + missing + ' audio frame @ ' + (nextPtsNorm / inputTimeScale).toFixed(3) + 's due to ' + 1000 * delta / inputTimeScale + ' ms gap.');
  10931. for (var j = 0; j < missing; j++) {
  10932. newStamp = nextPtsNorm + initDTS;
  10933. newStamp = Math.max(newStamp, initDTS);
  10934. fillFrame = _aac2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  10935. if (!fillFrame) {
  10936. _logger.logger.log('Unable to get silent frame for given audio codec; duplicating last frame instead.');
  10937. fillFrame = sample.unit.subarray();
  10938. }
  10939. inputSamples.splice(i, 0, { unit: fillFrame, pts: newStamp, dts: newStamp });
  10940. track.len += fillFrame.length;
  10941. nextPtsNorm += inputSampleDuration;
  10942. i += 1;
  10943. }
  10944. // Adjust sample to next expected pts
  10945. sample.pts = sample.dts = nextPtsNorm + initDTS;
  10946. nextPtsNorm += inputSampleDuration;
  10947. i += 1;
  10948. }
  10949. // Otherwise, we're within half a frame duration, so just adjust pts
  10950. else {
  10951. if (Math.abs(delta) > 0.1 * inputSampleDuration) {
  10952. //logger.log(`Invalid frame delta ${Math.round(ptsNorm - nextPtsNorm + inputSampleDuration)} at PTS ${Math.round(ptsNorm / 90)} (should be ${Math.round(inputSampleDuration)}).`);
  10953. }
  10954. nextPtsNorm += inputSampleDuration;
  10955. if (i === 0) {
  10956. sample.pts = sample.dts = initDTS + nextAudioPts;
  10957. } else {
  10958. sample.pts = sample.dts = inputSamples[i - 1].pts + inputSampleDuration;
  10959. }
  10960. i += 1;
  10961. }
  10962. }
  10963. }
  10964. for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
  10965. audioSample = inputSamples[_j2];
  10966. unit = audioSample.unit;
  10967. pts = audioSample.pts - initDTS;
  10968. dts = audioSample.dts - initDTS;
  10969. //logger.log(`Audio/PTS:${Math.round(pts/90)}`);
  10970. // if not first sample
  10971. if (lastDTS !== undefined) {
  10972. ptsnorm = ptsNormalize(pts, lastDTS);
  10973. dtsnorm = ptsNormalize(dts, lastDTS);
  10974. mp4Sample.duration = Math.round((dtsnorm - lastDTS) / scaleFactor);
  10975. } else {
  10976. ptsnorm = ptsNormalize(pts, nextAudioPts);
  10977. dtsnorm = ptsNormalize(dts, nextAudioPts);
  10978. var _delta = Math.round(1000 * (ptsnorm - nextAudioPts) / inputTimeScale),
  10979. numMissingFrames = 0;
  10980. // if fragment are contiguous, detect hole/overlapping between fragments
  10981. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  10982. if (contiguous && track.isAAC) {
  10983. // log delta
  10984. if (_delta) {
  10985. if (_delta > 0) {
  10986. numMissingFrames = Math.round((ptsnorm - nextAudioPts) / inputSampleDuration);
  10987. _logger.logger.log(_delta + ' ms hole between AAC samples detected,filling it');
  10988. if (numMissingFrames > 0) {
  10989. fillFrame = _aac2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  10990. if (!fillFrame) {
  10991. fillFrame = unit.subarray();
  10992. }
  10993. track.len += numMissingFrames * fillFrame.length;
  10994. }
  10995. // if we have frame overlap, overlapping for more than half a frame duraion
  10996. } else if (_delta < -12) {
  10997. // drop overlapping audio frames... browser will deal with it
  10998. _logger.logger.log(-_delta + ' ms overlapping between AAC samples detected, drop frame');
  10999. track.len -= unit.byteLength;
  11000. continue;
  11001. }
  11002. // set PTS/DTS to expected PTS/DTS
  11003. ptsnorm = dtsnorm = nextAudioPts;
  11004. }
  11005. }
  11006. // remember first PTS of our audioSamples, ensure value is positive
  11007. firstPTS = Math.max(0, ptsnorm);
  11008. firstDTS = Math.max(0, dtsnorm);
  11009. if (track.len > 0) {
  11010. /* concatenate the audio data and construct the mdat in place
  11011. (need 8 more bytes to fill length and mdat type) */
  11012. var mdatSize = rawMPEG ? track.len : track.len + 8;
  11013. try {
  11014. mdat = new Uint8Array(mdatSize);
  11015. } catch (err) {
  11016. 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 });
  11017. return;
  11018. }
  11019. if (!rawMPEG) {
  11020. view = new DataView(mdat.buffer);
  11021. view.setUint32(0, mdatSize);
  11022. mdat.set(_mp4Generator2.default.types.mdat, 4);
  11023. }
  11024. } else {
  11025. // no audio samples
  11026. return;
  11027. }
  11028. for (var _i3 = 0; _i3 < numMissingFrames; _i3++) {
  11029. newStamp = ptsnorm - (numMissingFrames - _i3) * inputSampleDuration;
  11030. fillFrame = _aac2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  11031. if (!fillFrame) {
  11032. _logger.logger.log('Unable to get silent frame for given audio codec; duplicating this frame instead.');
  11033. fillFrame = unit.subarray();
  11034. }
  11035. mdat.set(fillFrame, offset);
  11036. offset += fillFrame.byteLength;
  11037. mp4Sample = {
  11038. size: fillFrame.byteLength,
  11039. cts: 0,
  11040. duration: 1024,
  11041. flags: {
  11042. isLeading: 0,
  11043. isDependedOn: 0,
  11044. hasRedundancy: 0,
  11045. degradPrio: 0,
  11046. dependsOn: 1
  11047. }
  11048. };
  11049. outputSamples.push(mp4Sample);
  11050. }
  11051. }
  11052. mdat.set(unit, offset);
  11053. var unitLen = unit.byteLength;
  11054. offset += unitLen;
  11055. //console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${audioSample.pts}/${audioSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(audioSample.pts/4294967296).toFixed(3)}');
  11056. mp4Sample = {
  11057. size: unitLen,
  11058. cts: 0,
  11059. duration: 0,
  11060. flags: {
  11061. isLeading: 0,
  11062. isDependedOn: 0,
  11063. hasRedundancy: 0,
  11064. degradPrio: 0,
  11065. dependsOn: 1
  11066. }
  11067. };
  11068. outputSamples.push(mp4Sample);
  11069. lastDTS = dtsnorm;
  11070. }
  11071. var lastSampleDuration = 0;
  11072. var nbSamples = outputSamples.length;
  11073. //set last sample duration as being identical to previous sample
  11074. if (nbSamples >= 2) {
  11075. lastSampleDuration = outputSamples[nbSamples - 2].duration;
  11076. mp4Sample.duration = lastSampleDuration;
  11077. }
  11078. if (nbSamples) {
  11079. // next audio sample PTS should be equal to last sample PTS + duration
  11080. this.nextAudioPts = ptsnorm + scaleFactor * lastSampleDuration;
  11081. //logger.log('Audio/PTS/PTSend:' + audioSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));
  11082. track.len = 0;
  11083. track.samples = outputSamples;
  11084. if (rawMPEG) {
  11085. moof = new Uint8Array();
  11086. } else {
  11087. moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstDTS / scaleFactor, track);
  11088. }
  11089. track.samples = [];
  11090. var audioData = {
  11091. data1: moof,
  11092. data2: mdat,
  11093. startPTS: firstPTS / inputTimeScale,
  11094. endPTS: this.nextAudioPts / inputTimeScale,
  11095. startDTS: firstDTS / inputTimeScale,
  11096. endDTS: (dtsnorm + scaleFactor * lastSampleDuration) / inputTimeScale,
  11097. type: 'audio',
  11098. nb: nbSamples
  11099. };
  11100. this.observer.trigger(_events2.default.FRAG_PARSING_DATA, audioData);
  11101. return audioData;
  11102. }
  11103. return null;
  11104. }
  11105. }, {
  11106. key: 'remuxEmptyAudio',
  11107. value: function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
  11108. var inputTimeScale = track.inputTimeScale,
  11109. mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale,
  11110. scaleFactor = inputTimeScale / mp4timeScale,
  11111. nextAudioPts = this.nextAudioPts,
  11112. // sync with video's timestamp
  11113. startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS,
  11114. endDTS = videoData.endDTS * inputTimeScale + this._initDTS,
  11115. // one sample's duration value
  11116. sampleDuration = 1024,
  11117. frameDuration = scaleFactor * sampleDuration,
  11118. // samples count of this segment's duration
  11119. nbSamples = Math.ceil((endDTS - startDTS) / frameDuration),
  11120. // silent frame
  11121. silentFrame = _aac2.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  11122. _logger.logger.warn('remux empty Audio');
  11123. // Can't remux if we can't generate a silent frame...
  11124. if (!silentFrame) {
  11125. _logger.logger.trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');
  11126. return;
  11127. }
  11128. var samples = [];
  11129. for (var i = 0; i < nbSamples; i++) {
  11130. var stamp = startDTS + i * frameDuration;
  11131. samples.push({ unit: silentFrame, pts: stamp, dts: stamp });
  11132. track.len += silentFrame.length;
  11133. }
  11134. track.samples = samples;
  11135. this.remuxAudio(track, timeOffset, contiguous);
  11136. }
  11137. }, {
  11138. key: 'remuxID3',
  11139. value: function remuxID3(track, timeOffset) {
  11140. var length = track.samples.length,
  11141. sample;
  11142. var inputTimeScale = track.inputTimeScale;
  11143. var initPTS = this._initPTS;
  11144. var initDTS = this._initDTS;
  11145. // consume samples
  11146. if (length) {
  11147. for (var index = 0; index < length; index++) {
  11148. sample = track.samples[index];
  11149. // setting id3 pts, dts to relative time
  11150. // using this._initPTS and this._initDTS to calculate relative time
  11151. sample.pts = (sample.pts - initPTS) / inputTimeScale;
  11152. sample.dts = (sample.dts - initDTS) / inputTimeScale;
  11153. }
  11154. this.observer.trigger(_events2.default.FRAG_PARSING_METADATA, {
  11155. samples: track.samples
  11156. });
  11157. }
  11158. track.samples = [];
  11159. timeOffset = timeOffset;
  11160. }
  11161. }, {
  11162. key: 'remuxText',
  11163. value: function remuxText(track, timeOffset) {
  11164. track.samples.sort(function (a, b) {
  11165. return a.pts - b.pts;
  11166. });
  11167. var length = track.samples.length,
  11168. sample;
  11169. var inputTimeScale = track.inputTimeScale;
  11170. var initPTS = this._initPTS;
  11171. // consume samples
  11172. if (length) {
  11173. for (var index = 0; index < length; index++) {
  11174. sample = track.samples[index];
  11175. // setting text pts, dts to relative time
  11176. // using this._initPTS and this._initDTS to calculate relative time
  11177. sample.pts = (sample.pts - initPTS) / inputTimeScale;
  11178. }
  11179. this.observer.trigger(_events2.default.FRAG_PARSING_USERDATA, {
  11180. samples: track.samples
  11181. });
  11182. }
  11183. track.samples = [];
  11184. timeOffset = timeOffset;
  11185. }
  11186. }, {
  11187. key: '_PTSNormalize',
  11188. value: function _PTSNormalize(value, reference) {
  11189. var offset;
  11190. if (reference === undefined) {
  11191. return value;
  11192. }
  11193. if (reference < value) {
  11194. // - 2^33
  11195. offset = -8589934592;
  11196. } else {
  11197. // + 2^33
  11198. offset = 8589934592;
  11199. }
  11200. /* PTS is 33bit (from 0 to 2^33 -1)
  11201. if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
  11202. PTS looping occured. fill the gap */
  11203. while (Math.abs(value - reference) > 4294967296) {
  11204. value += offset;
  11205. }
  11206. return value;
  11207. }
  11208. }]);
  11209. return MP4Remuxer;
  11210. }();
  11211. exports.default = MP4Remuxer;
  11212. },{"30":30,"32":32,"33":33,"41":41,"50":50}],43:[function(_dereq_,module,exports){
  11213. 'use strict';
  11214. Object.defineProperty(exports, "__esModule", {
  11215. value: true
  11216. });
  11217. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  11218. * passthrough remuxer
  11219. */
  11220. var _events = _dereq_(32);
  11221. var _events2 = _interopRequireDefault(_events);
  11222. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11223. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  11224. var PassThroughRemuxer = function () {
  11225. function PassThroughRemuxer(observer) {
  11226. _classCallCheck(this, PassThroughRemuxer);
  11227. this.observer = observer;
  11228. }
  11229. _createClass(PassThroughRemuxer, [{
  11230. key: 'destroy',
  11231. value: function destroy() {}
  11232. }, {
  11233. key: 'resetTimeStamp',
  11234. value: function resetTimeStamp() {}
  11235. }, {
  11236. key: 'resetInitSegment',
  11237. value: function resetInitSegment() {}
  11238. }, {
  11239. key: 'remux',
  11240. value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset, rawData) {
  11241. var observer = this.observer;
  11242. var streamType = '';
  11243. if (audioTrack) {
  11244. streamType += 'audio';
  11245. }
  11246. if (videoTrack) {
  11247. streamType += 'video';
  11248. }
  11249. observer.trigger(_events2.default.FRAG_PARSING_DATA, {
  11250. data1: rawData,
  11251. startPTS: timeOffset,
  11252. startDTS: timeOffset,
  11253. type: streamType,
  11254. nb: 1,
  11255. dropped: 0
  11256. });
  11257. //notify end of parsing
  11258. observer.trigger(_events2.default.FRAG_PARSED);
  11259. }
  11260. }]);
  11261. return PassThroughRemuxer;
  11262. }();
  11263. exports.default = PassThroughRemuxer;
  11264. },{"32":32}],44:[function(_dereq_,module,exports){
  11265. 'use strict';
  11266. Object.defineProperty(exports, "__esModule", {
  11267. value: true
  11268. });
  11269. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  11270. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  11271. var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/;
  11272. var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;
  11273. // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
  11274. var AttrList = function () {
  11275. function AttrList(attrs) {
  11276. _classCallCheck(this, AttrList);
  11277. if (typeof attrs === 'string') {
  11278. attrs = AttrList.parseAttrList(attrs);
  11279. }
  11280. for (var attr in attrs) {
  11281. if (attrs.hasOwnProperty(attr)) {
  11282. this[attr] = attrs[attr];
  11283. }
  11284. }
  11285. }
  11286. _createClass(AttrList, [{
  11287. key: 'decimalInteger',
  11288. value: function decimalInteger(attrName) {
  11289. var intValue = parseInt(this[attrName], 10);
  11290. if (intValue > Number.MAX_SAFE_INTEGER) {
  11291. return Infinity;
  11292. }
  11293. return intValue;
  11294. }
  11295. }, {
  11296. key: 'hexadecimalInteger',
  11297. value: function hexadecimalInteger(attrName) {
  11298. if (this[attrName]) {
  11299. var stringValue = (this[attrName] || '0x').slice(2);
  11300. stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
  11301. var value = new Uint8Array(stringValue.length / 2);
  11302. for (var i = 0; i < stringValue.length / 2; i++) {
  11303. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  11304. }
  11305. return value;
  11306. } else {
  11307. return null;
  11308. }
  11309. }
  11310. }, {
  11311. key: 'hexadecimalIntegerAsNumber',
  11312. value: function hexadecimalIntegerAsNumber(attrName) {
  11313. var intValue = parseInt(this[attrName], 16);
  11314. if (intValue > Number.MAX_SAFE_INTEGER) {
  11315. return Infinity;
  11316. }
  11317. return intValue;
  11318. }
  11319. }, {
  11320. key: 'decimalFloatingPoint',
  11321. value: function decimalFloatingPoint(attrName) {
  11322. return parseFloat(this[attrName]);
  11323. }
  11324. }, {
  11325. key: 'enumeratedString',
  11326. value: function enumeratedString(attrName) {
  11327. return this[attrName];
  11328. }
  11329. }, {
  11330. key: 'decimalResolution',
  11331. value: function decimalResolution(attrName) {
  11332. var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  11333. if (res === null) {
  11334. return undefined;
  11335. }
  11336. return {
  11337. width: parseInt(res[1], 10),
  11338. height: parseInt(res[2], 10)
  11339. };
  11340. }
  11341. }], [{
  11342. key: 'parseAttrList',
  11343. value: function parseAttrList(input) {
  11344. var match,
  11345. attrs = {};
  11346. ATTR_LIST_REGEX.lastIndex = 0;
  11347. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  11348. var value = match[2],
  11349. quote = '"';
  11350. if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
  11351. value = value.slice(1, -1);
  11352. }
  11353. attrs[match[1]] = value;
  11354. }
  11355. return attrs;
  11356. }
  11357. }]);
  11358. return AttrList;
  11359. }();
  11360. exports.default = AttrList;
  11361. },{}],45:[function(_dereq_,module,exports){
  11362. "use strict";
  11363. var BinarySearch = {
  11364. /**
  11365. * Searches for an item in an array which matches a certain condition.
  11366. * This requires the condition to only match one item in the array,
  11367. * and for the array to be ordered.
  11368. *
  11369. * @param {Array} list The array to search.
  11370. * @param {Function} comparisonFunction
  11371. * Called and provided a candidate item as the first argument.
  11372. * Should return:
  11373. * > -1 if the item should be located at a lower index than the provided item.
  11374. * > 1 if the item should be located at a higher index than the provided item.
  11375. * > 0 if the item is the item you're looking for.
  11376. *
  11377. * @return {*} The object if it is found or null otherwise.
  11378. */
  11379. search: function search(list, comparisonFunction) {
  11380. var minIndex = 0;
  11381. var maxIndex = list.length - 1;
  11382. var currentIndex = null;
  11383. var currentElement = null;
  11384. while (minIndex <= maxIndex) {
  11385. currentIndex = (minIndex + maxIndex) / 2 | 0;
  11386. currentElement = list[currentIndex];
  11387. var comparisonResult = comparisonFunction(currentElement);
  11388. if (comparisonResult > 0) {
  11389. minIndex = currentIndex + 1;
  11390. } else if (comparisonResult < 0) {
  11391. maxIndex = currentIndex - 1;
  11392. } else {
  11393. return currentElement;
  11394. }
  11395. }
  11396. return null;
  11397. }
  11398. };
  11399. module.exports = BinarySearch;
  11400. },{}],46:[function(_dereq_,module,exports){
  11401. 'use strict';
  11402. Object.defineProperty(exports, "__esModule", {
  11403. value: true
  11404. });
  11405. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  11406. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  11407. /**
  11408. *
  11409. * This code was ported from the dash.js project at:
  11410. * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
  11411. * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
  11412. *
  11413. * The original copyright appears below:
  11414. *
  11415. * The copyright in this software is being made available under the BSD License,
  11416. * included below. This software may be subject to other third party and contributor
  11417. * rights, including patent rights, and no such rights are granted under this license.
  11418. *
  11419. * Copyright (c) 2015-2016, DASH Industry Forum.
  11420. * All rights reserved.
  11421. *
  11422. * Redistribution and use in source and binary forms, with or without modification,
  11423. * are permitted provided that the following conditions are met:
  11424. * 1. Redistributions of source code must retain the above copyright notice, this
  11425. * list of conditions and the following disclaimer.
  11426. * * Redistributions in binary form must reproduce the above copyright notice,
  11427. * this list of conditions and the following disclaimer in the documentation and/or
  11428. * other materials provided with the distribution.
  11429. * 2. Neither the name of Dash Industry Forum nor the names of its
  11430. * contributors may be used to endorse or promote products derived from this software
  11431. * without specific prior written permission.
  11432. *
  11433. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
  11434. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  11435. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  11436. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  11437. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  11438. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  11439. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  11440. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  11441. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  11442. * POSSIBILITY OF SUCH DAMAGE.
  11443. */
  11444. /**
  11445. * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes
  11446. */
  11447. var specialCea608CharsCodes = {
  11448. 0x2a: 0xe1, // lowercase a, acute accent
  11449. 0x5c: 0xe9, // lowercase e, acute accent
  11450. 0x5e: 0xed, // lowercase i, acute accent
  11451. 0x5f: 0xf3, // lowercase o, acute accent
  11452. 0x60: 0xfa, // lowercase u, acute accent
  11453. 0x7b: 0xe7, // lowercase c with cedilla
  11454. 0x7c: 0xf7, // division symbol
  11455. 0x7d: 0xd1, // uppercase N tilde
  11456. 0x7e: 0xf1, // lowercase n tilde
  11457. 0x7f: 0x2588, // Full block
  11458. // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  11459. // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
  11460. // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
  11461. 0x80: 0xae, // Registered symbol (R)
  11462. 0x81: 0xb0, // degree sign
  11463. 0x82: 0xbd, // 1/2 symbol
  11464. 0x83: 0xbf, // Inverted (open) question mark
  11465. 0x84: 0x2122, // Trademark symbol (TM)
  11466. 0x85: 0xa2, // Cents symbol
  11467. 0x86: 0xa3, // Pounds sterling
  11468. 0x87: 0x266a, // Music 8'th note
  11469. 0x88: 0xe0, // lowercase a, grave accent
  11470. 0x89: 0x20, // transparent space (regular)
  11471. 0x8a: 0xe8, // lowercase e, grave accent
  11472. 0x8b: 0xe2, // lowercase a, circumflex accent
  11473. 0x8c: 0xea, // lowercase e, circumflex accent
  11474. 0x8d: 0xee, // lowercase i, circumflex accent
  11475. 0x8e: 0xf4, // lowercase o, circumflex accent
  11476. 0x8f: 0xfb, // lowercase u, circumflex accent
  11477. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  11478. // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
  11479. 0x90: 0xc1, // capital letter A with acute
  11480. 0x91: 0xc9, // capital letter E with acute
  11481. 0x92: 0xd3, // capital letter O with acute
  11482. 0x93: 0xda, // capital letter U with acute
  11483. 0x94: 0xdc, // capital letter U with diaresis
  11484. 0x95: 0xfc, // lowercase letter U with diaeresis
  11485. 0x96: 0x2018, // opening single quote
  11486. 0x97: 0xa1, // inverted exclamation mark
  11487. 0x98: 0x2a, // asterisk
  11488. 0x99: 0x2019, // closing single quote
  11489. 0x9a: 0x2501, // box drawings heavy horizontal
  11490. 0x9b: 0xa9, // copyright sign
  11491. 0x9c: 0x2120, // Service mark
  11492. 0x9d: 0x2022, // (round) bullet
  11493. 0x9e: 0x201c, // Left double quotation mark
  11494. 0x9f: 0x201d, // Right double quotation mark
  11495. 0xa0: 0xc0, // uppercase A, grave accent
  11496. 0xa1: 0xc2, // uppercase A, circumflex
  11497. 0xa2: 0xc7, // uppercase C with cedilla
  11498. 0xa3: 0xc8, // uppercase E, grave accent
  11499. 0xa4: 0xca, // uppercase E, circumflex
  11500. 0xa5: 0xcb, // capital letter E with diaresis
  11501. 0xa6: 0xeb, // lowercase letter e with diaresis
  11502. 0xa7: 0xce, // uppercase I, circumflex
  11503. 0xa8: 0xcf, // uppercase I, with diaresis
  11504. 0xa9: 0xef, // lowercase i, with diaresis
  11505. 0xaa: 0xd4, // uppercase O, circumflex
  11506. 0xab: 0xd9, // uppercase U, grave accent
  11507. 0xac: 0xf9, // lowercase u, grave accent
  11508. 0xad: 0xdb, // uppercase U, circumflex
  11509. 0xae: 0xab, // left-pointing double angle quotation mark
  11510. 0xaf: 0xbb, // right-pointing double angle quotation mark
  11511. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  11512. // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
  11513. 0xb0: 0xc3, // Uppercase A, tilde
  11514. 0xb1: 0xe3, // Lowercase a, tilde
  11515. 0xb2: 0xcd, // Uppercase I, acute accent
  11516. 0xb3: 0xcc, // Uppercase I, grave accent
  11517. 0xb4: 0xec, // Lowercase i, grave accent
  11518. 0xb5: 0xd2, // Uppercase O, grave accent
  11519. 0xb6: 0xf2, // Lowercase o, grave accent
  11520. 0xb7: 0xd5, // Uppercase O, tilde
  11521. 0xb8: 0xf5, // Lowercase o, tilde
  11522. 0xb9: 0x7b, // Open curly brace
  11523. 0xba: 0x7d, // Closing curly brace
  11524. 0xbb: 0x5c, // Backslash
  11525. 0xbc: 0x5e, // Caret
  11526. 0xbd: 0x5f, // Underscore
  11527. 0xbe: 0x7c, // Pipe (vertical line)
  11528. 0xbf: 0x223c, // Tilde operator
  11529. 0xc0: 0xc4, // Uppercase A, umlaut
  11530. 0xc1: 0xe4, // Lowercase A, umlaut
  11531. 0xc2: 0xd6, // Uppercase O, umlaut
  11532. 0xc3: 0xf6, // Lowercase o, umlaut
  11533. 0xc4: 0xdf, // Esszett (sharp S)
  11534. 0xc5: 0xa5, // Yen symbol
  11535. 0xc6: 0xa4, // Generic currency sign
  11536. 0xc7: 0x2503, // Box drawings heavy vertical
  11537. 0xc8: 0xc5, // Uppercase A, ring
  11538. 0xc9: 0xe5, // Lowercase A, ring
  11539. 0xca: 0xd8, // Uppercase O, stroke
  11540. 0xcb: 0xf8, // Lowercase o, strok
  11541. 0xcc: 0x250f, // Box drawings heavy down and right
  11542. 0xcd: 0x2513, // Box drawings heavy down and left
  11543. 0xce: 0x2517, // Box drawings heavy up and right
  11544. 0xcf: 0x251b // Box drawings heavy up and left
  11545. };
  11546. /**
  11547. * Utils
  11548. */
  11549. var getCharForByte = function getCharForByte(byte) {
  11550. var charCode = byte;
  11551. if (specialCea608CharsCodes.hasOwnProperty(byte)) {
  11552. charCode = specialCea608CharsCodes[byte];
  11553. }
  11554. return String.fromCharCode(charCode);
  11555. };
  11556. var NR_ROWS = 15,
  11557. NR_COLS = 100;
  11558. // Tables to look up row from PAC data
  11559. var rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 };
  11560. var rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 };
  11561. var rowsLowCh2 = { 0x19: 1, 0x1A: 3, 0x1D: 5, 0x1E: 7, 0x1F: 9, 0x18: 11, 0x1B: 12, 0x1C: 14 };
  11562. var rowsHighCh2 = { 0x19: 2, 0x1A: 4, 0x1D: 6, 0x1E: 8, 0x1F: 10, 0x1B: 13, 0x1C: 15 };
  11563. var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];
  11564. /**
  11565. * Simple logger class to be able to write with time-stamps and filter on level.
  11566. */
  11567. var logger = {
  11568. verboseFilter: { 'DATA': 3, 'DEBUG': 3, 'INFO': 2, 'WARNING': 2, 'TEXT': 1, 'ERROR': 0 },
  11569. time: null,
  11570. verboseLevel: 0, // Only write errors
  11571. setTime: function setTime(newTime) {
  11572. this.time = newTime;
  11573. },
  11574. log: function log(severity, msg) {
  11575. var minLevel = this.verboseFilter[severity];
  11576. if (this.verboseLevel >= minLevel) {
  11577. console.log(this.time + ' [' + severity + '] ' + msg);
  11578. }
  11579. }
  11580. };
  11581. var numArrayToHexArray = function numArrayToHexArray(numArray) {
  11582. var hexArray = [];
  11583. for (var j = 0; j < numArray.length; j++) {
  11584. hexArray.push(numArray[j].toString(16));
  11585. }
  11586. return hexArray;
  11587. };
  11588. var PenState = function () {
  11589. function PenState(foreground, underline, italics, background, flash) {
  11590. _classCallCheck(this, PenState);
  11591. this.foreground = foreground || 'white';
  11592. this.underline = underline || false;
  11593. this.italics = italics || false;
  11594. this.background = background || 'black';
  11595. this.flash = flash || false;
  11596. }
  11597. _createClass(PenState, [{
  11598. key: 'reset',
  11599. value: function reset() {
  11600. this.foreground = 'white';
  11601. this.underline = false;
  11602. this.italics = false;
  11603. this.background = 'black';
  11604. this.flash = false;
  11605. }
  11606. }, {
  11607. key: 'setStyles',
  11608. value: function setStyles(styles) {
  11609. var attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];
  11610. for (var i = 0; i < attribs.length; i++) {
  11611. var style = attribs[i];
  11612. if (styles.hasOwnProperty(style)) {
  11613. this[style] = styles[style];
  11614. }
  11615. }
  11616. }
  11617. }, {
  11618. key: 'isDefault',
  11619. value: function isDefault() {
  11620. return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;
  11621. }
  11622. }, {
  11623. key: 'equals',
  11624. value: function equals(other) {
  11625. return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
  11626. }
  11627. }, {
  11628. key: 'copy',
  11629. value: function copy(newPenState) {
  11630. this.foreground = newPenState.foreground;
  11631. this.underline = newPenState.underline;
  11632. this.italics = newPenState.italics;
  11633. this.background = newPenState.background;
  11634. this.flash = newPenState.flash;
  11635. }
  11636. }, {
  11637. key: 'toString',
  11638. value: function toString() {
  11639. return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;
  11640. }
  11641. }]);
  11642. return PenState;
  11643. }();
  11644. /**
  11645. * Unicode character with styling and background.
  11646. * @constructor
  11647. */
  11648. var StyledUnicodeChar = function () {
  11649. function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) {
  11650. _classCallCheck(this, StyledUnicodeChar);
  11651. this.uchar = uchar || ' '; // unicode character
  11652. this.penState = new PenState(foreground, underline, italics, background, flash);
  11653. }
  11654. _createClass(StyledUnicodeChar, [{
  11655. key: 'reset',
  11656. value: function reset() {
  11657. this.uchar = ' ';
  11658. this.penState.reset();
  11659. }
  11660. }, {
  11661. key: 'setChar',
  11662. value: function setChar(uchar, newPenState) {
  11663. this.uchar = uchar;
  11664. this.penState.copy(newPenState);
  11665. }
  11666. }, {
  11667. key: 'setPenState',
  11668. value: function setPenState(newPenState) {
  11669. this.penState.copy(newPenState);
  11670. }
  11671. }, {
  11672. key: 'equals',
  11673. value: function equals(other) {
  11674. return this.uchar === other.uchar && this.penState.equals(other.penState);
  11675. }
  11676. }, {
  11677. key: 'copy',
  11678. value: function copy(newChar) {
  11679. this.uchar = newChar.uchar;
  11680. this.penState.copy(newChar.penState);
  11681. }
  11682. }, {
  11683. key: 'isEmpty',
  11684. value: function isEmpty() {
  11685. return this.uchar === ' ' && this.penState.isDefault();
  11686. }
  11687. }]);
  11688. return StyledUnicodeChar;
  11689. }();
  11690. /**
  11691. * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
  11692. * @constructor
  11693. */
  11694. var Row = function () {
  11695. function Row() {
  11696. _classCallCheck(this, Row);
  11697. this.chars = [];
  11698. for (var i = 0; i < NR_COLS; i++) {
  11699. this.chars.push(new StyledUnicodeChar());
  11700. }
  11701. this.pos = 0;
  11702. this.currPenState = new PenState();
  11703. }
  11704. _createClass(Row, [{
  11705. key: 'equals',
  11706. value: function equals(other) {
  11707. var equal = true;
  11708. for (var i = 0; i < NR_COLS; i++) {
  11709. if (!this.chars[i].equals(other.chars[i])) {
  11710. equal = false;
  11711. break;
  11712. }
  11713. }
  11714. return equal;
  11715. }
  11716. }, {
  11717. key: 'copy',
  11718. value: function copy(other) {
  11719. for (var i = 0; i < NR_COLS; i++) {
  11720. this.chars[i].copy(other.chars[i]);
  11721. }
  11722. }
  11723. }, {
  11724. key: 'isEmpty',
  11725. value: function isEmpty() {
  11726. var empty = true;
  11727. for (var i = 0; i < NR_COLS; i++) {
  11728. if (!this.chars[i].isEmpty()) {
  11729. empty = false;
  11730. break;
  11731. }
  11732. }
  11733. return empty;
  11734. }
  11735. /**
  11736. * Set the cursor to a valid column.
  11737. */
  11738. }, {
  11739. key: 'setCursor',
  11740. value: function setCursor(absPos) {
  11741. if (this.pos !== absPos) {
  11742. this.pos = absPos;
  11743. }
  11744. if (this.pos < 0) {
  11745. logger.log('ERROR', 'Negative cursor position ' + this.pos);
  11746. this.pos = 0;
  11747. } else if (this.pos > NR_COLS) {
  11748. logger.log('ERROR', 'Too large cursor position ' + this.pos);
  11749. this.pos = NR_COLS;
  11750. }
  11751. }
  11752. /**
  11753. * Move the cursor relative to current position.
  11754. */
  11755. }, {
  11756. key: 'moveCursor',
  11757. value: function moveCursor(relPos) {
  11758. var newPos = this.pos + relPos;
  11759. if (relPos > 1) {
  11760. for (var i = this.pos + 1; i < newPos + 1; i++) {
  11761. this.chars[i].setPenState(this.currPenState);
  11762. }
  11763. }
  11764. this.setCursor(newPos);
  11765. }
  11766. /**
  11767. * Backspace, move one step back and clear character.
  11768. */
  11769. }, {
  11770. key: 'backSpace',
  11771. value: function backSpace() {
  11772. this.moveCursor(-1);
  11773. this.chars[this.pos].setChar(' ', this.currPenState);
  11774. }
  11775. }, {
  11776. key: 'insertChar',
  11777. value: function insertChar(byte) {
  11778. if (byte >= 0x90) {
  11779. //Extended char
  11780. this.backSpace();
  11781. }
  11782. var char = getCharForByte(byte);
  11783. if (this.pos >= NR_COLS) {
  11784. logger.log('ERROR', 'Cannot insert ' + byte.toString(16) + ' (' + char + ') at position ' + this.pos + '. Skipping it!');
  11785. return;
  11786. }
  11787. this.chars[this.pos].setChar(char, this.currPenState);
  11788. this.moveCursor(1);
  11789. }
  11790. }, {
  11791. key: 'clearFromPos',
  11792. value: function clearFromPos(startPos) {
  11793. var i;
  11794. for (i = startPos; i < NR_COLS; i++) {
  11795. this.chars[i].reset();
  11796. }
  11797. }
  11798. }, {
  11799. key: 'clear',
  11800. value: function clear() {
  11801. this.clearFromPos(0);
  11802. this.pos = 0;
  11803. this.currPenState.reset();
  11804. }
  11805. }, {
  11806. key: 'clearToEndOfRow',
  11807. value: function clearToEndOfRow() {
  11808. this.clearFromPos(this.pos);
  11809. }
  11810. }, {
  11811. key: 'getTextString',
  11812. value: function getTextString() {
  11813. var chars = [];
  11814. var empty = true;
  11815. for (var i = 0; i < NR_COLS; i++) {
  11816. var char = this.chars[i].uchar;
  11817. if (char !== ' ') {
  11818. empty = false;
  11819. }
  11820. chars.push(char);
  11821. }
  11822. if (empty) {
  11823. return '';
  11824. } else {
  11825. return chars.join('');
  11826. }
  11827. }
  11828. }, {
  11829. key: 'setPenStyles',
  11830. value: function setPenStyles(styles) {
  11831. this.currPenState.setStyles(styles);
  11832. var currChar = this.chars[this.pos];
  11833. currChar.setPenState(this.currPenState);
  11834. }
  11835. }]);
  11836. return Row;
  11837. }();
  11838. /**
  11839. * Keep a CEA-608 screen of 32x15 styled characters
  11840. * @constructor
  11841. */
  11842. var CaptionScreen = function () {
  11843. function CaptionScreen() {
  11844. _classCallCheck(this, CaptionScreen);
  11845. this.rows = [];
  11846. for (var i = 0; i < NR_ROWS; i++) {
  11847. this.rows.push(new Row()); // Note that we use zero-based numbering (0-14)
  11848. }
  11849. this.currRow = NR_ROWS - 1;
  11850. this.nrRollUpRows = null;
  11851. this.reset();
  11852. }
  11853. _createClass(CaptionScreen, [{
  11854. key: 'reset',
  11855. value: function reset() {
  11856. for (var i = 0; i < NR_ROWS; i++) {
  11857. this.rows[i].clear();
  11858. }
  11859. this.currRow = NR_ROWS - 1;
  11860. }
  11861. }, {
  11862. key: 'equals',
  11863. value: function equals(other) {
  11864. var equal = true;
  11865. for (var i = 0; i < NR_ROWS; i++) {
  11866. if (!this.rows[i].equals(other.rows[i])) {
  11867. equal = false;
  11868. break;
  11869. }
  11870. }
  11871. return equal;
  11872. }
  11873. }, {
  11874. key: 'copy',
  11875. value: function copy(other) {
  11876. for (var i = 0; i < NR_ROWS; i++) {
  11877. this.rows[i].copy(other.rows[i]);
  11878. }
  11879. }
  11880. }, {
  11881. key: 'isEmpty',
  11882. value: function isEmpty() {
  11883. var empty = true;
  11884. for (var i = 0; i < NR_ROWS; i++) {
  11885. if (!this.rows[i].isEmpty()) {
  11886. empty = false;
  11887. break;
  11888. }
  11889. }
  11890. return empty;
  11891. }
  11892. }, {
  11893. key: 'backSpace',
  11894. value: function backSpace() {
  11895. var row = this.rows[this.currRow];
  11896. row.backSpace();
  11897. }
  11898. }, {
  11899. key: 'clearToEndOfRow',
  11900. value: function clearToEndOfRow() {
  11901. var row = this.rows[this.currRow];
  11902. row.clearToEndOfRow();
  11903. }
  11904. /**
  11905. * Insert a character (without styling) in the current row.
  11906. */
  11907. }, {
  11908. key: 'insertChar',
  11909. value: function insertChar(char) {
  11910. var row = this.rows[this.currRow];
  11911. row.insertChar(char);
  11912. }
  11913. }, {
  11914. key: 'setPen',
  11915. value: function setPen(styles) {
  11916. var row = this.rows[this.currRow];
  11917. row.setPenStyles(styles);
  11918. }
  11919. }, {
  11920. key: 'moveCursor',
  11921. value: function moveCursor(relPos) {
  11922. var row = this.rows[this.currRow];
  11923. row.moveCursor(relPos);
  11924. }
  11925. }, {
  11926. key: 'setCursor',
  11927. value: function setCursor(absPos) {
  11928. logger.log('INFO', 'setCursor: ' + absPos);
  11929. var row = this.rows[this.currRow];
  11930. row.setCursor(absPos);
  11931. }
  11932. }, {
  11933. key: 'setPAC',
  11934. value: function setPAC(pacData) {
  11935. logger.log('INFO', 'pacData = ' + JSON.stringify(pacData));
  11936. var newRow = pacData.row - 1;
  11937. if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
  11938. newRow = this.nrRollUpRows - 1;
  11939. }
  11940. //Make sure this only affects Roll-up Captions by checking this.nrRollUpRows
  11941. if (this.nrRollUpRows && this.currRow !== newRow) {
  11942. //clear all rows first
  11943. for (var i = 0; i < NR_ROWS; i++) {
  11944. this.rows[i].clear();
  11945. }
  11946. //Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location
  11947. //topRowIndex - the start of rows to copy (inclusive index)
  11948. var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  11949. //We only copy if the last position was already shown.
  11950. //We use the cueStartTime value to check this.
  11951. var lastOutputScreen = this.lastOutputScreen;
  11952. if (lastOutputScreen) {
  11953. var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
  11954. if (prevLineTime && prevLineTime < logger.time) {
  11955. for (var _i = 0; _i < this.nrRollUpRows; _i++) {
  11956. this.rows[newRow - this.nrRollUpRows + _i + 1].copy(lastOutputScreen.rows[topRowIndex + _i]);
  11957. }
  11958. }
  11959. }
  11960. }
  11961. this.currRow = newRow;
  11962. var row = this.rows[this.currRow];
  11963. if (pacData.indent !== null) {
  11964. var indent = pacData.indent;
  11965. var prevPos = Math.max(indent - 1, 0);
  11966. row.setCursor(pacData.indent);
  11967. pacData.color = row.chars[prevPos].penState.foreground;
  11968. }
  11969. var styles = { foreground: pacData.color, underline: pacData.underline, italics: pacData.italics, background: 'black', flash: false };
  11970. this.setPen(styles);
  11971. }
  11972. /**
  11973. * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
  11974. */
  11975. }, {
  11976. key: 'setBkgData',
  11977. value: function setBkgData(bkgData) {
  11978. logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData));
  11979. this.backSpace();
  11980. this.setPen(bkgData);
  11981. this.insertChar(0x20); //Space
  11982. }
  11983. }, {
  11984. key: 'setRollUpRows',
  11985. value: function setRollUpRows(nrRows) {
  11986. this.nrRollUpRows = nrRows;
  11987. }
  11988. }, {
  11989. key: 'rollUp',
  11990. value: function rollUp() {
  11991. if (this.nrRollUpRows === null) {
  11992. logger.log('DEBUG', 'roll_up but nrRollUpRows not set yet');
  11993. return; //Not properly setup
  11994. }
  11995. logger.log('TEXT', this.getDisplayText());
  11996. var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  11997. var topRow = this.rows.splice(topRowIndex, 1)[0];
  11998. topRow.clear();
  11999. this.rows.splice(this.currRow, 0, topRow);
  12000. logger.log('INFO', 'Rolling up');
  12001. //logger.log('TEXT', this.get_display_text())
  12002. }
  12003. /**
  12004. * Get all non-empty rows with as unicode text.
  12005. */
  12006. }, {
  12007. key: 'getDisplayText',
  12008. value: function getDisplayText(asOneRow) {
  12009. asOneRow = asOneRow || false;
  12010. var displayText = [];
  12011. var text = '';
  12012. var rowNr = -1;
  12013. for (var i = 0; i < NR_ROWS; i++) {
  12014. var rowText = this.rows[i].getTextString();
  12015. if (rowText) {
  12016. rowNr = i + 1;
  12017. if (asOneRow) {
  12018. displayText.push('Row ' + rowNr + ': \'' + rowText + '\'');
  12019. } else {
  12020. displayText.push(rowText.trim());
  12021. }
  12022. }
  12023. }
  12024. if (displayText.length > 0) {
  12025. if (asOneRow) {
  12026. text = '[' + displayText.join(' | ') + ']';
  12027. } else {
  12028. text = displayText.join('\n');
  12029. }
  12030. }
  12031. return text;
  12032. }
  12033. }, {
  12034. key: 'getTextAndFormat',
  12035. value: function getTextAndFormat() {
  12036. return this.rows;
  12037. }
  12038. }]);
  12039. return CaptionScreen;
  12040. }();
  12041. //var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
  12042. var Cea608Channel = function () {
  12043. function Cea608Channel(channelNumber, outputFilter) {
  12044. _classCallCheck(this, Cea608Channel);
  12045. this.chNr = channelNumber;
  12046. this.outputFilter = outputFilter;
  12047. this.mode = null;
  12048. this.verbose = 0;
  12049. this.displayedMemory = new CaptionScreen();
  12050. this.nonDisplayedMemory = new CaptionScreen();
  12051. this.lastOutputScreen = new CaptionScreen();
  12052. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  12053. this.writeScreen = this.displayedMemory;
  12054. this.mode = null;
  12055. this.cueStartTime = null; // Keeps track of where a cue started.
  12056. }
  12057. _createClass(Cea608Channel, [{
  12058. key: 'reset',
  12059. value: function reset() {
  12060. this.mode = null;
  12061. this.displayedMemory.reset();
  12062. this.nonDisplayedMemory.reset();
  12063. this.lastOutputScreen.reset();
  12064. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  12065. this.writeScreen = this.displayedMemory;
  12066. this.mode = null;
  12067. this.cueStartTime = null;
  12068. this.lastCueEndTime = null;
  12069. }
  12070. }, {
  12071. key: 'getHandler',
  12072. value: function getHandler() {
  12073. return this.outputFilter;
  12074. }
  12075. }, {
  12076. key: 'setHandler',
  12077. value: function setHandler(newHandler) {
  12078. this.outputFilter = newHandler;
  12079. }
  12080. }, {
  12081. key: 'setPAC',
  12082. value: function setPAC(pacData) {
  12083. this.writeScreen.setPAC(pacData);
  12084. }
  12085. }, {
  12086. key: 'setBkgData',
  12087. value: function setBkgData(bkgData) {
  12088. this.writeScreen.setBkgData(bkgData);
  12089. }
  12090. }, {
  12091. key: 'setMode',
  12092. value: function setMode(newMode) {
  12093. if (newMode === this.mode) {
  12094. return;
  12095. }
  12096. this.mode = newMode;
  12097. logger.log('INFO', 'MODE=' + newMode);
  12098. if (this.mode === 'MODE_POP-ON') {
  12099. this.writeScreen = this.nonDisplayedMemory;
  12100. } else {
  12101. this.writeScreen = this.displayedMemory;
  12102. this.writeScreen.reset();
  12103. }
  12104. if (this.mode !== 'MODE_ROLL-UP') {
  12105. this.displayedMemory.nrRollUpRows = null;
  12106. this.nonDisplayedMemory.nrRollUpRows = null;
  12107. }
  12108. this.mode = newMode;
  12109. }
  12110. }, {
  12111. key: 'insertChars',
  12112. value: function insertChars(chars) {
  12113. for (var i = 0; i < chars.length; i++) {
  12114. this.writeScreen.insertChar(chars[i]);
  12115. }
  12116. var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';
  12117. logger.log('INFO', screen + ': ' + this.writeScreen.getDisplayText(true));
  12118. if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
  12119. logger.log('TEXT', 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));
  12120. this.outputDataUpdate();
  12121. }
  12122. }
  12123. }, {
  12124. key: 'ccRCL',
  12125. value: function ccRCL() {
  12126. // Resume Caption Loading (switch mode to Pop On)
  12127. logger.log('INFO', 'RCL - Resume Caption Loading');
  12128. this.setMode('MODE_POP-ON');
  12129. }
  12130. }, {
  12131. key: 'ccBS',
  12132. value: function ccBS() {
  12133. // BackSpace
  12134. logger.log('INFO', 'BS - BackSpace');
  12135. if (this.mode === 'MODE_TEXT') {
  12136. return;
  12137. }
  12138. this.writeScreen.backSpace();
  12139. if (this.writeScreen === this.displayedMemory) {
  12140. this.outputDataUpdate();
  12141. }
  12142. }
  12143. }, {
  12144. key: 'ccAOF',
  12145. value: function ccAOF() {
  12146. // Reserved (formerly Alarm Off)
  12147. return;
  12148. }
  12149. }, {
  12150. key: 'ccAON',
  12151. value: function ccAON() {
  12152. // Reserved (formerly Alarm On)
  12153. return;
  12154. }
  12155. }, {
  12156. key: 'ccDER',
  12157. value: function ccDER() {
  12158. // Delete to End of Row
  12159. logger.log('INFO', 'DER- Delete to End of Row');
  12160. this.writeScreen.clearToEndOfRow();
  12161. this.outputDataUpdate();
  12162. }
  12163. }, {
  12164. key: 'ccRU',
  12165. value: function ccRU(nrRows) {
  12166. //Roll-Up Captions-2,3,or 4 Rows
  12167. logger.log('INFO', 'RU(' + nrRows + ') - Roll Up');
  12168. this.writeScreen = this.displayedMemory;
  12169. this.setMode('MODE_ROLL-UP');
  12170. this.writeScreen.setRollUpRows(nrRows);
  12171. }
  12172. }, {
  12173. key: 'ccFON',
  12174. value: function ccFON() {
  12175. //Flash On
  12176. logger.log('INFO', 'FON - Flash On');
  12177. this.writeScreen.setPen({ flash: true });
  12178. }
  12179. }, {
  12180. key: 'ccRDC',
  12181. value: function ccRDC() {
  12182. // Resume Direct Captioning (switch mode to PaintOn)
  12183. logger.log('INFO', 'RDC - Resume Direct Captioning');
  12184. this.setMode('MODE_PAINT-ON');
  12185. }
  12186. }, {
  12187. key: 'ccTR',
  12188. value: function ccTR() {
  12189. // Text Restart in text mode (not supported, however)
  12190. logger.log('INFO', 'TR');
  12191. this.setMode('MODE_TEXT');
  12192. }
  12193. }, {
  12194. key: 'ccRTD',
  12195. value: function ccRTD() {
  12196. // Resume Text Display in Text mode (not supported, however)
  12197. logger.log('INFO', 'RTD');
  12198. this.setMode('MODE_TEXT');
  12199. }
  12200. }, {
  12201. key: 'ccEDM',
  12202. value: function ccEDM() {
  12203. // Erase Displayed Memory
  12204. logger.log('INFO', 'EDM - Erase Displayed Memory');
  12205. this.displayedMemory.reset();
  12206. this.outputDataUpdate();
  12207. }
  12208. }, {
  12209. key: 'ccCR',
  12210. value: function ccCR() {
  12211. // Carriage Return
  12212. logger.log('CR - Carriage Return');
  12213. this.writeScreen.rollUp();
  12214. this.outputDataUpdate();
  12215. }
  12216. }, {
  12217. key: 'ccENM',
  12218. value: function ccENM() {
  12219. //Erase Non-Displayed Memory
  12220. logger.log('INFO', 'ENM - Erase Non-displayed Memory');
  12221. this.nonDisplayedMemory.reset();
  12222. }
  12223. }, {
  12224. key: 'ccEOC',
  12225. value: function ccEOC() {
  12226. //End of Caption (Flip Memories)
  12227. logger.log('INFO', 'EOC - End Of Caption');
  12228. if (this.mode === 'MODE_POP-ON') {
  12229. var tmp = this.displayedMemory;
  12230. this.displayedMemory = this.nonDisplayedMemory;
  12231. this.nonDisplayedMemory = tmp;
  12232. this.writeScreen = this.nonDisplayedMemory;
  12233. logger.log('TEXT', 'DISP: ' + this.displayedMemory.getDisplayText());
  12234. }
  12235. this.outputDataUpdate();
  12236. }
  12237. }, {
  12238. key: 'ccTO',
  12239. value: function ccTO(nrCols) {
  12240. // Tab Offset 1,2, or 3 columns
  12241. logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset');
  12242. this.writeScreen.moveCursor(nrCols);
  12243. }
  12244. }, {
  12245. key: 'ccMIDROW',
  12246. value: function ccMIDROW(secondByte) {
  12247. // Parse MIDROW command
  12248. var styles = { flash: false };
  12249. styles.underline = secondByte % 2 === 1;
  12250. styles.italics = secondByte >= 0x2e;
  12251. if (!styles.italics) {
  12252. var colorIndex = Math.floor(secondByte / 2) - 0x10;
  12253. var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];
  12254. styles.foreground = colors[colorIndex];
  12255. } else {
  12256. styles.foreground = 'white';
  12257. }
  12258. logger.log('INFO', 'MIDROW: ' + JSON.stringify(styles));
  12259. this.writeScreen.setPen(styles);
  12260. }
  12261. }, {
  12262. key: 'outputDataUpdate',
  12263. value: function outputDataUpdate() {
  12264. var t = logger.time;
  12265. if (t === null) {
  12266. return;
  12267. }
  12268. if (this.outputFilter) {
  12269. if (this.outputFilter.updateData) {
  12270. this.outputFilter.updateData(t, this.displayedMemory);
  12271. }
  12272. if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
  12273. // Start of a new cue
  12274. this.cueStartTime = t;
  12275. } else {
  12276. if (!this.displayedMemory.equals(this.lastOutputScreen)) {
  12277. if (this.outputFilter.newCue) {
  12278. this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen);
  12279. }
  12280. this.cueStartTime = this.displayedMemory.isEmpty() ? null : t;
  12281. }
  12282. }
  12283. this.lastOutputScreen.copy(this.displayedMemory);
  12284. }
  12285. }
  12286. }, {
  12287. key: 'cueSplitAtTime',
  12288. value: function cueSplitAtTime(t) {
  12289. if (this.outputFilter) {
  12290. if (!this.displayedMemory.isEmpty()) {
  12291. if (this.outputFilter.newCue) {
  12292. this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
  12293. }
  12294. this.cueStartTime = t;
  12295. }
  12296. }
  12297. }
  12298. }]);
  12299. return Cea608Channel;
  12300. }();
  12301. var Cea608Parser = function () {
  12302. function Cea608Parser(field, out1, out2) {
  12303. _classCallCheck(this, Cea608Parser);
  12304. this.field = field || 1;
  12305. this.outputs = [out1, out2];
  12306. this.channels = [new Cea608Channel(1, out1), new Cea608Channel(2, out2)];
  12307. this.currChNr = -1; // Will be 1 or 2
  12308. this.lastCmdA = null; // First byte of last command
  12309. this.lastCmdB = null; // Second byte of last command
  12310. this.bufferedData = [];
  12311. this.startTime = null;
  12312. this.lastTime = null;
  12313. this.dataCounters = { 'padding': 0, 'char': 0, 'cmd': 0, 'other': 0 };
  12314. }
  12315. _createClass(Cea608Parser, [{
  12316. key: 'getHandler',
  12317. value: function getHandler(index) {
  12318. return this.channels[index].getHandler();
  12319. }
  12320. }, {
  12321. key: 'setHandler',
  12322. value: function setHandler(index, newHandler) {
  12323. this.channels[index].setHandler(newHandler);
  12324. }
  12325. /**
  12326. * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
  12327. */
  12328. }, {
  12329. key: 'addData',
  12330. value: function addData(t, byteList) {
  12331. var cmdFound,
  12332. a,
  12333. b,
  12334. charsFound = false;
  12335. this.lastTime = t;
  12336. logger.setTime(t);
  12337. for (var i = 0; i < byteList.length; i += 2) {
  12338. a = byteList[i] & 0x7f;
  12339. b = byteList[i + 1] & 0x7f;
  12340. if (a === 0 && b === 0) {
  12341. this.dataCounters.padding += 2;
  12342. continue;
  12343. } else {
  12344. logger.log('DATA', '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');
  12345. }
  12346. cmdFound = this.parseCmd(a, b);
  12347. if (!cmdFound) {
  12348. cmdFound = this.parseMidrow(a, b);
  12349. }
  12350. if (!cmdFound) {
  12351. cmdFound = this.parsePAC(a, b);
  12352. }
  12353. if (!cmdFound) {
  12354. cmdFound = this.parseBackgroundAttributes(a, b);
  12355. }
  12356. if (!cmdFound) {
  12357. charsFound = this.parseChars(a, b);
  12358. if (charsFound) {
  12359. if (this.currChNr && this.currChNr >= 0) {
  12360. var channel = this.channels[this.currChNr - 1];
  12361. channel.insertChars(charsFound);
  12362. } else {
  12363. logger.log('WARNING', 'No channel found yet. TEXT-MODE?');
  12364. }
  12365. }
  12366. }
  12367. if (cmdFound) {
  12368. this.dataCounters.cmd += 2;
  12369. } else if (charsFound) {
  12370. this.dataCounters.char += 2;
  12371. } else {
  12372. this.dataCounters.other += 2;
  12373. logger.log('WARNING', 'Couldn\'t parse cleaned data ' + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));
  12374. }
  12375. }
  12376. }
  12377. /**
  12378. * Parse Command.
  12379. * @returns {Boolean} Tells if a command was found
  12380. */
  12381. }, {
  12382. key: 'parseCmd',
  12383. value: function parseCmd(a, b) {
  12384. var chNr = null;
  12385. var cond1 = (a === 0x14 || a === 0x1C) && 0x20 <= b && b <= 0x2F;
  12386. var cond2 = (a === 0x17 || a === 0x1F) && 0x21 <= b && b <= 0x23;
  12387. if (!(cond1 || cond2)) {
  12388. return false;
  12389. }
  12390. if (a === this.lastCmdA && b === this.lastCmdB) {
  12391. this.lastCmdA = null;
  12392. this.lastCmdB = null; // Repeated commands are dropped (once)
  12393. logger.log('DEBUG', 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');
  12394. return true;
  12395. }
  12396. if (a === 0x14 || a === 0x17) {
  12397. chNr = 1;
  12398. } else {
  12399. chNr = 2; // (a === 0x1C || a=== 0x1f)
  12400. }
  12401. var channel = this.channels[chNr - 1];
  12402. if (a === 0x14 || a === 0x1C) {
  12403. if (b === 0x20) {
  12404. channel.ccRCL();
  12405. } else if (b === 0x21) {
  12406. channel.ccBS();
  12407. } else if (b === 0x22) {
  12408. channel.ccAOF();
  12409. } else if (b === 0x23) {
  12410. channel.ccAON();
  12411. } else if (b === 0x24) {
  12412. channel.ccDER();
  12413. } else if (b === 0x25) {
  12414. channel.ccRU(2);
  12415. } else if (b === 0x26) {
  12416. channel.ccRU(3);
  12417. } else if (b === 0x27) {
  12418. channel.ccRU(4);
  12419. } else if (b === 0x28) {
  12420. channel.ccFON();
  12421. } else if (b === 0x29) {
  12422. channel.ccRDC();
  12423. } else if (b === 0x2A) {
  12424. channel.ccTR();
  12425. } else if (b === 0x2B) {
  12426. channel.ccRTD();
  12427. } else if (b === 0x2C) {
  12428. channel.ccEDM();
  12429. } else if (b === 0x2D) {
  12430. channel.ccCR();
  12431. } else if (b === 0x2E) {
  12432. channel.ccENM();
  12433. } else if (b === 0x2F) {
  12434. channel.ccEOC();
  12435. }
  12436. } else {
  12437. //a == 0x17 || a == 0x1F
  12438. channel.ccTO(b - 0x20);
  12439. }
  12440. this.lastCmdA = a;
  12441. this.lastCmdB = b;
  12442. this.currChNr = chNr;
  12443. return true;
  12444. }
  12445. /**
  12446. * Parse midrow styling command
  12447. * @returns {Boolean}
  12448. */
  12449. }, {
  12450. key: 'parseMidrow',
  12451. value: function parseMidrow(a, b) {
  12452. var chNr = null;
  12453. if ((a === 0x11 || a === 0x19) && 0x20 <= b && b <= 0x2f) {
  12454. if (a === 0x11) {
  12455. chNr = 1;
  12456. } else {
  12457. chNr = 2;
  12458. }
  12459. if (chNr !== this.currChNr) {
  12460. logger.log('ERROR', 'Mismatch channel in midrow parsing');
  12461. return false;
  12462. }
  12463. var channel = this.channels[chNr - 1];
  12464. channel.ccMIDROW(b);
  12465. logger.log('DEBUG', 'MIDROW (' + numArrayToHexArray([a, b]) + ')');
  12466. return true;
  12467. }
  12468. return false;
  12469. }
  12470. /**
  12471. * Parse Preable Access Codes (Table 53).
  12472. * @returns {Boolean} Tells if PAC found
  12473. */
  12474. }, {
  12475. key: 'parsePAC',
  12476. value: function parsePAC(a, b) {
  12477. var chNr = null;
  12478. var row = null;
  12479. var case1 = (0x11 <= a && a <= 0x17 || 0x19 <= a && a <= 0x1F) && 0x40 <= b && b <= 0x7F;
  12480. var case2 = (a === 0x10 || a === 0x18) && 0x40 <= b && b <= 0x5F;
  12481. if (!(case1 || case2)) {
  12482. return false;
  12483. }
  12484. if (a === this.lastCmdA && b === this.lastCmdB) {
  12485. this.lastCmdA = null;
  12486. this.lastCmdB = null;
  12487. return true; // Repeated commands are dropped (once)
  12488. }
  12489. chNr = a <= 0x17 ? 1 : 2;
  12490. if (0x40 <= b && b <= 0x5F) {
  12491. row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
  12492. } else {
  12493. // 0x60 <= b <= 0x7F
  12494. row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
  12495. }
  12496. var pacData = this.interpretPAC(row, b);
  12497. var channel = this.channels[chNr - 1];
  12498. channel.setPAC(pacData);
  12499. this.lastCmdA = a;
  12500. this.lastCmdB = b;
  12501. this.currChNr = chNr;
  12502. return true;
  12503. }
  12504. /**
  12505. * Interpret the second byte of the pac, and return the information.
  12506. * @returns {Object} pacData with style parameters.
  12507. */
  12508. }, {
  12509. key: 'interpretPAC',
  12510. value: function interpretPAC(row, byte) {
  12511. var pacIndex = byte;
  12512. var pacData = { color: null, italics: false, indent: null, underline: false, row: row };
  12513. if (byte > 0x5F) {
  12514. pacIndex = byte - 0x60;
  12515. } else {
  12516. pacIndex = byte - 0x40;
  12517. }
  12518. pacData.underline = (pacIndex & 1) === 1;
  12519. if (pacIndex <= 0xd) {
  12520. pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];
  12521. } else if (pacIndex <= 0xf) {
  12522. pacData.italics = true;
  12523. pacData.color = 'white';
  12524. } else {
  12525. pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;
  12526. }
  12527. return pacData; // Note that row has zero offset. The spec uses 1.
  12528. }
  12529. /**
  12530. * Parse characters.
  12531. * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
  12532. */
  12533. }, {
  12534. key: 'parseChars',
  12535. value: function parseChars(a, b) {
  12536. var channelNr = null,
  12537. charCodes = null,
  12538. charCode1 = null;
  12539. if (a >= 0x19) {
  12540. channelNr = 2;
  12541. charCode1 = a - 8;
  12542. } else {
  12543. channelNr = 1;
  12544. charCode1 = a;
  12545. }
  12546. if (0x11 <= charCode1 && charCode1 <= 0x13) {
  12547. // Special character
  12548. var oneCode = b;
  12549. if (charCode1 === 0x11) {
  12550. oneCode = b + 0x50;
  12551. } else if (charCode1 === 0x12) {
  12552. oneCode = b + 0x70;
  12553. } else {
  12554. oneCode = b + 0x90;
  12555. }
  12556. logger.log('INFO', 'Special char \'' + getCharForByte(oneCode) + '\' in channel ' + channelNr);
  12557. charCodes = [oneCode];
  12558. } else if (0x20 <= a && a <= 0x7f) {
  12559. charCodes = b === 0 ? [a] : [a, b];
  12560. }
  12561. if (charCodes) {
  12562. var hexCodes = numArrayToHexArray(charCodes);
  12563. logger.log('DEBUG', 'Char codes = ' + hexCodes.join(','));
  12564. this.lastCmdA = null;
  12565. this.lastCmdB = null;
  12566. }
  12567. return charCodes;
  12568. }
  12569. /**
  12570. * Parse extended background attributes as well as new foreground color black.
  12571. * @returns{Boolean} Tells if background attributes are found
  12572. */
  12573. }, {
  12574. key: 'parseBackgroundAttributes',
  12575. value: function parseBackgroundAttributes(a, b) {
  12576. var bkgData, index, chNr, channel;
  12577. var case1 = (a === 0x10 || a === 0x18) && 0x20 <= b && b <= 0x2f;
  12578. var case2 = (a === 0x17 || a === 0x1f) && 0x2d <= b && b <= 0x2f;
  12579. if (!(case1 || case2)) {
  12580. return false;
  12581. }
  12582. bkgData = {};
  12583. if (a === 0x10 || a === 0x18) {
  12584. index = Math.floor((b - 0x20) / 2);
  12585. bkgData.background = backgroundColors[index];
  12586. if (b % 2 === 1) {
  12587. bkgData.background = bkgData.background + '_semi';
  12588. }
  12589. } else if (b === 0x2d) {
  12590. bkgData.background = 'transparent';
  12591. } else {
  12592. bkgData.foreground = 'black';
  12593. if (b === 0x2f) {
  12594. bkgData.underline = true;
  12595. }
  12596. }
  12597. chNr = a < 0x18 ? 1 : 2;
  12598. channel = this.channels[chNr - 1];
  12599. channel.setBkgData(bkgData);
  12600. this.lastCmdA = null;
  12601. this.lastCmdB = null;
  12602. return true;
  12603. }
  12604. /**
  12605. * Reset state of parser and its channels.
  12606. */
  12607. }, {
  12608. key: 'reset',
  12609. value: function reset() {
  12610. for (var i = 0; i < this.channels.length; i++) {
  12611. if (this.channels[i]) {
  12612. this.channels[i].reset();
  12613. }
  12614. }
  12615. this.lastCmdA = null;
  12616. this.lastCmdB = null;
  12617. }
  12618. /**
  12619. * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
  12620. */
  12621. }, {
  12622. key: 'cueSplitAtTime',
  12623. value: function cueSplitAtTime(t) {
  12624. for (var i = 0; i < this.channels.length; i++) {
  12625. if (this.channels[i]) {
  12626. this.channels[i].cueSplitAtTime(t);
  12627. }
  12628. }
  12629. }
  12630. }]);
  12631. return Cea608Parser;
  12632. }();
  12633. exports.default = Cea608Parser;
  12634. },{}],47:[function(_dereq_,module,exports){
  12635. 'use strict';
  12636. var _vttparser = _dereq_(53);
  12637. var Cues = {
  12638. newCue: function newCue(track, startTime, endTime, captionScreen) {
  12639. var row;
  12640. var cue;
  12641. var indenting;
  12642. var indent;
  12643. var text;
  12644. var VTTCue = window.VTTCue || window.TextTrackCue;
  12645. for (var r = 0; r < captionScreen.rows.length; r++) {
  12646. row = captionScreen.rows[r];
  12647. indenting = true;
  12648. indent = 0;
  12649. text = '';
  12650. if (!row.isEmpty()) {
  12651. for (var c = 0; c < row.chars.length; c++) {
  12652. if (row.chars[c].uchar.match(/\s/) && indenting) {
  12653. indent++;
  12654. } else {
  12655. text += row.chars[c].uchar;
  12656. indenting = false;
  12657. }
  12658. }
  12659. //To be used for cleaning-up orphaned roll-up captions
  12660. row.cueStartTime = startTime;
  12661. // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
  12662. if (startTime === endTime) {
  12663. endTime += 0.0001;
  12664. }
  12665. cue = new VTTCue(startTime, endTime, (0, _vttparser.fixLineBreaks)(text.trim()));
  12666. if (indent >= 16) {
  12667. indent--;
  12668. } else {
  12669. indent++;
  12670. }
  12671. // VTTCue.line get's flakey when using controls, so let's now include line 13&14
  12672. // also, drop line 1 since it's to close to the top
  12673. if (navigator.userAgent.match(/Firefox\//)) {
  12674. cue.line = r + 1;
  12675. } else {
  12676. cue.line = r > 7 ? r - 2 : r + 1;
  12677. }
  12678. cue.align = 'left';
  12679. // Clamp the position between 0 and 100 - if out of these bounds, Firefox throws an exception and captions break
  12680. cue.position = Math.max(0, Math.min(100, 100 * (indent / 32) + (navigator.userAgent.match(/Firefox\//) ? 50 : 0)));
  12681. track.addCue(cue);
  12682. }
  12683. }
  12684. }
  12685. };
  12686. module.exports = Cues;
  12687. },{"53":53}],48:[function(_dereq_,module,exports){
  12688. 'use strict';
  12689. Object.defineProperty(exports, "__esModule", {
  12690. value: true
  12691. });
  12692. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  12693. * EWMA Bandwidth Estimator
  12694. * - heavily inspired from shaka-player
  12695. * Tracks bandwidth samples and estimates available bandwidth.
  12696. * Based on the minimum of two exponentially-weighted moving averages with
  12697. * different half-lives.
  12698. */
  12699. var _ewma = _dereq_(49);
  12700. var _ewma2 = _interopRequireDefault(_ewma);
  12701. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12702. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  12703. var EwmaBandWidthEstimator = function () {
  12704. function EwmaBandWidthEstimator(hls, slow, fast, defaultEstimate) {
  12705. _classCallCheck(this, EwmaBandWidthEstimator);
  12706. this.hls = hls;
  12707. this.defaultEstimate_ = defaultEstimate;
  12708. this.minWeight_ = 0.001;
  12709. this.minDelayMs_ = 50;
  12710. this.slow_ = new _ewma2.default(slow);
  12711. this.fast_ = new _ewma2.default(fast);
  12712. }
  12713. _createClass(EwmaBandWidthEstimator, [{
  12714. key: 'sample',
  12715. value: function sample(durationMs, numBytes) {
  12716. durationMs = Math.max(durationMs, this.minDelayMs_);
  12717. var bandwidth = 8000 * numBytes / durationMs,
  12718. //console.log('instant bw:'+ Math.round(bandwidth));
  12719. // we weight sample using loading duration....
  12720. weight = durationMs / 1000;
  12721. this.fast_.sample(weight, bandwidth);
  12722. this.slow_.sample(weight, bandwidth);
  12723. }
  12724. }, {
  12725. key: 'canEstimate',
  12726. value: function canEstimate() {
  12727. var fast = this.fast_;
  12728. return fast && fast.getTotalWeight() >= this.minWeight_;
  12729. }
  12730. }, {
  12731. key: 'getEstimate',
  12732. value: function getEstimate() {
  12733. if (this.canEstimate()) {
  12734. //console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
  12735. //console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
  12736. // Take the minimum of these two estimates. This should have the effect of
  12737. // adapting down quickly, but up more slowly.
  12738. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  12739. } else {
  12740. return this.defaultEstimate_;
  12741. }
  12742. }
  12743. }, {
  12744. key: 'destroy',
  12745. value: function destroy() {}
  12746. }]);
  12747. return EwmaBandWidthEstimator;
  12748. }();
  12749. exports.default = EwmaBandWidthEstimator;
  12750. },{"49":49}],49:[function(_dereq_,module,exports){
  12751. "use strict";
  12752. Object.defineProperty(exports, "__esModule", {
  12753. value: true
  12754. });
  12755. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  12756. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  12757. /*
  12758. * compute an Exponential Weighted moving average
  12759. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  12760. * - heavily inspired from shaka-player
  12761. */
  12762. var EWMA = function () {
  12763. // About half of the estimated value will be from the last |halfLife| samples by weight.
  12764. function EWMA(halfLife) {
  12765. _classCallCheck(this, EWMA);
  12766. // Larger values of alpha expire historical data more slowly.
  12767. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  12768. this.estimate_ = 0;
  12769. this.totalWeight_ = 0;
  12770. }
  12771. _createClass(EWMA, [{
  12772. key: "sample",
  12773. value: function sample(weight, value) {
  12774. var adjAlpha = Math.pow(this.alpha_, weight);
  12775. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  12776. this.totalWeight_ += weight;
  12777. }
  12778. }, {
  12779. key: "getTotalWeight",
  12780. value: function getTotalWeight() {
  12781. return this.totalWeight_;
  12782. }
  12783. }, {
  12784. key: "getEstimate",
  12785. value: function getEstimate() {
  12786. if (this.alpha_) {
  12787. var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  12788. return this.estimate_ / zeroFactor;
  12789. } else {
  12790. return this.estimate_;
  12791. }
  12792. }
  12793. }]);
  12794. return EWMA;
  12795. }();
  12796. exports.default = EWMA;
  12797. },{}],50:[function(_dereq_,module,exports){
  12798. 'use strict';
  12799. Object.defineProperty(exports, "__esModule", {
  12800. value: true
  12801. });
  12802. 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; };
  12803. function noop() {}
  12804. var fakeLogger = {
  12805. trace: noop,
  12806. debug: noop,
  12807. log: noop,
  12808. warn: noop,
  12809. info: noop,
  12810. error: noop
  12811. };
  12812. var exportedLogger = fakeLogger;
  12813. /*globals self: false */
  12814. //let lastCallTime;
  12815. // function formatMsgWithTimeInfo(type, msg) {
  12816. // const now = Date.now();
  12817. // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
  12818. // lastCallTime = now;
  12819. // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
  12820. // return msg;
  12821. // }
  12822. function formatMsg(type, msg) {
  12823. msg = '[' + type + '] > ' + msg;
  12824. return msg;
  12825. }
  12826. function consolePrintFn(type) {
  12827. var func = self.console[type];
  12828. if (func) {
  12829. return function () {
  12830. for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  12831. args[_key] = arguments[_key];
  12832. }
  12833. if (args[0]) {
  12834. args[0] = formatMsg(type, args[0]);
  12835. }
  12836. func.apply(self.console, args);
  12837. };
  12838. }
  12839. return noop;
  12840. }
  12841. function exportLoggerFunctions(debugConfig) {
  12842. for (var _len2 = arguments.length, functions = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  12843. functions[_key2 - 1] = arguments[_key2];
  12844. }
  12845. functions.forEach(function (type) {
  12846. exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
  12847. });
  12848. }
  12849. var enableLogs = exports.enableLogs = function enableLogs(debugConfig) {
  12850. if (debugConfig === true || (typeof debugConfig === 'undefined' ? 'undefined' : _typeof(debugConfig)) === 'object') {
  12851. exportLoggerFunctions(debugConfig,
  12852. // Remove out from list here to hard-disable a log-level
  12853. //'trace',
  12854. 'debug', 'log', 'info', 'warn', 'error');
  12855. // Some browsers don't allow to use bind on console object anyway
  12856. // fallback to default if needed
  12857. try {
  12858. exportedLogger.log();
  12859. } catch (e) {
  12860. exportedLogger = fakeLogger;
  12861. }
  12862. } else {
  12863. exportedLogger = fakeLogger;
  12864. }
  12865. };
  12866. var logger = exports.logger = exportedLogger;
  12867. },{}],51:[function(_dereq_,module,exports){
  12868. 'use strict';
  12869. /**
  12870. * TimeRanges to string helper
  12871. */
  12872. var TimeRanges = {
  12873. toString: function toString(r) {
  12874. var log = '',
  12875. len = r.length;
  12876. for (var i = 0; i < len; i++) {
  12877. log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';
  12878. }
  12879. return log;
  12880. }
  12881. };
  12882. module.exports = TimeRanges;
  12883. },{}],52:[function(_dereq_,module,exports){
  12884. 'use strict';
  12885. Object.defineProperty(exports, "__esModule", {
  12886. value: true
  12887. });
  12888. /**
  12889. * Copyright 2013 vtt.js Contributors
  12890. *
  12891. * Licensed under the Apache License, Version 2.0 (the "License");
  12892. * you may not use this file except in compliance with the License.
  12893. * You may obtain a copy of the License at
  12894. *
  12895. * http://www.apache.org/licenses/LICENSE-2.0
  12896. *
  12897. * Unless required by applicable law or agreed to in writing, software
  12898. * distributed under the License is distributed on an "AS IS" BASIS,
  12899. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12900. * See the License for the specific language governing permissions and
  12901. * limitations under the License.
  12902. */
  12903. exports.default = function () {
  12904. if (typeof window !== 'undefined' && window.VTTCue) {
  12905. return window.VTTCue;
  12906. }
  12907. var autoKeyword = 'auto';
  12908. var directionSetting = {
  12909. '': true,
  12910. lr: true,
  12911. rl: true
  12912. };
  12913. var alignSetting = {
  12914. start: true,
  12915. middle: true,
  12916. end: true,
  12917. left: true,
  12918. right: true
  12919. };
  12920. function findDirectionSetting(value) {
  12921. if (typeof value !== 'string') {
  12922. return false;
  12923. }
  12924. var dir = directionSetting[value.toLowerCase()];
  12925. return dir ? value.toLowerCase() : false;
  12926. }
  12927. function findAlignSetting(value) {
  12928. if (typeof value !== 'string') {
  12929. return false;
  12930. }
  12931. var align = alignSetting[value.toLowerCase()];
  12932. return align ? value.toLowerCase() : false;
  12933. }
  12934. function extend(obj) {
  12935. var i = 1;
  12936. for (; i < arguments.length; i++) {
  12937. var cobj = arguments[i];
  12938. for (var p in cobj) {
  12939. obj[p] = cobj[p];
  12940. }
  12941. }
  12942. return obj;
  12943. }
  12944. function VTTCue(startTime, endTime, text) {
  12945. var cue = this;
  12946. var isIE8 = function () {
  12947. if (typeof navigator === 'undefined') {
  12948. return;
  12949. }
  12950. return (/MSIE\s8\.0/.test(navigator.userAgent)
  12951. );
  12952. }();
  12953. var baseObj = {};
  12954. if (isIE8) {
  12955. cue = document.createElement('custom');
  12956. } else {
  12957. baseObj.enumerable = true;
  12958. }
  12959. /**
  12960. * Shim implementation specific properties. These properties are not in
  12961. * the spec.
  12962. */
  12963. // Lets us know when the VTTCue's data has changed in such a way that we need
  12964. // to recompute its display state. This lets us compute its display state
  12965. // lazily.
  12966. cue.hasBeenReset = false;
  12967. /**
  12968. * VTTCue and TextTrackCue properties
  12969. * http://dev.w3.org/html5/webvtt/#vttcue-interface
  12970. */
  12971. var _id = '';
  12972. var _pauseOnExit = false;
  12973. var _startTime = startTime;
  12974. var _endTime = endTime;
  12975. var _text = text;
  12976. var _region = null;
  12977. var _vertical = '';
  12978. var _snapToLines = true;
  12979. var _line = 'auto';
  12980. var _lineAlign = 'start';
  12981. var _position = 50;
  12982. var _positionAlign = 'middle';
  12983. var _size = 50;
  12984. var _align = 'middle';
  12985. Object.defineProperty(cue, 'id', extend({}, baseObj, {
  12986. get: function get() {
  12987. return _id;
  12988. },
  12989. set: function set(value) {
  12990. _id = '' + value;
  12991. }
  12992. }));
  12993. Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {
  12994. get: function get() {
  12995. return _pauseOnExit;
  12996. },
  12997. set: function set(value) {
  12998. _pauseOnExit = !!value;
  12999. }
  13000. }));
  13001. Object.defineProperty(cue, 'startTime', extend({}, baseObj, {
  13002. get: function get() {
  13003. return _startTime;
  13004. },
  13005. set: function set(value) {
  13006. if (typeof value !== 'number') {
  13007. throw new TypeError('Start time must be set to a number.');
  13008. }
  13009. _startTime = value;
  13010. this.hasBeenReset = true;
  13011. }
  13012. }));
  13013. Object.defineProperty(cue, 'endTime', extend({}, baseObj, {
  13014. get: function get() {
  13015. return _endTime;
  13016. },
  13017. set: function set(value) {
  13018. if (typeof value !== 'number') {
  13019. throw new TypeError('End time must be set to a number.');
  13020. }
  13021. _endTime = value;
  13022. this.hasBeenReset = true;
  13023. }
  13024. }));
  13025. Object.defineProperty(cue, 'text', extend({}, baseObj, {
  13026. get: function get() {
  13027. return _text;
  13028. },
  13029. set: function set(value) {
  13030. _text = '' + value;
  13031. this.hasBeenReset = true;
  13032. }
  13033. }));
  13034. Object.defineProperty(cue, 'region', extend({}, baseObj, {
  13035. get: function get() {
  13036. return _region;
  13037. },
  13038. set: function set(value) {
  13039. _region = value;
  13040. this.hasBeenReset = true;
  13041. }
  13042. }));
  13043. Object.defineProperty(cue, 'vertical', extend({}, baseObj, {
  13044. get: function get() {
  13045. return _vertical;
  13046. },
  13047. set: function set(value) {
  13048. var setting = findDirectionSetting(value);
  13049. // Have to check for false because the setting an be an empty string.
  13050. if (setting === false) {
  13051. throw new SyntaxError('An invalid or illegal string was specified.');
  13052. }
  13053. _vertical = setting;
  13054. this.hasBeenReset = true;
  13055. }
  13056. }));
  13057. Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {
  13058. get: function get() {
  13059. return _snapToLines;
  13060. },
  13061. set: function set(value) {
  13062. _snapToLines = !!value;
  13063. this.hasBeenReset = true;
  13064. }
  13065. }));
  13066. Object.defineProperty(cue, 'line', extend({}, baseObj, {
  13067. get: function get() {
  13068. return _line;
  13069. },
  13070. set: function set(value) {
  13071. if (typeof value !== 'number' && value !== autoKeyword) {
  13072. throw new SyntaxError('An invalid number or illegal string was specified.');
  13073. }
  13074. _line = value;
  13075. this.hasBeenReset = true;
  13076. }
  13077. }));
  13078. Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {
  13079. get: function get() {
  13080. return _lineAlign;
  13081. },
  13082. set: function set(value) {
  13083. var setting = findAlignSetting(value);
  13084. if (!setting) {
  13085. throw new SyntaxError('An invalid or illegal string was specified.');
  13086. }
  13087. _lineAlign = setting;
  13088. this.hasBeenReset = true;
  13089. }
  13090. }));
  13091. Object.defineProperty(cue, 'position', extend({}, baseObj, {
  13092. get: function get() {
  13093. return _position;
  13094. },
  13095. set: function set(value) {
  13096. if (value < 0 || value > 100) {
  13097. throw new Error('Position must be between 0 and 100.');
  13098. }
  13099. _position = value;
  13100. this.hasBeenReset = true;
  13101. }
  13102. }));
  13103. Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {
  13104. get: function get() {
  13105. return _positionAlign;
  13106. },
  13107. set: function set(value) {
  13108. var setting = findAlignSetting(value);
  13109. if (!setting) {
  13110. throw new SyntaxError('An invalid or illegal string was specified.');
  13111. }
  13112. _positionAlign = setting;
  13113. this.hasBeenReset = true;
  13114. }
  13115. }));
  13116. Object.defineProperty(cue, 'size', extend({}, baseObj, {
  13117. get: function get() {
  13118. return _size;
  13119. },
  13120. set: function set(value) {
  13121. if (value < 0 || value > 100) {
  13122. throw new Error('Size must be between 0 and 100.');
  13123. }
  13124. _size = value;
  13125. this.hasBeenReset = true;
  13126. }
  13127. }));
  13128. Object.defineProperty(cue, 'align', extend({}, baseObj, {
  13129. get: function get() {
  13130. return _align;
  13131. },
  13132. set: function set(value) {
  13133. var setting = findAlignSetting(value);
  13134. if (!setting) {
  13135. throw new SyntaxError('An invalid or illegal string was specified.');
  13136. }
  13137. _align = setting;
  13138. this.hasBeenReset = true;
  13139. }
  13140. }));
  13141. /**
  13142. * Other <track> spec defined properties
  13143. */
  13144. // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
  13145. cue.displayState = undefined;
  13146. if (isIE8) {
  13147. return cue;
  13148. }
  13149. }
  13150. /**
  13151. * VTTCue methods
  13152. */
  13153. VTTCue.prototype.getCueAsHTML = function () {
  13154. // Assume WebVTT.convertCueToDOMTree is on the global.
  13155. var WebVTT = window.WebVTT;
  13156. return WebVTT.convertCueToDOMTree(window, this.text);
  13157. };
  13158. return VTTCue;
  13159. }();
  13160. },{}],53:[function(_dereq_,module,exports){
  13161. 'use strict';
  13162. Object.defineProperty(exports, "__esModule", {
  13163. value: true
  13164. });
  13165. exports.fixLineBreaks = undefined;
  13166. var _vttcue = _dereq_(52);
  13167. var _vttcue2 = _interopRequireDefault(_vttcue);
  13168. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13169. var StringDecoder = function StringDecoder() {
  13170. return {
  13171. decode: function decode(data) {
  13172. if (!data) {
  13173. return '';
  13174. }
  13175. if (typeof data !== 'string') {
  13176. throw new Error('Error - expected string data.');
  13177. }
  13178. return decodeURIComponent(encodeURIComponent(data));
  13179. }
  13180. };
  13181. }; /*
  13182. * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js#L1716
  13183. */
  13184. function VTTParser() {
  13185. this.window = window;
  13186. this.state = 'INITIAL';
  13187. this.buffer = '';
  13188. this.decoder = new StringDecoder();
  13189. this.regionList = [];
  13190. }
  13191. // Try to parse input as a time stamp.
  13192. function parseTimeStamp(input) {
  13193. function computeSeconds(h, m, s, f) {
  13194. return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
  13195. }
  13196. var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);
  13197. if (!m) {
  13198. return null;
  13199. }
  13200. if (m[3]) {
  13201. // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
  13202. return computeSeconds(m[1], m[2], m[3].replace(':', ''), m[4]);
  13203. } else if (m[1] > 59) {
  13204. // Timestamp takes the form of [hours]:[minutes].[milliseconds]
  13205. // First position is hours as it's over 59.
  13206. return computeSeconds(m[1], m[2], 0, m[4]);
  13207. } else {
  13208. // Timestamp takes the form of [minutes]:[seconds].[milliseconds]
  13209. return computeSeconds(0, m[1], m[2], m[4]);
  13210. }
  13211. }
  13212. // A settings object holds key/value pairs and will ignore anything but the first
  13213. // assignment to a specific key.
  13214. function Settings() {
  13215. this.values = Object.create(null);
  13216. }
  13217. Settings.prototype = {
  13218. // Only accept the first assignment to any key.
  13219. set: function set(k, v) {
  13220. if (!this.get(k) && v !== '') {
  13221. this.values[k] = v;
  13222. }
  13223. },
  13224. // Return the value for a key, or a default value.
  13225. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  13226. // a number of possible default values as properties where 'defaultKey' is
  13227. // the key of the property that will be chosen; otherwise it's assumed to be
  13228. // a single value.
  13229. get: function get(k, dflt, defaultKey) {
  13230. if (defaultKey) {
  13231. return this.has(k) ? this.values[k] : dflt[defaultKey];
  13232. }
  13233. return this.has(k) ? this.values[k] : dflt;
  13234. },
  13235. // Check whether we have a value for a key.
  13236. has: function has(k) {
  13237. return k in this.values;
  13238. },
  13239. // Accept a setting if its one of the given alternatives.
  13240. alt: function alt(k, v, a) {
  13241. for (var n = 0; n < a.length; ++n) {
  13242. if (v === a[n]) {
  13243. this.set(k, v);
  13244. break;
  13245. }
  13246. }
  13247. },
  13248. // Accept a setting if its a valid (signed) integer.
  13249. integer: function integer(k, v) {
  13250. if (/^-?\d+$/.test(v)) {
  13251. // integer
  13252. this.set(k, parseInt(v, 10));
  13253. }
  13254. },
  13255. // Accept a setting if its a valid percentage.
  13256. percent: function percent(k, v) {
  13257. var m;
  13258. if (m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/)) {
  13259. v = parseFloat(v);
  13260. if (v >= 0 && v <= 100) {
  13261. this.set(k, v);
  13262. return true;
  13263. }
  13264. }
  13265. return false;
  13266. }
  13267. };
  13268. // Helper function to parse input into groups separated by 'groupDelim', and
  13269. // interprete each group as a key/value pair separated by 'keyValueDelim'.
  13270. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  13271. var groups = groupDelim ? input.split(groupDelim) : [input];
  13272. for (var i in groups) {
  13273. if (typeof groups[i] !== 'string') {
  13274. continue;
  13275. }
  13276. var kv = groups[i].split(keyValueDelim);
  13277. if (kv.length !== 2) {
  13278. continue;
  13279. }
  13280. var k = kv[0];
  13281. var v = kv[1];
  13282. callback(k, v);
  13283. }
  13284. }
  13285. var defaults = new _vttcue2.default(0, 0, 0);
  13286. // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244
  13287. // Chrome and Safari don't yet support this change, but FF does
  13288. var center = defaults.align === 'middle' ? 'middle' : 'center';
  13289. function parseCue(input, cue, regionList) {
  13290. // Remember the original input if we need to throw an error.
  13291. var oInput = input;
  13292. // 4.1 WebVTT timestamp
  13293. function consumeTimeStamp() {
  13294. var ts = parseTimeStamp(input);
  13295. if (ts === null) {
  13296. throw new Error('Malformed timestamp: ' + oInput);
  13297. }
  13298. // Remove time stamp from input.
  13299. input = input.replace(/^[^\sa-zA-Z-]+/, '');
  13300. return ts;
  13301. }
  13302. // 4.4.2 WebVTT cue settings
  13303. function consumeCueSettings(input, cue) {
  13304. var settings = new Settings();
  13305. parseOptions(input, function (k, v) {
  13306. switch (k) {
  13307. case 'region':
  13308. // Find the last region we parsed with the same region id.
  13309. for (var i = regionList.length - 1; i >= 0; i--) {
  13310. if (regionList[i].id === v) {
  13311. settings.set(k, regionList[i].region);
  13312. break;
  13313. }
  13314. }
  13315. break;
  13316. case 'vertical':
  13317. settings.alt(k, v, ['rl', 'lr']);
  13318. break;
  13319. case 'line':
  13320. var vals = v.split(','),
  13321. vals0 = vals[0];
  13322. settings.integer(k, vals0);
  13323. if (settings.percent(k, vals0)) {
  13324. settings.set('snapToLines', false);
  13325. }
  13326. settings.alt(k, vals0, ['auto']);
  13327. if (vals.length === 2) {
  13328. settings.alt('lineAlign', vals[1], ['start', center, 'end']);
  13329. }
  13330. break;
  13331. case 'position':
  13332. vals = v.split(',');
  13333. settings.percent(k, vals[0]);
  13334. if (vals.length === 2) {
  13335. settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);
  13336. }
  13337. break;
  13338. case 'size':
  13339. settings.percent(k, v);
  13340. break;
  13341. case 'align':
  13342. settings.alt(k, v, ['start', center, 'end', 'left', 'right']);
  13343. break;
  13344. }
  13345. }, /:/, /\s/);
  13346. // Apply default values for any missing fields.
  13347. cue.region = settings.get('region', null);
  13348. cue.vertical = settings.get('vertical', '');
  13349. var line = settings.get('line', 'auto');
  13350. if (line === 'auto' && defaults.line === -1) {
  13351. // set numeric line number for Safari
  13352. line = -1;
  13353. }
  13354. cue.line = line;
  13355. cue.lineAlign = settings.get('lineAlign', 'start');
  13356. cue.snapToLines = settings.get('snapToLines', true);
  13357. cue.size = settings.get('size', 100);
  13358. cue.align = settings.get('align', center);
  13359. var position = settings.get('position', 'auto');
  13360. if (position === 'auto' && defaults.position === 50) {
  13361. // set numeric position for Safari
  13362. position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;
  13363. }
  13364. cue.position = position;
  13365. }
  13366. function skipWhitespace() {
  13367. input = input.replace(/^\s+/, '');
  13368. }
  13369. // 4.1 WebVTT cue timings.
  13370. skipWhitespace();
  13371. cue.startTime = consumeTimeStamp(); // (1) collect cue start time
  13372. skipWhitespace();
  13373. if (input.substr(0, 3) !== '-->') {
  13374. // (3) next characters must match '-->'
  13375. throw new Error('Malformed time stamp (time stamps must be separated by \'-->\'): ' + oInput);
  13376. }
  13377. input = input.substr(3);
  13378. skipWhitespace();
  13379. cue.endTime = consumeTimeStamp(); // (5) collect cue end time
  13380. // 4.1 WebVTT cue settings list.
  13381. skipWhitespace();
  13382. consumeCueSettings(input, cue);
  13383. }
  13384. function fixLineBreaks(input) {
  13385. return input.replace(/<br(?: \/)?>/gi, '\n');
  13386. }
  13387. VTTParser.prototype = {
  13388. parse: function parse(data) {
  13389. var self = this;
  13390. // If there is no data then we won't decode it, but will just try to parse
  13391. // whatever is in buffer already. This may occur in circumstances, for
  13392. // example when flush() is called.
  13393. if (data) {
  13394. // Try to decode the data that we received.
  13395. self.buffer += self.decoder.decode(data, { stream: true });
  13396. }
  13397. function collectNextLine() {
  13398. var buffer = self.buffer;
  13399. var pos = 0;
  13400. buffer = fixLineBreaks(buffer);
  13401. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  13402. ++pos;
  13403. }
  13404. var line = buffer.substr(0, pos);
  13405. // Advance the buffer early in case we fail below.
  13406. if (buffer[pos] === '\r') {
  13407. ++pos;
  13408. }
  13409. if (buffer[pos] === '\n') {
  13410. ++pos;
  13411. }
  13412. self.buffer = buffer.substr(pos);
  13413. return line;
  13414. }
  13415. // 3.2 WebVTT metadata header syntax
  13416. function parseHeader(input) {
  13417. parseOptions(input, function (k, v) {
  13418. switch (k) {
  13419. case 'Region':
  13420. // 3.3 WebVTT region metadata header syntax
  13421. console.log('parse region', v);
  13422. //parseRegion(v);
  13423. break;
  13424. }
  13425. }, /:/);
  13426. }
  13427. // 5.1 WebVTT file parsing.
  13428. try {
  13429. var line;
  13430. if (self.state === 'INITIAL') {
  13431. // We can't start parsing until we have the first line.
  13432. if (!/\r\n|\n/.test(self.buffer)) {
  13433. return this;
  13434. }
  13435. line = collectNextLine();
  13436. var m = line.match(/^WEBVTT([ \t].*)?$/);
  13437. if (!m || !m[0]) {
  13438. throw new Error('Malformed WebVTT signature.');
  13439. }
  13440. self.state = 'HEADER';
  13441. }
  13442. var alreadyCollectedLine = false;
  13443. while (self.buffer) {
  13444. // We can't parse a line until we have the full line.
  13445. if (!/\r\n|\n/.test(self.buffer)) {
  13446. return this;
  13447. }
  13448. if (!alreadyCollectedLine) {
  13449. line = collectNextLine();
  13450. } else {
  13451. alreadyCollectedLine = false;
  13452. }
  13453. switch (self.state) {
  13454. case 'HEADER':
  13455. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  13456. if (/:/.test(line)) {
  13457. parseHeader(line);
  13458. } else if (!line) {
  13459. // An empty line terminates the header and starts the body (cues).
  13460. self.state = 'ID';
  13461. }
  13462. continue;
  13463. case 'NOTE':
  13464. // Ignore NOTE blocks.
  13465. if (!line) {
  13466. self.state = 'ID';
  13467. }
  13468. continue;
  13469. case 'ID':
  13470. // Check for the start of NOTE blocks.
  13471. if (/^NOTE($|[ \t])/.test(line)) {
  13472. self.state = 'NOTE';
  13473. break;
  13474. }
  13475. // 19-29 - Allow any number of line terminators, then initialize new cue values.
  13476. if (!line) {
  13477. continue;
  13478. }
  13479. self.cue = new _vttcue2.default(0, 0, '');
  13480. self.state = 'CUE';
  13481. // 30-39 - Check if self line contains an optional identifier or timing data.
  13482. if (line.indexOf('-->') === -1) {
  13483. self.cue.id = line;
  13484. continue;
  13485. }
  13486. // Process line as start of a cue.
  13487. /*falls through*/
  13488. case 'CUE':
  13489. // 40 - Collect cue timings and settings.
  13490. try {
  13491. parseCue(line, self.cue, self.regionList);
  13492. } catch (e) {
  13493. // In case of an error ignore rest of the cue.
  13494. self.cue = null;
  13495. self.state = 'BADCUE';
  13496. continue;
  13497. }
  13498. self.state = 'CUETEXT';
  13499. continue;
  13500. case 'CUETEXT':
  13501. var hasSubstring = line.indexOf('-->') !== -1;
  13502. // 34 - If we have an empty line then report the cue.
  13503. // 35 - If we have the special substring '-->' then report the cue,
  13504. // but do not collect the line as we need to process the current
  13505. // one as a new cue.
  13506. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  13507. // We are done parsing self cue.
  13508. if (self.oncue) {
  13509. self.oncue(self.cue);
  13510. }
  13511. self.cue = null;
  13512. self.state = 'ID';
  13513. continue;
  13514. }
  13515. if (self.cue.text) {
  13516. self.cue.text += '\n';
  13517. }
  13518. self.cue.text += line;
  13519. continue;
  13520. case 'BADCUE':
  13521. // BADCUE
  13522. // 54-62 - Collect and discard the remaining cue.
  13523. if (!line) {
  13524. self.state = 'ID';
  13525. }
  13526. continue;
  13527. }
  13528. }
  13529. } catch (e) {
  13530. // If we are currently parsing a cue, report what we have.
  13531. if (self.state === 'CUETEXT' && self.cue && self.oncue) {
  13532. self.oncue(self.cue);
  13533. }
  13534. self.cue = null;
  13535. // Enter BADWEBVTT state if header was not parsed correctly otherwise
  13536. // another exception occurred so enter BADCUE state.
  13537. self.state = self.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';
  13538. }
  13539. return this;
  13540. },
  13541. flush: function flush() {
  13542. var self = this;
  13543. try {
  13544. // Finish decoding the stream.
  13545. self.buffer += self.decoder.decode();
  13546. // Synthesize the end of the current cue or region.
  13547. if (self.cue || self.state === 'HEADER') {
  13548. self.buffer += '\n\n';
  13549. self.parse();
  13550. }
  13551. // If we've flushed, parsed, and we're still on the INITIAL state then
  13552. // that means we don't have enough of the stream to parse the first
  13553. // line.
  13554. if (self.state === 'INITIAL') {
  13555. throw new Error('Malformed WebVTT signature.');
  13556. }
  13557. } catch (e) {
  13558. throw e;
  13559. }
  13560. if (self.onflush) {
  13561. self.onflush();
  13562. }
  13563. return this;
  13564. }
  13565. };
  13566. exports.fixLineBreaks = fixLineBreaks;
  13567. exports.default = VTTParser;
  13568. },{"52":52}],54:[function(_dereq_,module,exports){
  13569. 'use strict';
  13570. var _vttparser = _dereq_(53);
  13571. var _vttparser2 = _interopRequireDefault(_vttparser);
  13572. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13573. var cueString2millis = function cueString2millis(timeString) {
  13574. var ts = parseInt(timeString.substr(-3));
  13575. var secs = parseInt(timeString.substr(-6, 2));
  13576. var mins = parseInt(timeString.substr(-9, 2));
  13577. var hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;
  13578. if (isNaN(ts) || isNaN(secs) || isNaN(mins) || isNaN(hours)) {
  13579. return -1;
  13580. }
  13581. ts += 1000 * secs;
  13582. ts += 60 * 1000 * mins;
  13583. ts += 60 * 60 * 1000 * hours;
  13584. return ts;
  13585. };
  13586. var calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {
  13587. var currCC = vttCCs[cc];
  13588. var prevCC = vttCCs[currCC.prevCC];
  13589. // This is the first discontinuity or cues have been processed since the last discontinuity
  13590. // Offset = current discontinuity time
  13591. if (!prevCC || !prevCC.new && currCC.new) {
  13592. vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
  13593. currCC.new = false;
  13594. return;
  13595. }
  13596. // There have been discontinuities since cues were last parsed.
  13597. // Offset = time elapsed
  13598. while (prevCC && prevCC.new) {
  13599. vttCCs.ccOffset += currCC.start - prevCC.start;
  13600. currCC.new = false;
  13601. currCC = prevCC;
  13602. prevCC = vttCCs[currCC.prevCC];
  13603. }
  13604. vttCCs.presentationOffset = presentationTime;
  13605. };
  13606. var WebVTTParser = {
  13607. parse: function parse(vttByteArray, syncPTS, vttCCs, cc, callBack, errorCallBack) {
  13608. // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character.
  13609. var re = /\r\n|\n\r|\n|\r/g;
  13610. var vttLines = String.fromCharCode.apply(null, new Uint8Array(vttByteArray)).trim().replace(re, '\n').split('\n');
  13611. var cueTime = '00:00.000';
  13612. var mpegTs = 0;
  13613. var localTime = 0;
  13614. var presentationTime = 0;
  13615. var cues = [];
  13616. var parsingError = void 0;
  13617. var inHeader = true;
  13618. // let VTTCue = VTTCue || window.TextTrackCue;
  13619. // Create parser object using VTTCue with TextTrackCue fallback on certain browsers.
  13620. var parser = new _vttparser2.default();
  13621. parser.oncue = function (cue) {
  13622. // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.
  13623. var currCC = vttCCs[cc];
  13624. var cueOffset = vttCCs.ccOffset;
  13625. // Update offsets for new discontinuities
  13626. if (currCC && currCC.new) {
  13627. if (localTime) {
  13628. // When local time is provided, offset = discontinuity start time - local time
  13629. cueOffset = vttCCs.ccOffset = currCC.start;
  13630. } else {
  13631. calculateOffset(vttCCs, cc, presentationTime);
  13632. }
  13633. }
  13634. if (presentationTime && !localTime) {
  13635. // If we have MPEGTS but no LOCAL time, offset = presentation time + discontinuity offset
  13636. cueOffset = presentationTime + vttCCs.ccOffset - vttCCs.presentationOffset;
  13637. }
  13638. cue.startTime += cueOffset - localTime;
  13639. cue.endTime += cueOffset - localTime;
  13640. // Fix encoding of special characters. TODO: Test with all sorts of weird characters.
  13641. cue.text = decodeURIComponent(escape(cue.text));
  13642. if (cue.endTime > 0) {
  13643. cues.push(cue);
  13644. }
  13645. };
  13646. parser.onparsingerror = function (e) {
  13647. parsingError = e;
  13648. };
  13649. parser.onflush = function () {
  13650. if (parsingError && errorCallBack) {
  13651. errorCallBack(parsingError);
  13652. return;
  13653. }
  13654. callBack(cues);
  13655. };
  13656. // Go through contents line by line.
  13657. vttLines.forEach(function (line) {
  13658. if (inHeader) {
  13659. // Look for X-TIMESTAMP-MAP in header.
  13660. if (line.startsWith('X-TIMESTAMP-MAP=')) {
  13661. // Once found, no more are allowed anyway, so stop searching.
  13662. inHeader = false;
  13663. // Extract LOCAL and MPEGTS.
  13664. line.substr(16).split(',').forEach(function (timestamp) {
  13665. if (timestamp.startsWith('LOCAL:')) {
  13666. cueTime = timestamp.substr(6);
  13667. } else if (timestamp.startsWith('MPEGTS:')) {
  13668. mpegTs = parseInt(timestamp.substr(7));
  13669. }
  13670. });
  13671. try {
  13672. // Calculate subtitle offset in milliseconds.
  13673. // If sync PTS is less than zero, we have a 33-bit wraparound, which is fixed by adding 2^33 = 8589934592.
  13674. syncPTS = syncPTS < 0 ? syncPTS + 8589934592 : syncPTS;
  13675. // Adjust MPEGTS by sync PTS.
  13676. mpegTs -= syncPTS;
  13677. // Convert cue time to seconds
  13678. localTime = cueString2millis(cueTime) / 1000;
  13679. // Convert MPEGTS to seconds from 90kHz.
  13680. presentationTime = mpegTs / 90000;
  13681. if (localTime === -1) {
  13682. parsingError = new Error('Malformed X-TIMESTAMP-MAP: ' + line);
  13683. }
  13684. } catch (e) {
  13685. parsingError = new Error('Malformed X-TIMESTAMP-MAP: ' + line);
  13686. }
  13687. // Return without parsing X-TIMESTAMP-MAP line.
  13688. return;
  13689. } else if (line === '') {
  13690. inHeader = false;
  13691. }
  13692. }
  13693. // Parse line by default.
  13694. parser.parse(line + '\n');
  13695. });
  13696. parser.flush();
  13697. }
  13698. };
  13699. module.exports = WebVTTParser;
  13700. },{"53":53}],55:[function(_dereq_,module,exports){
  13701. 'use strict';
  13702. Object.defineProperty(exports, "__esModule", {
  13703. value: true
  13704. });
  13705. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  13706. * XHR based logger
  13707. */
  13708. var _logger = _dereq_(50);
  13709. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13710. var XhrLoader = function () {
  13711. function XhrLoader(config) {
  13712. _classCallCheck(this, XhrLoader);
  13713. if (config && config.xhrSetup) {
  13714. this.xhrSetup = config.xhrSetup;
  13715. }
  13716. }
  13717. _createClass(XhrLoader, [{
  13718. key: 'destroy',
  13719. value: function destroy() {
  13720. this.abort();
  13721. this.loader = null;
  13722. }
  13723. }, {
  13724. key: 'abort',
  13725. value: function abort() {
  13726. var loader = this.loader;
  13727. if (loader && loader.readyState !== 4) {
  13728. this.stats.aborted = true;
  13729. loader.abort();
  13730. }
  13731. window.clearTimeout(this.requestTimeout);
  13732. this.requestTimeout = null;
  13733. window.clearTimeout(this.retryTimeout);
  13734. this.retryTimeout = null;
  13735. }
  13736. }, {
  13737. key: 'load',
  13738. value: function load(context, config, callbacks) {
  13739. this.context = context;
  13740. this.config = config;
  13741. this.callbacks = callbacks;
  13742. this.stats = { trequest: performance.now(), retry: 0 };
  13743. this.retryDelay = config.retryDelay;
  13744. this.loadInternal();
  13745. }
  13746. }, {
  13747. key: 'loadInternal',
  13748. value: function loadInternal() {
  13749. var xhr,
  13750. context = this.context;
  13751. if (typeof XDomainRequest !== 'undefined') {
  13752. xhr = this.loader = new XDomainRequest();
  13753. } else {
  13754. xhr = this.loader = new XMLHttpRequest();
  13755. }
  13756. var stats = this.stats;
  13757. stats.tfirst = 0;
  13758. stats.loaded = 0;
  13759. var xhrSetup = this.xhrSetup;
  13760. if (xhrSetup) {
  13761. try {
  13762. xhrSetup(xhr, context.url);
  13763. } catch (e) {
  13764. // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");}
  13765. // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN
  13766. xhr.open('GET', context.url, true);
  13767. xhrSetup(xhr, context.url);
  13768. }
  13769. }
  13770. if (!xhr.readyState) {
  13771. xhr.open('GET', context.url, true);
  13772. }
  13773. if (context.rangeEnd) {
  13774. xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
  13775. }
  13776. xhr.onreadystatechange = this.readystatechange.bind(this);
  13777. xhr.onprogress = this.loadprogress.bind(this);
  13778. xhr.responseType = context.responseType;
  13779. // setup timeout before we perform request
  13780. this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout);
  13781. xhr.send();
  13782. }
  13783. }, {
  13784. key: 'readystatechange',
  13785. value: function readystatechange(event) {
  13786. var xhr = event.currentTarget,
  13787. readyState = xhr.readyState,
  13788. stats = this.stats,
  13789. context = this.context,
  13790. config = this.config;
  13791. // don't proceed if xhr has been aborted
  13792. if (stats.aborted) {
  13793. return;
  13794. }
  13795. // >= HEADERS_RECEIVED
  13796. if (readyState >= 2) {
  13797. // clear xhr timeout and rearm it if readyState less than 4
  13798. window.clearTimeout(this.requestTimeout);
  13799. if (stats.tfirst === 0) {
  13800. stats.tfirst = Math.max(performance.now(), stats.trequest);
  13801. }
  13802. if (readyState === 4) {
  13803. var status = xhr.status;
  13804. // http status between 200 to 299 are all successful
  13805. if (status >= 200 && status < 300) {
  13806. stats.tload = Math.max(stats.tfirst, performance.now());
  13807. var data = void 0,
  13808. len = void 0;
  13809. if (context.responseType === 'arraybuffer') {
  13810. data = xhr.response;
  13811. len = data.byteLength;
  13812. } else {
  13813. data = xhr.responseText;
  13814. len = data.length;
  13815. }
  13816. stats.loaded = stats.total = len;
  13817. var response = { url: xhr.responseURL, data: data };
  13818. this.callbacks.onSuccess(response, stats, context);
  13819. } else {
  13820. // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
  13821. if (stats.retry >= config.maxRetry || status >= 400 && status < 499) {
  13822. _logger.logger.error(status + ' while loading ' + context.url);
  13823. this.callbacks.onError({ code: status, text: xhr.statusText }, context);
  13824. } else {
  13825. // retry
  13826. _logger.logger.warn(status + ' while loading ' + context.url + ', retrying in ' + this.retryDelay + '...');
  13827. // aborts and resets internal state
  13828. this.destroy();
  13829. // schedule retry
  13830. this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  13831. // set exponential backoff
  13832. this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);
  13833. stats.retry++;
  13834. }
  13835. }
  13836. } else {
  13837. // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
  13838. this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout);
  13839. }
  13840. }
  13841. }
  13842. }, {
  13843. key: 'loadtimeout',
  13844. value: function loadtimeout() {
  13845. _logger.logger.warn('timeout while loading ' + this.context.url);
  13846. this.callbacks.onTimeout(this.stats, this.context);
  13847. }
  13848. }, {
  13849. key: 'loadprogress',
  13850. value: function loadprogress(event) {
  13851. var stats = this.stats;
  13852. stats.loaded = event.loaded;
  13853. if (event.lengthComputable) {
  13854. stats.total = event.total;
  13855. }
  13856. var onProgress = this.callbacks.onProgress;
  13857. if (onProgress) {
  13858. // last args is to provide on progress data
  13859. onProgress(stats, this.context, null);
  13860. }
  13861. }
  13862. }]);
  13863. return XhrLoader;
  13864. }();
  13865. exports.default = XhrLoader;
  13866. },{"50":50}]},{},[37])(37)
  13867. });
  13868. //# sourceMappingURL=hls.js.map